From 48b6262b383365b7319ef76fa9c6d2c63c4d70e1 Mon Sep 17 00:00:00 2001 From: Jyun-Yan You Date: Sun, 5 May 2013 22:29:10 +0800 Subject: [PATCH 001/248] preliminary Linux ARM support --- mk/platform.mk | 26 ++++++++++++++++++++++++++ mk/rt.mk | 4 ++++ src/librustc/back/arm.rs | 2 +- src/rt/arch/arm/record_sp.S | 8 ++++++++ src/rt/rust_task.h | 3 +++ 5 files changed, 42 insertions(+), 1 deletion(-) diff --git a/mk/platform.mk b/mk/platform.mk index e03b7c152478f..78ca57f9c62c0 100644 --- a/mk/platform.mk +++ b/mk/platform.mk @@ -239,6 +239,32 @@ CFG_RUN_arm-linux-androideabi= CFG_RUN_TARG_arm-linux-androideabi= RUSTC_FLAGS_arm-linux-androideabi :=--android-cross-path=$(CFG_ANDROID_CROSS_PATH) +# arm-unknown-linux-gnueabihf configuration +CC_arm-unknown-linux-gnueabihf=arm-linux-gnueabihf-gcc +CXX_arm-unknown-linux-gnueabihf=arm-linux-gnueabihf-g++ +CPP_arm-unknown-linux-gnueabihf=arm-linux-gnueabihf-gcc -E +AR_arm-unknown-linux-gnueabihf=arm-linux-gnueabihf-ar +CFG_LIB_NAME_arm-unknown-linux-gnueabihf=lib$(1).so +CFG_LIB_GLOB_arm-unknown-linux-gnueabihf=lib$(1)-*.so +CFG_LIB_DSYM_GLOB_arm-unknown-linux-gnueabihf=lib$(1)-*.dylib.dSYM +CFG_GCCISH_CFLAGS_arm-unknown-linux-gnueabihf := -Wall -g -fPIC +CFG_GCCISH_CXXFLAGS_arm-unknown-linux-gnueabihf := -fno-rtti +CFG_GCCISH_LINK_FLAGS_arm-unknown-linux-gnueabihf := -shared -fPIC -g +CFG_GCCISH_DEF_FLAG_arm-unknown-linux-gnueabihf := -Wl,--export-dynamic,--dynamic-list= +CFG_GCCISH_PRE_LIB_FLAGS_arm-unknown-linux-gnueabihf := -Wl,-whole-archive +CFG_GCCISH_POST_LIB_FLAGS_arm-unknown-linux-gnueabihf := -Wl,-no-whole-archive +CFG_DEF_SUFFIX_arm-unknown-linux-gnueabihf := .linux.def +CFG_INSTALL_NAME_ar,-unknown-linux-gnueabihf = +CFG_LIBUV_LINK_FLAGS_arm-unknown-linux-gnueabihf = +CFG_EXE_SUFFIX_arm-unknown-linux-gnueabihf := +CFG_WINDOWSY_arm-unknown-linux-gnueabihf := +CFG_UNIXY_arm-unknown-linux-gnueabihf := 1 +CFG_PATH_MUNGE_arm-unknown-linux-gnueabihf := true +CFG_LDPATH_arm-unknown-linux-gnueabihf := +CFG_RUN_arm-unknown-linux-gnueabihf= +CFG_RUN_TARG_arm-unknown-linux-gnueabihf= +RUSTC_FLAGS_arm-unknown-linux-gnueabihf := --linker=$(CC_arm-unknown-linux-gnueabihf) + # mips-unknown-linux-gnu configuration CC_mips-unknown-linux-gnu=mips-linux-gnu-gcc CXX_mips-unknown-linux-gnu=mips-linux-gnu-g++ diff --git a/mk/rt.mk b/mk/rt.mk index 30dda2fb276c9..e26d7ac517ecf 100644 --- a/mk/rt.mk +++ b/mk/rt.mk @@ -26,7 +26,11 @@ # Hack for passing flags into LIBUV, see below. LIBUV_FLAGS_i386 = -m32 -fPIC LIBUV_FLAGS_x86_64 = -m64 -fPIC +ifeq ($(OSTYPE_$(1)), linux-androideabi) LIBUV_FLAGS_arm = -fPIC -DANDROID -std=gnu99 +else +LIBUV_FLAGS_arm = -fPIC -std=gnu99 +endif LIBUV_FLAGS_mips = -fPIC -mips32r2 -msoft-float -mabi=32 # when we're doing a snapshot build, we intentionally degrade as many diff --git a/src/librustc/back/arm.rs b/src/librustc/back/arm.rs index dfe5751f21b83..ff3c71da458a2 100644 --- a/src/librustc/back/arm.rs +++ b/src/librustc/back/arm.rs @@ -64,7 +64,7 @@ pub fn get_target_strs(target_os: session::os) -> target_strs::t { target_triple: match target_os { session::os_macos => ~"arm-apple-darwin", session::os_win32 => ~"arm-pc-mingw32", - session::os_linux => ~"arm-unknown-linux", + session::os_linux => ~"arm-unknown-linux-gnueabihf", session::os_android => ~"arm-linux-androideabi", session::os_freebsd => ~"arm-unknown-freebsd" }, diff --git a/src/rt/arch/arm/record_sp.S b/src/rt/arch/arm/record_sp.S index 95fce8746a118..8d5f24bc5a8c5 100644 --- a/src/rt/arch/arm/record_sp.S +++ b/src/rt/arch/arm/record_sp.S @@ -15,13 +15,21 @@ record_sp_limit: mrc p15, #0, r3, c13, c0, #3 +#if __ANDROID__ add r3, r3, #252 +#elif __linux__ + add r3, r3, #4 +#endif str r0, [r3] mov pc, lr get_sp_limit: mrc p15, #0, r3, c13, c0, #3 +#if __ANDROID__ add r3, r3, #252 +#elif __linux__ + add r3, r3, #4 +#endif ldr r0, [r3] mov pc, lr diff --git a/src/rt/rust_task.h b/src/rt/rust_task.h index fd4e8451b642a..6813e3b46c458 100644 --- a/src/rt/rust_task.h +++ b/src/rt/rust_task.h @@ -146,6 +146,9 @@ #ifdef __mips__ #define RED_ZONE_SIZE RZ_LINUX_32 #endif +#ifdef __arm__ +#define RED_ZONE_SIZE RZ_LINUX_32 +#endif #endif #ifdef __APPLE__ #ifdef __i386__ From 34be071353adf441a9d324528dafadc7c4aba82c Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 24 Apr 2013 18:26:49 -0700 Subject: [PATCH 002/248] core::rt: Remove Close trait We will just use RAII for now. --- src/libcore/rt/io/file.rs | 6 +----- src/libcore/rt/io/mod.rs | 11 +---------- src/libcore/rt/io/native/file.rs | 8 -------- src/libcore/rt/io/net/tcp.rs | 4 ---- src/libcore/rt/io/net/udp.rs | 4 ---- src/libcore/rt/io/net/unix.rs | 4 ---- src/libcore/rt/io/stdio.rs | 9 +-------- 7 files changed, 3 insertions(+), 43 deletions(-) diff --git a/src/libcore/rt/io/file.rs b/src/libcore/rt/io/file.rs index 85dc180452ffc..1f61cf25fbdd4 100644 --- a/src/libcore/rt/io/file.rs +++ b/src/libcore/rt/io/file.rs @@ -10,7 +10,7 @@ use prelude::*; use super::support::PathLike; -use super::{Reader, Writer, Seek, Close}; +use super::{Reader, Writer, Seek}; use super::SeekStyle; /// # XXX @@ -69,10 +69,6 @@ impl Seek for FileStream { fn seek(&mut self, _pos: i64, _style: SeekStyle) { fail!() } } -impl Close for FileStream { - fn close(&mut self) { fail!() } -} - #[test] #[ignore] fn super_simple_smoke_test_lets_go_read_some_files_and_have_a_good_time() { diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index fea32bc5b7509..d2249aad95ed2 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -383,16 +383,7 @@ pub trait Writer { fn flush(&mut self); } -/// I/O types that may be closed -/// -/// Any further operations performed on a closed resource will raise -/// on `io_error` -pub trait Close { - /// Close the I/O resource - fn close(&mut self); -} - -pub trait Stream: Reader + Writer + Close { } +pub trait Stream: Reader + Writer { } pub enum SeekStyle { /// Seek from the beginning of the stream diff --git a/src/libcore/rt/io/native/file.rs b/src/libcore/rt/io/native/file.rs index e203df815f2f4..31c90336a24c2 100644 --- a/src/libcore/rt/io/native/file.rs +++ b/src/libcore/rt/io/native/file.rs @@ -40,10 +40,6 @@ impl Writer for FileDesc { fn flush(&mut self) { fail!() } } -impl Close for FileDesc { - fn close(&mut self) { fail!() } -} - impl Seek for FileDesc { fn tell(&self) -> u64 { fail!() } @@ -72,10 +68,6 @@ impl Writer for CFile { fn flush(&mut self) { fail!() } } -impl Close for CFile { - fn close(&mut self) { fail!() } -} - impl Seek for CFile { fn tell(&self) -> u64 { fail!() } fn seek(&mut self, _pos: i64, _style: SeekStyle) { fail!() } diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index c95b4344fe75d..00b48738d0bb7 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -32,10 +32,6 @@ impl Writer for TcpStream { fn flush(&mut self) { fail!() } } -impl Close for TcpStream { - fn close(&mut self) { fail!() } -} - pub struct TcpListener; impl TcpListener { diff --git a/src/libcore/rt/io/net/udp.rs b/src/libcore/rt/io/net/udp.rs index 1f1254a7029f0..bb5457e334dda 100644 --- a/src/libcore/rt/io/net/udp.rs +++ b/src/libcore/rt/io/net/udp.rs @@ -32,10 +32,6 @@ impl Writer for UdpStream { fn flush(&mut self) { fail!() } } -impl Close for UdpStream { - fn close(&mut self) { fail!() } -} - pub struct UdpListener; impl UdpListener { diff --git a/src/libcore/rt/io/net/unix.rs b/src/libcore/rt/io/net/unix.rs index f449a857467cc..b85b7dd059d82 100644 --- a/src/libcore/rt/io/net/unix.rs +++ b/src/libcore/rt/io/net/unix.rs @@ -32,10 +32,6 @@ impl Writer for UnixStream { fn flush(&mut self) { fail!() } } -impl Close for UnixStream { - fn close(&mut self) { fail!() } -} - pub struct UnixListener; impl UnixListener { diff --git a/src/libcore/rt/io/stdio.rs b/src/libcore/rt/io/stdio.rs index 26950986f7a09..247fe9544088b 100644 --- a/src/libcore/rt/io/stdio.rs +++ b/src/libcore/rt/io/stdio.rs @@ -9,7 +9,7 @@ // except according to those terms. use prelude::*; -use super::{Reader, Writer, Close}; +use super::{Reader, Writer}; pub fn stdin() -> StdReader { fail!() } @@ -39,10 +39,6 @@ impl Reader for StdReader { fn eof(&mut self) -> bool { fail!() } } -impl Close for StdReader { - fn close(&mut self) { fail!() } -} - pub struct StdWriter; impl StdWriter { @@ -55,6 +51,3 @@ impl Writer for StdWriter { fn flush(&mut self) { fail!() } } -impl Close for StdWriter { - fn close(&mut self) { fail!() } -} From 0b4d4edf8bc6a90c0bcbf06599ddf92fea1ed58f Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 24 Apr 2013 18:27:30 -0700 Subject: [PATCH 003/248] core::rt: Fix a warning about unnecessary mutable variable --- src/libcore/rt/test.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index 63db705408800..0c6843c605d15 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -77,7 +77,7 @@ pub fn spawntask_try(f: ~fn()) -> Result<(), ()> { // Switch to the scheduler let f = Cell(Cell(f)); - let mut sched = local_sched::take(); + let sched = local_sched::take(); do sched.deschedule_running_task_and_then() |old_task| { let old_task = Cell(old_task); let f = f.take(); From b2fbd34603c5e209ab7a61a09ca943bd5b15f1a3 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 24 Apr 2013 20:20:03 -0700 Subject: [PATCH 004/248] core::rt: Begin implementing TcpStream This ended up touching a lot of code related to error handling. --- src/libcore/macros.rs | 8 ++ src/libcore/rt/io/mod.rs | 11 +- src/libcore/rt/io/net/tcp.rs | 164 ++++++++++++++++++++++++---- src/libcore/rt/local_services.rs | 3 +- src/libcore/rt/mod.rs | 12 +- src/libcore/rt/rtio.rs | 5 +- src/libcore/rt/sched/local_sched.rs | 31 ++++-- src/libcore/rt/uv/mod.rs | 60 +++++++++- src/libcore/rt/uv/net.rs | 14 ++- src/libcore/rt/uvio.rs | 24 ++-- src/libcore/rt/uvll.rs | 7 ++ 11 files changed, 282 insertions(+), 57 deletions(-) diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index b19a753b71577..b2e94f327c86e 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -30,6 +30,14 @@ macro_rules! rtdebug ( ($( $arg:expr),+) => ( $(let _ = $arg)*; ) ) +macro_rules! rtassert ( + ( $arg:expr ) => ( { + if !$arg { + abort!("assertion failed: %s", stringify!($arg)); + } + } ) +) + macro_rules! abort( ($( $msg:expr),+) => ( { rtdebug!($($msg),+); diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index d2249aad95ed2..93daa36dd60a7 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -252,7 +252,9 @@ pub use self::stdio::println; pub use self::file::FileStream; pub use self::net::ip::IpAddr; +#[cfg(not(stage0))] pub use self::net::tcp::TcpListener; +#[cfg(not(stage0))] pub use self::net::tcp::TcpStream; pub use self::net::udp::UdpStream; @@ -266,6 +268,7 @@ pub mod file; /// Synchronous, non-blocking network I/O. pub mod net { + #[cfg(not(stage0))] pub mod tcp; pub mod udp; pub mod ip; @@ -326,12 +329,14 @@ pub struct IoError { #[deriving(Eq)] pub enum IoErrorKind { + PreviousIoError, + OtherIoError, + EndOfFile, FileNotFound, - FilePermission, + PermissionDenied, ConnectionFailed, Closed, - OtherIoError, - PreviousIoError + ConnectionRefused, } // XXX: Can't put doc comments on macros diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 00b48738d0bb7..2ac2ffb60a8cf 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -8,63 +8,179 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use prelude::*; -use super::super::*; -use super::ip::IpAddr; +use option::{Option, Some, None}; +use result::{Result, Ok, Err}; +use ops::Drop; +use rt::sched::local_sched::unsafe_borrow_io; +use rt::io::net::ip::IpAddr; +use rt::io::{Reader, Writer, Listener}; +use rt::io::io_error; +use rt::rtio; +use rt::rtio::{IoFactory, TcpListener, Stream}; -pub struct TcpStream; +pub struct TcpStream { + rtstream: ~rtio::StreamObject +} impl TcpStream { - pub fn connect(_addr: IpAddr) -> Option { - fail!() + fn new(s: ~rtio::StreamObject) -> TcpStream { + TcpStream { + rtstream: s + } + } + + pub fn connect(addr: IpAddr) -> Option { + let stream = unsafe { + rtdebug!("borrowing io to connect"); + let io = unsafe_borrow_io(); + rtdebug!("about to connect"); + io.connect(addr) + }; + + match stream { + Ok(s) => { + Some(TcpStream::new(s)) + } + Err(ioerr) => { + rtdebug!("failed to connect: %?", ioerr); + io_error::cond.raise(ioerr); + return None; + } + } } } impl Reader for TcpStream { - fn read(&mut self, _buf: &mut [u8]) -> Option { fail!() } + fn read(&mut self, buf: &mut [u8]) -> Option { + let bytes_read = self.rtstream.read(buf); + match bytes_read { + Ok(read) => Some(read), + Err(_) => { + abort!("TODO"); + } + } + } fn eof(&mut self) -> bool { fail!() } } impl Writer for TcpStream { - fn write(&mut self, _buf: &[u8]) { fail!() } + fn write(&mut self, buf: &[u8]) { + let res = self.rtstream.write(buf); + match res { + Ok(_) => (), + Err(_) => { + abort!("TODO"); + } + } + } fn flush(&mut self) { fail!() } } -pub struct TcpListener; +impl Drop for TcpStream { + fn finalize(&self) { + self.rtstream.close(); + } +} + +pub struct TcpListener { + rtlistener: ~rtio::TcpListenerObject +} impl TcpListener { - pub fn bind(_addr: IpAddr) -> Option { - fail!() + pub fn bind(addr: IpAddr) -> Option { + let listener = unsafe { unsafe_borrow_io().bind(addr) }; + match listener { + Ok(l) => { + Some(TcpListener { + rtlistener: l + }) + } + Err(ioerr) => { + io_error::cond.raise(ioerr); + return None; + } + } } } impl Listener for TcpListener { - fn accept(&mut self) -> Option { fail!() } + fn accept(&mut self) -> Option { + let rtstream = self.rtlistener.listen(); + match rtstream { + Some(s) => { + Some(TcpStream::new(s)) + } + None => { + abort!("TODO"); + } + } + } +} + +impl Drop for TcpListener { + fn finalize(&self) { + self.rtlistener.close(); + } } #[cfg(test)] mod test { + use super::*; + use rt::test::*; + use rt::io::net::ip::Ipv4; + use rt::io::*; + + #[test] + fn bind_error() { + do run_in_newsched_task { + let mut called = false; + do io_error::cond.trap(|e| { + assert!(e.kind == PermissionDenied); + called = true; + }).in { + let addr = Ipv4(0, 0, 0, 0, 1); + let listener = TcpListener::bind(addr); + assert!(listener.is_none()); + } + assert!(called); + } + } + + #[test] + fn connect_error() { + do run_in_newsched_task { + let mut called = false; + do io_error::cond.trap(|e| { + assert!(e.kind == ConnectionRefused); + called = true; + }).in { + let addr = Ipv4(0, 0, 0, 0, 1); + let stream = TcpStream::connect(addr); + assert!(stream.is_none()); + } + assert!(called); + } + } - #[test] #[ignore] + #[test] fn smoke_test() { - /*do run_in_newsched_task { + do run_in_newsched_task { let addr = next_test_ip4(); - do spawn_immediately { - let listener = TcpListener::bind(addr); - do listener.accept() { - let mut buf = [0]; - listener.read(buf); - assert!(buf[0] == 99); - } + do spawntask_immediately { + let mut listener = TcpListener::bind(addr); + let mut stream = listener.accept(); + let mut buf = [0]; + stream.read(buf); + assert!(buf[0] == 99); } - do spawn_immediately { - let stream = TcpStream::connect(addr); + do spawntask_immediately { + let mut stream = TcpStream::connect(addr); stream.write([99]); } - }*/ + } } } diff --git a/src/libcore/rt/local_services.rs b/src/libcore/rt/local_services.rs index 01bef5e245888..47e8669b54692 100644 --- a/src/libcore/rt/local_services.rs +++ b/src/libcore/rt/local_services.rs @@ -177,7 +177,8 @@ pub unsafe fn unsafe_borrow_local_services() -> &mut LocalServices { transmute_mut_region(&mut task.local_services) } None => { - fail!(~"no local services for schedulers yet") + // Don't fail. Infinite recursion + abort!("no local services for schedulers yet") } } } diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 25f6c870654a6..72715ea9b2823 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -8,7 +8,15 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/*! The Rust runtime, including the scheduler and I/O interface */ +/*! The Rust runtime, including the scheduler and I/O interface + +# XXX + +* Unsafe uses of borrowed pointers should just use unsafe pointers +* Unwinding is not wired up correctly + +*/ + #[doc(hidden)]; @@ -16,7 +24,7 @@ use libc::c_char; #[path = "sched/mod.rs"] mod sched; -mod rtio; +pub mod rtio; pub mod uvll; mod uvio; #[path = "uv/mod.rs"] diff --git a/src/libcore/rt/rtio.rs b/src/libcore/rt/rtio.rs index fd64438c61b46..961a032607eb3 100644 --- a/src/libcore/rt/rtio.rs +++ b/src/libcore/rt/rtio.rs @@ -11,6 +11,7 @@ use option::*; use result::*; +use rt::io::IoError; use super::io::net::ip::IpAddr; // XXX: ~object doesn't work currently so these are some placeholder @@ -28,8 +29,8 @@ pub trait EventLoop { } pub trait IoFactory { - fn connect(&mut self, addr: IpAddr) -> Option<~StreamObject>; - fn bind(&mut self, addr: IpAddr) -> Option<~TcpListenerObject>; + fn connect(&mut self, addr: IpAddr) -> Result<~StreamObject, IoError>; + fn bind(&mut self, addr: IpAddr) -> Result<~TcpListenerObject, IoError>; } pub trait TcpListener { diff --git a/src/libcore/rt/sched/local_sched.rs b/src/libcore/rt/sched/local_sched.rs index a7e02f30e0167..c4153381d91aa 100644 --- a/src/libcore/rt/sched/local_sched.rs +++ b/src/libcore/rt/sched/local_sched.rs @@ -13,18 +13,21 @@ use prelude::*; use ptr::mut_null; use libc::c_void; -use cast::transmute; +use cast; +use cell::Cell; use super::Scheduler; use super::super::rtio::IoFactoryObject; use tls = super::super::thread_local_storage; +use unstable::finally::Finally; + #[cfg(test)] use super::super::uvio::UvEventLoop; /// Give the Scheduler to thread-local storage pub fn put(sched: ~Scheduler) { unsafe { let key = tls_key(); - let void_sched: *mut c_void = transmute::<~Scheduler, *mut c_void>(sched); + let void_sched: *mut c_void = cast::transmute(sched); tls::set(key, void_sched); } } @@ -34,8 +37,8 @@ pub fn take() -> ~Scheduler { unsafe { let key = tls_key(); let void_sched: *mut c_void = tls::get(key); - assert!(void_sched.is_not_null()); - let sched = transmute::<*mut c_void, ~Scheduler>(void_sched); + rtassert!(void_sched.is_not_null()); + let sched: ~Scheduler = cast::transmute(void_sched); tls::set(key, mut_null()); return sched; } @@ -55,8 +58,18 @@ pub fn exists() -> bool { /// While the scheduler is borrowed it is not available in TLS. pub fn borrow(f: &fn(&mut Scheduler)) { let mut sched = take(); - f(sched); - put(sched); + + // XXX: Need a different abstraction from 'finally' here to avoid unsafety + unsafe { + let unsafe_sched = cast::transmute_mut_region(&mut *sched); + let sched = Cell(sched); + + do (|| { + f(unsafe_sched); + }).finally { + put(sched.take()); + } + } } /// Borrow a mutable reference to the thread-local Scheduler @@ -68,11 +81,11 @@ pub fn borrow(f: &fn(&mut Scheduler)) { pub unsafe fn unsafe_borrow() -> &mut Scheduler { let key = tls_key(); let mut void_sched: *mut c_void = tls::get(key); - assert!(void_sched.is_not_null()); + rtassert!(void_sched.is_not_null()); { let void_sched_ptr = &mut void_sched; let sched: &mut ~Scheduler = { - transmute::<&mut *mut c_void, &mut ~Scheduler>(void_sched_ptr) + cast::transmute::<&mut *mut c_void, &mut ~Scheduler>(void_sched_ptr) }; let sched: &mut Scheduler = &mut **sched; return sched; @@ -91,7 +104,7 @@ fn tls_key() -> tls::Key { fn maybe_tls_key() -> Option { unsafe { let key: *mut c_void = rust_get_sched_tls_key(); - let key: &mut tls::Key = transmute(key); + let key: &mut tls::Key = cast::transmute(key); let key = *key; // Check that the key has been initialized. diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 013a28abf2813..87aa7524ed610 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -34,17 +34,22 @@ via `close` and `delete` methods. */ +use libc; +use vec; +use ptr; +use cast; +use str; use option::*; use str::raw::from_c_str; use to_str::ToStr; -use vec; -use ptr; use libc::{c_void, c_int, size_t, malloc, free}; use cast::transmute; use ptr::null; -use super::uvll; use unstable::finally::Finally; +use rt::uvll; +use rt::io::{IoError, FileNotFound}; + #[cfg(test)] use unstable::run_in_bare_thread; pub use self::file::{FsRequest, FsCallback}; @@ -211,6 +216,55 @@ fn error_smoke_test() { assert!(err.to_str() == ~"EOF: end of file"); } +pub fn last_uv_error>(watcher: &W) -> UvError { + unsafe { + let loop_ = loop_from_watcher(watcher); + UvError(uvll::last_error(loop_.native_handle())) + } +} + +pub fn uv_error_to_io_error(uverr: UvError) -> IoError { + + // XXX: Could go in str::raw + unsafe fn c_str_to_static_slice(s: *libc::c_char) -> &'static str { + let s = s as *u8; + let mut curr = s, len = 0u; + while *curr != 0u8 { + len += 1u; + curr = ptr::offset(s, len); + } + + str::raw::buf_as_slice(s, len, |d| cast::transmute(d)) + } + + + unsafe { + // Importing error constants + use rt::uvll::*; + use rt::io::*; + + // uv error descriptions are static + let c_desc = uvll::strerror(&*uverr); + let desc = c_str_to_static_slice(c_desc); + + let kind = match uverr.code { + UNKNOWN => OtherIoError, + OK => OtherIoError, + EOF => EndOfFile, + EACCES => PermissionDenied, + ECONNREFUSED => ConnectionRefused, + e => { + abort!("unknown uv error code: %u", e as uint); + } + }; + + IoError { + kind: kind, + desc: desc, + detail: None + } + } +} /// Given a uv handle, convert a callback status to a UvError // XXX: Follow the pattern below by parameterizing over T: Watcher, not T diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index 376231e3b27c5..6d8979e04d68e 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -18,13 +18,14 @@ use super::{Loop, Watcher, Request, UvError, Buf, Callback, NativeHandle, NullCa install_watcher_data, get_watcher_data, drop_watcher_data, vec_to_uv_buf, vec_from_uv_buf}; use super::super::io::net::ip::{IpAddr, Ipv4, Ipv6}; +use rt::uv::last_uv_error; #[cfg(test)] use cell::Cell; #[cfg(test)] use unstable::run_in_bare_thread; #[cfg(test)] use super::super::thread::Thread; #[cfg(test)] use super::super::test::*; -fn ip4_as_uv_ip4(addr: IpAddr, f: &fn(*sockaddr_in)) { +fn ip4_as_uv_ip4(addr: IpAddr, f: &fn(*sockaddr_in) -> T) -> T { match addr { Ipv4(a, b, c, d, p) => { unsafe { @@ -34,7 +35,7 @@ fn ip4_as_uv_ip4(addr: IpAddr, f: &fn(*sockaddr_in)) { c as uint, d as uint), p as int); do (|| { - f(addr); + f(addr) }).finally { free_ip4_addr(addr); } @@ -193,15 +194,18 @@ pub impl TcpWatcher { } } - fn bind(&mut self, address: IpAddr) { + fn bind(&mut self, address: IpAddr) -> Result<(), UvError> { match address { Ipv4(*) => { do ip4_as_uv_ip4(address) |addr| { let result = unsafe { uvll::tcp_bind(self.native_handle(), addr) }; - // XXX: bind is likely to fail. need real error handling - assert!(result == 0); + if result == 0 { + Ok(()) + } else { + Err(last_uv_error(self)) + } } } _ => fail!() diff --git a/src/libcore/rt/uvio.rs b/src/libcore/rt/uvio.rs index 8f1a6ea0d34c1..2c4ff37e4be45 100644 --- a/src/libcore/rt/uvio.rs +++ b/src/libcore/rt/uvio.rs @@ -11,6 +11,7 @@ use option::*; use result::*; +use rt::io::IoError; use super::io::net::ip::IpAddr; use super::uv::*; use super::rtio::*; @@ -98,11 +99,11 @@ impl IoFactory for UvIoFactory { // Connect to an address and return a new stream // NB: This blocks the task waiting on the connection. // It would probably be better to return a future - fn connect(&mut self, addr: IpAddr) -> Option<~StreamObject> { + fn connect(&mut self, addr: IpAddr) -> Result<~StreamObject, IoError> { // Create a cell in the task to hold the result. We will fill // the cell before resuming the task. let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; + let result_cell_ptr: *Cell> = &result_cell; let scheduler = local_sched::take(); assert!(scheduler.in_task_context()); @@ -122,11 +123,12 @@ impl IoFactory for UvIoFactory { rtdebug!("connect: in connect callback"); let maybe_stream = if status.is_none() { rtdebug!("status is none"); - Some(~UvStream(stream_watcher)) + Ok(~UvStream(stream_watcher)) } else { rtdebug!("status is some"); + // XXX: Wait for close stream_watcher.close(||()); - None + Err(uv_error_to_io_error(status.get())) }; // Store the stream in the task's stack @@ -142,10 +144,16 @@ impl IoFactory for UvIoFactory { return result_cell.take(); } - fn bind(&mut self, addr: IpAddr) -> Option<~TcpListenerObject> { + fn bind(&mut self, addr: IpAddr) -> Result<~TcpListenerObject, IoError> { let mut watcher = TcpWatcher::new(self.uv_loop()); - watcher.bind(addr); - return Some(~UvTcpListener(watcher)); + match watcher.bind(addr) { + Ok(_) => Ok(~UvTcpListener(watcher)), + Err(uverr) => { + // XXX: Should we wait until close completes? + watcher.as_stream().close(||()); + Err(uv_error_to_io_error(uverr)) + } + } } } @@ -321,7 +329,7 @@ fn test_simple_io_no_connect() { let io = unsafe { local_sched::unsafe_borrow_io() }; let addr = next_test_ip4(); let maybe_chan = io.connect(addr); - assert!(maybe_chan.is_none()); + assert!(maybe_chan.is_err()); } } diff --git a/src/libcore/rt/uvll.rs b/src/libcore/rt/uvll.rs index 4bff3bff7d3ae..2a2812c671847 100644 --- a/src/libcore/rt/uvll.rs +++ b/src/libcore/rt/uvll.rs @@ -33,6 +33,13 @@ use libc::{size_t, c_int, c_uint, c_void, c_char, uintptr_t}; use libc::{malloc, free}; use prelude::*; +pub static UNKNOWN: c_int = -1; +pub static OK: c_int = 0; +pub static EOF: c_int = 1; +pub static EADDRINFO: c_int = 2; +pub static EACCES: c_int = 3; +pub static ECONNREFUSED: c_int = 12; + pub struct uv_err_t { code: c_int, sys_errno_: c_int From 93ca5ebccb4ff6761fc61b31f7a9e1e6ffc866df Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 26 Apr 2013 18:59:59 -0700 Subject: [PATCH 005/248] core::rt: Clean up the interface to rtio Make names that better match rt::io. Return error types. --- src/libcore/rt/io/mod.rs | 1 + src/libcore/rt/io/net/tcp.rs | 23 ++++++----- src/libcore/rt/rtio.rs | 18 ++++---- src/libcore/rt/uv/mod.rs | 2 +- src/libcore/rt/uvio.rs | 79 ++++++++++++++++++------------------ 5 files changed, 63 insertions(+), 60 deletions(-) diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index 93daa36dd60a7..8f56005d0a4f6 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -238,6 +238,7 @@ Out of scope * How does I/O relate to the Iterator trait? * std::base64 filters * Using conditions is a big unknown since we don't have much experience with them +* Too many uses of OtherIoError */ diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 2ac2ffb60a8cf..95f43b259ce52 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -9,21 +9,22 @@ // except according to those terms. use option::{Option, Some, None}; -use result::{Result, Ok, Err}; +use result::{Ok, Err}; use ops::Drop; use rt::sched::local_sched::unsafe_borrow_io; use rt::io::net::ip::IpAddr; use rt::io::{Reader, Writer, Listener}; use rt::io::io_error; -use rt::rtio; -use rt::rtio::{IoFactory, TcpListener, Stream}; +use rt::rtio::{IoFactory, + RtioTcpListener, RtioTcpListenerObject, + RtioTcpStream, RtioTcpStreamObject}; pub struct TcpStream { - rtstream: ~rtio::StreamObject + rtstream: ~RtioTcpStreamObject } impl TcpStream { - fn new(s: ~rtio::StreamObject) -> TcpStream { + fn new(s: ~RtioTcpStreamObject) -> TcpStream { TcpStream { rtstream: s } @@ -34,7 +35,7 @@ impl TcpStream { rtdebug!("borrowing io to connect"); let io = unsafe_borrow_io(); rtdebug!("about to connect"); - io.connect(addr) + io.tcp_connect(addr) }; match stream { @@ -85,12 +86,12 @@ impl Drop for TcpStream { } pub struct TcpListener { - rtlistener: ~rtio::TcpListenerObject + rtlistener: ~RtioTcpListenerObject } impl TcpListener { pub fn bind(addr: IpAddr) -> Option { - let listener = unsafe { unsafe_borrow_io().bind(addr) }; + let listener = unsafe { unsafe_borrow_io().tcp_bind(addr) }; match listener { Ok(l) => { Some(TcpListener { @@ -107,12 +108,12 @@ impl TcpListener { impl Listener for TcpListener { fn accept(&mut self) -> Option { - let rtstream = self.rtlistener.listen(); + let rtstream = self.rtlistener.accept(); match rtstream { - Some(s) => { + Ok(s) => { Some(TcpStream::new(s)) } - None => { + Err(_) => { abort!("TODO"); } } diff --git a/src/libcore/rt/rtio.rs b/src/libcore/rt/rtio.rs index 961a032607eb3..1d8604bc3fd6c 100644 --- a/src/libcore/rt/rtio.rs +++ b/src/libcore/rt/rtio.rs @@ -18,8 +18,8 @@ use super::io::net::ip::IpAddr; // types to use instead pub type EventLoopObject = super::uvio::UvEventLoop; pub type IoFactoryObject = super::uvio::UvIoFactory; -pub type StreamObject = super::uvio::UvStream; -pub type TcpListenerObject = super::uvio::UvTcpListener; +pub type RtioTcpStreamObject = super::uvio::UvTcpStream; +pub type RtioTcpListenerObject = super::uvio::UvTcpListener; pub trait EventLoop { fn run(&mut self); @@ -29,15 +29,15 @@ pub trait EventLoop { } pub trait IoFactory { - fn connect(&mut self, addr: IpAddr) -> Result<~StreamObject, IoError>; - fn bind(&mut self, addr: IpAddr) -> Result<~TcpListenerObject, IoError>; + fn tcp_connect(&mut self, addr: IpAddr) -> Result<~RtioTcpStreamObject, IoError>; + fn tcp_bind(&mut self, addr: IpAddr) -> Result<~RtioTcpListenerObject, IoError>; } -pub trait TcpListener { - fn listen(&mut self) -> Option<~StreamObject>; +pub trait RtioTcpListener { + fn accept(&mut self) -> Result<~RtioTcpStreamObject, IoError>; } -pub trait Stream { - fn read(&mut self, buf: &mut [u8]) -> Result; - fn write(&mut self, buf: &[u8]) -> Result<(), ()>; +pub trait RtioTcpStream { + fn read(&mut self, buf: &mut [u8]) -> Result; + fn write(&mut self, buf: &[u8]) -> Result<(), IoError>; } diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 87aa7524ed610..24b6c353cced0 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -48,7 +48,7 @@ use ptr::null; use unstable::finally::Finally; use rt::uvll; -use rt::io::{IoError, FileNotFound}; +use rt::io::IoError; #[cfg(test)] use unstable::run_in_bare_thread; diff --git a/src/libcore/rt/uvio.rs b/src/libcore/rt/uvio.rs index 2c4ff37e4be45..70f233a29d340 100644 --- a/src/libcore/rt/uvio.rs +++ b/src/libcore/rt/uvio.rs @@ -10,19 +10,20 @@ use option::*; use result::*; - -use rt::io::IoError; -use super::io::net::ip::IpAddr; -use super::uv::*; -use super::rtio::*; use ops::Drop; use cell::{Cell, empty_cell}; use cast::transmute; -use super::sched::{Scheduler, local_sched}; + +use rt::io::IoError; +use rt::io::net::ip::IpAddr; +use rt::uv::*; +use rt::rtio::*; +use rt::sched::{Scheduler, local_sched}; +use rt::io::{standard_error, OtherIoError}; #[cfg(test)] use uint; #[cfg(test)] use unstable::run_in_bare_thread; -#[cfg(test)] use super::test::*; +#[cfg(test)] use rt::test::*; pub struct UvEventLoop { uvio: UvIoFactory @@ -99,11 +100,11 @@ impl IoFactory for UvIoFactory { // Connect to an address and return a new stream // NB: This blocks the task waiting on the connection. // It would probably be better to return a future - fn connect(&mut self, addr: IpAddr) -> Result<~StreamObject, IoError> { + fn tcp_connect(&mut self, addr: IpAddr) -> Result<~RtioTcpStreamObject, IoError> { // Create a cell in the task to hold the result. We will fill // the cell before resuming the task. let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; + let result_cell_ptr: *Cell> = &result_cell; let scheduler = local_sched::take(); assert!(scheduler.in_task_context()); @@ -123,7 +124,7 @@ impl IoFactory for UvIoFactory { rtdebug!("connect: in connect callback"); let maybe_stream = if status.is_none() { rtdebug!("status is none"); - Ok(~UvStream(stream_watcher)) + Ok(~UvTcpStream(stream_watcher)) } else { rtdebug!("status is some"); // XXX: Wait for close @@ -144,7 +145,7 @@ impl IoFactory for UvIoFactory { return result_cell.take(); } - fn bind(&mut self, addr: IpAddr) -> Result<~TcpListenerObject, IoError> { + fn tcp_bind(&mut self, addr: IpAddr) -> Result<~RtioTcpListenerObject, IoError> { let mut watcher = TcpWatcher::new(self.uv_loop()); match watcher.bind(addr) { Ok(_) => Ok(~UvTcpListener(watcher)), @@ -177,12 +178,12 @@ impl Drop for UvTcpListener { } } -impl TcpListener for UvTcpListener { +impl RtioTcpListener for UvTcpListener { - fn listen(&mut self) -> Option<~StreamObject> { + fn accept(&mut self) -> Result<~RtioTcpStreamObject, IoError> { rtdebug!("entering listen"); let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; + let result_cell_ptr: *Cell> = &result_cell; let server_tcp_watcher = self.watcher(); @@ -199,9 +200,9 @@ impl TcpListener for UvTcpListener { let client_tcp_watcher = TcpWatcher::new(&mut loop_).as_stream(); // XXX: Needs to be surfaced in interface server_stream_watcher.accept(client_tcp_watcher); - Some(~UvStream::new(client_tcp_watcher)) + Ok(~UvTcpStream::new(client_tcp_watcher)) } else { - None + Err(standard_error(OtherIoError)) }; unsafe { (*result_cell_ptr).put_back(maybe_stream); } @@ -218,15 +219,15 @@ impl TcpListener for UvTcpListener { } } -pub struct UvStream(StreamWatcher); +pub struct UvTcpStream(StreamWatcher); -impl UvStream { - fn new(watcher: StreamWatcher) -> UvStream { - UvStream(watcher) +impl UvTcpStream { + fn new(watcher: StreamWatcher) -> UvTcpStream { + UvTcpStream(watcher) } fn watcher(&self) -> StreamWatcher { - match self { &UvStream(w) => w } + match self { &UvTcpStream(w) => w } } // XXX: finalize isn't working for ~UvStream??? @@ -236,17 +237,17 @@ impl UvStream { } } -impl Drop for UvStream { +impl Drop for UvTcpStream { fn finalize(&self) { rtdebug!("closing stream"); //self.watcher().close(||()); } } -impl Stream for UvStream { - fn read(&mut self, buf: &mut [u8]) -> Result { +impl RtioTcpStream for UvTcpStream { + fn read(&mut self, buf: &mut [u8]) -> Result { let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; + let result_cell_ptr: *Cell> = &result_cell; let scheduler = local_sched::take(); assert!(scheduler.in_task_context()); @@ -277,7 +278,7 @@ impl Stream for UvStream { assert!(nread >= 0); Ok(nread as uint) } else { - Err(()) + Err(standard_error(OtherIoError)) }; unsafe { (*result_cell_ptr).put_back(result); } @@ -291,9 +292,9 @@ impl Stream for UvStream { return result_cell.take(); } - fn write(&mut self, buf: &[u8]) -> Result<(), ()> { + fn write(&mut self, buf: &[u8]) -> Result<(), IoError> { let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; + let result_cell_ptr: *Cell> = &result_cell; let scheduler = local_sched::take(); assert!(scheduler.in_task_context()); let watcher = self.watcher(); @@ -308,7 +309,7 @@ impl Stream for UvStream { let result = if status.is_none() { Ok(()) } else { - Err(()) + Err(standard_error(OtherIoError)) }; unsafe { (*result_cell_ptr).put_back(result); } @@ -328,7 +329,7 @@ fn test_simple_io_no_connect() { do run_in_newsched_task { let io = unsafe { local_sched::unsafe_borrow_io() }; let addr = next_test_ip4(); - let maybe_chan = io.connect(addr); + let maybe_chan = io.tcp_connect(addr); assert!(maybe_chan.is_err()); } } @@ -342,8 +343,8 @@ fn test_simple_tcp_server_and_client() { do spawntask_immediately { unsafe { let io = local_sched::unsafe_borrow_io(); - let mut listener = io.bind(addr).unwrap(); - let mut stream = listener.listen().unwrap(); + let mut listener = io.tcp_bind(addr).unwrap(); + let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; let nread = stream.read(buf).unwrap(); assert!(nread == 8); @@ -359,7 +360,7 @@ fn test_simple_tcp_server_and_client() { do spawntask_immediately { unsafe { let io = local_sched::unsafe_borrow_io(); - let mut stream = io.connect(addr).unwrap(); + let mut stream = io.tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.close(); } @@ -374,8 +375,8 @@ fn test_read_and_block() { do spawntask_immediately { let io = unsafe { local_sched::unsafe_borrow_io() }; - let mut listener = io.bind(addr).unwrap(); - let mut stream = listener.listen().unwrap(); + let mut listener = io.tcp_bind(addr).unwrap(); + let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; let expected = 32; @@ -412,7 +413,7 @@ fn test_read_and_block() { do spawntask_immediately { let io = unsafe { local_sched::unsafe_borrow_io() }; - let mut stream = io.connect(addr).unwrap(); + let mut stream = io.tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); @@ -432,8 +433,8 @@ fn test_read_read_read() { do spawntask_immediately { unsafe { let io = local_sched::unsafe_borrow_io(); - let mut listener = io.bind(addr).unwrap(); - let mut stream = listener.listen().unwrap(); + let mut listener = io.tcp_bind(addr).unwrap(); + let mut stream = listener.accept().unwrap(); let mut buf = [1, .. 2048]; let mut total_bytes_written = 0; while total_bytes_written < MAX { @@ -447,7 +448,7 @@ fn test_read_read_read() { do spawntask_immediately { let io = unsafe { local_sched::unsafe_borrow_io() }; - let mut stream = io.connect(addr).unwrap(); + let mut stream = io.tcp_connect(addr).unwrap(); let mut buf = [0, .. 2048]; let mut total_bytes_read = 0; while total_bytes_read < MAX { From 23bf892ae5f185146d170af621c4da17e559dfa4 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 26 Apr 2013 23:21:58 -0700 Subject: [PATCH 006/248] core::rt: Improve docs --- src/libcore/rt/mod.rs | 65 +++++++++++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 72715ea9b2823..c332e48489a72 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -8,12 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/*! The Rust runtime, including the scheduler and I/O interface +/*! Rust runtime services, including the task scheduler and I/O interface # XXX * Unsafe uses of borrowed pointers should just use unsafe pointers -* Unwinding is not wired up correctly */ @@ -22,29 +21,76 @@ use libc::c_char; +/// The Scheduler and Task types, and thread-local access thereof #[path = "sched/mod.rs"] mod sched; -pub mod rtio; -pub mod uvll; -mod uvio; + +/// Synchronous I/O +#[path = "io/mod.rs"] +pub mod io; + +/// Thread-local implementations of language-critical runtime features like @ +pub mod local_services; + +/// The EventLoop and internal synchronous I/O interface, dynamically +/// overridable so that it's primary implementation on libuv can +/// live outside of core. +mod rtio; + +/// libuv #[path = "uv/mod.rs"] mod uv; -#[path = "io/mod.rs"] -mod io; + +/// The implementation of `rtio` for libuv +mod uvio; + +/// C bindings to libuv +pub mod uvll; + + // FIXME #5248: The import in `sched` doesn't resolve unless this is pub! +/// Bindings to pthread/windows thread-local storage pub mod thread_local_storage; + +/// A parallel work-stealing queue mod work_queue; + +/// Stack segments and their cacheing mod stack; + +/// CPU context swapping mod context; + +/// Bindings to system threading libraries mod thread; + +/// The runtime configuration, read from environment variables pub mod env; -pub mod local_services; + +/// The local, managed heap mod local_heap; /// Tools for testing the runtime #[cfg(test)] pub mod test; +/// Set up a default runtime configuration, given compiler-supplied arguments. +/// +/// This is invoked by the `start` _language item_ (unstable::lang) to +/// run a Rust executable. +/// +/// # Arguments +/// +/// * `main` - A C-abi function that takes no arguments and returns `c_void`. +/// It is a wrapper around the user-defined `main` function, and will be run +/// in a task. +/// * `argc` & `argv` - The argument vector. On Unix this information is used +/// by os::args. +/// * `crate_map` - Runtime information about the executing crate, mostly for logging +/// +/// # Return value +/// +/// The return value is used as the process return code. 0 on success, 101 on error. pub fn start(main: *u8, _argc: int, _argv: **c_char, _crate_map: *u8) -> int { use self::sched::{Scheduler, Task}; @@ -79,6 +125,8 @@ pub fn start(main: *u8, _argc: int, _argv: **c_char, _crate_map: *u8) -> int { /// Possible contexts in which Rust code may be executing. /// Different runtime services are available depending on context. +/// Mostly used for determining if we're using the new scheduler +/// or the old scheduler. #[deriving(Eq)] pub enum RuntimeContext { // Only the exchange heap is available @@ -91,6 +139,7 @@ pub enum RuntimeContext { OldTaskContext } +/// Determine the current RuntimeContext pub fn context() -> RuntimeContext { use task::rt::rust_task; From ab284d44d8d181b12783d82755ff83a014027e4a Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 00:09:27 -0700 Subject: [PATCH 007/248] core::rt Restructure some modules Put all uv code under rt::uv, as if it were in its own crate. Pull local_sched out of rt::sched. --- src/libcore/rt/{sched => }/local_sched.rs | 8 ++++---- src/libcore/rt/mod.rs | 19 +++++++------------ src/libcore/rt/rtio.rs | 9 +++++---- src/libcore/rt/{sched/mod.rs => sched.rs} | 2 +- src/libcore/rt/test.rs | 2 +- src/libcore/rt/uv/file.rs | 4 ++-- src/libcore/rt/uv/mod.rs | 12 +++++++++--- src/libcore/rt/uv/net.rs | 4 ++-- src/libcore/rt/{ => uv}/uvio.rs | 0 src/libcore/rt/{ => uv}/uvll.rs | 0 10 files changed, 31 insertions(+), 29 deletions(-) rename src/libcore/rt/{sched => }/local_sched.rs (96%) rename src/libcore/rt/{sched/mod.rs => sched.rs} (99%) rename src/libcore/rt/{ => uv}/uvio.rs (100%) rename src/libcore/rt/{ => uv}/uvll.rs (100%) diff --git a/src/libcore/rt/sched/local_sched.rs b/src/libcore/rt/local_sched.rs similarity index 96% rename from src/libcore/rt/sched/local_sched.rs rename to src/libcore/rt/local_sched.rs index c4153381d91aa..6ef3d0bad5e0b 100644 --- a/src/libcore/rt/sched/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -16,12 +16,12 @@ use libc::c_void; use cast; use cell::Cell; -use super::Scheduler; -use super::super::rtio::IoFactoryObject; -use tls = super::super::thread_local_storage; +use rt::sched::Scheduler; +use rt::rtio::{EventLoop, IoFactoryObject}; +use tls = rt::thread_local_storage; use unstable::finally::Finally; -#[cfg(test)] use super::super::uvio::UvEventLoop; +#[cfg(test)] use rt::uv::uvio::UvEventLoop; /// Give the Scheduler to thread-local storage pub fn put(sched: ~Scheduler) { diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index c332e48489a72..8501e36111f86 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -21,10 +21,12 @@ use libc::c_char; -/// The Scheduler and Task types, and thread-local access thereof -#[path = "sched/mod.rs"] +/// The Scheduler and Task types mod sched; +/// Thread-local access to the current Scheduler +mod local_sched; + /// Synchronous I/O #[path = "io/mod.rs"] pub mod io; @@ -39,14 +41,7 @@ mod rtio; /// libuv #[path = "uv/mod.rs"] -mod uv; - -/// The implementation of `rtio` for libuv -mod uvio; - -/// C bindings to libuv -pub mod uvll; - +pub mod uv; // FIXME #5248: The import in `sched` doesn't resolve unless this is pub! /// Bindings to pthread/windows thread-local storage @@ -94,7 +89,7 @@ pub mod test; pub fn start(main: *u8, _argc: int, _argv: **c_char, _crate_map: *u8) -> int { use self::sched::{Scheduler, Task}; - use self::uvio::UvEventLoop; + use self::uv::uvio::UvEventLoop; use sys::Closure; use ptr; use cast; @@ -175,7 +170,7 @@ pub fn context() -> RuntimeContext { fn test_context() { use unstable::run_in_bare_thread; use self::sched::{local_sched, Task}; - use self::uvio::UvEventLoop; + use rt::uv::uvio::UvEventLoop; use cell::Cell; assert!(context() == OldTaskContext); diff --git a/src/libcore/rt/rtio.rs b/src/libcore/rt/rtio.rs index 1d8604bc3fd6c..497ff8841b6bd 100644 --- a/src/libcore/rt/rtio.rs +++ b/src/libcore/rt/rtio.rs @@ -13,13 +13,14 @@ use result::*; use rt::io::IoError; use super::io::net::ip::IpAddr; +use rt::uv::uvio; // XXX: ~object doesn't work currently so these are some placeholder // types to use instead -pub type EventLoopObject = super::uvio::UvEventLoop; -pub type IoFactoryObject = super::uvio::UvIoFactory; -pub type RtioTcpStreamObject = super::uvio::UvTcpStream; -pub type RtioTcpListenerObject = super::uvio::UvTcpListener; +pub type EventLoopObject = uvio::UvEventLoop; +pub type IoFactoryObject = uvio::UvIoFactory; +pub type RtioTcpStreamObject = uvio::UvTcpStream; +pub type RtioTcpListenerObject = uvio::UvTcpListener; pub trait EventLoop { fn run(&mut self); diff --git a/src/libcore/rt/sched/mod.rs b/src/libcore/rt/sched.rs similarity index 99% rename from src/libcore/rt/sched/mod.rs rename to src/libcore/rt/sched.rs index ba057254583b0..1ab4b5debd380 100644 --- a/src/libcore/rt/sched/mod.rs +++ b/src/libcore/rt/sched.rs @@ -19,7 +19,7 @@ use super::context::Context; use super::local_services::LocalServices; use cell::Cell; -#[cfg(test)] use super::uvio::UvEventLoop; +#[cfg(test)] use rt::uv::uvio::UvEventLoop; #[cfg(test)] use unstable::run_in_bare_thread; #[cfg(test)] use int; diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index 0c6843c605d15..185443563fc9b 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -19,7 +19,7 @@ use rt::local_services::LocalServices; pub fn run_in_newsched_task(f: ~fn()) { use unstable::run_in_bare_thread; use super::sched::Task; - use super::uvio::UvEventLoop; + use rt::uv::uvio::UvEventLoop; let f = Cell(f); diff --git a/src/libcore/rt/uv/file.rs b/src/libcore/rt/uv/file.rs index a4aef7485d737..816a3a10a9016 100644 --- a/src/libcore/rt/uv/file.rs +++ b/src/libcore/rt/uv/file.rs @@ -12,8 +12,8 @@ use prelude::*; use ptr::null; use libc::c_void; use super::{UvError, Callback, Request, NativeHandle, Loop}; -use super::super::uvll; -use super::super::uvll::*; +use rt::uv::uvll; +use rt::uv::uvll::*; pub type FsCallback = ~fn(FsRequest, Option); impl Callback for FsCallback { } diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 24b6c353cced0..5d31f39411da0 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -10,7 +10,7 @@ /*! -Bindings to libuv. +Bindings to libuv, along with the default implementation of `core::rt::rtio`. UV types consist of the event loop (Loop), Watchers, Requests and Callbacks. @@ -47,7 +47,6 @@ use cast::transmute; use ptr::null; use unstable::finally::Finally; -use rt::uvll; use rt::io::IoError; #[cfg(test)] use unstable::run_in_bare_thread; @@ -56,6 +55,13 @@ pub use self::file::{FsRequest, FsCallback}; pub use self::net::{StreamWatcher, TcpWatcher}; pub use self::net::{ReadCallback, AllocCallback, ConnectionCallback, ConnectCallback}; + +/// The implementation of `rtio` for libuv +pub mod uvio; + +/// C bindings to libuv +pub mod uvll; + pub mod file; pub mod net; @@ -240,7 +246,7 @@ pub fn uv_error_to_io_error(uverr: UvError) -> IoError { unsafe { // Importing error constants - use rt::uvll::*; + use rt::uv::uvll::*; use rt::io::*; // uv error descriptions are static diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index 6d8979e04d68e..ff47e2caec8fe 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -11,8 +11,8 @@ use prelude::*; use libc::{size_t, ssize_t, c_int, c_void}; use cast::transmute_mut_region; -use super::super::uvll; -use super::super::uvll::*; +use rt::uv::uvll; +use rt::uv::uvll::*; use super::{Loop, Watcher, Request, UvError, Buf, Callback, NativeHandle, NullCallback, loop_from_watcher, status_to_maybe_uv_error, install_watcher_data, get_watcher_data, drop_watcher_data, diff --git a/src/libcore/rt/uvio.rs b/src/libcore/rt/uv/uvio.rs similarity index 100% rename from src/libcore/rt/uvio.rs rename to src/libcore/rt/uv/uvio.rs diff --git a/src/libcore/rt/uvll.rs b/src/libcore/rt/uv/uvll.rs similarity index 100% rename from src/libcore/rt/uvll.rs rename to src/libcore/rt/uv/uvll.rs From 01b7b7d5a0feeb88b5dba1e295925a7564473685 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 02:07:32 -0700 Subject: [PATCH 008/248] core::rt: Use unsafe pointers instead of transmuted regions --- src/libcore/rt/context.rs | 6 +-- src/libcore/rt/io/net/tcp.rs | 4 +- src/libcore/rt/local_sched.rs | 19 ++++----- src/libcore/rt/local_services.rs | 21 +++++----- src/libcore/rt/mod.rs | 9 +---- src/libcore/rt/sched.rs | 41 +++++++++++--------- src/libcore/rt/uv/uvio.rs | 60 ++++++++++++++++------------- src/libcore/sys.rs | 2 +- src/libcore/task/local_data_priv.rs | 2 +- src/libuv | 2 +- 10 files changed, 86 insertions(+), 80 deletions(-) diff --git a/src/libcore/rt/context.rs b/src/libcore/rt/context.rs index 9c1e566f218f6..9c1612884f044 100644 --- a/src/libcore/rt/context.rs +++ b/src/libcore/rt/context.rs @@ -111,9 +111,9 @@ fn initialize_call_frame(regs: &mut Registers, fptr: *c_void, arg: *c_void, sp: let sp = align_down(sp); let sp = mut_offset(sp, -4); - unsafe { *sp = arg as uint; } + unsafe { *sp = arg as uint }; let sp = mut_offset(sp, -1); - unsafe { *sp = 0; } // The final return address + unsafe { *sp = 0 }; // The final return address regs.esp = sp as u32; regs.eip = fptr as u32; @@ -195,7 +195,7 @@ fn initialize_call_frame(regs: &mut Registers, fptr: *c_void, arg: *c_void, sp: fn align_down(sp: *mut uint) -> *mut uint { unsafe { - let sp = transmute::<*mut uint, uint>(sp); + let sp: uint = transmute(sp); let sp = sp & !(16 - 1); transmute::(sp) } diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 95f43b259ce52..0c7e0cf129d7f 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -35,7 +35,7 @@ impl TcpStream { rtdebug!("borrowing io to connect"); let io = unsafe_borrow_io(); rtdebug!("about to connect"); - io.tcp_connect(addr) + (*io).tcp_connect(addr) }; match stream { @@ -91,7 +91,7 @@ pub struct TcpListener { impl TcpListener { pub fn bind(addr: IpAddr) -> Option { - let listener = unsafe { unsafe_borrow_io().tcp_bind(addr) }; + let listener = unsafe { (*unsafe_borrow_io()).tcp_bind(addr) }; match listener { Ok(l) => { Some(TcpListener { diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index 6ef3d0bad5e0b..ef159d9fe5dde 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -78,23 +78,24 @@ pub fn borrow(f: &fn(&mut Scheduler)) { /// /// Because this leaves the Scheduler in thread-local storage it is possible /// For the Scheduler pointer to be aliased -pub unsafe fn unsafe_borrow() -> &mut Scheduler { +pub unsafe fn unsafe_borrow() -> *mut Scheduler { let key = tls_key(); let mut void_sched: *mut c_void = tls::get(key); rtassert!(void_sched.is_not_null()); { - let void_sched_ptr = &mut void_sched; - let sched: &mut ~Scheduler = { - cast::transmute::<&mut *mut c_void, &mut ~Scheduler>(void_sched_ptr) - }; - let sched: &mut Scheduler = &mut **sched; + let sched: *mut *mut c_void = &mut void_sched; + let sched: *mut ~Scheduler = sched as *mut ~Scheduler; + let sched: *mut Scheduler = &mut **sched; return sched; } } -pub unsafe fn unsafe_borrow_io() -> &mut IoFactoryObject { - let sched = unsafe_borrow(); - return sched.event_loop.io().unwrap(); +pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { + unsafe { + let sched = unsafe_borrow(); + let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); + return io; + } } fn tls_key() -> tls::Key { diff --git a/src/libcore/rt/local_services.rs b/src/libcore/rt/local_services.rs index 47e8669b54692..94840d7b5d584 100644 --- a/src/libcore/rt/local_services.rs +++ b/src/libcore/rt/local_services.rs @@ -169,16 +169,17 @@ pub fn borrow_local_services(f: &fn(&mut LocalServices)) { } } -pub unsafe fn unsafe_borrow_local_services() -> &mut LocalServices { - use cast::transmute_mut_region; - - match local_sched::unsafe_borrow().current_task { - Some(~ref mut task) => { - transmute_mut_region(&mut task.local_services) - } - None => { - // Don't fail. Infinite recursion - abort!("no local services for schedulers yet") +pub unsafe fn unsafe_borrow_local_services() -> *mut LocalServices { + unsafe { + match (*local_sched::unsafe_borrow()).current_task { + Some(~ref mut task) => { + let s: *mut LocalServices = &mut task.local_services; + return s; + } + None => { + // Don't fail. Infinite recursion + abort!("no local services for schedulers yet") + } } } } diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 8501e36111f86..b5fba51ca7f4d 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -8,14 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/*! Rust runtime services, including the task scheduler and I/O interface - -# XXX - -* Unsafe uses of borrowed pointers should just use unsafe pointers - -*/ - +//! Rust runtime services, including the task scheduler and I/O interface #[doc(hidden)]; diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 1ab4b5debd380..546272474edb6 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -106,6 +106,7 @@ pub impl Scheduler { } } + let scheduler = &mut *scheduler; scheduler.event_loop.callback(run_scheduler_once); scheduler.event_loop.run(); } @@ -179,7 +180,7 @@ pub impl Scheduler { // Take pointers to both the task and scheduler's saved registers. unsafe { let sched = local_sched::unsafe_borrow(); - let (sched_context, _, next_task_context) = sched.get_contexts(); + let (sched_context, _, next_task_context) = (*sched).get_contexts(); let next_task_context = next_task_context.unwrap(); // Context switch to the task, restoring it's registers // and saving the scheduler's @@ -187,10 +188,10 @@ pub impl Scheduler { let sched = local_sched::unsafe_borrow(); // The running task should have passed ownership elsewhere - assert!(sched.current_task.is_none()); + assert!((*sched).current_task.is_none()); // Running tasks may have asked us to do some cleanup - sched.run_cleanup_job(); + (*sched).run_cleanup_job(); } } @@ -208,21 +209,25 @@ pub impl Scheduler { rtdebug!("blocking task"); - let blocked_task = this.current_task.swap_unwrap(); - let f_fake_region = unsafe { transmute::<&fn(~Task), &fn(~Task)>(f) }; - let f_opaque = ClosureConverter::from_fn(f_fake_region); - this.enqueue_cleanup_job(GiveTask(blocked_task, f_opaque)); + unsafe { + let blocked_task = this.current_task.swap_unwrap(); + let f_fake_region = transmute::<&fn(~Task), &fn(~Task)>(f); + let f_opaque = ClosureConverter::from_fn(f_fake_region); + this.enqueue_cleanup_job(GiveTask(blocked_task, f_opaque)); + } local_sched::put(this); - let sched = unsafe { local_sched::unsafe_borrow() }; - let (sched_context, last_task_context, _) = sched.get_contexts(); - let last_task_context = last_task_context.unwrap(); - Context::swap(last_task_context, sched_context); + unsafe { + let sched = local_sched::unsafe_borrow(); + let (sched_context, last_task_context, _) = (*sched).get_contexts(); + let last_task_context = last_task_context.unwrap(); + Context::swap(last_task_context, sched_context); - // We could be executing in a different thread now - let sched = unsafe { local_sched::unsafe_borrow() }; - sched.run_cleanup_job(); + // We could be executing in a different thread now + let sched = local_sched::unsafe_borrow(); + (*sched).run_cleanup_job(); + } } /// Switch directly to another task, without going through the scheduler. @@ -244,14 +249,14 @@ pub impl Scheduler { unsafe { let sched = local_sched::unsafe_borrow(); - let (_, last_task_context, next_task_context) = sched.get_contexts(); + let (_, last_task_context, next_task_context) = (*sched).get_contexts(); let last_task_context = last_task_context.unwrap(); let next_task_context = next_task_context.unwrap(); Context::swap(last_task_context, next_task_context); // We could be executing in a different thread now let sched = local_sched::unsafe_borrow(); - sched.run_cleanup_job(); + (*sched).run_cleanup_job(); } } @@ -356,10 +361,10 @@ pub impl Task { // have asked us to do some cleanup. unsafe { let sched = local_sched::unsafe_borrow(); - sched.run_cleanup_job(); + (*sched).run_cleanup_job(); let sched = local_sched::unsafe_borrow(); - let task = sched.current_task.get_mut_ref(); + let task = (*sched).current_task.get_mut_ref(); // FIXME #6141: shouldn't neet to put `start()` in another closure task.local_services.run(||start()); } diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 70f233a29d340..704294102ae98 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -327,10 +327,12 @@ impl RtioTcpStream for UvTcpStream { #[test] fn test_simple_io_no_connect() { do run_in_newsched_task { - let io = unsafe { local_sched::unsafe_borrow_io() }; - let addr = next_test_ip4(); - let maybe_chan = io.tcp_connect(addr); - assert!(maybe_chan.is_err()); + unsafe { + let io = local_sched::unsafe_borrow_io(); + let addr = next_test_ip4(); + let maybe_chan = (*io).tcp_connect(addr); + assert!(maybe_chan.is_err()); + } } } @@ -343,7 +345,7 @@ fn test_simple_tcp_server_and_client() { do spawntask_immediately { unsafe { let io = local_sched::unsafe_borrow_io(); - let mut listener = io.tcp_bind(addr).unwrap(); + let mut listener = (*io).tcp_bind(addr).unwrap(); let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; let nread = stream.read(buf).unwrap(); @@ -360,7 +362,7 @@ fn test_simple_tcp_server_and_client() { do spawntask_immediately { unsafe { let io = local_sched::unsafe_borrow_io(); - let mut stream = io.tcp_connect(addr).unwrap(); + let mut stream = (*io).tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.close(); } @@ -375,7 +377,7 @@ fn test_read_and_block() { do spawntask_immediately { let io = unsafe { local_sched::unsafe_borrow_io() }; - let mut listener = io.tcp_bind(addr).unwrap(); + let mut listener = unsafe { (*io).tcp_bind(addr).unwrap() }; let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; @@ -412,13 +414,15 @@ fn test_read_and_block() { } do spawntask_immediately { - let io = unsafe { local_sched::unsafe_borrow_io() }; - let mut stream = io.tcp_connect(addr).unwrap(); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.close(); + unsafe { + let io = local_sched::unsafe_borrow_io(); + let mut stream = (*io).tcp_connect(addr).unwrap(); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.close(); + } } } @@ -433,7 +437,7 @@ fn test_read_read_read() { do spawntask_immediately { unsafe { let io = local_sched::unsafe_borrow_io(); - let mut listener = io.tcp_bind(addr).unwrap(); + let mut listener = (*io).tcp_bind(addr).unwrap(); let mut stream = listener.accept().unwrap(); let mut buf = [1, .. 2048]; let mut total_bytes_written = 0; @@ -447,20 +451,22 @@ fn test_read_read_read() { } do spawntask_immediately { - let io = unsafe { local_sched::unsafe_borrow_io() }; - let mut stream = io.tcp_connect(addr).unwrap(); - let mut buf = [0, .. 2048]; - let mut total_bytes_read = 0; - while total_bytes_read < MAX { - let nread = stream.read(buf).unwrap(); - rtdebug!("read %u bytes", nread as uint); - total_bytes_read += nread; - for uint::range(0, nread) |i| { - assert!(buf[i] == 1); + unsafe { + let io = local_sched::unsafe_borrow_io(); + let mut stream = (*io).tcp_connect(addr).unwrap(); + let mut buf = [0, .. 2048]; + let mut total_bytes_read = 0; + while total_bytes_read < MAX { + let nread = stream.read(buf).unwrap(); + rtdebug!("read %u bytes", nread as uint); + total_bytes_read += nread; + for uint::range(0, nread) |i| { + assert!(buf[i] == 1); + } } + rtdebug!("read %u bytes total", total_bytes_read as uint); + stream.close(); } - rtdebug!("read %u bytes total", total_bytes_read as uint); - stream.close(); } } } diff --git a/src/libcore/sys.rs b/src/libcore/sys.rs index 4eca7ebbb371e..a27b6fe615f33 100644 --- a/src/libcore/sys.rs +++ b/src/libcore/sys.rs @@ -218,7 +218,7 @@ pub fn begin_unwind_(msg: *c_char, file: *c_char, line: size_t) -> ! { gc::cleanup_stack_for_failure(); unsafe { let local_services = unsafe_borrow_local_services(); - match local_services.unwinder { + match (*local_services).unwinder { Some(ref mut unwinder) => unwinder.begin_unwind(), None => abort!("failure without unwinder. aborting process") } diff --git a/src/libcore/task/local_data_priv.rs b/src/libcore/task/local_data_priv.rs index a30db039f30d7..27f58057e2ff5 100644 --- a/src/libcore/task/local_data_priv.rs +++ b/src/libcore/task/local_data_priv.rs @@ -36,7 +36,7 @@ impl Handle { } _ => { let local_services = unsafe_borrow_local_services(); - NewHandle(&mut local_services.storage) + NewHandle(&mut (*local_services).storage) } } } diff --git a/src/libuv b/src/libuv index 218ab86721eef..97ac7c087a0ca 160000 --- a/src/libuv +++ b/src/libuv @@ -1 +1 @@ -Subproject commit 218ab86721eefd7b7e97fa6d9f95a80a1fa8686c +Subproject commit 97ac7c087a0caf6b0f611b80e14f7fe3cb18bb27 From b771c993044d87d80c4ebc740e86b1b744770c57 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 15:21:03 -0700 Subject: [PATCH 009/248] core::rt: Fix the finalizer on UvTcpStream and UvTcpListener Eliminates a lot of calls to `close` --- src/libcore/rt/io/net/tcp.rs | 13 --------- src/libcore/rt/uv/uvio.rs | 55 +++++++++++------------------------- 2 files changed, 16 insertions(+), 52 deletions(-) diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 0c7e0cf129d7f..ae4a7a2039717 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -10,7 +10,6 @@ use option::{Option, Some, None}; use result::{Ok, Err}; -use ops::Drop; use rt::sched::local_sched::unsafe_borrow_io; use rt::io::net::ip::IpAddr; use rt::io::{Reader, Writer, Listener}; @@ -79,12 +78,6 @@ impl Writer for TcpStream { fn flush(&mut self) { fail!() } } -impl Drop for TcpStream { - fn finalize(&self) { - self.rtstream.close(); - } -} - pub struct TcpListener { rtlistener: ~RtioTcpListenerObject } @@ -120,12 +113,6 @@ impl Listener for TcpListener { } } -impl Drop for TcpListener { - fn finalize(&self) { - self.rtlistener.close(); - } -} - #[cfg(test)] mod test { use super::*; diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 704294102ae98..49fbf1429630d 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -124,7 +124,7 @@ impl IoFactory for UvIoFactory { rtdebug!("connect: in connect callback"); let maybe_stream = if status.is_none() { rtdebug!("status is none"); - Ok(~UvTcpStream(stream_watcher)) + Ok(~UvTcpStream { watcher: stream_watcher }) } else { rtdebug!("status is some"); // XXX: Wait for close @@ -148,7 +148,7 @@ impl IoFactory for UvIoFactory { fn tcp_bind(&mut self, addr: IpAddr) -> Result<~RtioTcpListenerObject, IoError> { let mut watcher = TcpWatcher::new(self.uv_loop()); match watcher.bind(addr) { - Ok(_) => Ok(~UvTcpListener(watcher)), + Ok(_) => Ok(~UvTcpListener { watcher: watcher }), Err(uverr) => { // XXX: Should we wait until close completes? watcher.as_stream().close(||()); @@ -158,23 +158,19 @@ impl IoFactory for UvIoFactory { } } -pub struct UvTcpListener(TcpWatcher); +// FIXME #6090: Prefer newtype structs but Drop doesn't work +pub struct UvTcpListener { + watcher: TcpWatcher +} impl UvTcpListener { - fn watcher(&self) -> TcpWatcher { - match self { &UvTcpListener(w) => w } - } - - fn close(&self) { - // XXX: Need to wait until close finishes before returning - self.watcher().as_stream().close(||()); - } + fn watcher(&self) -> TcpWatcher { self.watcher } } impl Drop for UvTcpListener { fn finalize(&self) { - // XXX: Again, this never gets called. Use .close() instead - //self.watcher().as_stream().close(||()); + // XXX: Need to wait until close finishes before returning + self.watcher().as_stream().close(||()); } } @@ -200,7 +196,7 @@ impl RtioTcpListener for UvTcpListener { let client_tcp_watcher = TcpWatcher::new(&mut loop_).as_stream(); // XXX: Needs to be surfaced in interface server_stream_watcher.accept(client_tcp_watcher); - Ok(~UvTcpStream::new(client_tcp_watcher)) + Ok(~UvTcpStream { watcher: client_tcp_watcher }) } else { Err(standard_error(OtherIoError)) }; @@ -219,28 +215,19 @@ impl RtioTcpListener for UvTcpListener { } } -pub struct UvTcpStream(StreamWatcher); +// FIXME #6090: Prefer newtype structs but Drop doesn't work +pub struct UvTcpStream { + watcher: StreamWatcher +} impl UvTcpStream { - fn new(watcher: StreamWatcher) -> UvTcpStream { - UvTcpStream(watcher) - } - - fn watcher(&self) -> StreamWatcher { - match self { &UvTcpStream(w) => w } - } - - // XXX: finalize isn't working for ~UvStream??? - fn close(&self) { - // XXX: Need to wait until this finishes before returning - self.watcher().close(||()); - } + fn watcher(&self) -> StreamWatcher { self.watcher } } impl Drop for UvTcpStream { fn finalize(&self) { rtdebug!("closing stream"); - //self.watcher().close(||()); + self.watcher().close(||()); } } @@ -354,8 +341,6 @@ fn test_simple_tcp_server_and_client() { rtdebug!("%u", buf[i] as uint); assert!(buf[i] == i as u8); } - stream.close(); - listener.close(); } } @@ -364,7 +349,6 @@ fn test_simple_tcp_server_and_client() { let io = local_sched::unsafe_borrow_io(); let mut stream = (*io).tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.close(); } } } @@ -408,9 +392,6 @@ fn test_read_and_block() { // Make sure we had multiple reads assert!(reads > 1); - - stream.close(); - listener.close(); } do spawntask_immediately { @@ -421,7 +402,6 @@ fn test_read_and_block() { stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.close(); } } @@ -445,8 +425,6 @@ fn test_read_read_read() { stream.write(buf); total_bytes_written += buf.len(); } - stream.close(); - listener.close(); } } @@ -465,7 +443,6 @@ fn test_read_read_read() { } } rtdebug!("read %u bytes total", total_bytes_read as uint); - stream.close(); } } } From cfd183db15af50f06b5e2803b03f87061adad9f5 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 17:26:35 -0700 Subject: [PATCH 010/248] core::rt: Fix some copies in uv --- src/libcore/rt/uv/mod.rs | 2 -- src/libcore/rt/uv/net.rs | 17 ++++++++--------- src/libcore/rt/uv/uvio.rs | 4 +--- 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 5d31f39411da0..22ed82fbed391 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -362,7 +362,6 @@ struct WatcherData { connect_cb: Option, close_cb: Option, alloc_cb: Option, - buf: Option } pub fn install_watcher_data>(watcher: &mut W) { @@ -373,7 +372,6 @@ pub fn install_watcher_data>(watcher: &mut W) { connect_cb: None, close_cb: None, alloc_cb: None, - buf: None }; let data = transmute::<~WatcherData, *c_void>(data); uvll::set_data_for_uv_handle(watcher.native_handle(), data); diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index ff47e2caec8fe..49c42fa3587ac 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -11,12 +11,13 @@ use prelude::*; use libc::{size_t, ssize_t, c_int, c_void}; use cast::transmute_mut_region; +use util::ignore; use rt::uv::uvll; use rt::uv::uvll::*; use super::{Loop, Watcher, Request, UvError, Buf, Callback, NativeHandle, NullCallback, loop_from_watcher, status_to_maybe_uv_error, install_watcher_data, get_watcher_data, drop_watcher_data, - vec_to_uv_buf, vec_from_uv_buf}; + vec_to_uv_buf, vec_from_uv_buf, slice_to_uv_buf}; use super::super::io::net::ip::{IpAddr, Ipv4, Ipv6}; use rt::uv::last_uv_error; @@ -99,17 +100,13 @@ pub impl StreamWatcher { unsafe { uvll::read_stop(handle); } } - // XXX: Needs to take &[u8], not ~[u8] - fn write(&mut self, msg: ~[u8], cb: ConnectionCallback) { + fn write(&mut self, buf: Buf, cb: ConnectionCallback) { // XXX: Borrowck let data = get_watcher_data(unsafe { transmute_mut_region(self) }); assert!(data.write_cb.is_none()); data.write_cb = Some(cb); let req = WriteRequest::new(); - let buf = vec_to_uv_buf(msg); - assert!(data.buf.is_none()); - data.buf = Some(buf); let bufs = [buf]; unsafe { assert!(0 == uvll::write(req.native_handle(), @@ -123,7 +120,6 @@ pub impl StreamWatcher { write_request.delete(); let cb = { let data = get_watcher_data(&mut stream_watcher); - let _vec = vec_from_uv_buf(data.buf.swap_unwrap()); let cb = data.write_cb.swap_unwrap(); cb }; @@ -434,10 +430,13 @@ fn listen() { assert!(status.is_none()); let mut stream_watcher = stream_watcher; let msg = ~[0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9]; - do stream_watcher.write(msg) |stream_watcher, status| { + let buf = slice_to_uv_buf(msg); + let msg_cell = Cell(msg); + do stream_watcher.write(buf) |stream_watcher, status| { rtdebug!("writing"); assert!(status.is_none()); - stream_watcher.close(||()); + let msg_cell = Cell(msg_cell.take()); + stream_watcher.close(||ignore(msg_cell.take())); } } loop_.run(); diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 49fbf1429630d..d8858717f6f39 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -289,9 +289,7 @@ impl RtioTcpStream for UvTcpStream { do scheduler.deschedule_running_task_and_then |task| { let mut watcher = watcher; let task_cell = Cell(task); - let buf = unsafe { &*buf_ptr }; - // XXX: OMGCOPIES - let buf = buf.to_vec(); + let buf = unsafe { slice_to_uv_buf(*buf_ptr) }; do watcher.write(buf) |_watcher, status| { let result = if status.is_none() { Ok(()) From 6ab02c03da1e610f9c2f4c9a185a74f37f6195f2 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 17:47:33 -0700 Subject: [PATCH 011/248] core::rt: Convert some uv functions to extension methods --- src/libcore/rt/uv/mod.rs | 193 ++++++++++++++++++-------------------- src/libcore/rt/uv/net.rs | 75 +++++++-------- src/libcore/rt/uv/uvio.rs | 7 +- 3 files changed, 127 insertions(+), 148 deletions(-) diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 22ed82fbed391..7d5a4f00204d8 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -77,9 +77,7 @@ pub trait Request { } /// handle. Watchers are generally created, then `start`ed, `stop`ed /// and `close`ed, but due to their complex life cycle may not be /// entirely memory safe if used in unanticipated patterns. -pub trait Watcher { - fn event_loop(&self) -> Loop; -} +pub trait Watcher { } pub type NullCallback = ~fn(); impl Callback for NullCallback { } @@ -123,12 +121,7 @@ impl NativeHandle<*uvll::uv_loop_t> for Loop { } pub struct IdleWatcher(*uvll::uv_idle_t); - -impl Watcher for IdleWatcher { - fn event_loop(&self) -> Loop { - loop_from_watcher(self) - } -} +impl Watcher for IdleWatcher { } pub type IdleCallback = ~fn(IdleWatcher, Option); impl Callback for IdleCallback { } @@ -146,14 +139,14 @@ pub impl IdleWatcher { fn start(&mut self, cb: IdleCallback) { - set_watcher_callback(self, cb); + self.set_callback(cb); unsafe { assert!(0 == uvll::idle_start(self.native_handle(), idle_cb)) }; extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { let idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); - let cb: &IdleCallback = borrow_callback_from_watcher(&idle_watcher); + let cb: &IdleCallback = idle_watcher.borrow_callback(); let status = status_to_maybe_uv_error(handle, status); (*cb)(idle_watcher, status); } @@ -167,9 +160,11 @@ pub impl IdleWatcher { unsafe { uvll::close(self.native_handle(), close_cb) }; extern fn close_cb(handle: *uvll::uv_idle_t) { - let mut idle_watcher = NativeHandle::from_native_handle(handle); - drop_watcher_callback::(&mut idle_watcher); - unsafe { uvll::idle_delete(handle) }; + unsafe { + let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); + idle_watcher.drop_callback::(); + uvll::idle_delete(handle); + } } } } @@ -224,7 +219,7 @@ fn error_smoke_test() { pub fn last_uv_error>(watcher: &W) -> UvError { unsafe { - let loop_ = loop_from_watcher(watcher); + let loop_ = watcher.event_loop(); UvError(uvll::last_error(loop_.native_handle())) } } @@ -288,111 +283,103 @@ pub fn status_to_maybe_uv_error(handle: *T, status: c_int) -> Option } } -/// Get the uv event loop from a Watcher -pub fn loop_from_watcher>( - watcher: &W) -> Loop { - - let handle = watcher.native_handle(); - let loop_ = unsafe { uvll::get_loop_for_uv_handle(handle) }; - NativeHandle::from_native_handle(loop_) +/// Callbacks used by StreamWatchers, set as custom data on the foreign handle +struct WatcherData { + read_cb: Option, + write_cb: Option, + connect_cb: Option, + close_cb: Option, + alloc_cb: Option, } -/// Set the custom data on a handle to a callback Note: This is only -/// suitable for watchers that make just one type of callback. For -/// others use WatcherData -pub fn set_watcher_callback, CB: Callback>( - watcher: &mut W, cb: CB) { - - drop_watcher_callback::(watcher); - // XXX: Boxing the callback so it fits into a - // pointer. Unfortunate extra allocation - let boxed_cb = ~cb; - let data = unsafe { transmute::<~CB, *c_void>(boxed_cb) }; - unsafe { uvll::set_data_for_uv_handle(watcher.native_handle(), data) }; +pub trait WatcherInterop { + fn event_loop(&self) -> Loop; + fn set_callback(&mut self, cb: CB); + fn drop_callback(&mut self); + fn borrow_callback(&self) -> &CB; + fn install_watcher_data(&mut self); + fn get_watcher_data<'r>(&'r mut self) -> &'r mut WatcherData; + fn drop_watcher_data(&mut self); } -/// Delete a callback from a handle's custom data -pub fn drop_watcher_callback, CB: Callback>( - watcher: &mut W) { - - unsafe { - let handle = watcher.native_handle(); - let handle_data: *c_void = uvll::get_data_for_uv_handle(handle); - if handle_data.is_not_null() { - // Take ownership of the callback and drop it - let _cb = transmute::<*c_void, ~CB>(handle_data); - // Make sure the pointer is zeroed - uvll::set_data_for_uv_handle(watcher.native_handle(), null::<()>()); +impl> WatcherInterop for W { + /// Get the uv event loop from a Watcher + pub fn event_loop(&self) -> Loop { + unsafe { + let handle = self.native_handle(); + let loop_ = uvll::get_loop_for_uv_handle(handle); + NativeHandle::from_native_handle(loop_) } } -} -/// Take a pointer to the callback installed as custom data -pub fn borrow_callback_from_watcher, - CB: Callback>(watcher: &W) -> &CB { + /// Set the custom data on a handle to a callback Note: This is only + /// suitable for watchers that make just one type of callback. For + /// others use WatcherData + pub fn set_callback(&mut self, cb: CB) { + unsafe { + self.drop_callback::(); - unsafe { - let handle = watcher.native_handle(); - let handle_data: *c_void = uvll::get_data_for_uv_handle(handle); - assert!(handle_data.is_not_null()); - let cb = transmute::<&*c_void, &~CB>(&handle_data); - return &**cb; + // XXX: Boxing the callback so it fits into a + // pointer. Unfortunate extra allocation + let boxed_cb = ~cb; + let data = transmute::<~CB, *c_void>(boxed_cb); + uvll::set_data_for_uv_handle(self.native_handle(), data); + } } -} -/// Take ownership of the callback installed as custom data -pub fn take_callback_from_watcher, CB: Callback>( - watcher: &mut W) -> CB { - - unsafe { - let handle = watcher.native_handle(); - let handle_data: *c_void = uvll::get_data_for_uv_handle(handle); - assert!(handle_data.is_not_null()); - uvll::set_data_for_uv_handle(handle, null::<()>()); - let cb: ~CB = transmute::<*c_void, ~CB>(handle_data); - let cb = match cb { ~cb => cb }; - return cb; + /// Delete a callback from a handle's custom data + pub fn drop_callback(&mut self) { + unsafe { + let handle = self.native_handle(); + let handle_data: *c_void = uvll::get_data_for_uv_handle(handle); + if handle_data.is_not_null() { + // Take ownership of the callback and drop it + let _cb = transmute::<*c_void, ~CB>(handle_data); + // Make sure the pointer is zeroed + uvll::set_data_for_uv_handle(self.native_handle(), null::<()>()); + } + } } -} - -/// Callbacks used by StreamWatchers, set as custom data on the foreign handle -struct WatcherData { - read_cb: Option, - write_cb: Option, - connect_cb: Option, - close_cb: Option, - alloc_cb: Option, -} -pub fn install_watcher_data>(watcher: &mut W) { - unsafe { - let data = ~WatcherData { - read_cb: None, - write_cb: None, - connect_cb: None, - close_cb: None, - alloc_cb: None, - }; - let data = transmute::<~WatcherData, *c_void>(data); - uvll::set_data_for_uv_handle(watcher.native_handle(), data); + /// Take a pointer to the callback installed as custom data + pub fn borrow_callback(&self) -> &CB { + unsafe { + let handle = self.native_handle(); + let handle_data: *c_void = uvll::get_data_for_uv_handle(handle); + assert!(handle_data.is_not_null()); + let cb = transmute::<&*c_void, &~CB>(&handle_data); + return &**cb; + } } -} -pub fn get_watcher_data<'r, H, W: Watcher + NativeHandle<*H>>( - watcher: &'r mut W) -> &'r mut WatcherData { + pub fn install_watcher_data(&mut self) { + unsafe { + let data = ~WatcherData { + read_cb: None, + write_cb: None, + connect_cb: None, + close_cb: None, + alloc_cb: None, + }; + let data = transmute::<~WatcherData, *c_void>(data); + uvll::set_data_for_uv_handle(self.native_handle(), data); + } + } - unsafe { - let data = uvll::get_data_for_uv_handle(watcher.native_handle()); - let data = transmute::<&*c_void, &mut ~WatcherData>(&data); - return &mut **data; + pub fn get_watcher_data<'r>(&'r mut self) -> &'r mut WatcherData { + unsafe { + let data = uvll::get_data_for_uv_handle(self.native_handle()); + let data = transmute::<&*c_void, &mut ~WatcherData>(&data); + return &mut **data; + } } -} -pub fn drop_watcher_data>(watcher: &mut W) { - unsafe { - let data = uvll::get_data_for_uv_handle(watcher.native_handle()); - let _data = transmute::<*c_void, ~WatcherData>(data); - uvll::set_data_for_uv_handle(watcher.native_handle(), null::<()>()); + pub fn drop_watcher_data(&mut self) { + unsafe { + let data = uvll::get_data_for_uv_handle(self.native_handle()); + let _data = transmute::<*c_void, ~WatcherData>(data); + uvll::set_data_for_uv_handle(self.native_handle(), null::<()>()); + } } } diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index 49c42fa3587ac..1209609347aec 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -10,14 +10,11 @@ use prelude::*; use libc::{size_t, ssize_t, c_int, c_void}; -use cast::transmute_mut_region; use util::ignore; use rt::uv::uvll; use rt::uv::uvll::*; use super::{Loop, Watcher, Request, UvError, Buf, Callback, NativeHandle, NullCallback, - loop_from_watcher, status_to_maybe_uv_error, - install_watcher_data, get_watcher_data, drop_watcher_data, - vec_to_uv_buf, vec_from_uv_buf, slice_to_uv_buf}; + status_to_maybe_uv_error, vec_to_uv_buf, vec_from_uv_buf, slice_to_uv_buf}; use super::super::io::net::ip::{IpAddr, Ipv4, Ipv6}; use rt::uv::last_uv_error; @@ -49,12 +46,7 @@ fn ip4_as_uv_ip4(addr: IpAddr, f: &fn(*sockaddr_in) -> T) -> T { // uv_stream t is the parent class of uv_tcp_t, uv_pipe_t, uv_tty_t // and uv_file_t pub struct StreamWatcher(*uvll::uv_stream_t); - -impl Watcher for StreamWatcher { - fn event_loop(&self) -> Loop { - loop_from_watcher(self) - } -} +impl Watcher for StreamWatcher { } pub type ReadCallback = ~fn(StreamWatcher, int, Buf, Option); impl Callback for ReadCallback { } @@ -66,17 +58,18 @@ impl Callback for AllocCallback { } pub impl StreamWatcher { fn read_start(&mut self, alloc: AllocCallback, cb: ReadCallback) { - // XXX: Borrowchk problems - let data = get_watcher_data(unsafe { transmute_mut_region(self) }); - data.alloc_cb = Some(alloc); - data.read_cb = Some(cb); + { + let data = self.get_watcher_data(); + data.alloc_cb = Some(alloc); + data.read_cb = Some(cb); + } let handle = self.native_handle(); unsafe { uvll::read_start(handle, alloc_cb, read_cb); } extern fn alloc_cb(stream: *uvll::uv_stream_t, suggested_size: size_t) -> Buf { let mut stream_watcher: StreamWatcher = NativeHandle::from_native_handle(stream); - let data = get_watcher_data(&mut stream_watcher); + let data = stream_watcher.get_watcher_data(); let alloc_cb = data.alloc_cb.get_ref(); return (*alloc_cb)(suggested_size as uint); } @@ -85,7 +78,7 @@ pub impl StreamWatcher { rtdebug!("buf addr: %x", buf.base as uint); rtdebug!("buf len: %d", buf.len as int); let mut stream_watcher: StreamWatcher = NativeHandle::from_native_handle(stream); - let data = get_watcher_data(&mut stream_watcher); + let data = stream_watcher.get_watcher_data(); let cb = data.read_cb.get_ref(); let status = status_to_maybe_uv_error(stream, nread as c_int); (*cb)(stream_watcher, nread as int, buf, status); @@ -101,17 +94,18 @@ pub impl StreamWatcher { } fn write(&mut self, buf: Buf, cb: ConnectionCallback) { - // XXX: Borrowck - let data = get_watcher_data(unsafe { transmute_mut_region(self) }); - assert!(data.write_cb.is_none()); - data.write_cb = Some(cb); + { + let data = self.get_watcher_data(); + assert!(data.write_cb.is_none()); + data.write_cb = Some(cb); + } let req = WriteRequest::new(); let bufs = [buf]; unsafe { assert!(0 == uvll::write(req.native_handle(), - self.native_handle(), - bufs, write_cb)); + self.native_handle(), + bufs, write_cb)); } extern fn write_cb(req: *uvll::uv_write_t, status: c_int) { @@ -119,7 +113,7 @@ pub impl StreamWatcher { let mut stream_watcher = write_request.stream(); write_request.delete(); let cb = { - let data = get_watcher_data(&mut stream_watcher); + let data = stream_watcher.get_watcher_data(); let cb = data.write_cb.swap_unwrap(); cb }; @@ -139,7 +133,7 @@ pub impl StreamWatcher { fn close(self, cb: NullCallback) { { let mut this = self; - let data = get_watcher_data(&mut this); + let data = this.get_watcher_data(); assert!(data.close_cb.is_none()); data.close_cb = Some(cb); } @@ -149,9 +143,10 @@ pub impl StreamWatcher { extern fn close_cb(handle: *uvll::uv_stream_t) { let mut stream_watcher: StreamWatcher = NativeHandle::from_native_handle(handle); { - get_watcher_data(&mut stream_watcher).close_cb.swap_unwrap()(); + let mut data = stream_watcher.get_watcher_data(); + data.close_cb.swap_unwrap()(); } - drop_watcher_data(&mut stream_watcher); + stream_watcher.drop_watcher_data(); unsafe { free_handle(handle as *c_void) } } } @@ -168,12 +163,7 @@ impl NativeHandle<*uvll::uv_stream_t> for StreamWatcher { } pub struct TcpWatcher(*uvll::uv_tcp_t); - -impl Watcher for TcpWatcher { - fn event_loop(&self) -> Loop { - loop_from_watcher(self) - } -} +impl Watcher for TcpWatcher { } pub type ConnectionCallback = ~fn(StreamWatcher, Option); impl Callback for ConnectionCallback { } @@ -184,8 +174,8 @@ pub impl TcpWatcher { let handle = malloc_handle(UV_TCP); assert!(handle.is_not_null()); assert!(0 == uvll::tcp_init(loop_.native_handle(), handle)); - let mut watcher = NativeHandle::from_native_handle(handle); - install_watcher_data(&mut watcher); + let mut watcher: TcpWatcher = NativeHandle::from_native_handle(handle); + watcher.install_watcher_data(); return watcher; } } @@ -210,8 +200,8 @@ pub impl TcpWatcher { fn connect(&mut self, address: IpAddr, cb: ConnectionCallback) { unsafe { - assert!(get_watcher_data(self).connect_cb.is_none()); - get_watcher_data(self).connect_cb = Some(cb); + assert!(self.get_watcher_data().connect_cb.is_none()); + self.get_watcher_data().connect_cb = Some(cb); let connect_handle = ConnectRequest::new().native_handle(); match address { @@ -232,7 +222,7 @@ pub impl TcpWatcher { let mut stream_watcher = connect_request.stream(); connect_request.delete(); let cb: ConnectionCallback = { - let data = get_watcher_data(&mut stream_watcher); + let data = stream_watcher.get_watcher_data(); data.connect_cb.swap_unwrap() }; let status = status_to_maybe_uv_error(stream_watcher.native_handle(), status); @@ -242,10 +232,11 @@ pub impl TcpWatcher { } fn listen(&mut self, cb: ConnectionCallback) { - // XXX: Borrowck - let data = get_watcher_data(unsafe { transmute_mut_region(self) }); - assert!(data.connect_cb.is_none()); - data.connect_cb = Some(cb); + { + let data = self.get_watcher_data(); + assert!(data.connect_cb.is_none()); + data.connect_cb = Some(cb); + } unsafe { static BACKLOG: c_int = 128; // XXX should be configurable @@ -257,7 +248,7 @@ pub impl TcpWatcher { extern fn connection_cb(handle: *uvll::uv_stream_t, status: c_int) { rtdebug!("connection_cb"); let mut stream_watcher: StreamWatcher = NativeHandle::from_native_handle(handle); - let cb = get_watcher_data(&mut stream_watcher).connect_cb.swap_unwrap(); + let cb = stream_watcher.get_watcher_data().connect_cb.swap_unwrap(); let status = status_to_maybe_uv_error(stream_watcher.native_handle(), status); cb(stream_watcher, status); } diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index d8858717f6f39..af3bac5b65430 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -192,9 +192,10 @@ impl RtioTcpListener for UvTcpListener { do server_tcp_watcher.listen |server_stream_watcher, status| { let maybe_stream = if status.is_none() { let mut server_stream_watcher = server_stream_watcher; - let mut loop_ = loop_from_watcher(&server_stream_watcher); - let client_tcp_watcher = TcpWatcher::new(&mut loop_).as_stream(); - // XXX: Needs to be surfaced in interface + let mut loop_ = server_stream_watcher.event_loop(); + let mut client_tcp_watcher = TcpWatcher::new(&mut loop_); + let client_tcp_watcher = client_tcp_watcher.as_stream(); + // XXX: Need's to be surfaced in interface server_stream_watcher.accept(client_tcp_watcher); Ok(~UvTcpStream { watcher: client_tcp_watcher }) } else { From 91ca3a9b295404e6dc36677d415573935a9989db Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 18:50:35 -0700 Subject: [PATCH 012/248] core::rt: Reording code --- src/libcore/rt/uv/mod.rs | 229 ++++++++++++++++++++------------------- 1 file changed, 115 insertions(+), 114 deletions(-) diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 7d5a4f00204d8..79afaf69ad35a 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -178,111 +178,6 @@ impl NativeHandle<*uvll::uv_idle_t> for IdleWatcher { } } -// XXX: Need to define the error constants like EOF so they can be -// compared to the UvError type - -pub struct UvError(uvll::uv_err_t); - -pub impl UvError { - - fn name(&self) -> ~str { - unsafe { - let inner = match self { &UvError(ref a) => a }; - let name_str = uvll::err_name(inner); - assert!(name_str.is_not_null()); - from_c_str(name_str) - } - } - - fn desc(&self) -> ~str { - unsafe { - let inner = match self { &UvError(ref a) => a }; - let desc_str = uvll::strerror(inner); - assert!(desc_str.is_not_null()); - from_c_str(desc_str) - } - } -} - -impl ToStr for UvError { - fn to_str(&self) -> ~str { - fmt!("%s: %s", self.name(), self.desc()) - } -} - -#[test] -fn error_smoke_test() { - let err = uvll::uv_err_t { code: 1, sys_errno_: 1 }; - let err: UvError = UvError(err); - assert!(err.to_str() == ~"EOF: end of file"); -} - -pub fn last_uv_error>(watcher: &W) -> UvError { - unsafe { - let loop_ = watcher.event_loop(); - UvError(uvll::last_error(loop_.native_handle())) - } -} - -pub fn uv_error_to_io_error(uverr: UvError) -> IoError { - - // XXX: Could go in str::raw - unsafe fn c_str_to_static_slice(s: *libc::c_char) -> &'static str { - let s = s as *u8; - let mut curr = s, len = 0u; - while *curr != 0u8 { - len += 1u; - curr = ptr::offset(s, len); - } - - str::raw::buf_as_slice(s, len, |d| cast::transmute(d)) - } - - - unsafe { - // Importing error constants - use rt::uv::uvll::*; - use rt::io::*; - - // uv error descriptions are static - let c_desc = uvll::strerror(&*uverr); - let desc = c_str_to_static_slice(c_desc); - - let kind = match uverr.code { - UNKNOWN => OtherIoError, - OK => OtherIoError, - EOF => EndOfFile, - EACCES => PermissionDenied, - ECONNREFUSED => ConnectionRefused, - e => { - abort!("unknown uv error code: %u", e as uint); - } - }; - - IoError { - kind: kind, - desc: desc, - detail: None - } - } -} - -/// Given a uv handle, convert a callback status to a UvError -// XXX: Follow the pattern below by parameterizing over T: Watcher, not T -pub fn status_to_maybe_uv_error(handle: *T, status: c_int) -> Option { - if status != -1 { - None - } else { - unsafe { - rtdebug!("handle: %x", handle as uint); - let loop_ = uvll::get_loop_for_uv_handle(handle); - rtdebug!("loop: %x", loop_ as uint); - let err = uvll::last_error(loop_); - Some(UvError(err)) - } - } -} - /// Callbacks used by StreamWatchers, set as custom data on the foreign handle struct WatcherData { read_cb: Option, @@ -383,21 +278,109 @@ impl> WatcherInterop for W { } } +// XXX: Need to define the error constants like EOF so they can be +// compared to the UvError type + +pub struct UvError(uvll::uv_err_t); + +pub impl UvError { + + fn name(&self) -> ~str { + unsafe { + let inner = match self { &UvError(ref a) => a }; + let name_str = uvll::err_name(inner); + assert!(name_str.is_not_null()); + from_c_str(name_str) + } + } + + fn desc(&self) -> ~str { + unsafe { + let inner = match self { &UvError(ref a) => a }; + let desc_str = uvll::strerror(inner); + assert!(desc_str.is_not_null()); + from_c_str(desc_str) + } + } +} + +impl ToStr for UvError { + fn to_str(&self) -> ~str { + fmt!("%s: %s", self.name(), self.desc()) + } +} + #[test] -fn test_slice_to_uv_buf() { - let slice = [0, .. 20]; - let buf = slice_to_uv_buf(slice); +fn error_smoke_test() { + let err = uvll::uv_err_t { code: 1, sys_errno_: 1 }; + let err: UvError = UvError(err); + assert!(err.to_str() == ~"EOF: end of file"); +} + +pub fn last_uv_error>(watcher: &W) -> UvError { + unsafe { + let loop_ = watcher.event_loop(); + UvError(uvll::last_error(loop_.native_handle())) + } +} + +pub fn uv_error_to_io_error(uverr: UvError) -> IoError { + + // XXX: Could go in str::raw + unsafe fn c_str_to_static_slice(s: *libc::c_char) -> &'static str { + let s = s as *u8; + let mut curr = s, len = 0u; + while *curr != 0u8 { + len += 1u; + curr = ptr::offset(s, len); + } + + str::raw::buf_as_slice(s, len, |d| cast::transmute(d)) + } - assert!(buf.len == 20); unsafe { - let base = transmute::<*u8, *mut u8>(buf.base); - (*base) = 1; - (*ptr::mut_offset(base, 1)) = 2; + // Importing error constants + use rt::uv::uvll::*; + use rt::io::*; + + // uv error descriptions are static + let c_desc = uvll::strerror(&*uverr); + let desc = c_str_to_static_slice(c_desc); + + let kind = match uverr.code { + UNKNOWN => OtherIoError, + OK => OtherIoError, + EOF => EndOfFile, + EACCES => PermissionDenied, + ECONNREFUSED => ConnectionRefused, + e => { + abort!("unknown uv error code: %u", e as uint); + } + }; + + IoError { + kind: kind, + desc: desc, + detail: None + } } +} - assert!(slice[0] == 1); - assert!(slice[1] == 2); +/// Given a uv handle, convert a callback status to a UvError +// XXX: Follow the pattern below by parameterizing over T: Watcher, not T +pub fn status_to_maybe_uv_error(handle: *T, status: c_int) -> Option { + if status != -1 { + None + } else { + unsafe { + rtdebug!("handle: %x", handle as uint); + let loop_ = uvll::get_loop_for_uv_handle(handle); + rtdebug!("loop: %x", loop_ as uint); + let err = uvll::last_error(loop_); + Some(UvError(err)) + } + } } /// The uv buffer type @@ -437,6 +420,24 @@ pub fn vec_from_uv_buf(buf: Buf) -> Option<~[u8]> { } } +#[test] +fn test_slice_to_uv_buf() { + let slice = [0, .. 20]; + let buf = slice_to_uv_buf(slice); + + assert!(buf.len == 20); + + unsafe { + let base = transmute::<*u8, *mut u8>(buf.base); + (*base) = 1; + (*ptr::mut_offset(base, 1)) = 2; + } + + assert!(slice[0] == 1); + assert!(slice[1] == 2); +} + + #[test] fn loop_smoke_test() { do run_in_bare_thread { From 9138feab1509e930a811d5b727e5cad61e369852 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 19:28:40 -0700 Subject: [PATCH 013/248] core::rt: Only use one mechanism for attaching custom data to uv handles --- src/libcore/rt/uv/mod.rs | 69 +++++++++++----------------------------- 1 file changed, 19 insertions(+), 50 deletions(-) diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 79afaf69ad35a..801a6173b1ed2 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -132,28 +132,38 @@ pub impl IdleWatcher { let handle = uvll::idle_new(); assert!(handle.is_not_null()); assert!(0 == uvll::idle_init(loop_.native_handle(), handle)); - uvll::set_data_for_uv_handle(handle, null::<()>()); - NativeHandle::from_native_handle(handle) + let mut watcher: IdleWatcher = NativeHandle::from_native_handle(handle); + watcher.install_watcher_data(); + return watcher } } fn start(&mut self, cb: IdleCallback) { + { + let data = self.get_watcher_data(); + data.idle_cb = Some(cb); + } - self.set_callback(cb); unsafe { assert!(0 == uvll::idle_start(self.native_handle(), idle_cb)) }; extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { - let idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); - let cb: &IdleCallback = idle_watcher.borrow_callback(); + let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); + let data = idle_watcher.get_watcher_data(); + let cb: &IdleCallback = data.idle_cb.get_ref(); let status = status_to_maybe_uv_error(handle, status); (*cb)(idle_watcher, status); } } fn stop(&mut self) { - unsafe { assert!(0 == uvll::idle_stop(self.native_handle())); } + // NB: Not resetting the Rust idl_cb to None here because `stop` is likely + // called from *within* the idle callback, which would cause a use after free + + unsafe { + assert!(0 == uvll::idle_stop(self.native_handle())); + } } fn close(self) { @@ -162,7 +172,7 @@ pub impl IdleWatcher { extern fn close_cb(handle: *uvll::uv_idle_t) { unsafe { let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); - idle_watcher.drop_callback::(); + idle_watcher.drop_watcher_data(); uvll::idle_delete(handle); } } @@ -185,13 +195,11 @@ struct WatcherData { connect_cb: Option, close_cb: Option, alloc_cb: Option, + idle_cb: Option } pub trait WatcherInterop { fn event_loop(&self) -> Loop; - fn set_callback(&mut self, cb: CB); - fn drop_callback(&mut self); - fn borrow_callback(&self) -> &CB; fn install_watcher_data(&mut self); fn get_watcher_data<'r>(&'r mut self) -> &'r mut WatcherData; fn drop_watcher_data(&mut self); @@ -207,46 +215,6 @@ impl> WatcherInterop for W { } } - /// Set the custom data on a handle to a callback Note: This is only - /// suitable for watchers that make just one type of callback. For - /// others use WatcherData - pub fn set_callback(&mut self, cb: CB) { - unsafe { - self.drop_callback::(); - - // XXX: Boxing the callback so it fits into a - // pointer. Unfortunate extra allocation - let boxed_cb = ~cb; - let data = transmute::<~CB, *c_void>(boxed_cb); - uvll::set_data_for_uv_handle(self.native_handle(), data); - } - } - - /// Delete a callback from a handle's custom data - pub fn drop_callback(&mut self) { - unsafe { - let handle = self.native_handle(); - let handle_data: *c_void = uvll::get_data_for_uv_handle(handle); - if handle_data.is_not_null() { - // Take ownership of the callback and drop it - let _cb = transmute::<*c_void, ~CB>(handle_data); - // Make sure the pointer is zeroed - uvll::set_data_for_uv_handle(self.native_handle(), null::<()>()); - } - } - } - - /// Take a pointer to the callback installed as custom data - pub fn borrow_callback(&self) -> &CB { - unsafe { - let handle = self.native_handle(); - let handle_data: *c_void = uvll::get_data_for_uv_handle(handle); - assert!(handle_data.is_not_null()); - let cb = transmute::<&*c_void, &~CB>(&handle_data); - return &**cb; - } - } - pub fn install_watcher_data(&mut self) { unsafe { let data = ~WatcherData { @@ -255,6 +223,7 @@ impl> WatcherInterop for W { connect_cb: None, close_cb: None, alloc_cb: None, + idle_cb: None }; let data = transmute::<~WatcherData, *c_void>(data); uvll::set_data_for_uv_handle(self.native_handle(), data); From dbf89664aa9f5414aa02b4c1ab2b481581de17b9 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 19:36:08 -0700 Subject: [PATCH 014/248] core::rt: Move the implementation of IdleWatcher to its own file --- src/libcore/rt/uv/idle.rs | 83 +++++++++++++++++++++++++++++++++++++++ src/libcore/rt/uv/mod.rs | 71 +-------------------------------- src/libcore/rt/uv/uvio.rs | 1 + 3 files changed, 86 insertions(+), 69 deletions(-) create mode 100644 src/libcore/rt/uv/idle.rs diff --git a/src/libcore/rt/uv/idle.rs b/src/libcore/rt/uv/idle.rs new file mode 100644 index 0000000000000..aba5b3df9370e --- /dev/null +++ b/src/libcore/rt/uv/idle.rs @@ -0,0 +1,83 @@ +// 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. + +use libc::c_int; +use option::{Option, Some, None}; +use rt::uv::uvll; +use rt::uv::{Watcher, Callback, Loop, UvError, NativeHandle}; +use rt::uv::status_to_maybe_uv_error; + +pub struct IdleWatcher(*uvll::uv_idle_t); +impl Watcher for IdleWatcher { } + +pub type IdleCallback = ~fn(IdleWatcher, Option); +impl Callback for IdleCallback { } + +pub impl IdleWatcher { + fn new(loop_: &mut Loop) -> IdleWatcher { + unsafe { + let handle = uvll::idle_new(); + assert!(handle.is_not_null()); + assert!(0 == uvll::idle_init(loop_.native_handle(), handle)); + let mut watcher: IdleWatcher = NativeHandle::from_native_handle(handle); + watcher.install_watcher_data(); + return watcher + } + } + + fn start(&mut self, cb: IdleCallback) { + { + let data = self.get_watcher_data(); + data.idle_cb = Some(cb); + } + + unsafe { + assert!(0 == uvll::idle_start(self.native_handle(), idle_cb)) + }; + + extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { + let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); + let data = idle_watcher.get_watcher_data(); + let cb: &IdleCallback = data.idle_cb.get_ref(); + let status = status_to_maybe_uv_error(handle, status); + (*cb)(idle_watcher, status); + } + } + + fn stop(&mut self) { + // NB: Not resetting the Rust idle_cb to None here because `stop` is likely + // called from *within* the idle callback, causing a use after free + + unsafe { + assert!(0 == uvll::idle_stop(self.native_handle())); + } + } + + fn close(self) { + unsafe { uvll::close(self.native_handle(), close_cb) }; + + extern fn close_cb(handle: *uvll::uv_idle_t) { + unsafe { + let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); + idle_watcher.drop_watcher_data(); + uvll::idle_delete(handle); + } + } + } +} + +impl NativeHandle<*uvll::uv_idle_t> for IdleWatcher { + fn from_native_handle(handle: *uvll::uv_idle_t) -> IdleWatcher { + IdleWatcher(handle) + } + fn native_handle(&self) -> *uvll::uv_idle_t { + match self { &IdleWatcher(ptr) => ptr } + } +} diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 801a6173b1ed2..79eda96a25fe9 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -54,7 +54,7 @@ use rt::io::IoError; pub use self::file::{FsRequest, FsCallback}; pub use self::net::{StreamWatcher, TcpWatcher}; pub use self::net::{ReadCallback, AllocCallback, ConnectionCallback, ConnectCallback}; - +pub use self::idle::{IdleWatcher, IdleCallback}; /// The implementation of `rtio` for libuv pub mod uvio; @@ -64,6 +64,7 @@ pub mod uvll; pub mod file; pub mod net; +pub mod idle; /// A trait for callbacks to implement. Provides a little extra type safety /// for generic, unsafe interop functions like `set_watcher_callback`. @@ -120,74 +121,6 @@ impl NativeHandle<*uvll::uv_loop_t> for Loop { } } -pub struct IdleWatcher(*uvll::uv_idle_t); -impl Watcher for IdleWatcher { } - -pub type IdleCallback = ~fn(IdleWatcher, Option); -impl Callback for IdleCallback { } - -pub impl IdleWatcher { - fn new(loop_: &mut Loop) -> IdleWatcher { - unsafe { - let handle = uvll::idle_new(); - assert!(handle.is_not_null()); - assert!(0 == uvll::idle_init(loop_.native_handle(), handle)); - let mut watcher: IdleWatcher = NativeHandle::from_native_handle(handle); - watcher.install_watcher_data(); - return watcher - } - } - - fn start(&mut self, cb: IdleCallback) { - { - let data = self.get_watcher_data(); - data.idle_cb = Some(cb); - } - - unsafe { - assert!(0 == uvll::idle_start(self.native_handle(), idle_cb)) - }; - - extern fn idle_cb(handle: *uvll::uv_idle_t, status: c_int) { - let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); - let data = idle_watcher.get_watcher_data(); - let cb: &IdleCallback = data.idle_cb.get_ref(); - let status = status_to_maybe_uv_error(handle, status); - (*cb)(idle_watcher, status); - } - } - - fn stop(&mut self) { - // NB: Not resetting the Rust idl_cb to None here because `stop` is likely - // called from *within* the idle callback, which would cause a use after free - - unsafe { - assert!(0 == uvll::idle_stop(self.native_handle())); - } - } - - fn close(self) { - unsafe { uvll::close(self.native_handle(), close_cb) }; - - extern fn close_cb(handle: *uvll::uv_idle_t) { - unsafe { - let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); - idle_watcher.drop_watcher_data(); - uvll::idle_delete(handle); - } - } - } -} - -impl NativeHandle<*uvll::uv_idle_t> for IdleWatcher { - fn from_native_handle(handle: *uvll::uv_idle_t) -> IdleWatcher { - IdleWatcher(handle) - } - fn native_handle(&self) -> *uvll::uv_idle_t { - match self { &IdleWatcher(ptr) => ptr } - } -} - /// Callbacks used by StreamWatchers, set as custom data on the foreign handle struct WatcherData { read_cb: Option, diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index af3bac5b65430..0c52bca0dc83a 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -17,6 +17,7 @@ use cast::transmute; use rt::io::IoError; use rt::io::net::ip::IpAddr; use rt::uv::*; +use rt::uv::idle::IdleWatcher; use rt::rtio::*; use rt::sched::{Scheduler, local_sched}; use rt::io::{standard_error, OtherIoError}; From a134503d74814b40a07c31133a72638dc29ba6fc Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 19:53:42 -0700 Subject: [PATCH 015/248] core::rt: Move all the uv callback definitions to one place --- src/libcore/rt/uv/file.rs | 6 +----- src/libcore/rt/uv/idle.rs | 7 ++----- src/libcore/rt/uv/mod.rs | 35 ++++++++++++++++++----------------- src/libcore/rt/uv/net.rs | 17 ++--------------- 4 files changed, 23 insertions(+), 42 deletions(-) diff --git a/src/libcore/rt/uv/file.rs b/src/libcore/rt/uv/file.rs index 816a3a10a9016..2d14505509759 100644 --- a/src/libcore/rt/uv/file.rs +++ b/src/libcore/rt/uv/file.rs @@ -11,15 +11,11 @@ use prelude::*; use ptr::null; use libc::c_void; -use super::{UvError, Callback, Request, NativeHandle, Loop}; +use rt::uv::{Request, NativeHandle, Loop, FsCallback}; use rt::uv::uvll; use rt::uv::uvll::*; -pub type FsCallback = ~fn(FsRequest, Option); -impl Callback for FsCallback { } - pub struct FsRequest(*uvll::uv_fs_t); - impl Request for FsRequest; impl FsRequest { diff --git a/src/libcore/rt/uv/idle.rs b/src/libcore/rt/uv/idle.rs index aba5b3df9370e..fe1ce8697bf9e 100644 --- a/src/libcore/rt/uv/idle.rs +++ b/src/libcore/rt/uv/idle.rs @@ -9,17 +9,14 @@ // except according to those terms. use libc::c_int; -use option::{Option, Some, None}; +use option::{Some, None}; use rt::uv::uvll; -use rt::uv::{Watcher, Callback, Loop, UvError, NativeHandle}; +use rt::uv::{Watcher, Loop, NativeHandle, IdleCallback}; use rt::uv::status_to_maybe_uv_error; pub struct IdleWatcher(*uvll::uv_idle_t); impl Watcher for IdleWatcher { } -pub type IdleCallback = ~fn(IdleWatcher, Option); -impl Callback for IdleCallback { } - pub impl IdleWatcher { fn new(loop_: &mut Loop) -> IdleWatcher { unsafe { diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 79eda96a25fe9..2c83873359a8f 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -51,10 +51,9 @@ use rt::io::IoError; #[cfg(test)] use unstable::run_in_bare_thread; -pub use self::file::{FsRequest, FsCallback}; +pub use self::file::FsRequest; pub use self::net::{StreamWatcher, TcpWatcher}; -pub use self::net::{ReadCallback, AllocCallback, ConnectionCallback, ConnectCallback}; -pub use self::idle::{IdleWatcher, IdleCallback}; +pub use self::idle::IdleWatcher; /// The implementation of `rtio` for libuv pub mod uvio; @@ -66,11 +65,12 @@ pub mod file; pub mod net; pub mod idle; -/// A trait for callbacks to implement. Provides a little extra type safety -/// for generic, unsafe interop functions like `set_watcher_callback`. -pub trait Callback { } - -pub trait Request { } +/// XXX: Loop(*handle) is buggy with destructors. Normal structs +/// with dtors may not be destructured, but tuple structs can, +/// but the results are not correct. +pub struct Loop { + handle: *uvll::uv_loop_t +} /// The trait implemented by uv 'watchers' (handles). Watchers are /// non-owning wrappers around the uv handles and are not completely @@ -80,8 +80,7 @@ pub trait Request { } /// entirely memory safe if used in unanticipated patterns. pub trait Watcher { } -pub type NullCallback = ~fn(); -impl Callback for NullCallback { } +pub trait Request { } /// A type that wraps a native handle pub trait NativeHandle { @@ -89,13 +88,6 @@ pub trait NativeHandle { pub fn native_handle(&self) -> T; } -/// XXX: Loop(*handle) is buggy with destructors. Normal structs -/// with dtors may not be destructured, but tuple structs can, -/// but the results are not correct. -pub struct Loop { - handle: *uvll::uv_loop_t -} - pub impl Loop { fn new() -> Loop { let handle = unsafe { uvll::loop_new() }; @@ -121,6 +113,15 @@ impl NativeHandle<*uvll::uv_loop_t> for Loop { } } +// XXX: The uv alloc callback also has a *uv_handle_t arg +pub type AllocCallback = ~fn(uint) -> Buf; +pub type ReadCallback = ~fn(StreamWatcher, int, Buf, Option); +pub type NullCallback = ~fn(); +pub type IdleCallback = ~fn(IdleWatcher, Option); +pub type ConnectionCallback = ~fn(StreamWatcher, Option); +pub type FsCallback = ~fn(FsRequest, Option); + + /// Callbacks used by StreamWatchers, set as custom data on the foreign handle struct WatcherData { read_cb: Option, diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index 1209609347aec..6261996a8b650 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -13,7 +13,8 @@ use libc::{size_t, ssize_t, c_int, c_void}; use util::ignore; use rt::uv::uvll; use rt::uv::uvll::*; -use super::{Loop, Watcher, Request, UvError, Buf, Callback, NativeHandle, NullCallback, +use rt::uv::{AllocCallback, ConnectionCallback, ReadCallback}; +use super::{Loop, Watcher, Request, UvError, Buf, NativeHandle, NullCallback, status_to_maybe_uv_error, vec_to_uv_buf, vec_from_uv_buf, slice_to_uv_buf}; use super::super::io::net::ip::{IpAddr, Ipv4, Ipv6}; use rt::uv::last_uv_error; @@ -48,13 +49,6 @@ fn ip4_as_uv_ip4(addr: IpAddr, f: &fn(*sockaddr_in) -> T) -> T { pub struct StreamWatcher(*uvll::uv_stream_t); impl Watcher for StreamWatcher { } -pub type ReadCallback = ~fn(StreamWatcher, int, Buf, Option); -impl Callback for ReadCallback { } - -// XXX: The uv alloc callback also has a *uv_handle_t arg -pub type AllocCallback = ~fn(uint) -> Buf; -impl Callback for AllocCallback { } - pub impl StreamWatcher { fn read_start(&mut self, alloc: AllocCallback, cb: ReadCallback) { @@ -165,9 +159,6 @@ impl NativeHandle<*uvll::uv_stream_t> for StreamWatcher { pub struct TcpWatcher(*uvll::uv_tcp_t); impl Watcher for TcpWatcher { } -pub type ConnectionCallback = ~fn(StreamWatcher, Option); -impl Callback for ConnectionCallback { } - pub impl TcpWatcher { fn new(loop_: &mut Loop) -> TcpWatcher { unsafe { @@ -268,12 +259,8 @@ impl NativeHandle<*uvll::uv_tcp_t> for TcpWatcher { } } -pub type ConnectCallback = ~fn(ConnectRequest, Option); -impl Callback for ConnectCallback { } - // uv_connect_t is a subclass of uv_req_t struct ConnectRequest(*uvll::uv_connect_t); - impl Request for ConnectRequest { } impl ConnectRequest { From ad6719ee0b4977c949a34b7a2250ed7274cf442e Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 2 May 2013 22:44:20 -0700 Subject: [PATCH 016/248] core::rt: Just a small fix to TcpStream --- src/libcore/rt/io/net/tcp.rs | 26 ++++++++++++++++++++++++++ src/libcore/rt/uv/net.rs | 7 ++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index ae4a7a2039717..a669509a48a35 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -171,4 +171,30 @@ mod test { } } } + + #[test] #[ignore] + fn multiple_connect_serial() { + do run_in_newsched_task { + let addr = next_test_ip4(); + let max = 100; + + do spawntask_immediately { + let mut listener = TcpListener::bind(addr); + for max.times { + let mut stream = listener.accept(); + let mut buf = [0]; + stream.read(buf); + assert!(buf[0] == 99); + } + } + + do spawntask_immediately { + for max.times { + let mut stream = TcpStream::connect(addr); + stream.write([99]); + } + } + } + } + } diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index 6261996a8b650..b22adafdf2d9e 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -239,9 +239,10 @@ pub impl TcpWatcher { extern fn connection_cb(handle: *uvll::uv_stream_t, status: c_int) { rtdebug!("connection_cb"); let mut stream_watcher: StreamWatcher = NativeHandle::from_native_handle(handle); - let cb = stream_watcher.get_watcher_data().connect_cb.swap_unwrap(); - let status = status_to_maybe_uv_error(stream_watcher.native_handle(), status); - cb(stream_watcher, status); + let data = stream_watcher.get_watcher_data(); + let cb = data.connect_cb.get_ref(); + let status = status_to_maybe_uv_error(handle, status); + (*cb)(stream_watcher, status); } } From 10355d7a7d1ba87d49149e5fcdc5d3955932afe2 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 27 Apr 2013 18:57:15 -0700 Subject: [PATCH 017/248] core::rt Wire up logging to newsched tasks --- src/libcore/core.rc | 5 ++- src/libcore/logging.rs | 68 +++++++++++++++++++++++--------- src/libcore/macros.rs | 4 +- src/libcore/rt/local_services.rs | 24 +++++++++-- src/libcore/rt/logging.rs | 38 ++++++++++++++++++ src/libcore/rt/mod.rs | 3 ++ 6 files changed, 117 insertions(+), 25 deletions(-) create mode 100644 src/libcore/rt/logging.rs diff --git a/src/libcore/core.rc b/src/libcore/core.rc index d029fbc07f6fb..073a6dcf4d259 100644 --- a/src/libcore/core.rc +++ b/src/libcore/core.rc @@ -246,8 +246,11 @@ mod unicode; #[path = "num/cmath.rs"] mod cmath; mod stackwalk; + +// XXX: This shouldn't be pub, and it should be reexported under 'unstable' +// but name resolution doesn't work without it being pub. #[path = "rt/mod.rs"] -mod rt; +pub mod rt; // A curious inner-module that's not exported that contains the binding // 'core' so that macro-expanded references to core::error and such diff --git a/src/libcore/logging.rs b/src/libcore/logging.rs index 69ecad56a8f5c..4ecd72ebd0c00 100644 --- a/src/libcore/logging.rs +++ b/src/libcore/logging.rs @@ -10,17 +10,15 @@ //! Logging -pub mod rustrt { - use libc; - - pub extern { - unsafe fn rust_log_console_on(); - unsafe fn rust_log_console_off(); - unsafe fn rust_log_str(level: u32, - string: *libc::c_char, - size: libc::size_t); - } -} +use option::*; +use either::*; +use rt; +use rt::logging::{Logger, StdErrLogger}; +use io; +use libc; +use repr; +use vec; +use cast; /// Turns on logging to stdout globally pub fn console_on() { @@ -45,17 +43,51 @@ pub fn console_off() { #[cfg(not(test))] #[lang="log_type"] pub fn log_type(level: u32, object: &T) { - use cast::transmute; - use io; - use libc; - use repr; - use vec; let bytes = do io::with_bytes_writer |writer| { repr::write_repr(writer, object); }; + + match rt::context() { + rt::OldTaskContext => { + unsafe { + let len = bytes.len() as libc::size_t; + rustrt::rust_log_str(level, cast::transmute(vec::raw::to_ptr(bytes)), len); + } + } + _ => { + // XXX: Bad allocation + let msg = bytes.to_str(); + newsched_log_str(msg); + } + } +} + +fn newsched_log_str(msg: ~str) { + unsafe { - let len = bytes.len() as libc::size_t; - rustrt::rust_log_str(level, transmute(vec::raw::to_ptr(bytes)), len); + match rt::local_services::unsafe_try_borrow_local_services() { + Some(local) => { + // Use the available logger + (*local).logger.log(Left(msg)); + } + None => { + // There is no logger anywhere, just write to stderr + let mut logger = StdErrLogger; + logger.log(Left(msg)); + } + } + } +} + +pub mod rustrt { + use libc; + + pub extern { + unsafe fn rust_log_console_on(); + unsafe fn rust_log_console_off(); + unsafe fn rust_log_str(level: u32, + string: *libc::c_char, + size: libc::size_t); } } diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index b2e94f327c86e..c4f0384f71ed6 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -11,7 +11,7 @@ #[macro_escape]; // Some basic logging -macro_rules! rtdebug_ ( +macro_rules! rtdebug ( ($( $arg:expr),+) => ( { dumb_println(fmt!( $($arg),+ )); @@ -26,7 +26,7 @@ macro_rules! rtdebug_ ( ) // An alternate version with no output, for turning off logging -macro_rules! rtdebug ( +macro_rules! rtdebug_ ( ($( $arg:expr),+) => ( $(let _ = $arg)*; ) ) diff --git a/src/libcore/rt/local_services.rs b/src/libcore/rt/local_services.rs index 94840d7b5d584..b8bf6e067801f 100644 --- a/src/libcore/rt/local_services.rs +++ b/src/libcore/rt/local_services.rs @@ -23,19 +23,19 @@ use libc::{c_void, uintptr_t}; use cast::transmute; use super::sched::local_sched; use super::local_heap::LocalHeap; +use rt::logging::{Logger, StdErrLogger}; pub struct LocalServices { heap: LocalHeap, gc: GarbageCollector, storage: LocalStorage, - logger: Logger, + logger: StdErrLogger, unwinder: Option, destroyed: bool } pub struct GarbageCollector; pub struct LocalStorage(*c_void, Option<~fn(*c_void)>); -pub struct Logger; pub struct Unwinder { unwinding: bool, @@ -47,7 +47,7 @@ impl LocalServices { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(ptr::null(), None), - logger: Logger, + logger: StdErrLogger, unwinder: Some(Unwinder { unwinding: false }), destroyed: false } @@ -58,7 +58,7 @@ impl LocalServices { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(ptr::null(), None), - logger: Logger, + logger: StdErrLogger, unwinder: None, destroyed: false } @@ -184,6 +184,14 @@ pub unsafe fn unsafe_borrow_local_services() -> *mut LocalServices { } } +pub unsafe fn unsafe_try_borrow_local_services() -> Option<*mut LocalServices> { + if local_sched::exists() { + Some(unsafe_borrow_local_services()) + } else { + None + } +} + #[cfg(test)] mod test { use rt::test::*; @@ -231,4 +239,12 @@ mod test { let _ = r.next(); } } + + #[test] + fn logging() { + do run_in_newsched_task() { + info!("here i am. logging in a newsched task"); + } + } } + diff --git a/src/libcore/rt/logging.rs b/src/libcore/rt/logging.rs new file mode 100644 index 0000000000000..4ed09fd829f22 --- /dev/null +++ b/src/libcore/rt/logging.rs @@ -0,0 +1,38 @@ +// 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. + +use either::*; + +pub trait Logger { + fn log(&mut self, msg: Either<~str, &'static str>); +} + +pub struct StdErrLogger; + +impl Logger for StdErrLogger { + fn log(&mut self, msg: Either<~str, &'static str>) { + use io::{Writer, WriterUtil}; + + let s: &str = match msg { + Left(ref s) => { + let s: &str = *s; + s + } + Right(ref s) => { + let s: &str = *s; + s + } + }; + let dbg = ::libc::STDERR_FILENO as ::io::fd_t; + dbg.write_str(s); + dbg.write_str("\n"); + dbg.flush(); + } +} \ No newline at end of file diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index b5fba51ca7f4d..c7cdb277247cb 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -58,6 +58,9 @@ pub mod env; /// The local, managed heap mod local_heap; +/// The Logger trait and implementations +pub mod logging; + /// Tools for testing the runtime #[cfg(test)] pub mod test; From 272c3c2cfb1008ffc4437599ce94aad59e0b72b7 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 3 May 2013 13:26:41 -0700 Subject: [PATCH 018/248] Tidy --- src/libcore/logging.rs | 1 - src/libcore/rt/io/net/tcp.rs | 6 +++--- src/libcore/rt/local_sched.rs | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/libcore/logging.rs b/src/libcore/logging.rs index 4ecd72ebd0c00..70195afb20a84 100644 --- a/src/libcore/logging.rs +++ b/src/libcore/logging.rs @@ -64,7 +64,6 @@ pub fn log_type(level: u32, object: &T) { } fn newsched_log_str(msg: ~str) { - unsafe { match rt::local_services::unsafe_try_borrow_local_services() { Some(local) => { diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index a669509a48a35..49acc53f4f125 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -56,7 +56,7 @@ impl Reader for TcpStream { match bytes_read { Ok(read) => Some(read), Err(_) => { - abort!("TODO"); + abort!("XXX"); } } } @@ -70,7 +70,7 @@ impl Writer for TcpStream { match res { Ok(_) => (), Err(_) => { - abort!("TODO"); + abort!("XXX"); } } } @@ -107,7 +107,7 @@ impl Listener for TcpListener { Some(TcpStream::new(s)) } Err(_) => { - abort!("TODO"); + abort!("XXX"); } } } diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index ef159d9fe5dde..44dbd55373fc9 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -63,7 +63,7 @@ pub fn borrow(f: &fn(&mut Scheduler)) { unsafe { let unsafe_sched = cast::transmute_mut_region(&mut *sched); let sched = Cell(sched); - + do (|| { f(unsafe_sched); }).finally { From 936fce551587fd5584722022252f489c88be292c Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 3 May 2013 15:48:18 -0700 Subject: [PATCH 019/248] Warnings --- src/libcore/rt/uv/net.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index b22adafdf2d9e..550acd8aee400 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -10,7 +10,6 @@ use prelude::*; use libc::{size_t, ssize_t, c_int, c_void}; -use util::ignore; use rt::uv::uvll; use rt::uv::uvll::*; use rt::uv::{AllocCallback, ConnectionCallback, ReadCallback}; @@ -19,6 +18,7 @@ use super::{Loop, Watcher, Request, UvError, Buf, NativeHandle, NullCallback, use super::super::io::net::ip::{IpAddr, Ipv4, Ipv6}; use rt::uv::last_uv_error; +#[cfg(test)] use util::ignore; #[cfg(test)] use cell::Cell; #[cfg(test)] use unstable::run_in_bare_thread; #[cfg(test)] use super::super::thread::Thread; From 40a9de5ebc8bea4d0a42a89e657a35a5b07d4042 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 3 May 2013 16:58:20 -0700 Subject: [PATCH 020/248] core::rt: Add a very simple ref counted pointer --- src/libcore/rt/mod.rs | 3 + src/libcore/rt/rc.rs | 143 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+) create mode 100644 src/libcore/rt/rc.rs diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index c7cdb277247cb..ce3fb71ef2c4e 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -65,6 +65,9 @@ pub mod logging; #[cfg(test)] pub mod test; +/// Reference counting +pub mod rc; + /// Set up a default runtime configuration, given compiler-supplied arguments. /// /// This is invoked by the `start` _language item_ (unstable::lang) to diff --git a/src/libcore/rt/rc.rs b/src/libcore/rt/rc.rs new file mode 100644 index 0000000000000..2ee254466e4b0 --- /dev/null +++ b/src/libcore/rt/rc.rs @@ -0,0 +1,143 @@ +// 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. + +//! An owned, task-local, reference counted type +//! +//! # Safety note +//! +//! XXX There is currently no type-system mechanism for enforcing that +//! reference counted types are both allocated on the exchange heap +//! and also non-sendable +//! +//! This doesn't prevent borrowing multiple aliasable mutable pointers + +use ops::Drop; +use clone::Clone; +use libc::c_void; +use sys; +use cast; + +pub struct RC { + p: *c_void // ~(uint, T) +} + +impl RC { + pub fn new(val: T) -> RC { + unsafe { + let v = ~(1, val); + let p: *c_void = cast::transmute(v); + RC { p: p } + } + } + + fn get_mut_state(&mut self) -> *mut (uint, T) { + unsafe { + let p: &mut ~(uint, T) = cast::transmute(&mut self.p); + let p: *mut (uint, T) = &mut **p; + return p; + } + } + + fn get_state(&self) -> *(uint, T) { + unsafe { + let p: &~(uint, T) = cast::transmute(&self.p); + let p: *(uint, T) = &**p; + return p; + } + } + + pub fn unsafe_borrow_mut(&mut self) -> *mut T { + unsafe { + match *self.get_mut_state() { + (_, ref mut p) => { + let p: *mut T = p; + return p; + } + } + } + } + + pub fn refcount(&self) -> uint { + unsafe { + match *self.get_state() { + (count, _) => count + } + } + } +} + +#[unsafe_destructor] +impl Drop for RC { + fn finalize(&self) { + assert!(self.refcount() > 0); + + unsafe { + // XXX: Mutable finalizer + let this: &mut RC = cast::transmute_mut(self); + + match *this.get_mut_state() { + (ref mut count, _) => { + *count = *count - 1 + } + } + + if this.refcount() == 0 { + let _: ~(uint, T) = cast::transmute(this.p); + } + } + } +} + +impl Clone for RC { + fn clone(&self) -> RC { + unsafe { + // XXX: Mutable clone + let this: &mut RC = cast::transmute_mut(self); + + match *this.get_mut_state() { + (ref mut count, _) => { + *count = *count + 1; + } + } + } + + RC { p: self.p } + } +} + +#[cfg(test)] +mod test { + use super::RC; + + #[test] + fn smoke_test() { + unsafe { + let mut v1 = RC::new(100); + assert!(*v1.unsafe_borrow_mut() == 100); + assert!(v1.refcount() == 1); + + let mut v2 = v1.clone(); + assert!(*v2.unsafe_borrow_mut() == 100); + assert!(v2.refcount() == 2); + + *v2.unsafe_borrow_mut() = 200; + assert!(*v2.unsafe_borrow_mut() == 200); + assert!(*v1.unsafe_borrow_mut() == 200); + + let v3 = v2.clone(); + assert!(v3.refcount() == 3); + { + let _v1 = v1; + let _v2 = v2; + } + assert!(v3.refcount() == 1); + } + } +} From 414f3c7d252fcd54562c0c8a85499d7d07f5e612 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 4 May 2013 17:30:31 -0700 Subject: [PATCH 021/248] core::rt: Add a simple channel type for passing buffered messages between Scheduler and Task Called 'Tube' for lack of anything better. --- src/libcore/logging.rs | 3 +- src/libcore/rt/mod.rs | 6 +- src/libcore/rt/tube.rs | 182 +++++++++++++++++++++++++++++++++++++++++ src/libcore/sys.rs | 29 +++++-- 4 files changed, 212 insertions(+), 8 deletions(-) create mode 100644 src/libcore/rt/tube.rs diff --git a/src/libcore/logging.rs b/src/libcore/logging.rs index 70195afb20a84..4308d22548f43 100644 --- a/src/libcore/logging.rs +++ b/src/libcore/logging.rs @@ -19,6 +19,7 @@ use libc; use repr; use vec; use cast; +use str; /// Turns on logging to stdout globally pub fn console_on() { @@ -57,7 +58,7 @@ pub fn log_type(level: u32, object: &T) { } _ => { // XXX: Bad allocation - let msg = bytes.to_str(); + let msg = str::from_bytes(bytes); newsched_log_str(msg); } } diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index ce3fb71ef2c4e..b2ba6d7d3c407 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -18,7 +18,7 @@ use libc::c_char; mod sched; /// Thread-local access to the current Scheduler -mod local_sched; +pub mod local_sched; /// Synchronous I/O #[path = "io/mod.rs"] @@ -68,6 +68,10 @@ pub mod test; /// Reference counting pub mod rc; +/// A simple single-threaded channel type for passing buffered data between +/// scheduler and task context +pub mod tube; + /// Set up a default runtime configuration, given compiler-supplied arguments. /// /// This is invoked by the `start` _language item_ (unstable::lang) to diff --git a/src/libcore/rt/tube.rs b/src/libcore/rt/tube.rs new file mode 100644 index 0000000000000..ef376199fcbdc --- /dev/null +++ b/src/libcore/rt/tube.rs @@ -0,0 +1,182 @@ +// 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. + +//! A very simple unsynchronized channel type for sending buffered data from +//! scheduler context to task context. +//! +//! XXX: This would be safer to use if split into two types like Port/Chan + +use option::*; +use clone::Clone; +use super::rc::RC; +use rt::sched::Task; +use rt::{context, TaskContext, SchedulerContext}; +use rt::local_sched; + +struct TubeState { + blocked_task: Option<~Task>, + buf: ~[T] +} + +pub struct Tube { + p: RC> +} + +impl Tube { + pub fn new() -> Tube { + Tube { + p: RC::new(TubeState { + blocked_task: None, + buf: ~[] + }) + } + } + + pub fn send(&mut self, val: T) { + rtdebug!("tube send"); + assert!(context() == SchedulerContext); + + unsafe { + let state = self.p.unsafe_borrow_mut(); + (*state).buf.push(val); + + if (*state).blocked_task.is_some() { + // There's a waiting task. Wake it up + rtdebug!("waking blocked tube"); + let task = (*state).blocked_task.swap_unwrap(); + let sched = local_sched::take(); + sched.resume_task_immediately(task); + } + } + } + + pub fn recv(&mut self) -> T { + assert!(context() == TaskContext); + + unsafe { + let state = self.p.unsafe_borrow_mut(); + if !(*state).buf.is_empty() { + return (*state).buf.shift(); + } else { + // Block and wait for the next message + rtdebug!("blocking on tube recv"); + assert!(self.p.refcount() > 1); // There better be somebody to wake us up + assert!((*state).blocked_task.is_none()); + let sched = local_sched::take(); + do sched.deschedule_running_task_and_then |task| { + (*state).blocked_task = Some(task); + } + rtdebug!("waking after tube recv"); + let buf = &mut (*state).buf; + assert!(!buf.is_empty()); + return buf.shift(); + } + } + } +} + +impl Clone for Tube { + fn clone(&self) -> Tube { + Tube { p: self.p.clone() } + } +} + +#[cfg(test)] +mod test { + use int; + use cell::Cell; + use rt::local_sched; + use rt::test::*; + use rt::rtio::EventLoop; + use super::*; + + #[test] + fn simple_test() { + do run_in_newsched_task { + let mut tube: Tube = Tube::new(); + let tube_clone = tube.clone(); + let tube_clone_cell = Cell(tube_clone); + let sched = local_sched::take(); + do sched.deschedule_running_task_and_then |task| { + let mut tube_clone = tube_clone_cell.take(); + tube_clone.send(1); + let sched = local_sched::take(); + sched.resume_task_immediately(task); + } + + assert!(tube.recv() == 1); + } + } + + #[test] + fn blocking_test() { + do run_in_newsched_task { + let mut tube: Tube = Tube::new(); + let tube_clone = tube.clone(); + let tube_clone = Cell(Cell(Cell(tube_clone))); + let sched = local_sched::take(); + do sched.deschedule_running_task_and_then |task| { + let tube_clone = tube_clone.take(); + do local_sched::borrow |sched| { + let tube_clone = tube_clone.take(); + do sched.event_loop.callback { + let mut tube_clone = tube_clone.take(); + // The task should be blocked on this now and + // sending will wake it up. + tube_clone.send(1); + } + } + let sched = local_sched::take(); + sched.resume_task_immediately(task); + } + + assert!(tube.recv() == 1); + } + } + + #[test] + fn many_blocking_test() { + static MAX: int = 100; + + do run_in_newsched_task { + let mut tube: Tube = Tube::new(); + let tube_clone = tube.clone(); + let tube_clone = Cell(tube_clone); + let sched = local_sched::take(); + do sched.deschedule_running_task_and_then |task| { + callback_send(tube_clone.take(), 0); + + fn callback_send(tube: Tube, i: int) { + if i == 100 { return; } + + let tube = Cell(Cell(tube)); + do local_sched::borrow |sched| { + let tube = tube.take(); + do sched.event_loop.callback { + let mut tube = tube.take(); + // The task should be blocked on this now and + // sending will wake it up. + tube.send(i); + callback_send(tube, i + 1); + } + } + } + + let sched = local_sched::take(); + sched.resume_task_immediately(task); + } + + for int::range(0, MAX) |i| { + let j = tube.recv(); + assert!(j == i); + } + } + } +} diff --git a/src/libcore/sys.rs b/src/libcore/sys.rs index a27b6fe615f33..50a739ec67df7 100644 --- a/src/libcore/sys.rs +++ b/src/libcore/sys.rs @@ -202,10 +202,12 @@ impl FailWithCause for &'static str { // FIXME #4427: Temporary until rt::rt_fail_ goes away pub fn begin_unwind_(msg: *c_char, file: *c_char, line: size_t) -> ! { - use rt::{context, OldTaskContext}; - use rt::local_services::unsafe_borrow_local_services; + use option::Option; + use rt::{context, OldTaskContext, TaskContext}; + use rt::local_services::{unsafe_borrow_local_services, Unwinder}; - match context() { + let context = context(); + match context { OldTaskContext => { unsafe { gc::cleanup_stack_for_failure(); @@ -214,11 +216,26 @@ pub fn begin_unwind_(msg: *c_char, file: *c_char, line: size_t) -> ! { } } _ => { - // XXX: Need to print the failure message - gc::cleanup_stack_for_failure(); unsafe { + // XXX: Bad re-allocations. fail! needs some refactoring + let msg = str::raw::from_c_str(msg); + let file = str::raw::from_c_str(file); + + let outmsg = fmt!("%s at line %i of file %s", msg, line as int, file); + + // XXX: Logging doesn't work correctly in non-task context because it + // invokes the local heap + if context == TaskContext { + error!(outmsg); + } else { + rtdebug!("%s", outmsg); + } + + gc::cleanup_stack_for_failure(); + let local_services = unsafe_borrow_local_services(); - match (*local_services).unwinder { + let unwinder: &mut Option = &mut (*local_services).unwinder; + match *unwinder { Some(ref mut unwinder) => unwinder.begin_unwind(), None => abort!("failure without unwinder. aborting process") } From d234cf7e440db0abbf867997c45d993a542ee640 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 6 May 2013 14:28:16 -0700 Subject: [PATCH 022/248] core::rt: Make TCP servers work --- src/libcore/rt/io/net/tcp.rs | 86 ++++++++++++++++++++++++++++++++++-- src/libcore/rt/test.rs | 40 +++++++++++++++++ src/libcore/rt/uv/uvio.rs | 69 ++++++++++++++++------------- 3 files changed, 161 insertions(+), 34 deletions(-) diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 49acc53f4f125..90f99f8df8b87 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -79,7 +79,7 @@ impl Writer for TcpStream { } pub struct TcpListener { - rtlistener: ~RtioTcpListenerObject + rtlistener: ~RtioTcpListenerObject, } impl TcpListener { @@ -116,6 +116,8 @@ impl Listener for TcpListener { #[cfg(test)] mod test { use super::*; + use int; + use cell::Cell; use rt::test::*; use rt::io::net::ip::Ipv4; use rt::io::*; @@ -172,11 +174,11 @@ mod test { } } - #[test] #[ignore] + #[test] fn multiple_connect_serial() { do run_in_newsched_task { let addr = next_test_ip4(); - let max = 100; + let max = 10; do spawntask_immediately { let mut listener = TcpListener::bind(addr); @@ -197,4 +199,82 @@ mod test { } } + #[test] + fn multiple_connect_interleaved_greedy_schedule() { + do run_in_newsched_task { + let addr = next_test_ip4(); + static MAX: int = 10; + + do spawntask_immediately { + let mut listener = TcpListener::bind(addr); + for int::range(0, MAX) |i| { + let stream = Cell(listener.accept()); + rtdebug!("accepted"); + // Start another task to handle the connection + do spawntask_immediately { + let mut stream = stream.take(); + let mut buf = [0]; + stream.read(buf); + assert!(buf[0] == i as u8); + rtdebug!("read"); + } + } + } + + connect(0, addr); + + fn connect(i: int, addr: IpAddr) { + if i == MAX { return } + + do spawntask_immediately { + rtdebug!("connecting"); + let mut stream = TcpStream::connect(addr); + // Connect again before writing + connect(i + 1, addr); + rtdebug!("writing"); + stream.write([i as u8]); + } + } + } + } + + #[test] + fn multiple_connect_interleaved_lazy_schedule() { + do run_in_newsched_task { + let addr = next_test_ip4(); + static MAX: int = 10; + + do spawntask_immediately { + let mut listener = TcpListener::bind(addr); + for int::range(0, MAX) |_| { + let stream = Cell(listener.accept()); + rtdebug!("accepted"); + // Start another task to handle the connection + do spawntask_later { + let mut stream = stream.take(); + let mut buf = [0]; + stream.read(buf); + assert!(buf[0] == 99); + rtdebug!("read"); + } + } + } + + connect(0, addr); + + fn connect(i: int, addr: IpAddr) { + if i == MAX { return } + + do spawntask_later { + rtdebug!("connecting"); + let mut stream = TcpStream::connect(addr); + // Connect again before writing + connect(i + 1, addr); + rtdebug!("writing"); + stream.write([99]); + } + } + } + } + } diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index 185443563fc9b..8d0ae0caf4d62 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -64,6 +64,46 @@ pub fn spawntask_immediately(f: ~fn()) { } } +/// Create a new task and run it right now. Aborts on failure +pub fn spawntask_later(f: ~fn()) { + use super::sched::*; + + let mut sched = local_sched::take(); + let task = ~Task::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f); + + sched.task_queue.push_front(task); + local_sched::put(sched); +} + +/// Spawn a task and either run it immediately or run it later +pub fn spawntask_random(f: ~fn()) { + use super::sched::*; + use rand::{Rand, rng}; + + let mut rng = rng(); + let run_now: bool = Rand::rand(&mut rng); + + let mut sched = local_sched::take(); + let task = ~Task::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f); + + if run_now { + do sched.switch_running_tasks_and_then(task) |task| { + let task = Cell(task); + do local_sched::borrow |sched| { + sched.task_queue.push_front(task.take()); + } + } + } else { + sched.task_queue.push_front(task); + local_sched::put(sched); + } +} + + /// Spawn a task and wait for it to finish, returning whether it completed successfully or failed pub fn spawntask_try(f: ~fn()) -> Result<(), ()> { use cell::Cell; diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 0c52bca0dc83a..2218c0734fbfb 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -21,6 +21,7 @@ use rt::uv::idle::IdleWatcher; use rt::rtio::*; use rt::sched::{Scheduler, local_sched}; use rt::io::{standard_error, OtherIoError}; +use rt::tube::Tube; #[cfg(test)] use uint; #[cfg(test)] use unstable::run_in_bare_thread; @@ -149,7 +150,7 @@ impl IoFactory for UvIoFactory { fn tcp_bind(&mut self, addr: IpAddr) -> Result<~RtioTcpListenerObject, IoError> { let mut watcher = TcpWatcher::new(self.uv_loop()); match watcher.bind(addr) { - Ok(_) => Ok(~UvTcpListener { watcher: watcher }), + Ok(_) => Ok(~UvTcpListener::new(watcher)), Err(uverr) => { // XXX: Should we wait until close completes? watcher.as_stream().close(||()); @@ -161,10 +162,20 @@ impl IoFactory for UvIoFactory { // FIXME #6090: Prefer newtype structs but Drop doesn't work pub struct UvTcpListener { - watcher: TcpWatcher + watcher: TcpWatcher, + listening: bool, + incoming_streams: Tube> } impl UvTcpListener { + fn new(watcher: TcpWatcher) -> UvTcpListener { + UvTcpListener { + watcher: watcher, + listening: false, + incoming_streams: Tube::new() + } + } + fn watcher(&self) -> TcpWatcher { self.watcher } } @@ -179,41 +190,37 @@ impl RtioTcpListener for UvTcpListener { fn accept(&mut self) -> Result<~RtioTcpStreamObject, IoError> { rtdebug!("entering listen"); - let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; - let server_tcp_watcher = self.watcher(); + if self.listening { + return self.incoming_streams.recv(); + } - let scheduler = local_sched::take(); - assert!(scheduler.in_task_context()); + self.listening = true; - do scheduler.deschedule_running_task_and_then |task| { - let task_cell = Cell(task); - let mut server_tcp_watcher = server_tcp_watcher; - do server_tcp_watcher.listen |server_stream_watcher, status| { - let maybe_stream = if status.is_none() { - let mut server_stream_watcher = server_stream_watcher; - let mut loop_ = server_stream_watcher.event_loop(); - let mut client_tcp_watcher = TcpWatcher::new(&mut loop_); - let client_tcp_watcher = client_tcp_watcher.as_stream(); - // XXX: Need's to be surfaced in interface - server_stream_watcher.accept(client_tcp_watcher); - Ok(~UvTcpStream { watcher: client_tcp_watcher }) - } else { - Err(standard_error(OtherIoError)) - }; - - unsafe { (*result_cell_ptr).put_back(maybe_stream); } + let server_tcp_watcher = self.watcher(); + let incoming_streams_cell = Cell(self.incoming_streams.clone()); + + let incoming_streams_cell = Cell(incoming_streams_cell.take()); + let mut server_tcp_watcher = server_tcp_watcher; + do server_tcp_watcher.listen |server_stream_watcher, status| { + let maybe_stream = if status.is_none() { + let mut server_stream_watcher = server_stream_watcher; + let mut loop_ = server_stream_watcher.event_loop(); + let mut client_tcp_watcher = TcpWatcher::new(&mut loop_); + let client_tcp_watcher = client_tcp_watcher.as_stream(); + // XXX: Need's to be surfaced in interface + server_stream_watcher.accept(client_tcp_watcher); + Ok(~UvTcpStream { watcher: client_tcp_watcher }) + } else { + Err(standard_error(OtherIoError)) + }; - rtdebug!("resuming task from listen"); - // Context switch - let scheduler = local_sched::take(); - scheduler.resume_task_immediately(task_cell.take()); - } + let mut incoming_streams = incoming_streams_cell.take(); + incoming_streams.send(maybe_stream); + incoming_streams_cell.put_back(incoming_streams); } - assert!(!result_cell.is_empty()); - return result_cell.take(); + return self.incoming_streams.recv(); } } From 101aaa38616411b7fcef0599a3e514cea7df3a87 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 6 May 2013 18:53:45 -0700 Subject: [PATCH 023/248] core::rt: 0 is a valid TLS key --- src/libcore/rt/local_sched.rs | 2 +- src/rt/rust_builtin.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index 44dbd55373fc9..e96a2e8de2d65 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -119,7 +119,7 @@ fn maybe_tls_key() -> Option { // another thread. I think this is fine since the only action // they could take if it was initialized would be to check the // thread-local value and see that it's not set. - if key != 0 { + if key != -1 { return Some(key); } else { return None; diff --git a/src/rt/rust_builtin.cpp b/src/rt/rust_builtin.cpp index 903289281222b..39a6f5bfd1b7b 100644 --- a/src/rt/rust_builtin.cpp +++ b/src/rt/rust_builtin.cpp @@ -830,9 +830,9 @@ rust_get_rt_env() { } #ifndef _WIN32 -pthread_key_t sched_key; +pthread_key_t sched_key = -1; #else -DWORD sched_key; +DWORD sched_key = -1; #endif extern "C" void* From 4472a50ceb5b6f0337371226d3ef7cc3c30ee04c Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 6 May 2013 23:10:59 -0700 Subject: [PATCH 024/248] rtdebug off --- src/libcore/macros.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index c4f0384f71ed6..b2e94f327c86e 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -11,7 +11,7 @@ #[macro_escape]; // Some basic logging -macro_rules! rtdebug ( +macro_rules! rtdebug_ ( ($( $arg:expr),+) => ( { dumb_println(fmt!( $($arg),+ )); @@ -26,7 +26,7 @@ macro_rules! rtdebug ( ) // An alternate version with no output, for turning off logging -macro_rules! rtdebug_ ( +macro_rules! rtdebug ( ($( $arg:expr),+) => ( $(let _ = $arg)*; ) ) From 52f015acebd7b1fa4fb040aa40d94416f053de24 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Tue, 7 May 2013 15:57:15 -0700 Subject: [PATCH 025/248] core: Cleanup warnings --- src/libcore/macros.rs | 8 +- src/libcore/rt/local_sched.rs | 8 +- src/libcore/rt/local_services.rs | 20 ++-- src/libcore/rt/rc.rs | 1 - src/libcore/rt/uv/idle.rs | 2 +- src/libcore/rt/uv/net.rs | 187 ++++++++++++++++--------------- 6 files changed, 117 insertions(+), 109 deletions(-) diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index b2e94f327c86e..fda48b6ffb7d9 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -42,6 +42,12 @@ macro_rules! abort( ($( $msg:expr),+) => ( { rtdebug!($($msg),+); - unsafe { ::libc::abort(); } + do_abort(); + + // NB: This is in a fn to avoid putting the `unsafe` block in a macro, + // which causes spurious 'unnecessary unsafe block' warnings. + fn do_abort() -> ! { + unsafe { ::libc::abort(); } + } } ) ) diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index e96a2e8de2d65..eb35eb7881d39 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -91,11 +91,9 @@ pub unsafe fn unsafe_borrow() -> *mut Scheduler { } pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { - unsafe { - let sched = unsafe_borrow(); - let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); - return io; - } + let sched = unsafe_borrow(); + let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); + return io; } fn tls_key() -> tls::Key { diff --git a/src/libcore/rt/local_services.rs b/src/libcore/rt/local_services.rs index b8bf6e067801f..673b2a6c2bc41 100644 --- a/src/libcore/rt/local_services.rs +++ b/src/libcore/rt/local_services.rs @@ -23,7 +23,7 @@ use libc::{c_void, uintptr_t}; use cast::transmute; use super::sched::local_sched; use super::local_heap::LocalHeap; -use rt::logging::{Logger, StdErrLogger}; +use rt::logging::StdErrLogger; pub struct LocalServices { heap: LocalHeap, @@ -170,16 +170,14 @@ pub fn borrow_local_services(f: &fn(&mut LocalServices)) { } pub unsafe fn unsafe_borrow_local_services() -> *mut LocalServices { - unsafe { - match (*local_sched::unsafe_borrow()).current_task { - Some(~ref mut task) => { - let s: *mut LocalServices = &mut task.local_services; - return s; - } - None => { - // Don't fail. Infinite recursion - abort!("no local services for schedulers yet") - } + match (*local_sched::unsafe_borrow()).current_task { + Some(~ref mut task) => { + let s: *mut LocalServices = &mut task.local_services; + return s; + } + None => { + // Don't fail. Infinite recursion + abort!("no local services for schedulers yet") } } } diff --git a/src/libcore/rt/rc.rs b/src/libcore/rt/rc.rs index 2ee254466e4b0..1c0c8c14fdfa6 100644 --- a/src/libcore/rt/rc.rs +++ b/src/libcore/rt/rc.rs @@ -21,7 +21,6 @@ use ops::Drop; use clone::Clone; use libc::c_void; -use sys; use cast; pub struct RC { diff --git a/src/libcore/rt/uv/idle.rs b/src/libcore/rt/uv/idle.rs index fe1ce8697bf9e..518429eeaff05 100644 --- a/src/libcore/rt/uv/idle.rs +++ b/src/libcore/rt/uv/idle.rs @@ -9,7 +9,7 @@ // except according to those terms. use libc::c_int; -use option::{Some, None}; +use option::Some; use rt::uv::uvll; use rt::uv::{Watcher, Loop, NativeHandle, IdleCallback}; use rt::uv::status_to_maybe_uv_error; diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index 550acd8aee400..fede71ec67931 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -13,17 +13,11 @@ use libc::{size_t, ssize_t, c_int, c_void}; use rt::uv::uvll; use rt::uv::uvll::*; use rt::uv::{AllocCallback, ConnectionCallback, ReadCallback}; -use super::{Loop, Watcher, Request, UvError, Buf, NativeHandle, NullCallback, - status_to_maybe_uv_error, vec_to_uv_buf, vec_from_uv_buf, slice_to_uv_buf}; -use super::super::io::net::ip::{IpAddr, Ipv4, Ipv6}; +use rt::uv::{Loop, Watcher, Request, UvError, Buf, NativeHandle, NullCallback, + status_to_maybe_uv_error}; +use rt::io::net::ip::{IpAddr, Ipv4, Ipv6}; use rt::uv::last_uv_error; -#[cfg(test)] use util::ignore; -#[cfg(test)] use cell::Cell; -#[cfg(test)] use unstable::run_in_bare_thread; -#[cfg(test)] use super::super::thread::Thread; -#[cfg(test)] use super::super::test::*; - fn ip4_as_uv_ip4(addr: IpAddr, f: &fn(*sockaddr_in) -> T) -> T { match addr { Ipv4(a, b, c, d, p) => { @@ -334,96 +328,109 @@ impl NativeHandle<*uvll::uv_write_t> for WriteRequest { } -#[test] -fn connect_close() { - do run_in_bare_thread() { - let mut loop_ = Loop::new(); - let mut tcp_watcher = { TcpWatcher::new(&mut loop_) }; - // Connect to a port where nobody is listening - let addr = next_test_ip4(); - do tcp_watcher.connect(addr) |stream_watcher, status| { - rtdebug!("tcp_watcher.connect!"); - assert!(status.is_some()); - assert!(status.get().name() == ~"ECONNREFUSED"); - stream_watcher.close(||()); +#[cfg(test)] +mod test { + use super::*; + use util::ignore; + use cell::Cell; + use vec; + use unstable::run_in_bare_thread; + use rt::thread::Thread; + use rt::test::*; + use rt::uv::{Loop, AllocCallback}; + use rt::uv::{vec_from_uv_buf, vec_to_uv_buf, slice_to_uv_buf}; + + #[test] + fn connect_close() { + do run_in_bare_thread() { + let mut loop_ = Loop::new(); + let mut tcp_watcher = { TcpWatcher::new(&mut loop_) }; + // Connect to a port where nobody is listening + let addr = next_test_ip4(); + do tcp_watcher.connect(addr) |stream_watcher, status| { + rtdebug!("tcp_watcher.connect!"); + assert!(status.is_some()); + assert!(status.get().name() == ~"ECONNREFUSED"); + stream_watcher.close(||()); + } + loop_.run(); + loop_.close(); } - loop_.run(); - loop_.close(); } -} -#[test] -fn listen() { - do run_in_bare_thread() { - static MAX: int = 10; - let mut loop_ = Loop::new(); - let mut server_tcp_watcher = { TcpWatcher::new(&mut loop_) }; - let addr = next_test_ip4(); - server_tcp_watcher.bind(addr); - let loop_ = loop_; - rtdebug!("listening"); - do server_tcp_watcher.listen |server_stream_watcher, status| { - rtdebug!("listened!"); - assert!(status.is_none()); - let mut server_stream_watcher = server_stream_watcher; - let mut loop_ = loop_; - let mut client_tcp_watcher = TcpWatcher::new(&mut loop_); - let mut client_tcp_watcher = client_tcp_watcher.as_stream(); - server_stream_watcher.accept(client_tcp_watcher); - let count_cell = Cell(0); - let server_stream_watcher = server_stream_watcher; - rtdebug!("starting read"); - let alloc: AllocCallback = |size| { - vec_to_uv_buf(vec::from_elem(size, 0)) - }; - do client_tcp_watcher.read_start(alloc) - |stream_watcher, nread, buf, status| { - - rtdebug!("i'm reading!"); - let buf = vec_from_uv_buf(buf); - let mut count = count_cell.take(); - if status.is_none() { - rtdebug!("got %d bytes", nread); - let buf = buf.unwrap(); - for buf.slice(0, nread as uint).each |byte| { - assert!(*byte == count as u8); - rtdebug!("%u", *byte as uint); - count += 1; - } - } else { - assert!(count == MAX); - do stream_watcher.close { - server_stream_watcher.close(||()); + #[test] + fn listen() { + do run_in_bare_thread() { + static MAX: int = 10; + let mut loop_ = Loop::new(); + let mut server_tcp_watcher = { TcpWatcher::new(&mut loop_) }; + let addr = next_test_ip4(); + server_tcp_watcher.bind(addr); + let loop_ = loop_; + rtdebug!("listening"); + do server_tcp_watcher.listen |server_stream_watcher, status| { + rtdebug!("listened!"); + assert!(status.is_none()); + let mut server_stream_watcher = server_stream_watcher; + let mut loop_ = loop_; + let mut client_tcp_watcher = TcpWatcher::new(&mut loop_); + let mut client_tcp_watcher = client_tcp_watcher.as_stream(); + server_stream_watcher.accept(client_tcp_watcher); + let count_cell = Cell(0); + let server_stream_watcher = server_stream_watcher; + rtdebug!("starting read"); + let alloc: AllocCallback = |size| { + vec_to_uv_buf(vec::from_elem(size, 0)) + }; + do client_tcp_watcher.read_start(alloc) + |stream_watcher, nread, buf, status| { + + rtdebug!("i'm reading!"); + let buf = vec_from_uv_buf(buf); + let mut count = count_cell.take(); + if status.is_none() { + rtdebug!("got %d bytes", nread); + let buf = buf.unwrap(); + for buf.slice(0, nread as uint).each |byte| { + assert!(*byte == count as u8); + rtdebug!("%u", *byte as uint); + count += 1; + } + } else { + assert!(count == MAX); + do stream_watcher.close { + server_stream_watcher.close(||()); + } } + count_cell.put_back(count); } - count_cell.put_back(count); } - } - let _client_thread = do Thread::start { - rtdebug!("starting client thread"); - let mut loop_ = Loop::new(); - let mut tcp_watcher = { TcpWatcher::new(&mut loop_) }; - do tcp_watcher.connect(addr) |stream_watcher, status| { - rtdebug!("connecting"); - assert!(status.is_none()); - let mut stream_watcher = stream_watcher; - let msg = ~[0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9]; - let buf = slice_to_uv_buf(msg); - let msg_cell = Cell(msg); - do stream_watcher.write(buf) |stream_watcher, status| { - rtdebug!("writing"); + let _client_thread = do Thread::start { + rtdebug!("starting client thread"); + let mut loop_ = Loop::new(); + let mut tcp_watcher = { TcpWatcher::new(&mut loop_) }; + do tcp_watcher.connect(addr) |stream_watcher, status| { + rtdebug!("connecting"); assert!(status.is_none()); - let msg_cell = Cell(msg_cell.take()); - stream_watcher.close(||ignore(msg_cell.take())); + let mut stream_watcher = stream_watcher; + let msg = ~[0, 1, 2, 3, 4, 5, 6 ,7 ,8, 9]; + let buf = slice_to_uv_buf(msg); + let msg_cell = Cell(msg); + do stream_watcher.write(buf) |stream_watcher, status| { + rtdebug!("writing"); + assert!(status.is_none()); + let msg_cell = Cell(msg_cell.take()); + stream_watcher.close(||ignore(msg_cell.take())); + } } - } + loop_.run(); + loop_.close(); + }; + + let mut loop_ = loop_; loop_.run(); loop_.close(); - }; - - let mut loop_ = loop_; - loop_.run(); - loop_.close(); + } } -} +} \ No newline at end of file From 329dfcaba0af7af736ac7e853be45783ad7ac4b0 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Tue, 7 May 2013 15:54:06 -0700 Subject: [PATCH 026/248] core: Move unstable::exchange_alloc to rt::global_heap --- src/libcore/os.rs | 2 +- .../{unstable/exchange_alloc.rs => rt/global_heap.rs} | 0 src/libcore/rt/mod.rs | 5 ++++- src/libcore/unstable.rs | 2 -- src/libcore/unstable/lang.rs | 6 +++--- 5 files changed, 8 insertions(+), 7 deletions(-) rename src/libcore/{unstable/exchange_alloc.rs => rt/global_heap.rs} (100%) diff --git a/src/libcore/os.rs b/src/libcore/os.rs index d983377245c4e..022204fa69b62 100644 --- a/src/libcore/os.rs +++ b/src/libcore/os.rs @@ -724,7 +724,7 @@ pub fn list_dir(p: &Path) -> ~[~str] { use os::win32::{ as_utf16_p }; - use unstable::exchange_alloc::{malloc_raw, free_raw}; + use rt::global_heap::{malloc_raw, free_raw}; #[nolink] extern { unsafe fn rust_list_dir_wfd_size() -> libc::size_t; diff --git a/src/libcore/unstable/exchange_alloc.rs b/src/libcore/rt/global_heap.rs similarity index 100% rename from src/libcore/unstable/exchange_alloc.rs rename to src/libcore/rt/global_heap.rs diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index b2ba6d7d3c407..55f777ebf9ac7 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -14,7 +14,10 @@ use libc::c_char; -/// The Scheduler and Task types +/// The global (exchange) heap. +pub mod global_heap; + +/// The Scheduler and Task types. mod sched; /// Thread-local access to the current Scheduler diff --git a/src/libcore/unstable.rs b/src/libcore/unstable.rs index 25e4d07b01da1..9530d7ab50d64 100644 --- a/src/libcore/unstable.rs +++ b/src/libcore/unstable.rs @@ -26,8 +26,6 @@ pub mod global; pub mod finally; #[path = "unstable/weak_task.rs"] pub mod weak_task; -#[path = "unstable/exchange_alloc.rs"] -pub mod exchange_alloc; #[path = "unstable/intrinsics.rs"] pub mod intrinsics; #[path = "unstable/simd.rs"] diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index 8153c2d43d998..e521fb59fbe5f 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -16,12 +16,12 @@ use libc::{c_char, c_uchar, c_void, size_t, uintptr_t, c_int, STDERR_FILENO}; use managed::raw::BoxRepr; use str; use sys; -use unstable::exchange_alloc; use cast::transmute; use rt::{context, OldTaskContext}; use rt::local_services::borrow_local_services; use option::{Option, Some, None}; use io; +use rt::global_heap; #[allow(non_camel_case_types)] pub type rust_task = c_void; @@ -153,7 +153,7 @@ unsafe fn fail_borrowed(box: *mut BoxRepr, file: *c_char, line: size_t) { #[lang="exchange_malloc"] #[inline(always)] pub unsafe fn exchange_malloc(td: *c_char, size: uintptr_t) -> *c_char { - transmute(exchange_alloc::malloc(transmute(td), transmute(size))) + transmute(global_heap::malloc(transmute(td), transmute(size))) } /// Because this code is so perf. sensitive, use a static constant so that @@ -233,7 +233,7 @@ impl DebugPrints for io::fd_t { #[lang="exchange_free"] #[inline(always)] pub unsafe fn exchange_free(ptr: *c_char) { - exchange_alloc::free(transmute(ptr)) + global_heap::free(transmute(ptr)) } #[lang="malloc"] From f934fa73aca85cded967420ef2ab0dd9f14a6638 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 6 May 2013 23:11:02 -0700 Subject: [PATCH 027/248] core::rt: Docs --- src/libcore/rt/mod.rs | 74 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 13 deletions(-) diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 55f777ebf9ac7..5a6a6e4c7d88d 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -8,7 +8,57 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Rust runtime services, including the task scheduler and I/O interface +/*! The Rust Runtime, including the task scheduler and I/O + +The `rt` module provides the private runtime infrastructure necessary +to support core language features like the exchange and local heap, +the garbage collector, logging, local data and unwinding. It also +implements the default task scheduler and task model. Initialization +routines are provided for setting up runtime resources in common +configurations, including that used by `rustc` when generating +executables. + +It is intended that the features provided by `rt` can be factored in a +way such that the core library can be built with different 'profiles' +for different use cases, e.g. excluding the task scheduler. A number +of runtime features though are critical to the functioning of the +language and an implementation must be provided regardless of the +execution environment. + +Of foremost importance is the global exchange heap, in the module +`global_heap`. Very little practical Rust code can be written without +access to the global heap. Unlike most of `rt` the global heap is +truly a global resource and generally operates independently of the +rest of the runtime. + +All other runtime features are 'local', either thread-local or +task-local. Those critical to the functioning of the language are +defined in the module `local_services`. Local services are those which +are expected to be available to Rust code generally but rely on +thread- or task-local state. These currently include the local heap, +the garbage collector, local storage, logging and the stack unwinder. +Local services are primarily implemented for tasks, but may also +be implemented for use outside of tasks. + +The relationship between `rt` and the rest of the core library is +not entirely clear yet and some modules will be moving into or +out of `rt` as development proceeds. + +Several modules in `core` are clients of `rt`: + +* `core::task` - The user-facing interface to the Rust task model. +* `core::task::local_data` - The interface to local data. +* `core::gc` - The garbage collector. +* `core::unstable::lang` - Miscellaneous lang items, some of which rely on `core::rt`. +* `core::condition` - Uses local data. +* `core::cleanup` - Local heap destruction. +* `core::io` - In the future `core::io` will use an `rt` implementation. +* `core::logging` +* `core::pipes` +* `core::comm` +* `core::stackwalk` + +*/ #[doc(hidden)]; @@ -20,39 +70,37 @@ pub mod global_heap; /// The Scheduler and Task types. mod sched; -/// Thread-local access to the current Scheduler +/// Thread-local access to the current Scheduler. pub mod local_sched; -/// Synchronous I/O +/// Synchronous I/O. #[path = "io/mod.rs"] pub mod io; -/// Thread-local implementations of language-critical runtime features like @ +/// Thread-local implementations of language-critical runtime features like @. pub mod local_services; -/// The EventLoop and internal synchronous I/O interface, dynamically -/// overridable so that it's primary implementation on libuv can -/// live outside of core. +/// The EventLoop and internal synchronous I/O interface. mod rtio; -/// libuv +/// libuv and default rtio implementation. #[path = "uv/mod.rs"] pub mod uv; // FIXME #5248: The import in `sched` doesn't resolve unless this is pub! -/// Bindings to pthread/windows thread-local storage +/// Bindings to pthread/windows thread-local storage. pub mod thread_local_storage; -/// A parallel work-stealing queue +/// A parallel work-stealing dequeue. mod work_queue; -/// Stack segments and their cacheing +/// Stack segments and caching. mod stack; -/// CPU context swapping +/// CPU context swapping. mod context; -/// Bindings to system threading libraries +/// Bindings to system threading libraries. mod thread; /// The runtime configuration, read from environment variables From 204e3d82ccf5015e39f847aafea148d5180ab951 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 11 May 2013 18:59:28 -0700 Subject: [PATCH 028/248] core::rt: Register stacks with valgrind. #6428 --- src/libcore/rt/io/net/tcp.rs | 2 +- src/libcore/rt/stack.rs | 39 +++++++++++++++++++++++++++++++----- src/rt/rust_stack.cpp | 11 ++++++++++ src/rt/rustrt.def.in | 2 ++ 4 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 90f99f8df8b87..b4c021ed28ffe 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -122,7 +122,7 @@ mod test { use rt::io::net::ip::Ipv4; use rt::io::*; - #[test] + #[test] #[ignore] fn bind_error() { do run_in_newsched_task { let mut called = false; diff --git a/src/libcore/rt/stack.rs b/src/libcore/rt/stack.rs index 9eca3bda0473c..068bc834ce6a3 100644 --- a/src/libcore/rt/stack.rs +++ b/src/libcore/rt/stack.rs @@ -9,21 +9,36 @@ // except according to those terms. use vec; +use ops::Drop; +use libc::{c_uint, uintptr_t}; pub struct StackSegment { - buf: ~[u8] + buf: ~[u8], + valgrind_id: c_uint } pub impl StackSegment { fn new(size: uint) -> StackSegment { - // Crate a block of uninitialized values - let mut stack = vec::with_capacity(size); unsafe { + // Crate a block of uninitialized values + let mut stack = vec::with_capacity(size); vec::raw::set_len(&mut stack, size); + + let mut stk = StackSegment { + buf: stack, + valgrind_id: 0 + }; + + // XXX: Using the FFI to call a C macro. Slow + stk.valgrind_id = rust_valgrind_stack_register(stk.start(), stk.end()); + return stk; } + } - StackSegment { - buf: stack + /// Point to the low end of the allocated stack + fn start(&self) -> *uint { + unsafe { + vec::raw::to_ptr(self.buf) as *uint } } @@ -35,6 +50,15 @@ pub impl StackSegment { } } +impl Drop for StackSegment { + fn finalize(&self) { + unsafe { + // XXX: Using the FFI to call a C macro. Slow + rust_valgrind_stack_deregister(self.valgrind_id); + } + } +} + pub struct StackPool(()); impl StackPool { @@ -47,3 +71,8 @@ impl StackPool { fn give_segment(&self, _stack: StackSegment) { } } + +extern { + fn rust_valgrind_stack_register(start: *uintptr_t, end: *uintptr_t) -> c_uint; + fn rust_valgrind_stack_deregister(id: c_uint); +} \ No newline at end of file diff --git a/src/rt/rust_stack.cpp b/src/rt/rust_stack.cpp index f07690a955ea2..a609ac573245d 100644 --- a/src/rt/rust_stack.cpp +++ b/src/rt/rust_stack.cpp @@ -92,3 +92,14 @@ destroy_exchange_stack(rust_exchange_alloc *exchange, stk_seg *stk) { deregister_valgrind_stack(stk); exchange->free(stk); } + + +extern "C" CDECL unsigned int +rust_valgrind_stack_register(void *start, void *end) { + return VALGRIND_STACK_REGISTER(start, end); +} + +extern "C" CDECL void +rust_valgrind_stack_deregister(unsigned int id) { + VALGRIND_STACK_DEREGISTER(id); +} diff --git a/src/rt/rustrt.def.in b/src/rt/rustrt.def.in index 6be41251f1bd9..75a5a069605c7 100644 --- a/src/rt/rustrt.def.in +++ b/src/rt/rustrt.def.in @@ -234,3 +234,5 @@ rust_try rust_begin_unwind rust_take_task_borrow_list rust_set_task_borrow_list +rust_valgrind_stack_register +rust_valgrind_stack_deregister \ No newline at end of file From ee0ce64d9db10aebc491454b6595d6edf69fe513 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 12 May 2013 14:35:52 -0700 Subject: [PATCH 029/248] core::rt: Wait for handles to close --- src/libcore/rt/uv/idle.rs | 15 ++++++++-- src/libcore/rt/uv/mod.rs | 6 ++-- src/libcore/rt/uv/uvio.rs | 63 +++++++++++++++++++++++++++------------ 3 files changed, 60 insertions(+), 24 deletions(-) diff --git a/src/libcore/rt/uv/idle.rs b/src/libcore/rt/uv/idle.rs index 518429eeaff05..fecb9391caa54 100644 --- a/src/libcore/rt/uv/idle.rs +++ b/src/libcore/rt/uv/idle.rs @@ -11,7 +11,7 @@ use libc::c_int; use option::Some; use rt::uv::uvll; -use rt::uv::{Watcher, Loop, NativeHandle, IdleCallback}; +use rt::uv::{Watcher, Loop, NativeHandle, IdleCallback, NullCallback}; use rt::uv::status_to_maybe_uv_error; pub struct IdleWatcher(*uvll::uv_idle_t); @@ -57,12 +57,23 @@ pub impl IdleWatcher { } } - fn close(self) { + fn close(self, cb: NullCallback) { + { + let mut this = self; + let data = this.get_watcher_data(); + assert!(data.close_cb.is_none()); + data.close_cb = Some(cb); + } + unsafe { uvll::close(self.native_handle(), close_cb) }; extern fn close_cb(handle: *uvll::uv_idle_t) { unsafe { let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); + { + let mut data = idle_watcher.get_watcher_data(); + data.close_cb.swap_unwrap()(); + } idle_watcher.drop_watcher_data(); uvll::idle_delete(handle); } diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 2c83873359a8f..684099d7fd11f 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -356,7 +356,7 @@ fn idle_new_then_close() { do run_in_bare_thread { let mut loop_ = Loop::new(); let idle_watcher = { IdleWatcher::new(&mut loop_) }; - idle_watcher.close(); + idle_watcher.close(||()); } } @@ -372,7 +372,7 @@ fn idle_smoke_test() { assert!(status.is_none()); if unsafe { *count_ptr == 10 } { idle_watcher.stop(); - idle_watcher.close(); + idle_watcher.close(||()); } else { unsafe { *count_ptr = *count_ptr + 1; } } @@ -396,7 +396,7 @@ fn idle_start_stop_start() { assert!(status.is_none()); let mut idle_watcher = idle_watcher; idle_watcher.stop(); - idle_watcher.close(); + idle_watcher.close(||()); } } loop_.run(); diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 2218c0734fbfb..c031d7a1a6961 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -66,7 +66,7 @@ impl EventLoop for UvEventLoop { assert!(status.is_none()); let mut idle_watcher = idle_watcher; idle_watcher.stop(); - idle_watcher.close(); + idle_watcher.close(||()); f(); } } @@ -124,22 +124,26 @@ impl IoFactory for UvIoFactory { // Wait for a connection do tcp_watcher.connect(addr) |stream_watcher, status| { rtdebug!("connect: in connect callback"); - let maybe_stream = if status.is_none() { + if status.is_none() { rtdebug!("status is none"); - Ok(~UvTcpStream { watcher: stream_watcher }) + let res = Ok(~UvTcpStream { watcher: stream_watcher }); + + // Store the stream in the task's stack + unsafe { (*result_cell_ptr).put_back(res); } + + // Context switch + let scheduler = local_sched::take(); + scheduler.resume_task_immediately(task_cell.take()); } else { rtdebug!("status is some"); - // XXX: Wait for close - stream_watcher.close(||()); - Err(uv_error_to_io_error(status.get())) + let task_cell = Cell(task_cell.take()); + do stream_watcher.close { + let res = Err(uv_error_to_io_error(status.get())); + unsafe { (*result_cell_ptr).put_back(res); } + let scheduler = local_sched::take(); + scheduler.resume_task_immediately(task_cell.take()); + } }; - - // Store the stream in the task's stack - unsafe { (*result_cell_ptr).put_back(maybe_stream); } - - // Context switch - let scheduler = local_sched::take(); - scheduler.resume_task_immediately(task_cell.take()); } } @@ -152,8 +156,14 @@ impl IoFactory for UvIoFactory { match watcher.bind(addr) { Ok(_) => Ok(~UvTcpListener::new(watcher)), Err(uverr) => { - // XXX: Should we wait until close completes? - watcher.as_stream().close(||()); + let scheduler = local_sched::take(); + do scheduler.deschedule_running_task_and_then |task| { + let task_cell = Cell(task); + do watcher.as_stream().close { + let scheduler = local_sched::take(); + scheduler.resume_task_immediately(task_cell.take()); + } + } Err(uv_error_to_io_error(uverr)) } } @@ -181,8 +191,15 @@ impl UvTcpListener { impl Drop for UvTcpListener { fn finalize(&self) { - // XXX: Need to wait until close finishes before returning - self.watcher().as_stream().close(||()); + let watcher = self.watcher(); + let scheduler = local_sched::take(); + do scheduler.deschedule_running_task_and_then |task| { + let task_cell = Cell(task); + do watcher.as_stream().close { + let scheduler = local_sched::take(); + scheduler.resume_task_immediately(task_cell.take()); + } + } } } @@ -235,8 +252,16 @@ impl UvTcpStream { impl Drop for UvTcpStream { fn finalize(&self) { - rtdebug!("closing stream"); - self.watcher().close(||()); + rtdebug!("closing tcp stream"); + let watcher = self.watcher(); + let scheduler = local_sched::take(); + do scheduler.deschedule_running_task_and_then |task| { + let task_cell = Cell(task); + do watcher.close { + let scheduler = local_sched::take(); + scheduler.resume_task_immediately(task_cell.take()); + } + } } } From 6a6076ae810d470dfb511712c303a4ee7ffedf00 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Tue, 14 May 2013 19:06:20 -0700 Subject: [PATCH 030/248] core::rt: Ignore tcp test multiple_connect_interleaved_lazy_schedule Hangs on mac. --- src/libcore/rt/io/net/tcp.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index b4c021ed28ffe..addba40b31ebc 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -238,7 +238,7 @@ mod test { } } - #[test] + #[test] #[ignore(reason = "hangs on mac")] fn multiple_connect_interleaved_lazy_schedule() { do run_in_newsched_task { let addr = next_test_ip4(); From bfd9aa9755149725e39d8024d693ed76f92a30df Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Tue, 7 May 2013 18:13:15 -0700 Subject: [PATCH 031/248] core:rt: A few micro-opts --- src/libcore/rt/context.rs | 1 + src/libcore/rt/global_heap.rs | 14 +++++++++----- src/libcore/rt/local_sched.rs | 1 + src/libcore/rt/thread_local_storage.rs | 3 +++ src/rt/rust_exchange_alloc.cpp | 16 ++++++---------- src/rt/rustrt.def.in | 2 +- 6 files changed, 21 insertions(+), 16 deletions(-) diff --git a/src/libcore/rt/context.rs b/src/libcore/rt/context.rs index 9c1612884f044..2add314fd1196 100644 --- a/src/libcore/rt/context.rs +++ b/src/libcore/rt/context.rs @@ -84,6 +84,7 @@ pub impl Context { } extern { + #[rust_stack] fn swap_registers(out_regs: *mut Registers, in_regs: *Registers); } diff --git a/src/libcore/rt/global_heap.rs b/src/libcore/rt/global_heap.rs index 3b35c2fb8047f..ce7ff87b44580 100644 --- a/src/libcore/rt/global_heap.rs +++ b/src/libcore/rt/global_heap.rs @@ -9,7 +9,7 @@ // except according to those terms. use sys::{TypeDesc, size_of}; -use libc::{c_void, size_t}; +use libc::{c_void, size_t, uintptr_t}; use c_malloc = libc::malloc; use c_free = libc::free; use managed::raw::{BoxHeaderRepr, BoxRepr}; @@ -34,7 +34,7 @@ pub unsafe fn malloc(td: *TypeDesc, size: uint) -> *c_void { box.header.prev = null(); box.header.next = null(); - let exchange_count = &mut *rust_get_exchange_count_ptr(); + let exchange_count = &mut *exchange_count_ptr(); atomic_xadd(exchange_count, 1); return transmute(box); @@ -52,7 +52,7 @@ pub unsafe fn malloc_raw(size: uint) -> *c_void { } pub unsafe fn free(ptr: *c_void) { - let exchange_count = &mut *rust_get_exchange_count_ptr(); + let exchange_count = &mut *exchange_count_ptr(); atomic_xsub(exchange_count, 1); assert!(ptr.is_not_null()); @@ -77,7 +77,11 @@ fn align_to(size: uint, align: uint) -> uint { (size + align - 1) & !(align - 1) } +fn exchange_count_ptr() -> *mut int { + // XXX: Need mutable globals + unsafe { transmute(&rust_exchange_count) } +} + extern { - #[rust_stack] - fn rust_get_exchange_count_ptr() -> *mut int; + static rust_exchange_count: uintptr_t; } diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index eb35eb7881d39..1ef1fd33a83a5 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -126,6 +126,7 @@ fn maybe_tls_key() -> Option { } extern { + #[fast_ffi] fn rust_get_sched_tls_key() -> *mut c_void; } diff --git a/src/libcore/rt/thread_local_storage.rs b/src/libcore/rt/thread_local_storage.rs index 366996fb93560..6a08c0f59b183 100644 --- a/src/libcore/rt/thread_local_storage.rs +++ b/src/libcore/rt/thread_local_storage.rs @@ -46,8 +46,11 @@ type pthread_key_t = ::libc::c_uint; #[cfg(unix)] extern { + #[fast_ffi] fn pthread_key_create(key: *mut pthread_key_t, dtor: *u8) -> c_int; + #[fast_ffi] fn pthread_setspecific(key: pthread_key_t, value: *mut c_void) -> c_int; + #[fast_ffi] fn pthread_getspecific(key: pthread_key_t) -> *mut c_void; } diff --git a/src/rt/rust_exchange_alloc.cpp b/src/rt/rust_exchange_alloc.cpp index 5958c68f3e7d1..89257dc9f6e43 100644 --- a/src/rt/rust_exchange_alloc.cpp +++ b/src/rt/rust_exchange_alloc.cpp @@ -15,14 +15,15 @@ #include #include -uintptr_t exchange_count = 0; +extern uintptr_t rust_exchange_count; +uintptr_t rust_exchange_count = 0; void * rust_exchange_alloc::malloc(size_t size) { void *value = ::malloc(size); assert(value); - sync::increment(exchange_count); + sync::increment(rust_exchange_count); return value; } @@ -36,20 +37,15 @@ rust_exchange_alloc::realloc(void *ptr, size_t size) { void rust_exchange_alloc::free(void *ptr) { - sync::decrement(exchange_count); + sync::decrement(rust_exchange_count); ::free(ptr); } -extern "C" uintptr_t * -rust_get_exchange_count_ptr() { - return &exchange_count; -} - void rust_check_exchange_count_on_exit() { - if (exchange_count != 0) { + if (rust_exchange_count != 0) { printf("exchange heap not empty on exit\n"); - printf("%d dangling allocations\n", (int)exchange_count); + printf("%d dangling allocations\n", (int)rust_exchange_count); abort(); } } diff --git a/src/rt/rustrt.def.in b/src/rt/rustrt.def.in index 75a5a069605c7..a62d7991d4953 100644 --- a/src/rt/rustrt.def.in +++ b/src/rt/rustrt.def.in @@ -195,7 +195,7 @@ rust_register_exit_function rust_get_global_data_ptr rust_inc_kernel_live_count rust_dec_kernel_live_count -rust_get_exchange_count_ptr +rust_exchange_count rust_get_sched_tls_key swap_registers rust_readdir From 36ad366519137122871b04b407370dab4a97c645 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 8 May 2013 14:52:30 -0700 Subject: [PATCH 032/248] core::rt: Add a test of standalone use of the runtime --- src/libcore/rt/mod.rs | 24 ++---------------------- src/libcore/unstable/lang.rs | 19 +++++++++++++++++-- src/test/run-pass/core-rt-smoke.rs | 18 ++++++++++++++++++ 3 files changed, 37 insertions(+), 24 deletions(-) create mode 100644 src/test/run-pass/core-rt-smoke.rs diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index f04c38f79e800..5dee9a7773155 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -131,9 +131,6 @@ pub mod tube; /// /// # Arguments /// -/// * `main` - A C-abi function that takes no arguments and returns `c_void`. -/// It is a wrapper around the user-defined `main` function, and will be run -/// in a task. /// * `argc` & `argv` - The argument vector. On Unix this information is used /// by os::args. /// * `crate_map` - Runtime information about the executing crate, mostly for logging @@ -141,31 +138,14 @@ pub mod tube; /// # Return value /// /// The return value is used as the process return code. 0 on success, 101 on error. -pub fn start(main: *u8, _argc: int, _argv: **c_char, _crate_map: *u8) -> int { +pub fn start(_argc: int, _argv: **c_char, _crate_map: *u8, main: ~fn()) -> int { use self::sched::{Scheduler, Task}; use self::uv::uvio::UvEventLoop; - use sys::Closure; - use ptr; - use cast; let loop_ = ~UvEventLoop::new(); let mut sched = ~Scheduler::new(loop_); - - let main_task = ~do Task::new(&mut sched.stack_pool) { - - unsafe { - // `main` is an `fn() -> ()` that doesn't take an environment - // XXX: Could also call this as an `extern "Rust" fn` once they work - let main = Closure { - code: main as *(), - env: ptr::null(), - }; - let mainfn: &fn() = cast::transmute(main); - - mainfn(); - } - }; + let main_task = ~Task::new(&mut sched.stack_pool, main); sched.task_queue.push_back(main_task); sched.run(); diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index e521fb59fbe5f..ce32cb4c282f2 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -424,7 +424,10 @@ pub unsafe fn strdup_uniq(ptr: *c_uchar, len: uint) -> ~str { pub fn start(main: *u8, argc: int, argv: **c_char, crate_map: *u8) -> int { use libc::getenv; - use rt::start; + use rt; + use sys::Closure; + use ptr; + use cast; unsafe { let use_old_rt = do str::as_c_str("RUST_NEWRT") |s| { @@ -434,7 +437,19 @@ pub fn start(main: *u8, argc: int, argv: **c_char, return rust_start(main as *c_void, argc as c_int, argv, crate_map as *c_void) as int; } else { - return start(main, argc, argv, crate_map); + return do rt::start(argc, argv, crate_map) { + unsafe { + // `main` is an `fn() -> ()` that doesn't take an environment + // XXX: Could also call this as an `extern "Rust" fn` once they work + let main = Closure { + code: main as *(), + env: ptr::null(), + }; + let mainfn: &fn() = cast::transmute(main); + + mainfn(); + } + }; } } diff --git a/src/test/run-pass/core-rt-smoke.rs b/src/test/run-pass/core-rt-smoke.rs new file mode 100644 index 0000000000000..fb08cda3b2577 --- /dev/null +++ b/src/test/run-pass/core-rt-smoke.rs @@ -0,0 +1,18 @@ +// Copyright 2012 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. + +// A simple test of starting the runtime manually + +#[start] +fn start(argc: int, argv: **u8, crate_map: *u8) -> int { + do core::rt::start(argc, argv, crate_map) { + debug!("creating my own runtime is joy"); + } +} \ No newline at end of file From f6401bad24d2fb1e1f959595c2f57cb4964e7082 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 8 May 2013 15:26:07 -0700 Subject: [PATCH 033/248] core: Use a global lock instead of runtime lock for os::getenv, etc. #4726 --- src/libcore/os.rs | 26 ++++++++++++++------------ src/libuv | 2 +- src/rt/rust_env.cpp | 16 ++++++++++++++++ src/rt/rustrt.def.in | 5 ++++- 4 files changed, 35 insertions(+), 14 deletions(-) diff --git a/src/libcore/os.rs b/src/libcore/os.rs index 93319efa3b761..a198b495127e7 100644 --- a/src/libcore/os.rs +++ b/src/libcore/os.rs @@ -147,23 +147,25 @@ pub mod win32 { /* Accessing environment variables is not generally threadsafe. -This uses a per-runtime lock to serialize access. -FIXME #4726: It would probably be appropriate to make this a real global +Serialize access through a global lock. */ fn with_env_lock(f: &fn() -> T) -> T { - use unstable::global::global_data_clone_create; - use unstable::sync::{Exclusive, exclusive}; - - struct SharedValue(()); - type ValueMutex = Exclusive; - fn key(_: ValueMutex) { } + use unstable::finally::Finally; unsafe { - let lock: ValueMutex = global_data_clone_create(key, || { - ~exclusive(SharedValue(())) - }); + return do (|| { + rust_take_env_lock(); + f() + }).finally { + rust_drop_env_lock(); + }; + } - lock.with_imm(|_| f() ) + extern { + #[fast_ffi] + fn rust_take_env_lock(); + #[fast_ffi] + fn rust_drop_env_lock(); } } diff --git a/src/libuv b/src/libuv index 97ac7c087a0ca..218ab86721eef 160000 --- a/src/libuv +++ b/src/libuv @@ -1 +1 @@ -Subproject commit 97ac7c087a0caf6b0f611b80e14f7fe3cb18bb27 +Subproject commit 218ab86721eefd7b7e97fa6d9f95a80a1fa8686c diff --git a/src/rt/rust_env.cpp b/src/rt/rust_env.cpp index 360d611492853..ed38be3550f74 100644 --- a/src/rt/rust_env.cpp +++ b/src/rt/rust_env.cpp @@ -13,6 +13,7 @@ // that might come from the environment is loaded here, once, during // init. +#include "sync/lock_and_signal.h" #include "rust_env.h" // The environment variables that the runtime knows about @@ -26,6 +27,18 @@ #define RUST_DEBUG_MEM "RUST_DEBUG_MEM" #define RUST_DEBUG_BORROW "RUST_DEBUG_BORROW" +static lock_and_signal env_lock; + +extern "C" CDECL void +rust_take_env_lock() { + env_lock.lock(); +} + +extern "C" CDECL void +rust_drop_env_lock() { + env_lock.unlock(); +} + #if defined(__WIN32__) static int get_num_cpus() { @@ -119,6 +132,8 @@ copyenv(const char* name) { rust_env* load_env(int argc, char **argv) { + scoped_lock with(env_lock); + rust_env *env = (rust_env*)malloc(sizeof(rust_env)); env->num_sched_threads = (size_t)get_num_threads(); @@ -141,3 +156,4 @@ free_env(rust_env *env) { free(env->rust_seed); free(env); } + diff --git a/src/rt/rustrt.def.in b/src/rt/rustrt.def.in index a62d7991d4953..958b31eb3429b 100644 --- a/src/rt/rustrt.def.in +++ b/src/rt/rustrt.def.in @@ -235,4 +235,7 @@ rust_begin_unwind rust_take_task_borrow_list rust_set_task_borrow_list rust_valgrind_stack_register -rust_valgrind_stack_deregister \ No newline at end of file +rust_valgrind_stack_deregister +rust_take_env_lock +rust_drop_env_lock + From cc2897d559742c5f7630557975aa72c12a0eff01 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 8 May 2013 15:28:30 -0700 Subject: [PATCH 034/248] core: Replace use of libc::getenv with os::getenv --- src/libcore/unstable/lang.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index ce32cb4c282f2..071d21ae8a807 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -423,16 +423,14 @@ pub unsafe fn strdup_uniq(ptr: *c_uchar, len: uint) -> ~str { #[lang="start"] pub fn start(main: *u8, argc: int, argv: **c_char, crate_map: *u8) -> int { - use libc::getenv; use rt; use sys::Closure; use ptr; use cast; + use os; unsafe { - let use_old_rt = do str::as_c_str("RUST_NEWRT") |s| { - getenv(s).is_null() - }; + let use_old_rt = os::getenv("RUST_NEWRT").is_none(); if use_old_rt { return rust_start(main as *c_void, argc as c_int, argv, crate_map as *c_void) as int; From 0a54bad3d1d306845b04f146c2c31d4a70e9ede3 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 8 May 2013 16:53:40 -0700 Subject: [PATCH 035/248] core::rt: Initialize logging --- src/libcore/rt/logging.rs | 32 +++++++++++++++++++++++++++++++- src/libcore/rt/mod.rs | 11 +++++++++-- src/libcore/unstable/lang.rs | 2 +- src/rt/rust_log.cpp | 4 ++++ src/rt/rustrt.def.in | 2 +- 5 files changed, 46 insertions(+), 5 deletions(-) diff --git a/src/libcore/rt/logging.rs b/src/libcore/rt/logging.rs index 4ed09fd829f22..a0d0539768912 100644 --- a/src/libcore/rt/logging.rs +++ b/src/libcore/rt/logging.rs @@ -35,4 +35,34 @@ impl Logger for StdErrLogger { dbg.write_str("\n"); dbg.flush(); } -} \ No newline at end of file +} + +/// Configure logging by traversing the crate map and setting the +/// per-module global logging flags based on the logging spec +pub fn init(crate_map: *u8) { + use os; + use str; + use ptr; + use option::{Some, None}; + use libc::c_char; + + let log_spec = os::getenv("RUST_LOG"); + match log_spec { + Some(spec) => { + do str::as_c_str(spec) |s| { + unsafe { + rust_update_log_settings(crate_map, s); + } + } + } + None => { + unsafe { + rust_update_log_settings(crate_map, ptr::null()); + } + } + } + + extern { + fn rust_update_log_settings(crate_map: *u8, settings: *c_char); + } +} diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 5dee9a7773155..cebc87f8c2352 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -62,7 +62,6 @@ Several modules in `core` are clients of `rt`: #[doc(hidden)]; -use libc::c_char; use ptr::Ptr; /// The global (exchange) heap. @@ -138,11 +137,13 @@ pub mod tube; /// # Return value /// /// The return value is used as the process return code. 0 on success, 101 on error. -pub fn start(_argc: int, _argv: **c_char, _crate_map: *u8, main: ~fn()) -> int { +pub fn start(_argc: int, _argv: **u8, crate_map: *u8, main: ~fn()) -> int { use self::sched::{Scheduler, Task}; use self::uv::uvio::UvEventLoop; + init(crate_map); + let loop_ = ~UvEventLoop::new(); let mut sched = ~Scheduler::new(loop_); let main_task = ~Task::new(&mut sched.stack_pool, main); @@ -153,6 +154,12 @@ pub fn start(_argc: int, _argv: **c_char, _crate_map: *u8, main: ~fn()) -> int { return 0; } +/// One-time runtime initialization. Currently all this does is set up logging +/// based on the RUST_LOG environment variable. +pub fn init(crate_map: *u8) { + logging::init(crate_map); +} + /// Possible contexts in which Rust code may be executing. /// Different runtime services are available depending on context. /// Mostly used for determining if we're using the new scheduler diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index 071d21ae8a807..1249392484d23 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -435,7 +435,7 @@ pub fn start(main: *u8, argc: int, argv: **c_char, return rust_start(main as *c_void, argc as c_int, argv, crate_map as *c_void) as int; } else { - return do rt::start(argc, argv, crate_map) { + return do rt::start(argc, argv as **u8, crate_map) { unsafe { // `main` is an `fn() -> ()` that doesn't take an environment // XXX: Could also call this as an `extern "Rust" fn` once they work diff --git a/src/rt/rust_log.cpp b/src/rt/rust_log.cpp index c2b58c9fda732..df24f569495b4 100644 --- a/src/rt/rust_log.cpp +++ b/src/rt/rust_log.cpp @@ -324,6 +324,10 @@ void update_log_settings(void* crate_map, char* settings) { free(buffer); } +extern "C" CDECL void +rust_update_log_settings(void* crate_map, char* settings) { + update_log_settings(crate_map, settings); +} // // Local Variables: diff --git a/src/rt/rustrt.def.in b/src/rt/rustrt.def.in index 958b31eb3429b..f1ddb17c499a1 100644 --- a/src/rt/rustrt.def.in +++ b/src/rt/rustrt.def.in @@ -238,4 +238,4 @@ rust_valgrind_stack_register rust_valgrind_stack_deregister rust_take_env_lock rust_drop_env_lock - +rust_update_log_settings From 174ec1e42252c46cc6722296379968ba7a6c6fbd Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 8 May 2013 19:28:53 -0700 Subject: [PATCH 036/248] core::rt: Error handling for TcpStream.read --- src/libcore/macros.rs | 4 +- src/libcore/rt/io/mod.rs | 1 + src/libcore/rt/io/net/tcp.rs | 89 +++++++++++++++++++++++++++++++++--- src/libcore/rt/uv/mod.rs | 5 ++ src/libcore/rt/uv/uvio.rs | 4 +- src/libcore/rt/uv/uvll.rs | 1 + 6 files changed, 93 insertions(+), 11 deletions(-) diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index fda48b6ffb7d9..04ee086b9ae4b 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -11,7 +11,7 @@ #[macro_escape]; // Some basic logging -macro_rules! rtdebug_ ( +macro_rules! rtdebug ( ($( $arg:expr),+) => ( { dumb_println(fmt!( $($arg),+ )); @@ -26,7 +26,7 @@ macro_rules! rtdebug_ ( ) // An alternate version with no output, for turning off logging -macro_rules! rtdebug ( +macro_rules! rtdebug_ ( ($( $arg:expr),+) => ( $(let _ = $arg)*; ) ) diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index 8f56005d0a4f6..ab4b83f7cf0ea 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -338,6 +338,7 @@ pub enum IoErrorKind { ConnectionFailed, Closed, ConnectionRefused, + ConnectionReset } // XXX: Can't put doc comments on macros diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index addba40b31ebc..4a25334a2fcbc 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -13,7 +13,7 @@ use result::{Ok, Err}; use rt::sched::local_sched::unsafe_borrow_io; use rt::io::net::ip::IpAddr; use rt::io::{Reader, Writer, Listener}; -use rt::io::io_error; +use rt::io::{io_error, EndOfFile}; use rt::rtio::{IoFactory, RtioTcpListener, RtioTcpListenerObject, RtioTcpStream, RtioTcpStreamObject}; @@ -55,8 +55,12 @@ impl Reader for TcpStream { let bytes_read = self.rtstream.read(buf); match bytes_read { Ok(read) => Some(read), - Err(_) => { - abort!("XXX"); + Err(ioerr) => { + // EOF is indicated by returning None + if ioerr.kind != EndOfFile { + io_error::cond.raise(ioerr); + } + return None; } } } @@ -69,8 +73,8 @@ impl Writer for TcpStream { let res = self.rtstream.write(buf); match res { Ok(_) => (), - Err(_) => { - abort!("XXX"); + Err(ioerr) => { + io_error::cond.raise(ioerr); } } } @@ -106,8 +110,9 @@ impl Listener for TcpListener { Ok(s) => { Some(TcpStream::new(s)) } - Err(_) => { - abort!("XXX"); + Err(ioerr) => { + io_error::cond.raise(ioerr); + return None; } } } @@ -174,6 +179,76 @@ mod test { } } + #[test] + fn read_eof() { + do run_in_newsched_task { + let addr = next_test_ip4(); + + do spawntask_immediately { + let mut listener = TcpListener::bind(addr); + let mut stream = listener.accept(); + let mut buf = [0]; + let nread = stream.read(buf); + assert!(nread.is_none()); + } + + do spawntask_immediately { + let _stream = TcpStream::connect(addr); + // Close + } + } + } + + #[test] + fn read_eof_twice() { + do run_in_newsched_task { + let addr = next_test_ip4(); + + do spawntask_immediately { + let mut listener = TcpListener::bind(addr); + let mut stream = listener.accept(); + let mut buf = [0]; + let nread = stream.read(buf); + assert!(nread.is_none()); + let nread = stream.read(buf); + assert!(nread.is_none()); + } + + do spawntask_immediately { + let _stream = TcpStream::connect(addr); + // Close + } + } + } + + #[test] + fn write_close() { + do run_in_newsched_task { + let addr = next_test_ip4(); + + do spawntask_immediately { + let mut listener = TcpListener::bind(addr); + let mut stream = listener.accept(); + let buf = [0]; + loop { + let mut stop = false; + do io_error::cond.trap(|e| { + assert!(e.kind == ConnectionReset); + stop = true; + }).in { + stream.write(buf); + } + if stop { break } + } + } + + do spawntask_immediately { + let stream = TcpStream::connect(addr); + // Close + } + } + } + #[test] fn multiple_connect_serial() { do run_in_newsched_task { diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index e719449139758..3d9aef6cb61d4 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -210,6 +210,10 @@ pub impl UvError { from_c_str(desc_str) } } + + fn is_eof(&self) -> bool { + self.code == uvll::EOF + } } impl ToStr for UvError { @@ -262,6 +266,7 @@ pub fn uv_error_to_io_error(uverr: UvError) -> IoError { EOF => EndOfFile, EACCES => PermissionDenied, ECONNREFUSED => ConnectionRefused, + ECONNRESET => ConnectionReset, e => { abort!("unknown uv error code: %u", e as uint); } diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index cc9eb2ada4d17..25d912ce42eb5 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -301,7 +301,7 @@ impl RtioTcpStream for UvTcpStream { assert!(nread >= 0); Ok(nread as uint) } else { - Err(standard_error(OtherIoError)) + Err(uv_error_to_io_error(status.unwrap())) }; unsafe { (*result_cell_ptr).put_back(result); } @@ -330,7 +330,7 @@ impl RtioTcpStream for UvTcpStream { let result = if status.is_none() { Ok(()) } else { - Err(standard_error(OtherIoError)) + Err(uv_error_to_io_error(status.unwrap())) }; unsafe { (*result_cell_ptr).put_back(result); } diff --git a/src/libcore/rt/uv/uvll.rs b/src/libcore/rt/uv/uvll.rs index 2a2812c671847..76abf2a195d5c 100644 --- a/src/libcore/rt/uv/uvll.rs +++ b/src/libcore/rt/uv/uvll.rs @@ -39,6 +39,7 @@ pub static EOF: c_int = 1; pub static EADDRINFO: c_int = 2; pub static EACCES: c_int = 3; pub static ECONNREFUSED: c_int = 12; +pub static ECONNRESET: c_int = 13; pub struct uv_err_t { code: c_int, From afcf4f2639ea58f847d0c7260a46d65738179fae Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 9 May 2013 15:04:12 -0700 Subject: [PATCH 037/248] core::rt: Don't abort when reporting an unknown uv error --- src/libcore/rt/uv/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 3d9aef6cb61d4..871fd2a9042f9 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -267,8 +267,9 @@ pub fn uv_error_to_io_error(uverr: UvError) -> IoError { EACCES => PermissionDenied, ECONNREFUSED => ConnectionRefused, ECONNRESET => ConnectionReset, - e => { - abort!("unknown uv error code: %u", e as uint); + _ => { + // XXX: Need to map remaining uv error types + OtherIoError } }; From 013b7760b7bbc43ee56179588f8fe1a81d4567e5 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 9 May 2013 17:21:13 -0700 Subject: [PATCH 038/248] core: Turn task::unkillable, etc. into no-ops in newsched. #6377 Not necessary just yet but they make ARC not work. --- src/libcore/rt/mod.rs | 1 - src/libcore/task/mod.rs | 50 +++++++++++++++++++++++++++-------------- 2 files changed, 33 insertions(+), 18 deletions(-) diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index cebc87f8c2352..3e2e10504cf9b 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -113,7 +113,6 @@ mod local_heap; pub mod logging; /// Tools for testing the runtime -#[cfg(test)] pub mod test; /// Reference counting diff --git a/src/libcore/task/mod.rs b/src/libcore/task/mod.rs index d57bd5528bce4..a6edee38e188a 100644 --- a/src/libcore/task/mod.rs +++ b/src/libcore/task/mod.rs @@ -43,6 +43,7 @@ use task::rt::{task_id, sched_id}; use util; use util::replace; use unstable::finally::Finally; +use rt::{context, OldTaskContext}; #[cfg(test)] use comm::SharedChan; @@ -558,23 +559,33 @@ pub fn get_scheduler() -> Scheduler { * ~~~ */ pub unsafe fn unkillable(f: &fn() -> U) -> U { - let t = rt::rust_get_task(); - do (|| { - rt::rust_task_inhibit_kill(t); + if context() == OldTaskContext { + let t = rt::rust_get_task(); + do (|| { + rt::rust_task_inhibit_kill(t); + f() + }).finally { + rt::rust_task_allow_kill(t); + } + } else { + // FIXME #6377 f() - }).finally { - rt::rust_task_allow_kill(t); } } /// The inverse of unkillable. Only ever to be used nested in unkillable(). pub unsafe fn rekillable(f: &fn() -> U) -> U { - let t = rt::rust_get_task(); - do (|| { - rt::rust_task_allow_kill(t); + if context() == OldTaskContext { + let t = rt::rust_get_task(); + do (|| { + rt::rust_task_allow_kill(t); + f() + }).finally { + rt::rust_task_inhibit_kill(t); + } + } else { + // FIXME #6377 f() - }).finally { - rt::rust_task_inhibit_kill(t); } } @@ -583,14 +594,19 @@ pub unsafe fn rekillable(f: &fn() -> U) -> U { * For use with exclusive ARCs, which use pthread mutexes directly. */ pub unsafe fn atomically(f: &fn() -> U) -> U { - let t = rt::rust_get_task(); - do (|| { - rt::rust_task_inhibit_kill(t); - rt::rust_task_inhibit_yield(t); + if context() == OldTaskContext { + let t = rt::rust_get_task(); + do (|| { + rt::rust_task_inhibit_kill(t); + rt::rust_task_inhibit_yield(t); + f() + }).finally { + rt::rust_task_allow_yield(t); + rt::rust_task_allow_kill(t); + } + } else { + // FIXME #6377 f() - }).finally { - rt::rust_task_allow_yield(t); - rt::rust_task_allow_kill(t); } } From b764d4cb4f0c893caf5a6395db9b1e10a167a28f Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 9 May 2013 17:37:31 -0700 Subject: [PATCH 039/248] core::rt: Begin implementing Reader extension methods --- src/libcore/rt/io/extensions.rs | 266 +++++++++++++++++++++++++++++++- src/libcore/rt/io/mock.rs | 50 ++++++ src/libcore/rt/io/mod.rs | 14 +- 3 files changed, 325 insertions(+), 5 deletions(-) create mode 100644 src/libcore/rt/io/mock.rs diff --git a/src/libcore/rt/io/extensions.rs b/src/libcore/rt/io/extensions.rs index bb025b0ccb6d5..665b8a578e396 100644 --- a/src/libcore/rt/io/extensions.rs +++ b/src/libcore/rt/io/extensions.rs @@ -13,26 +13,103 @@ // XXX: Not sure how this should be structured // XXX: Iteration should probably be considered separately +use vec; +use rt::io::Reader; +use option::{Option, Some, None}; +use unstable::finally::Finally; + pub trait ReaderUtil { + /// Reads a single byte. Returns `None` on EOF. + /// + /// # Failure + /// + /// Raises the same conditions as the `read` method. Returns + /// `None` if the condition is handled. + fn read_byte(&mut self) -> Option; + + /// Reads `len` bytes and appends them to a vector. + /// + /// May push fewer than the requested number of bytes on error + /// or EOF. Returns true on success, false on EOF or error. + /// + /// # Failure + /// + /// Raises the same conditions as `read`. Returns `false` if + /// the condition is handled. + fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) -> bool; + /// Reads `len` bytes and gives you back a new vector /// /// # Failure /// - /// Raises the `io_error` condition on error. Returns an empty - /// vector if the condition is handled. + /// Raises the same conditions as the `read` method. May return + /// less than the requested number of bytes on error or EOF. fn read_bytes(&mut self, len: uint) -> ~[u8]; /// Reads all remaining bytes from the stream. /// /// # Failure /// - /// Raises the `io_error` condition on error. Returns an empty - /// vector if the condition is handled. + /// Raises the same conditions as the `read` method. fn read_to_end(&mut self) -> ~[u8]; } +impl ReaderUtil for T { + fn read_byte(&mut self) -> Option { + let mut buf = [0]; + match self.read(buf) { + Some(nread) if nread == 0 => { + debug!("read 0 bytes. trying again"); + self.read_byte() + } + Some(nread) => Some(buf[0]), + None => None + } + } + + fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) -> bool { + unsafe { + let start_len = buf.len(); + let mut total_read = 0; + let mut eof = false; + + vec::reserve_at_least(buf, start_len + len); + vec::raw::set_len(buf, start_len + len); + + do (|| { + while total_read < len { + let slice = vec::mut_slice(*buf, start_len + total_read, buf.len()); + match self.read(slice) { + Some(nread) => { + total_read += nread; + } + None => { + eof = true; + break; + } + } + } + }).finally { + vec::raw::set_len(buf, start_len + total_read); + } + + return !eof; + } + } + + fn read_bytes(&mut self, len: uint) -> ~[u8] { + let mut buf = vec::with_capacity(len); + self.push_bytes(&mut buf, len); + return buf; + } + + fn read_to_end(&mut self) -> ~[u8] { + fail!() + } +} + pub trait ReaderByteConversions { /// Reads `n` little-endian unsigned integer bytes. /// @@ -467,3 +544,184 @@ pub trait WriterByteConversions { /// Raises the `io_error` condition on error. fn write_i8(&mut self, n: i8); } + +#[cfg(test)] +mod test { + use super::*; + use option::{Some, None}; + use cell::Cell; + use rt::io::mem::MemReader; + use rt::io::mock::*; + use rt::io::{io_error, placeholder_error}; + + #[test] + fn read_byte() { + let mut reader = MemReader::new(~[10]); + let byte = reader.read_byte(); + assert!(byte == Some(10)); + } + + #[test] + fn read_byte_0_bytes() { + let mut reader = MockReader::new(); + let count = Cell(0); + reader.read = |buf| { + do count.with_mut_ref |count| { + if *count == 0 { + *count = 1; + Some(0) + } else { + buf[0] = 10; + Some(1) + } + } + }; + let byte = reader.read_byte(); + assert!(byte == Some(10)); + } + + #[test] + fn read_byte_eof() { + let mut reader = MockReader::new(); + reader.read = |_| None; + let byte = reader.read_byte(); + assert!(byte == None); + } + + #[test] + fn read_byte_error() { + let mut reader = MockReader::new(); + reader.read = |_| { + io_error::cond.raise(placeholder_error()); + None + }; + do io_error::cond.trap(|_| { + }).in { + let byte = reader.read_byte(); + assert!(byte == None); + } + } + + #[test] + fn read_bytes() { + let mut reader = MemReader::new(~[10, 11, 12, 13]); + let bytes = reader.read_bytes(4); + assert!(bytes == ~[10, 11, 12, 13]); + } + + #[test] + fn read_bytes_partial() { + let mut reader = MockReader::new(); + let count = Cell(0); + reader.read = |buf| { + do count.with_mut_ref |count| { + if *count == 0 { + *count = 1; + buf[0] = 10; + buf[1] = 11; + Some(2) + } else { + buf[0] = 12; + buf[1] = 13; + Some(2) + } + } + }; + let bytes = reader.read_bytes(4); + assert!(bytes == ~[10, 11, 12, 13]); + } + + #[test] + fn push_bytes() { + let mut reader = MemReader::new(~[10, 11, 12, 13]); + let mut buf = ~[8, 9]; + assert!(reader.push_bytes(&mut buf, 4)); + assert!(buf == ~[8, 9, 10, 11, 12, 13]); + } + + #[test] + fn push_bytes_partial() { + let mut reader = MockReader::new(); + let count = Cell(0); + reader.read = |buf| { + do count.with_mut_ref |count| { + if *count == 0 { + *count = 1; + buf[0] = 10; + buf[1] = 11; + Some(2) + } else { + buf[0] = 12; + buf[1] = 13; + Some(2) + } + } + }; + let mut buf = ~[8, 9]; + assert!(reader.push_bytes(&mut buf, 4)); + assert!(buf == ~[8, 9, 10, 11, 12, 13]); + } + + #[test] + fn push_bytes_eof() { + let mut reader = MemReader::new(~[10, 11]); + let mut buf = ~[8, 9]; + assert!(!reader.push_bytes(&mut buf, 4)); + assert!(buf == ~[8, 9, 10, 11]); + } + + #[test] + fn push_bytes_error() { + let mut reader = MockReader::new(); + let count = Cell(0); + reader.read = |buf| { + do count.with_mut_ref |count| { + if *count == 0 { + *count = 1; + buf[0] = 10; + Some(1) + } else { + io_error::cond.raise(placeholder_error()); + None + } + } + }; + let mut buf = ~[8, 9]; + do io_error::cond.trap(|_| { } ).in { + assert!(!reader.push_bytes(&mut buf, 4)); + } + assert!(buf == ~[8, 9, 10]); + } + + #[test] + #[should_fail] + #[ignore(cfg(windows))] + fn push_bytes_fail_reset_len() { + use unstable::finally::Finally; + + // push_bytes unsafely sets the vector length. This is testing that + // upon failure the length is reset correctly. + let mut reader = MockReader::new(); + let count = Cell(0); + reader.read = |buf| { + do count.with_mut_ref |count| { + if *count == 0 { + *count = 1; + buf[0] = 10; + Some(1) + } else { + io_error::cond.raise(placeholder_error()); + None + } + } + }; + let buf = @mut ~[8, 9]; + do (|| { + reader.push_bytes(&mut *buf, 4); + }).finally { + // NB: Using rtassert here to trigger abort on failure since this is a should_fail test + rtassert!(*buf == ~[8, 9, 10]); + } + } + +} diff --git a/src/libcore/rt/io/mock.rs b/src/libcore/rt/io/mock.rs new file mode 100644 index 0000000000000..b580b752bd985 --- /dev/null +++ b/src/libcore/rt/io/mock.rs @@ -0,0 +1,50 @@ +// 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. + +use option::{Option, None}; +use rt::io::{Reader, Writer}; + +pub struct MockReader { + read: ~fn(buf: &mut [u8]) -> Option, + eof: ~fn() -> bool +} + +impl MockReader { + pub fn new() -> MockReader { + MockReader { + read: |_| None, + eof: || false + } + } +} + +impl Reader for MockReader { + fn read(&mut self, buf: &mut [u8]) -> Option { (self.read)(buf) } + fn eof(&mut self) -> bool { (self.eof)() } +} + +pub struct MockWriter { + write: ~fn(buf: &[u8]), + flush: ~fn() +} + +impl MockWriter { + pub fn new() -> MockWriter { + MockWriter { + write: |_| (), + flush: || () + } + } +} + +impl Writer for MockWriter { + fn write(&mut self, buf: &[u8]) { (self.write)(buf) } + fn flush(&mut self) { (self.flush)() } +} \ No newline at end of file diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index ab4b83f7cf0ea..f3b0cd22c17c7 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -316,6 +316,8 @@ pub mod native { } } +/// Mock implementations for testing +mod mock; /// The type passed to I/O condition handlers to indicate error /// @@ -350,7 +352,8 @@ condition! { pub trait Reader { /// Read bytes, up to the length of `buf` and place them in `buf`. - /// Returns the number of bytes read, or `None` on EOF. + /// Returns the number of bytes read, or `None` on EOF. The number + /// of bytes read my be less than the number requested, even 0. /// /// # Failure /// @@ -361,6 +364,7 @@ pub trait Reader { /// This doesn't take a `len` argument like the old `read`. /// Will people often need to slice their vectors to call this /// and will that be annoying? + /// Is it actually possible for 0 bytes to be read successfully? fn read(&mut self, buf: &mut [u8]) -> Option; /// Return whether the Reader has reached the end of the stream. @@ -467,3 +471,11 @@ pub fn standard_error(kind: IoErrorKind) -> IoError { _ => fail!() } } + +pub fn placeholder_error() -> IoError { + IoError { + kind: OtherIoError, + desc: "Placeholder error. You shouldn't be seeing this", + detail: None + } +} \ No newline at end of file From 76e097761e0bb11ebe57bd18c13a0c645c655108 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 12 May 2013 21:24:48 -0700 Subject: [PATCH 040/248] core::rt: `read` raises `read_error` --- src/libcore/rt/io/extensions.rs | 238 +------------------------------- src/libcore/rt/io/mod.rs | 20 ++- src/libcore/rt/io/net/tcp.rs | 4 +- src/libcore/rt/io/option.rs | 8 +- 4 files changed, 29 insertions(+), 241 deletions(-) diff --git a/src/libcore/rt/io/extensions.rs b/src/libcore/rt/io/extensions.rs index 665b8a578e396..1c68934e80b05 100644 --- a/src/libcore/rt/io/extensions.rs +++ b/src/libcore/rt/io/extensions.rs @@ -114,434 +114,208 @@ pub trait ReaderByteConversions { /// Reads `n` little-endian unsigned integer bytes. /// /// `n` must be between 1 and 8, inclusive. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_uint_n(&mut self, nbytes: uint) -> u64; /// Reads `n` little-endian signed integer bytes. /// /// `n` must be between 1 and 8, inclusive. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_int_n(&mut self, nbytes: uint) -> i64; /// Reads `n` big-endian unsigned integer bytes. /// /// `n` must be between 1 and 8, inclusive. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_uint_n(&mut self, nbytes: uint) -> u64; /// Reads `n` big-endian signed integer bytes. /// /// `n` must be between 1 and 8, inclusive. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_int_n(&mut self, nbytes: uint) -> i64; /// Reads a little-endian unsigned integer. /// /// The number of bytes returned is system-dependant. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_uint(&mut self) -> uint; /// Reads a little-endian integer. /// /// The number of bytes returned is system-dependant. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_int(&mut self) -> int; /// Reads a big-endian unsigned integer. /// /// The number of bytes returned is system-dependant. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_uint(&mut self) -> uint; /// Reads a big-endian integer. /// /// The number of bytes returned is system-dependant. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_int(&mut self) -> int; /// Reads a big-endian `u64`. /// /// `u64`s are 8 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_u64(&mut self) -> u64; /// Reads a big-endian `u32`. /// /// `u32`s are 4 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_u32(&mut self) -> u32; /// Reads a big-endian `u16`. /// /// `u16`s are 2 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_u16(&mut self) -> u16; /// Reads a big-endian `i64`. /// /// `i64`s are 8 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_i64(&mut self) -> i64; /// Reads a big-endian `i32`. /// /// `i32`s are 4 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_i32(&mut self) -> i32; /// Reads a big-endian `i16`. /// /// `i16`s are 2 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_i16(&mut self) -> i16; /// Reads a big-endian `f64`. /// /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_f64(&mut self) -> f64; /// Reads a big-endian `f32`. /// /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_be_f32(&mut self) -> f32; /// Reads a little-endian `u64`. /// /// `u64`s are 8 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_u64(&mut self) -> u64; /// Reads a little-endian `u32`. /// /// `u32`s are 4 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_u32(&mut self) -> u32; /// Reads a little-endian `u16`. /// /// `u16`s are 2 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_u16(&mut self) -> u16; /// Reads a little-endian `i64`. /// /// `i64`s are 8 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_i64(&mut self) -> i64; /// Reads a little-endian `i32`. /// /// `i32`s are 4 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_i32(&mut self) -> i32; /// Reads a little-endian `i16`. /// /// `i16`s are 2 bytes long. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_i16(&mut self) -> i16; /// Reads a little-endian `f64`. /// /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_f64(&mut self) -> f64; /// Reads a little-endian `f32`. /// /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_le_f32(&mut self) -> f32; /// Read a u8. /// /// `u8`s are 1 byte. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_u8(&mut self) -> u8; /// Read an i8. /// /// `i8`s are 1 byte. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. Returns `0` if - /// the condition is handled. fn read_i8(&mut self) -> i8; } pub trait WriterByteConversions { /// Write the result of passing n through `int::to_str_bytes`. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_int(&mut self, n: int); /// Write the result of passing n through `uint::to_str_bytes`. - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_uint(&mut self, n: uint); /// Write a little-endian uint (number of bytes depends on system). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_uint(&mut self, n: uint); /// Write a little-endian int (number of bytes depends on system). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_int(&mut self, n: int); /// Write a big-endian uint (number of bytes depends on system). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_uint(&mut self, n: uint); /// Write a big-endian int (number of bytes depends on system). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_int(&mut self, n: int); /// Write a big-endian u64 (8 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_u64(&mut self, n: u64); /// Write a big-endian u32 (4 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_u32(&mut self, n: u32); /// Write a big-endian u16 (2 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_u16(&mut self, n: u16); /// Write a big-endian i64 (8 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_i64(&mut self, n: i64); /// Write a big-endian i32 (4 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_i32(&mut self, n: i32); /// Write a big-endian i16 (2 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_i16(&mut self, n: i16); /// Write a big-endian IEEE754 double-precision floating-point (8 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_f64(&mut self, f: f64); /// Write a big-endian IEEE754 single-precision floating-point (4 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_be_f32(&mut self, f: f32); /// Write a little-endian u64 (8 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_u64(&mut self, n: u64); /// Write a little-endian u32 (4 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_u32(&mut self, n: u32); /// Write a little-endian u16 (2 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_u16(&mut self, n: u16); /// Write a little-endian i64 (8 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_i64(&mut self, n: i64); /// Write a little-endian i32 (4 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_i32(&mut self, n: i32); /// Write a little-endian i16 (2 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_i16(&mut self, n: i16); /// Write a little-endian IEEE754 double-precision floating-point /// (8 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_f64(&mut self, f: f64); /// Write a litten-endian IEEE754 single-precision floating-point /// (4 bytes). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_le_f32(&mut self, f: f32); /// Write a u8 (1 byte). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_u8(&mut self, n: u8); /// Write a i8 (1 byte). - /// - /// # Failure - /// - /// Raises the `io_error` condition on error. fn write_i8(&mut self, n: i8); } @@ -552,7 +326,7 @@ mod test { use cell::Cell; use rt::io::mem::MemReader; use rt::io::mock::*; - use rt::io::{io_error, placeholder_error}; + use rt::io::{read_error, placeholder_error}; #[test] fn read_byte() { @@ -592,10 +366,10 @@ mod test { fn read_byte_error() { let mut reader = MockReader::new(); reader.read = |_| { - io_error::cond.raise(placeholder_error()); + read_error::cond.raise(placeholder_error()); None }; - do io_error::cond.trap(|_| { + do read_error::cond.trap(|_| { }).in { let byte = reader.read_byte(); assert!(byte == None); @@ -681,13 +455,13 @@ mod test { buf[0] = 10; Some(1) } else { - io_error::cond.raise(placeholder_error()); + read_error::cond.raise(placeholder_error()); None } } }; let mut buf = ~[8, 9]; - do io_error::cond.trap(|_| { } ).in { + do read_error::cond.trap(|_| { } ).in { assert!(!reader.push_bytes(&mut buf, 4)); } assert!(buf == ~[8, 9, 10]); @@ -710,7 +484,7 @@ mod test { buf[0] = 10; Some(1) } else { - io_error::cond.raise(placeholder_error()); + read_error::cond.raise(placeholder_error()); None } } diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index f3b0cd22c17c7..4ec5e83c38261 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -350,17 +350,31 @@ condition! { /*pub*/ io_error: super::IoError -> (); } +// XXX: Can't put doc comments on macros +// Raised by `read` on error +condition! { + // FIXME (#6009): uncomment `pub` after expansion support lands. + /*pub*/ read_error: super::IoError -> (); +} + pub trait Reader { /// Read bytes, up to the length of `buf` and place them in `buf`. - /// Returns the number of bytes read, or `None` on EOF. The number - /// of bytes read my be less than the number requested, even 0. + /// Returns the number of bytes read. The number of bytes read my + /// be less than the number requested, even 0. Returns `None` on EOF. /// /// # Failure /// - /// Raises the `io_error` condition on error, then returns `None`. + /// Raises the `read_error` condition on error. If the condition + /// is handled then no guarantee is made about the number of bytes + /// read and the contents of `buf`. If the condition is handled + /// returns `None` (XXX see below). /// /// # XXX /// + /// * Should raise error on eof + /// * If the condition is handled it should still return the bytes read, + /// in which case there's no need to return Option + /// /// This doesn't take a `len` argument like the old `read`. /// Will people often need to slice their vectors to call this /// and will that be annoying? diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 4a25334a2fcbc..f5b3c20f651e1 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -13,7 +13,7 @@ use result::{Ok, Err}; use rt::sched::local_sched::unsafe_borrow_io; use rt::io::net::ip::IpAddr; use rt::io::{Reader, Writer, Listener}; -use rt::io::{io_error, EndOfFile}; +use rt::io::{io_error, read_error, EndOfFile}; use rt::rtio::{IoFactory, RtioTcpListener, RtioTcpListenerObject, RtioTcpStream, RtioTcpStreamObject}; @@ -58,7 +58,7 @@ impl Reader for TcpStream { Err(ioerr) => { // EOF is indicated by returning None if ioerr.kind != EndOfFile { - io_error::cond.raise(ioerr); + read_error::cond.raise(ioerr); } return None; } diff --git a/src/libcore/rt/io/option.rs b/src/libcore/rt/io/option.rs index 95f8711cb5bd5..6ae747f8b4b4c 100644 --- a/src/libcore/rt/io/option.rs +++ b/src/libcore/rt/io/option.rs @@ -18,7 +18,7 @@ use option::*; use super::{Reader, Writer, Listener}; -use super::{standard_error, PreviousIoError, io_error, IoError}; +use super::{standard_error, PreviousIoError, io_error, read_error, IoError}; fn prev_io_error() -> IoError { standard_error(PreviousIoError) @@ -45,7 +45,7 @@ impl Reader for Option { match *self { Some(ref mut reader) => reader.read(buf), None => { - io_error::cond.raise(prev_io_error()); + read_error::cond.raise(prev_io_error()); None } } @@ -79,7 +79,7 @@ mod test { use option::*; use super::super::mem::*; use rt::test::*; - use super::super::{PreviousIoError, io_error}; + use super::super::{PreviousIoError, io_error, read_error}; #[test] fn test_option_writer() { @@ -133,7 +133,7 @@ mod test { let mut buf = []; let mut called = false; - do io_error::cond.trap(|err| { + do read_error::cond.trap(|err| { assert!(err.kind == PreviousIoError); called = true; }).in { From 4724966b0656761da94e24e73b028cd0d3420a7e Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 10 May 2013 17:07:41 -0700 Subject: [PATCH 041/248] core::rt: Add uv timer bindings --- src/libcore/rt/local_sched.rs | 5 +- src/libcore/rt/uv/mod.rs | 9 +- src/libcore/rt/uv/timer.rs | 186 ++++++++++++++++++++++++++++++++++ src/libcore/rt/uv/uvll.rs | 10 +- src/libstd/uv_ll.rs | 8 +- src/rt/rust_uv.cpp | 2 +- 6 files changed, 207 insertions(+), 13 deletions(-) create mode 100644 src/libcore/rt/uv/timer.rs diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index 1ef1fd33a83a5..ffc19c5b5e476 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -97,7 +97,10 @@ pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { } fn tls_key() -> tls::Key { - maybe_tls_key().get() + match maybe_tls_key() { + Some(key) => key, + None => abort!("runtime tls key not initialized") + } } fn maybe_tls_key() -> Option { diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 871fd2a9042f9..ee3c5ceffd236 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -59,6 +59,7 @@ use rt::io::IoError; pub use self::file::FsRequest; pub use self::net::{StreamWatcher, TcpWatcher}; pub use self::idle::IdleWatcher; +pub use self::timer::TimerWatcher; /// The implementation of `rtio` for libuv pub mod uvio; @@ -69,6 +70,7 @@ pub mod uvll; pub mod file; pub mod net; pub mod idle; +pub mod timer; /// XXX: Loop(*handle) is buggy with destructors. Normal structs /// with dtors may not be destructured, but tuple structs can, @@ -125,6 +127,7 @@ pub type NullCallback = ~fn(); pub type IdleCallback = ~fn(IdleWatcher, Option); pub type ConnectionCallback = ~fn(StreamWatcher, Option); pub type FsCallback = ~fn(FsRequest, Option); +pub type TimerCallback = ~fn(TimerWatcher, Option); /// Callbacks used by StreamWatchers, set as custom data on the foreign handle @@ -134,7 +137,8 @@ struct WatcherData { connect_cb: Option, close_cb: Option, alloc_cb: Option, - idle_cb: Option + idle_cb: Option, + timer_cb: Option } pub trait WatcherInterop { @@ -162,7 +166,8 @@ impl> WatcherInterop for W { connect_cb: None, close_cb: None, alloc_cb: None, - idle_cb: None + idle_cb: None, + timer_cb: None }; let data = transmute::<~WatcherData, *c_void>(data); uvll::set_data_for_uv_handle(self.native_handle(), data); diff --git a/src/libcore/rt/uv/timer.rs b/src/libcore/rt/uv/timer.rs new file mode 100644 index 0000000000000..1045a77da12fa --- /dev/null +++ b/src/libcore/rt/uv/timer.rs @@ -0,0 +1,186 @@ +// 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. + +use libc::{c_void, c_int}; +use option::Some; +use rt::uv::uvll; +use rt::uv::{Watcher, Loop, NativeHandle, TimerCallback, NullCallback}; +use rt::uv::status_to_maybe_uv_error; + +pub struct TimerWatcher(*uvll::uv_timer_t); +impl Watcher for TimerWatcher { } + +impl TimerWatcher { + pub fn new(loop_: &mut Loop) -> TimerWatcher { + unsafe { + let handle = uvll::malloc_handle(uvll::UV_TIMER); + assert!(handle.is_not_null()); + assert!(0 == uvll::timer_init(loop_.native_handle(), handle)); + let mut watcher: TimerWatcher = NativeHandle::from_native_handle(handle); + watcher.install_watcher_data(); + return watcher; + } + } + + pub fn start(&mut self, timeout: u64, repeat: u64, cb: TimerCallback) { + { + let data = self.get_watcher_data(); + data.timer_cb = Some(cb); + } + + unsafe { + uvll::timer_start(self.native_handle(), timer_cb, timeout, repeat); + } + + extern fn timer_cb(handle: *uvll::uv_timer_t, status: c_int) { + let mut watcher: TimerWatcher = NativeHandle::from_native_handle(handle); + let data = watcher.get_watcher_data(); + let cb = data.timer_cb.get_ref(); + let status = status_to_maybe_uv_error(handle, status); + (*cb)(watcher, status); + } + } + + pub fn stop(&mut self) { + unsafe { + uvll::timer_stop(self.native_handle()); + } + } + + pub fn close(self, cb: NullCallback) { + let mut watcher = self; + { + let data = watcher.get_watcher_data(); + assert!(data.close_cb.is_none()); + data.close_cb = Some(cb); + } + + unsafe { + uvll::close(watcher.native_handle(), close_cb); + } + + extern fn close_cb(handle: *uvll::uv_timer_t) { + let mut watcher: TimerWatcher = NativeHandle::from_native_handle(handle); + { + let mut data = watcher.get_watcher_data(); + data.close_cb.swap_unwrap()(); + } + watcher.drop_watcher_data(); + unsafe { + uvll::free_handle(handle as *c_void); + } + } + } +} + +impl NativeHandle<*uvll::uv_timer_t> for TimerWatcher { + fn from_native_handle(handle: *uvll::uv_timer_t) -> TimerWatcher { + TimerWatcher(handle) + } + fn native_handle(&self) -> *uvll::uv_idle_t { + match self { &TimerWatcher(ptr) => ptr } + } +} + +#[cfg(test)] +mod test { + use super::*; + use rt::uv::Loop; + use unstable::run_in_bare_thread; + + #[test] + fn smoke_test() { + do run_in_bare_thread { + let mut count = 0; + let count_ptr: *mut int = &mut count; + let mut loop_ = Loop::new(); + let mut timer = TimerWatcher::new(&mut loop_); + do timer.start(10, 0) |timer, status| { + assert!(status.is_none()); + unsafe { *count_ptr += 1 }; + timer.close(||()); + } + loop_.run(); + loop_.close(); + assert!(count == 1); + } + } + + #[test] + fn start_twice() { + do run_in_bare_thread { + let mut count = 0; + let count_ptr: *mut int = &mut count; + let mut loop_ = Loop::new(); + let mut timer = TimerWatcher::new(&mut loop_); + do timer.start(10, 0) |timer, status| { + let mut timer = timer; + assert!(status.is_none()); + unsafe { *count_ptr += 1 }; + do timer.start(10, 0) |timer, status| { + let mut timer = timer; + assert!(status.is_none()); + unsafe { *count_ptr += 1 }; + timer.close(||()); + } + } + loop_.run(); + loop_.close(); + assert!(count == 2); + } + } + + #[test] + fn repeat_stop() { + do run_in_bare_thread { + let mut count = 0; + let count_ptr: *mut int = &mut count; + let mut loop_ = Loop::new(); + let mut timer = TimerWatcher::new(&mut loop_); + do timer.start(10, 20) |timer, status| { + assert!(status.is_none()); + unsafe { + *count_ptr += 1; + + if *count_ptr == 10 { + + // Stop the timer and do something else + let mut timer = timer; + timer.stop(); + // Freeze timer so it can be captured + let timer = timer; + + let mut loop_ = timer.event_loop(); + let mut timer2 = TimerWatcher::new(&mut loop_); + do timer2.start(10, 0) |timer2, status| { + + unsafe { *count_ptr += 1; } + + let mut timer2 = timer2; + timer2.close(||()); + + // Restart the original timer + let mut timer = timer; + do timer.start(10, 0) |timer, status| { + unsafe { *count_ptr += 1; } + let mut timer = timer; + timer.close(||()); + } + } + } + }; + } + loop_.run(); + loop_.close(); + assert!(count == 12); + } + } + +} diff --git a/src/libcore/rt/uv/uvll.rs b/src/libcore/rt/uv/uvll.rs index 76abf2a195d5c..94e6b82ab8fa9 100644 --- a/src/libcore/rt/uv/uvll.rs +++ b/src/libcore/rt/uv/uvll.rs @@ -268,9 +268,9 @@ pub unsafe fn buf_init(input: *u8, len: uint) -> uv_buf_t { pub unsafe fn timer_init(loop_ptr: *c_void, timer_ptr: *uv_timer_t) -> c_int { return rust_uv_timer_init(loop_ptr, timer_ptr); } -pub unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: uint, - repeat: uint) -> c_int { - return rust_uv_timer_start(timer_ptr, cb, timeout as c_uint, repeat as c_uint); +pub unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: u64, + repeat: u64) -> c_int { + return rust_uv_timer_start(timer_ptr, cb, timeout, repeat); } pub unsafe fn timer_stop(timer_ptr: *uv_timer_t) -> c_int { return rust_uv_timer_stop(timer_ptr); @@ -431,8 +431,8 @@ extern { timer_handle: *uv_timer_t) -> c_int; fn rust_uv_timer_start(timer_handle: *uv_timer_t, cb: *u8, - timeout: c_uint, - repeat: c_uint) -> c_int; + timeout: libc::uint64_t, + repeat: libc::uint64_t) -> c_int; fn rust_uv_timer_stop(handle: *uv_timer_t) -> c_int; fn rust_uv_malloc_buf_base_of(sug_size: size_t) -> *u8; diff --git a/src/libstd/uv_ll.rs b/src/libstd/uv_ll.rs index a14c048b8ded5..96ceb1002d8b6 100644 --- a/src/libstd/uv_ll.rs +++ b/src/libstd/uv_ll.rs @@ -819,8 +819,8 @@ extern { unsafe fn rust_uv_timer_start( timer_handle: *uv_timer_t, cb: *u8, - timeout: libc::c_uint, - repeat: libc::c_uint) -> libc::c_int; + timeout: libc::uint64_t, + repeat: libc::uint64_t) -> libc::c_int; unsafe fn rust_uv_timer_stop(handle: *uv_timer_t) -> libc::c_int; unsafe fn rust_uv_getaddrinfo(loop_ptr: *libc::c_void, @@ -1084,8 +1084,8 @@ pub unsafe fn timer_init(loop_ptr: *libc::c_void, } pub unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: uint, repeat: uint) -> libc::c_int { - return rust_uv_timer_start(timer_ptr, cb, timeout as libc::c_uint, - repeat as libc::c_uint); + return rust_uv_timer_start(timer_ptr, cb, timeout as libc::uint64_t, + repeat as libc::uint64_t); } pub unsafe fn timer_stop(timer_ptr: *uv_timer_t) -> libc::c_int { return rust_uv_timer_stop(timer_ptr); diff --git a/src/rt/rust_uv.cpp b/src/rt/rust_uv.cpp index 8cf2bd4b4acb9..fefcbbcacf7d4 100644 --- a/src/rt/rust_uv.cpp +++ b/src/rt/rust_uv.cpp @@ -229,7 +229,7 @@ rust_uv_timer_init(uv_loop_t* loop, uv_timer_t* timer) { extern "C" int rust_uv_timer_start(uv_timer_t* the_timer, uv_timer_cb cb, - uint32_t timeout, uint32_t repeat) { + int64_t timeout, int64_t repeat) { return uv_timer_start(the_timer, cb, timeout, repeat); } From c42b03de17b2d0c567dc85417ec22518d69fd8ae Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 11 May 2013 00:42:16 -0700 Subject: [PATCH 042/248] core::rt: Fix scheduling logic for enqueued tasks --- src/libcore/macros.rs | 4 +- src/libcore/rt/mod.rs | 6 +- src/libcore/rt/rtio.rs | 1 + src/libcore/rt/sched.rs | 275 ++++++++++++++++++++--------------- src/libcore/rt/test.rs | 12 +- src/libcore/rt/uv/uvio.rs | 12 +- src/libcore/rt/work_queue.rs | 4 + 7 files changed, 188 insertions(+), 126 deletions(-) diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index 04ee086b9ae4b..fda48b6ffb7d9 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -11,7 +11,7 @@ #[macro_escape]; // Some basic logging -macro_rules! rtdebug ( +macro_rules! rtdebug_ ( ($( $arg:expr),+) => ( { dumb_println(fmt!( $($arg),+ )); @@ -26,7 +26,7 @@ macro_rules! rtdebug ( ) // An alternate version with no output, for turning off logging -macro_rules! rtdebug_ ( +macro_rules! rtdebug ( ($( $arg:expr),+) => ( $(let _ = $arg)*; ) ) diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 3e2e10504cf9b..4ed76003eeb60 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -147,7 +147,7 @@ pub fn start(_argc: int, _argv: **u8, crate_map: *u8, main: ~fn()) -> int { let mut sched = ~Scheduler::new(loop_); let main_task = ~Task::new(&mut sched.stack_pool, main); - sched.task_queue.push_back(main_task); + sched.enqueue_task(main_task); sched.run(); return 0; @@ -225,11 +225,11 @@ fn test_context() { assert!(context() == SchedulerContext); let task = Cell(task); do local_sched::borrow |sched| { - sched.task_queue.push_back(task.take()); + sched.enqueue_task(task.take()); } } }; - sched.task_queue.push_back(task); + sched.enqueue_task(task); sched.run(); } } diff --git a/src/libcore/rt/rtio.rs b/src/libcore/rt/rtio.rs index 497ff8841b6bd..4b5eda22ff5de 100644 --- a/src/libcore/rt/rtio.rs +++ b/src/libcore/rt/rtio.rs @@ -25,6 +25,7 @@ pub type RtioTcpListenerObject = uvio::UvTcpListener; pub trait EventLoop { fn run(&mut self); fn callback(&mut self, ~fn()); + fn callback_ms(&mut self, ms: u64, ~fn()); /// The asynchronous I/O services. Not all event loops may provide one fn io<'a>(&'a mut self) -> Option<&'a mut IoFactoryObject>; } diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 395f9099571a0..3469997833c5d 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -31,7 +31,7 @@ pub mod local_sched; /// thread local storage and the running task is owned by the /// scheduler. pub struct Scheduler { - task_queue: WorkQueue<~Task>, + priv task_queue: WorkQueue<~Task>, stack_pool: StackPool, /// The event loop used to drive the scheduler and perform I/O event_loop: ~EventLoopObject, @@ -91,44 +91,56 @@ pub impl Scheduler { fn run(~self) -> ~Scheduler { assert!(!self.in_task_context()); - // Give ownership of the scheduler (self) to the thread - local_sched::put(self); + let mut self_sched = self; unsafe { - let scheduler = local_sched::unsafe_borrow(); - fn run_scheduler_once() { - let scheduler = local_sched::take(); - if scheduler.resume_task_from_queue() { - // Ok, a task ran. Nice! We'll do it again later - do local_sched::borrow |scheduler| { - scheduler.event_loop.callback(run_scheduler_once); - } - } - } + let event_loop: *mut ~EventLoopObject = { + let event_loop: *mut ~EventLoopObject = &mut self_sched.event_loop; + event_loop + }; - let scheduler = &mut *scheduler; - scheduler.event_loop.callback(run_scheduler_once); - scheduler.event_loop.run(); + // Give ownership of the scheduler (self) to the thread + local_sched::put(self_sched); + + (*event_loop).run(); } - return local_sched::take(); + let sched = local_sched::take(); + assert!(sched.task_queue.is_empty()); + return sched; + } + + /// Schedule a task to be executed later. + /// + /// Pushes the task onto the work stealing queue and tells the event loop + /// to run it later. Always use this instead of pushing to the work queue + /// directly. + fn enqueue_task(&mut self, task: ~Task) { + self.task_queue.push_front(task); + self.event_loop.callback(resume_task_from_queue); + + fn resume_task_from_queue() { + let scheduler = local_sched::take(); + scheduler.resume_task_from_queue(); + } } // * Scheduler-context operations - fn resume_task_from_queue(~self) -> bool { + fn resume_task_from_queue(~self) { assert!(!self.in_task_context()); + rtdebug!("looking in work queue for task to schedule"); + let mut this = self; match this.task_queue.pop_front() { Some(task) => { + rtdebug!("resuming task from work queue"); this.resume_task_immediately(task); - return true; } None => { rtdebug!("no tasks in queue"); local_sched::put(this); - return false; } } } @@ -158,7 +170,7 @@ pub impl Scheduler { do self.switch_running_tasks_and_then(task) |last_task| { let last_task = Cell(last_task); do local_sched::borrow |sched| { - sched.task_queue.push_front(last_task.take()); + sched.enqueue_task(last_task.take()); } } } @@ -385,118 +397,153 @@ pub impl Task { } } -#[test] -fn test_simple_scheduling() { - do run_in_bare_thread { - let mut task_ran = false; - let task_ran_ptr: *mut bool = &mut task_ran; - - let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~do Task::new(&mut sched.stack_pool) { - unsafe { *task_ran_ptr = true; } - }; - sched.task_queue.push_back(task); - sched.run(); - assert!(task_ran); +#[cfg(test)] +mod test { + use int; + use cell::Cell; + use rt::uv::uvio::UvEventLoop; + use unstable::run_in_bare_thread; + use task::spawn; + use rt::test::*; + use super::*; + + #[test] + fn test_simple_scheduling() { + do run_in_bare_thread { + let mut task_ran = false; + let task_ran_ptr: *mut bool = &mut task_ran; + + let mut sched = ~UvEventLoop::new_scheduler(); + let task = ~do Task::new(&mut sched.stack_pool) { + unsafe { *task_ran_ptr = true; } + }; + sched.enqueue_task(task); + sched.run(); + assert!(task_ran); + } } -} -#[test] -fn test_several_tasks() { - do run_in_bare_thread { - let total = 10; - let mut task_count = 0; - let task_count_ptr: *mut int = &mut task_count; + #[test] + fn test_several_tasks() { + do run_in_bare_thread { + let total = 10; + let mut task_count = 0; + let task_count_ptr: *mut int = &mut task_count; - let mut sched = ~UvEventLoop::new_scheduler(); - for int::range(0, total) |_| { - let task = ~do Task::new(&mut sched.stack_pool) { - unsafe { *task_count_ptr = *task_count_ptr + 1; } - }; - sched.task_queue.push_back(task); + let mut sched = ~UvEventLoop::new_scheduler(); + for int::range(0, total) |_| { + let task = ~do Task::new(&mut sched.stack_pool) { + unsafe { *task_count_ptr = *task_count_ptr + 1; } + }; + sched.enqueue_task(task); + } + sched.run(); + assert!(task_count == total); } - sched.run(); - assert!(task_count == total); } -} -#[test] -fn test_swap_tasks_then() { - do run_in_bare_thread { - let mut count = 0; - let count_ptr: *mut int = &mut count; - - let mut sched = ~UvEventLoop::new_scheduler(); - let task1 = ~do Task::new(&mut sched.stack_pool) { - unsafe { *count_ptr = *count_ptr + 1; } - let mut sched = local_sched::take(); - let task2 = ~do Task::new(&mut sched.stack_pool) { + #[test] + fn test_swap_tasks_then() { + do run_in_bare_thread { + let mut count = 0; + let count_ptr: *mut int = &mut count; + + let mut sched = ~UvEventLoop::new_scheduler(); + let task1 = ~do Task::new(&mut sched.stack_pool) { unsafe { *count_ptr = *count_ptr + 1; } - }; - // Context switch directly to the new task - do sched.switch_running_tasks_and_then(task2) |task1| { - let task1 = Cell(task1); - do local_sched::borrow |sched| { - sched.task_queue.push_front(task1.take()); + let mut sched = local_sched::take(); + let task2 = ~do Task::new(&mut sched.stack_pool) { + unsafe { *count_ptr = *count_ptr + 1; } + }; + // Context switch directly to the new task + do sched.switch_running_tasks_and_then(task2) |task1| { + let task1 = Cell(task1); + do local_sched::borrow |sched| { + sched.enqueue_task(task1.take()); + } } - } - unsafe { *count_ptr = *count_ptr + 1; } - }; - sched.task_queue.push_back(task1); - sched.run(); - assert!(count == 3); + unsafe { *count_ptr = *count_ptr + 1; } + }; + sched.enqueue_task(task1); + sched.run(); + assert!(count == 3); + } } -} -#[bench] #[test] #[ignore(reason = "long test")] -fn test_run_a_lot_of_tasks_queued() { - do run_in_bare_thread { - static MAX: int = 1000000; - let mut count = 0; - let count_ptr: *mut int = &mut count; + #[bench] #[test] #[ignore(reason = "long test")] + fn test_run_a_lot_of_tasks_queued() { + do run_in_bare_thread { + static MAX: int = 1000000; + let mut count = 0; + let count_ptr: *mut int = &mut count; - let mut sched = ~UvEventLoop::new_scheduler(); + let mut sched = ~UvEventLoop::new_scheduler(); - let start_task = ~do Task::new(&mut sched.stack_pool) { - run_task(count_ptr); - }; - sched.task_queue.push_back(start_task); - sched.run(); + let start_task = ~do Task::new(&mut sched.stack_pool) { + run_task(count_ptr); + }; + sched.enqueue_task(start_task); + sched.run(); - assert!(count == MAX); + assert!(count == MAX); - fn run_task(count_ptr: *mut int) { - do local_sched::borrow |sched| { - let task = ~do Task::new(&mut sched.stack_pool) { - unsafe { - *count_ptr = *count_ptr + 1; - if *count_ptr != MAX { - run_task(count_ptr); + fn run_task(count_ptr: *mut int) { + do local_sched::borrow |sched| { + let task = ~do Task::new(&mut sched.stack_pool) { + unsafe { + *count_ptr = *count_ptr + 1; + if *count_ptr != MAX { + run_task(count_ptr); + } } + }; + sched.enqueue_task(task); + } + }; + } + } + + #[test] + fn test_block_task() { + do run_in_bare_thread { + let mut sched = ~UvEventLoop::new_scheduler(); + let task = ~do Task::new(&mut sched.stack_pool) { + let sched = local_sched::take(); + assert!(sched.in_task_context()); + do sched.deschedule_running_task_and_then() |task| { + let task = Cell(task); + do local_sched::borrow |sched| { + assert!(!sched.in_task_context()); + sched.enqueue_task(task.take()); } - }; - sched.task_queue.push_back(task); - } - }; + } + }; + sched.enqueue_task(task); + sched.run(); + } } -} -#[test] -fn test_block_task() { - do run_in_bare_thread { - let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~do Task::new(&mut sched.stack_pool) { - let sched = local_sched::take(); - assert!(sched.in_task_context()); - do sched.deschedule_running_task_and_then() |task| { - let task = Cell(task); - do local_sched::borrow |sched| { - assert!(!sched.in_task_context()); - sched.task_queue.push_back(task.take()); + #[test] + fn test_io_callback() { + // This is a regression test that when there are no schedulable tasks + // in the work queue, but we are performing I/O, that once we do put + // something in the work queue again the scheduler picks it up and doesn't + // exit before emptying the work queue + do run_in_newsched_task { + do spawn { + let sched = local_sched::take(); + do sched.deschedule_running_task_and_then |task| { + let mut sched = local_sched::take(); + let task = Cell(task); + do sched.event_loop.callback_ms(10) { + rtdebug!("in callback"); + let mut sched = local_sched::take(); + sched.enqueue_task(task.take()); + local_sched::put(sched); + } + local_sched::put(sched); } } - }; - sched.task_queue.push_back(task); - sched.run(); + } } } diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index 8d0ae0caf4d62..cfd1748ded35a 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -28,7 +28,7 @@ pub fn run_in_newsched_task(f: ~fn()) { let task = ~Task::with_local(&mut sched.stack_pool, LocalServices::without_unwinding(), f.take()); - sched.task_queue.push_back(task); + sched.enqueue_task(task); sched.run(); } } @@ -59,7 +59,7 @@ pub fn spawntask_immediately(f: ~fn()) { do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); do local_sched::borrow |sched| { - sched.task_queue.push_front(task.take()); + sched.enqueue_task(task.take()); } } } @@ -73,7 +73,7 @@ pub fn spawntask_later(f: ~fn()) { LocalServices::without_unwinding(), f); - sched.task_queue.push_front(task); + sched.enqueue_task(task); local_sched::put(sched); } @@ -94,11 +94,11 @@ pub fn spawntask_random(f: ~fn()) { do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); do local_sched::borrow |sched| { - sched.task_queue.push_front(task.take()); + sched.enqueue_task(task.take()); } } } else { - sched.task_queue.push_front(task); + sched.enqueue_task(task); local_sched::put(sched); } } @@ -132,7 +132,7 @@ pub fn spawntask_try(f: ~fn()) -> Result<(), ()> { do sched.switch_running_tasks_and_then(old_task.take()) |new_task| { let new_task = Cell(new_task); do local_sched::borrow |sched| { - sched.task_queue.push_front(new_task.take()); + sched.enqueue_task(new_task.take()); } } } diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 25d912ce42eb5..a25d18101a7fd 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -73,6 +73,16 @@ impl EventLoop for UvEventLoop { } } + fn callback_ms(&mut self, ms: u64, f: ~fn()) { + let mut timer = TimerWatcher::new(self.uvio.uv_loop()); + do timer.start(ms, 0) |timer, status| { + assert!(status.is_none()); + let mut timer = timer; + timer.close(||()); + f(); + } + } + fn io<'a>(&'a mut self) -> Option<&'a mut IoFactoryObject> { Some(&mut self.uvio) } @@ -419,7 +429,7 @@ fn test_read_and_block() { do scheduler.deschedule_running_task_and_then |task| { let task = Cell(task); do local_sched::borrow |scheduler| { - scheduler.task_queue.push_back(task.take()); + scheduler.enqueue_task(task.take()); } } } diff --git a/src/libcore/rt/work_queue.rs b/src/libcore/rt/work_queue.rs index 495cd75a0bf8e..f82b5847ef2b8 100644 --- a/src/libcore/rt/work_queue.rs +++ b/src/libcore/rt/work_queue.rs @@ -46,4 +46,8 @@ pub impl WorkQueue { None } } + + fn is_empty(&self) -> bool { + return self.queue.is_empty(); + } } From 56c0b188b66f71f55e2d577ca4a23830a31433e6 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 11 May 2013 19:46:43 -0700 Subject: [PATCH 043/248] rt: Rename sched_key to rt_key It is more general-purpose than holding scheduler pointers --- src/libcore/rt/local_sched.rs | 4 ++-- src/rt/rust_builtin.cpp | 14 +++++++------- src/rt/rustrt.def.in | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index ffc19c5b5e476..895354d2218e5 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -105,7 +105,7 @@ fn tls_key() -> tls::Key { fn maybe_tls_key() -> Option { unsafe { - let key: *mut c_void = rust_get_sched_tls_key(); + let key: *mut c_void = rust_get_rt_tls_key(); let key: &mut tls::Key = cast::transmute(key); let key = *key; // Check that the key has been initialized. @@ -130,7 +130,7 @@ fn maybe_tls_key() -> Option { extern { #[fast_ffi] - fn rust_get_sched_tls_key() -> *mut c_void; + fn rust_get_rt_tls_key() -> *mut c_void; } #[test] diff --git a/src/rt/rust_builtin.cpp b/src/rt/rust_builtin.cpp index 39a6f5bfd1b7b..1a64066b5a946 100644 --- a/src/rt/rust_builtin.cpp +++ b/src/rt/rust_builtin.cpp @@ -830,14 +830,14 @@ rust_get_rt_env() { } #ifndef _WIN32 -pthread_key_t sched_key = -1; +pthread_key_t rt_key = -1; #else -DWORD sched_key = -1; +DWORD rt_key = -1; #endif extern "C" void* -rust_get_sched_tls_key() { - return &sched_key; +rust_get_rt_tls_key() { + return &rt_key; } // Initialize the global state required by the new scheduler @@ -852,10 +852,10 @@ rust_initialize_global_state() { if (!initialized) { #ifndef _WIN32 - assert(!pthread_key_create(&sched_key, NULL)); + assert(!pthread_key_create(&rt_key, NULL)); #else - sched_key = TlsAlloc(); - assert(sched_key != TLS_OUT_OF_INDEXES); + rt_key = TlsAlloc(); + assert(rt_key != TLS_OUT_OF_INDEXES); #endif initialized = true; diff --git a/src/rt/rustrt.def.in b/src/rt/rustrt.def.in index f1ddb17c499a1..cdc282440b830 100644 --- a/src/rt/rustrt.def.in +++ b/src/rt/rustrt.def.in @@ -196,7 +196,7 @@ rust_get_global_data_ptr rust_inc_kernel_live_count rust_dec_kernel_live_count rust_exchange_count -rust_get_sched_tls_key +rust_get_rt_tls_key swap_registers rust_readdir rust_opendir From 7f5746f6d2bcc048aca5ddfbfdf41497ab874836 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 12 May 2013 15:08:07 -0700 Subject: [PATCH 044/248] core::rt: Rename Sched.task_queue to work_queue --- src/libcore/rt/sched.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 3469997833c5d..1e4a9c87a68fe 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -31,7 +31,7 @@ pub mod local_sched; /// thread local storage and the running task is owned by the /// scheduler. pub struct Scheduler { - priv task_queue: WorkQueue<~Task>, + priv work_queue: WorkQueue<~Task>, stack_pool: StackPool, /// The event loop used to drive the scheduler and perform I/O event_loop: ~EventLoopObject, @@ -76,7 +76,7 @@ pub impl Scheduler { Scheduler { event_loop: event_loop, - task_queue: WorkQueue::new(), + work_queue: WorkQueue::new(), stack_pool: StackPool::new(), saved_context: Context::empty(), current_task: None, @@ -106,7 +106,7 @@ pub impl Scheduler { } let sched = local_sched::take(); - assert!(sched.task_queue.is_empty()); + assert!(sched.work_queue.is_empty()); return sched; } @@ -116,7 +116,7 @@ pub impl Scheduler { /// to run it later. Always use this instead of pushing to the work queue /// directly. fn enqueue_task(&mut self, task: ~Task) { - self.task_queue.push_front(task); + self.work_queue.push_front(task); self.event_loop.callback(resume_task_from_queue); fn resume_task_from_queue() { @@ -133,7 +133,7 @@ pub impl Scheduler { rtdebug!("looking in work queue for task to schedule"); let mut this = self; - match this.task_queue.pop_front() { + match this.work_queue.pop_front() { Some(task) => { rtdebug!("resuming task from work queue"); this.resume_task_immediately(task); From 390dde571ede57133f249692ab020f83fd5d22ee Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 12 May 2013 15:26:19 -0700 Subject: [PATCH 045/248] core::rt: Rename Task to Coroutine --- src/libcore/rt/mod.rs | 10 +++--- src/libcore/rt/sched.rs | 66 +++++++++++++++++++-------------------- src/libcore/rt/test.rs | 34 ++++++++++---------- src/libcore/rt/tube.rs | 4 +-- src/libcore/task/spawn.rs | 2 +- 5 files changed, 58 insertions(+), 58 deletions(-) diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 4ed76003eeb60..7a772ff0f3b96 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -67,7 +67,7 @@ use ptr::Ptr; /// The global (exchange) heap. pub mod global_heap; -/// The Scheduler and Task types. +/// The Scheduler and Coroutine types. mod sched; /// Thread-local access to the current Scheduler. @@ -138,14 +138,14 @@ pub mod tube; /// The return value is used as the process return code. 0 on success, 101 on error. pub fn start(_argc: int, _argv: **u8, crate_map: *u8, main: ~fn()) -> int { - use self::sched::{Scheduler, Task}; + use self::sched::{Scheduler, Coroutine}; use self::uv::uvio::UvEventLoop; init(crate_map); let loop_ = ~UvEventLoop::new(); let mut sched = ~Scheduler::new(loop_); - let main_task = ~Task::new(&mut sched.stack_pool, main); + let main_task = ~Coroutine::new(&mut sched.stack_pool, main); sched.enqueue_task(main_task); sched.run(); @@ -210,7 +210,7 @@ pub fn context() -> RuntimeContext { #[test] fn test_context() { use unstable::run_in_bare_thread; - use self::sched::{local_sched, Task}; + use self::sched::{local_sched, Coroutine}; use rt::uv::uvio::UvEventLoop; use cell::Cell; @@ -218,7 +218,7 @@ fn test_context() { do run_in_bare_thread { assert!(context() == GlobalContext); let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~do Task::new(&mut sched.stack_pool) { + let task = ~do Coroutine::new(&mut sched.stack_pool) { assert!(context() == TaskContext); let sched = local_sched::take(); do sched.deschedule_running_task_and_then() |task| { diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 1e4a9c87a68fe..d92eaf89e5f3c 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -26,12 +26,12 @@ use cell::Cell; // A more convenient name for external callers, e.g. `local_sched::take()` pub mod local_sched; -/// The Scheduler is responsible for coordinating execution of Tasks +/// The Scheduler is responsible for coordinating execution of Coroutines /// on a single thread. When the scheduler is running it is owned by /// thread local storage and the running task is owned by the /// scheduler. pub struct Scheduler { - priv work_queue: WorkQueue<~Task>, + priv work_queue: WorkQueue<~Coroutine>, stack_pool: StackPool, /// The event loop used to drive the scheduler and perform I/O event_loop: ~EventLoopObject, @@ -39,7 +39,7 @@ pub struct Scheduler { /// Always valid when a task is executing, otherwise not priv saved_context: Context, /// The currently executing task - current_task: Option<~Task>, + current_task: Option<~Coroutine>, /// An action performed after a context switch on behalf of the /// code running before the context switch priv cleanup_job: Option @@ -49,17 +49,17 @@ pub struct Scheduler { // complaining type UnsafeTaskReceiver = sys::Closure; trait ClosureConverter { - fn from_fn(&fn(~Task)) -> Self; - fn to_fn(self) -> &fn(~Task); + fn from_fn(&fn(~Coroutine)) -> Self; + fn to_fn(self) -> &fn(~Coroutine); } impl ClosureConverter for UnsafeTaskReceiver { - fn from_fn(f: &fn(~Task)) -> UnsafeTaskReceiver { unsafe { transmute(f) } } - fn to_fn(self) -> &fn(~Task) { unsafe { transmute(self) } } + fn from_fn(f: &fn(~Coroutine)) -> UnsafeTaskReceiver { unsafe { transmute(f) } } + fn to_fn(self) -> &fn(~Coroutine) { unsafe { transmute(self) } } } enum CleanupJob { DoNothing, - GiveTask(~Task, UnsafeTaskReceiver) + GiveTask(~Coroutine, UnsafeTaskReceiver) } pub impl Scheduler { @@ -115,7 +115,7 @@ pub impl Scheduler { /// Pushes the task onto the work stealing queue and tells the event loop /// to run it later. Always use this instead of pushing to the work queue /// directly. - fn enqueue_task(&mut self, task: ~Task) { + fn enqueue_task(&mut self, task: ~Coroutine) { self.work_queue.push_front(task); self.event_loop.callback(resume_task_from_queue); @@ -164,7 +164,7 @@ pub impl Scheduler { abort!("control reached end of task"); } - fn schedule_new_task(~self, task: ~Task) { + fn schedule_new_task(~self, task: ~Coroutine) { assert!(self.in_task_context()); do self.switch_running_tasks_and_then(task) |last_task| { @@ -177,7 +177,7 @@ pub impl Scheduler { // Core scheduling ops - fn resume_task_immediately(~self, task: ~Task) { + fn resume_task_immediately(~self, task: ~Coroutine) { let mut this = self; assert!(!this.in_task_context()); @@ -215,7 +215,7 @@ pub impl Scheduler { /// The closure here is a *stack* closure that lives in the /// running task. It gets transmuted to the scheduler's lifetime /// and called while the task is blocked. - fn deschedule_running_task_and_then(~self, f: &fn(~Task)) { + fn deschedule_running_task_and_then(~self, f: &fn(~Coroutine)) { let mut this = self; assert!(this.in_task_context()); @@ -223,7 +223,7 @@ pub impl Scheduler { unsafe { let blocked_task = this.current_task.swap_unwrap(); - let f_fake_region = transmute::<&fn(~Task), &fn(~Task)>(f); + let f_fake_region = transmute::<&fn(~Coroutine), &fn(~Coroutine)>(f); let f_opaque = ClosureConverter::from_fn(f_fake_region); this.enqueue_cleanup_job(GiveTask(blocked_task, f_opaque)); } @@ -245,14 +245,14 @@ pub impl Scheduler { /// Switch directly to another task, without going through the scheduler. /// You would want to think hard about doing this, e.g. if there are /// pending I/O events it would be a bad idea. - fn switch_running_tasks_and_then(~self, next_task: ~Task, f: &fn(~Task)) { + fn switch_running_tasks_and_then(~self, next_task: ~Coroutine, f: &fn(~Coroutine)) { let mut this = self; assert!(this.in_task_context()); rtdebug!("switching tasks"); let old_running_task = this.current_task.swap_unwrap(); - let f_fake_region = unsafe { transmute::<&fn(~Task), &fn(~Task)>(f) }; + let f_fake_region = unsafe { transmute::<&fn(~Coroutine), &fn(~Coroutine)>(f) }; let f_opaque = ClosureConverter::from_fn(f_fake_region); this.enqueue_cleanup_job(GiveTask(old_running_task, f_opaque)); this.current_task = Some(next_task); @@ -318,7 +318,7 @@ pub impl Scheduler { // because borrowck thinks the three patterns are conflicting // borrows unsafe { - let last_task = transmute::, Option<&mut Task>>(last_task); + let last_task = transmute::, Option<&mut Coroutine>>(last_task); let last_task_context = match last_task { Some(t) => Some(&mut t.saved_context), None => None }; @@ -333,9 +333,9 @@ pub impl Scheduler { } } -static TASK_MIN_STACK_SIZE: uint = 10000000; // XXX: Too much stack +static MIN_STACK_SIZE: uint = 10000000; // XXX: Too much stack -pub struct Task { +pub struct Coroutine { /// The segment of stack on which the task is currently running or, /// if the task is blocked, on which the task will resume execution priv current_stack_segment: StackSegment, @@ -346,19 +346,19 @@ pub struct Task { local_services: LocalServices } -pub impl Task { - fn new(stack_pool: &mut StackPool, start: ~fn()) -> Task { - Task::with_local(stack_pool, LocalServices::new(), start) +pub impl Coroutine { + fn new(stack_pool: &mut StackPool, start: ~fn()) -> Coroutine { + Coroutine::with_local(stack_pool, LocalServices::new(), start) } fn with_local(stack_pool: &mut StackPool, local_services: LocalServices, - start: ~fn()) -> Task { - let start = Task::build_start_wrapper(start); - let mut stack = stack_pool.take_segment(TASK_MIN_STACK_SIZE); + start: ~fn()) -> Coroutine { + let start = Coroutine::build_start_wrapper(start); + let mut stack = stack_pool.take_segment(MIN_STACK_SIZE); // NB: Context holds a pointer to that ~fn let initial_context = Context::new(start, &mut stack); - return Task { + return Coroutine { current_stack_segment: stack, saved_context: initial_context, local_services: local_services @@ -390,7 +390,7 @@ pub impl Task { /// Destroy the task and try to reuse its components fn recycle(~self, stack_pool: &mut StackPool) { match self { - ~Task {current_stack_segment, _} => { + ~Coroutine {current_stack_segment, _} => { stack_pool.give_segment(current_stack_segment); } } @@ -414,7 +414,7 @@ mod test { let task_ran_ptr: *mut bool = &mut task_ran; let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~do Task::new(&mut sched.stack_pool) { + let task = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *task_ran_ptr = true; } }; sched.enqueue_task(task); @@ -432,7 +432,7 @@ mod test { let mut sched = ~UvEventLoop::new_scheduler(); for int::range(0, total) |_| { - let task = ~do Task::new(&mut sched.stack_pool) { + let task = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *task_count_ptr = *task_count_ptr + 1; } }; sched.enqueue_task(task); @@ -449,10 +449,10 @@ mod test { let count_ptr: *mut int = &mut count; let mut sched = ~UvEventLoop::new_scheduler(); - let task1 = ~do Task::new(&mut sched.stack_pool) { + let task1 = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *count_ptr = *count_ptr + 1; } let mut sched = local_sched::take(); - let task2 = ~do Task::new(&mut sched.stack_pool) { + let task2 = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *count_ptr = *count_ptr + 1; } }; // Context switch directly to the new task @@ -479,7 +479,7 @@ mod test { let mut sched = ~UvEventLoop::new_scheduler(); - let start_task = ~do Task::new(&mut sched.stack_pool) { + let start_task = ~do Coroutine::new(&mut sched.stack_pool) { run_task(count_ptr); }; sched.enqueue_task(start_task); @@ -489,7 +489,7 @@ mod test { fn run_task(count_ptr: *mut int) { do local_sched::borrow |sched| { - let task = ~do Task::new(&mut sched.stack_pool) { + let task = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *count_ptr = *count_ptr + 1; if *count_ptr != MAX { @@ -507,7 +507,7 @@ mod test { fn test_block_task() { do run_in_bare_thread { let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~do Task::new(&mut sched.stack_pool) { + let task = ~do Coroutine::new(&mut sched.stack_pool) { let sched = local_sched::take(); assert!(sched.in_task_context()); do sched.deschedule_running_task_and_then() |task| { diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index cfd1748ded35a..1294b9bcf4765 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -18,16 +18,16 @@ use rt::local_services::LocalServices; /// will abort the process. pub fn run_in_newsched_task(f: ~fn()) { use unstable::run_in_bare_thread; - use super::sched::Task; + use super::sched::Coroutine; use rt::uv::uvio::UvEventLoop; let f = Cell(f); do run_in_bare_thread { let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~Task::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f.take()); + let task = ~Coroutine::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f.take()); sched.enqueue_task(task); sched.run(); } @@ -38,9 +38,9 @@ pub fn spawntask(f: ~fn()) { use super::sched::*; let mut sched = local_sched::take(); - let task = ~Task::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); let sched = local_sched::take(); @@ -53,9 +53,9 @@ pub fn spawntask_immediately(f: ~fn()) { use super::sched::*; let mut sched = local_sched::take(); - let task = ~Task::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); do local_sched::borrow |sched| { @@ -69,9 +69,9 @@ pub fn spawntask_later(f: ~fn()) { use super::sched::*; let mut sched = local_sched::take(); - let task = ~Task::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f); sched.enqueue_task(task); local_sched::put(sched); @@ -86,9 +86,9 @@ pub fn spawntask_random(f: ~fn()) { let run_now: bool = Rand::rand(&mut rng); let mut sched = local_sched::take(); - let task = ~Task::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f); if run_now { do sched.switch_running_tasks_and_then(task) |task| { @@ -122,7 +122,7 @@ pub fn spawntask_try(f: ~fn()) -> Result<(), ()> { let old_task = Cell(old_task); let f = f.take(); let mut sched = local_sched::take(); - let new_task = ~do Task::new(&mut sched.stack_pool) { + let new_task = ~do Coroutine::new(&mut sched.stack_pool) { do (|| { (f.take())() }).finally { diff --git a/src/libcore/rt/tube.rs b/src/libcore/rt/tube.rs index 8e7bf72fa6308..bc9269f08faa9 100644 --- a/src/libcore/rt/tube.rs +++ b/src/libcore/rt/tube.rs @@ -16,14 +16,14 @@ use option::*; use clone::Clone; use super::rc::RC; -use rt::sched::Task; +use rt::sched::Coroutine; use rt::{context, TaskContext, SchedulerContext}; use rt::local_sched; use vec::OwnedVector; use container::Container; struct TubeState { - blocked_task: Option<~Task>, + blocked_task: Option<~Coroutine>, buf: ~[T] } diff --git a/src/libcore/task/spawn.rs b/src/libcore/task/spawn.rs index fc38702bc1605..5f9642604d0c1 100644 --- a/src/libcore/task/spawn.rs +++ b/src/libcore/task/spawn.rs @@ -581,7 +581,7 @@ fn spawn_raw_newsched(_opts: TaskOpts, f: ~fn()) { use rt::sched::*; let mut sched = local_sched::take(); - let task = ~Task::new(&mut sched.stack_pool, f); + let task = ~Coroutine::new(&mut sched.stack_pool, f); sched.schedule_new_task(task); } From 1c1f11e649c52135435f6ea747426568edac56a2 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 13 May 2013 14:25:56 -0700 Subject: [PATCH 046/248] core::rt: Warnings --- src/libcore/rt/io/extensions.rs | 6 ++++-- src/libcore/rt/io/net/tcp.rs | 2 +- src/libcore/rt/sched.rs | 4 ---- src/libcore/rt/uv/idle.rs | 2 +- src/libcore/rt/uv/net.rs | 4 ++-- src/libcore/rt/uv/timer.rs | 9 +++------ src/libcore/rt/uv/uvio.rs | 3 +-- 7 files changed, 12 insertions(+), 18 deletions(-) diff --git a/src/libcore/rt/io/extensions.rs b/src/libcore/rt/io/extensions.rs index 1c68934e80b05..97841f0db46c6 100644 --- a/src/libcore/rt/io/extensions.rs +++ b/src/libcore/rt/io/extensions.rs @@ -17,6 +17,7 @@ use vec; use rt::io::Reader; use option::{Option, Some, None}; use unstable::finally::Finally; +use util; pub trait ReaderUtil { @@ -60,11 +61,12 @@ impl ReaderUtil for T { fn read_byte(&mut self) -> Option { let mut buf = [0]; match self.read(buf) { - Some(nread) if nread == 0 => { + Some(0) => { debug!("read 0 bytes. trying again"); self.read_byte() } - Some(nread) => Some(buf[0]), + Some(1) => Some(buf[0]), + Some(_) => util::unreachable(), None => None } } diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index f5b3c20f651e1..04f4edd7e39f5 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -243,7 +243,7 @@ mod test { } do spawntask_immediately { - let stream = TcpStream::connect(addr); + let _stream = TcpStream::connect(addr); // Close } } diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index d92eaf89e5f3c..5c1a3410087c4 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -19,10 +19,6 @@ use super::context::Context; use super::local_services::LocalServices; use cell::Cell; -#[cfg(test)] use rt::uv::uvio::UvEventLoop; -#[cfg(test)] use unstable::run_in_bare_thread; -#[cfg(test)] use int; - // A more convenient name for external callers, e.g. `local_sched::take()` pub mod local_sched; diff --git a/src/libcore/rt/uv/idle.rs b/src/libcore/rt/uv/idle.rs index fecb9391caa54..2cf0b5c487288 100644 --- a/src/libcore/rt/uv/idle.rs +++ b/src/libcore/rt/uv/idle.rs @@ -71,7 +71,7 @@ pub impl IdleWatcher { unsafe { let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); { - let mut data = idle_watcher.get_watcher_data(); + let data = idle_watcher.get_watcher_data(); data.close_cb.swap_unwrap()(); } idle_watcher.drop_watcher_data(); diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index fd78b552119b5..bdd5588014c01 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -131,7 +131,7 @@ pub impl StreamWatcher { extern fn close_cb(handle: *uvll::uv_stream_t) { let mut stream_watcher: StreamWatcher = NativeHandle::from_native_handle(handle); { - let mut data = stream_watcher.get_watcher_data(); + let data = stream_watcher.get_watcher_data(); data.close_cb.swap_unwrap()(); } stream_watcher.drop_watcher_data(); @@ -373,7 +373,7 @@ mod test { assert!(status.is_none()); let mut server_stream_watcher = server_stream_watcher; let mut loop_ = loop_; - let mut client_tcp_watcher = TcpWatcher::new(&mut loop_); + let client_tcp_watcher = TcpWatcher::new(&mut loop_); let mut client_tcp_watcher = client_tcp_watcher.as_stream(); server_stream_watcher.accept(client_tcp_watcher); let count_cell = Cell(0); diff --git a/src/libcore/rt/uv/timer.rs b/src/libcore/rt/uv/timer.rs index 1045a77da12fa..5557a58098751 100644 --- a/src/libcore/rt/uv/timer.rs +++ b/src/libcore/rt/uv/timer.rs @@ -69,7 +69,7 @@ impl TimerWatcher { extern fn close_cb(handle: *uvll::uv_timer_t) { let mut watcher: TimerWatcher = NativeHandle::from_native_handle(handle); { - let mut data = watcher.get_watcher_data(); + let data = watcher.get_watcher_data(); data.close_cb.swap_unwrap()(); } watcher.drop_watcher_data(); @@ -125,7 +125,6 @@ mod test { assert!(status.is_none()); unsafe { *count_ptr += 1 }; do timer.start(10, 0) |timer, status| { - let mut timer = timer; assert!(status.is_none()); unsafe { *count_ptr += 1 }; timer.close(||()); @@ -159,18 +158,16 @@ mod test { let mut loop_ = timer.event_loop(); let mut timer2 = TimerWatcher::new(&mut loop_); - do timer2.start(10, 0) |timer2, status| { + do timer2.start(10, 0) |timer2, _| { unsafe { *count_ptr += 1; } - let mut timer2 = timer2; timer2.close(||()); // Restart the original timer let mut timer = timer; - do timer.start(10, 0) |timer, status| { + do timer.start(10, 0) |timer, _| { unsafe { *count_ptr += 1; } - let mut timer = timer; timer.close(||()); } } diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index a25d18101a7fd..ce4eb6aff8701 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -77,7 +77,6 @@ impl EventLoop for UvEventLoop { let mut timer = TimerWatcher::new(self.uvio.uv_loop()); do timer.start(ms, 0) |timer, status| { assert!(status.is_none()); - let mut timer = timer; timer.close(||()); f(); } @@ -235,7 +234,7 @@ impl RtioTcpListener for UvTcpListener { let maybe_stream = if status.is_none() { let mut server_stream_watcher = server_stream_watcher; let mut loop_ = server_stream_watcher.event_loop(); - let mut client_tcp_watcher = TcpWatcher::new(&mut loop_); + let client_tcp_watcher = TcpWatcher::new(&mut loop_); let client_tcp_watcher = client_tcp_watcher.as_stream(); // XXX: Need's to be surfaced in interface server_stream_watcher.accept(client_tcp_watcher); From 28a13ec8d76ba9a4f9645991e1260882a3b7dc68 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 13 May 2013 15:23:52 -0700 Subject: [PATCH 047/248] core::rt: Make push_bytes raise read_error on EOF --- src/libcore/rt/io/extensions.rs | 50 +++++++++++++++++++++------------ src/libcore/rt/io/mod.rs | 14 ++++++++- 2 files changed, 45 insertions(+), 19 deletions(-) diff --git a/src/libcore/rt/io/extensions.rs b/src/libcore/rt/io/extensions.rs index 97841f0db46c6..addafcf1d99c1 100644 --- a/src/libcore/rt/io/extensions.rs +++ b/src/libcore/rt/io/extensions.rs @@ -14,7 +14,7 @@ // XXX: Iteration should probably be considered separately use vec; -use rt::io::Reader; +use rt::io::{Reader, read_error, standard_error, EndOfFile}; use option::{Option, Some, None}; use unstable::finally::Finally; use util; @@ -36,16 +36,19 @@ pub trait ReaderUtil { /// /// # Failure /// - /// Raises the same conditions as `read`. Returns `false` if - /// the condition is handled. - fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) -> bool; + /// Raises the same conditions as `read`. Additionally raises `read_error` + /// on EOF. If `read_error` is handled then `push_bytes` returns without + /// pushing any bytes onto `buf` - that is, `buf` has the same length + /// upon exit as it did on entry. + fn push_bytes(&mut self, buf: &mut ~[u8], len: uint); - /// Reads `len` bytes and gives you back a new vector + /// Reads `len` bytes and gives you back a new vector of length `len` /// /// # Failure /// - /// Raises the same conditions as the `read` method. May return - /// less than the requested number of bytes on error or EOF. + /// Raises the same conditions as `read`. Additionally raises `read_error` + /// on EOF. If `read_error` is handled then the returned vector has + /// length 0. fn read_bytes(&mut self, len: uint) -> ~[u8]; /// Reads all remaining bytes from the stream. @@ -71,11 +74,10 @@ impl ReaderUtil for T { } } - fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) -> bool { + fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) { unsafe { let start_len = buf.len(); let mut total_read = 0; - let mut eof = false; vec::reserve_at_least(buf, start_len + len); vec::raw::set_len(buf, start_len + len); @@ -88,7 +90,9 @@ impl ReaderUtil for T { total_read += nread; } None => { - eof = true; + read_error::cond.raise(standard_error(EndOfFile)); + // Reset the vector length as though we didn't read anything + total_read = 0; break; } } @@ -96,8 +100,6 @@ impl ReaderUtil for T { }).finally { vec::raw::set_len(buf, start_len + total_read); } - - return !eof; } } @@ -407,11 +409,20 @@ mod test { assert!(bytes == ~[10, 11, 12, 13]); } + #[test] + fn read_bytes_eof() { + let mut reader = MemReader::new(~[10, 11]); + do read_error::cond.trap(|_| { + }).in { + assert!(reader.read_bytes(4) == ~[]); + } + } + #[test] fn push_bytes() { let mut reader = MemReader::new(~[10, 11, 12, 13]); let mut buf = ~[8, 9]; - assert!(reader.push_bytes(&mut buf, 4)); + reader.push_bytes(&mut buf, 4); assert!(buf == ~[8, 9, 10, 11, 12, 13]); } @@ -434,7 +445,7 @@ mod test { } }; let mut buf = ~[8, 9]; - assert!(reader.push_bytes(&mut buf, 4)); + reader.push_bytes(&mut buf, 4); assert!(buf == ~[8, 9, 10, 11, 12, 13]); } @@ -442,8 +453,11 @@ mod test { fn push_bytes_eof() { let mut reader = MemReader::new(~[10, 11]); let mut buf = ~[8, 9]; - assert!(!reader.push_bytes(&mut buf, 4)); - assert!(buf == ~[8, 9, 10, 11]); + do read_error::cond.trap(|_| { + }).in { + reader.push_bytes(&mut buf, 4); + assert!(buf == ~[8, 9]); + } } #[test] @@ -464,9 +478,9 @@ mod test { }; let mut buf = ~[8, 9]; do read_error::cond.trap(|_| { } ).in { - assert!(!reader.push_bytes(&mut buf, 4)); + reader.push_bytes(&mut buf, 4); } - assert!(buf == ~[8, 9, 10]); + assert!(buf == ~[8, 9]); } #[test] diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index 4ec5e83c38261..7e611a0b8bc91 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -260,8 +260,11 @@ pub use self::net::tcp::TcpStream; pub use self::net::udp::UdpStream; // Some extension traits that all Readers and Writers get. +#[cfg(not(stage0))] // Requires condition! fixes pub use self::extensions::ReaderUtil; +#[cfg(not(stage0))] // Requires condition! fixes pub use self::extensions::ReaderByteConversions; +#[cfg(not(stage0))] // Requires condition! fixes pub use self::extensions::WriterByteConversions; /// Synchronous, non-blocking file I/O. @@ -295,6 +298,7 @@ pub mod flate; pub mod comm_adapters; /// Extension traits +#[cfg(not(stage0))] // Requires condition! fixes mod extensions; /// Non-I/O things needed by the I/O module @@ -373,7 +377,8 @@ pub trait Reader { /// /// * Should raise error on eof /// * If the condition is handled it should still return the bytes read, - /// in which case there's no need to return Option + /// in which case there's no need to return Option - but then you *have* + /// to install a handler to detect eof. /// /// This doesn't take a `len` argument like the old `read`. /// Will people often need to slice their vectors to call this @@ -482,6 +487,13 @@ pub fn standard_error(kind: IoErrorKind) -> IoError { detail: None } } + EndOfFile => { + IoError { + kind: EndOfFile, + desc: "End of file", + detail: None + } + } _ => fail!() } } From d45dc8df7278649d101ce28fae1d934559e0e3c2 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 13 May 2013 16:56:16 -0700 Subject: [PATCH 048/248] core::rt: More work on Reader extensions and error handling --- src/libcore/rt/io/extensions.rs | 184 +++++++++++++++++++++----------- src/libcore/rt/io/mod.rs | 8 +- 2 files changed, 127 insertions(+), 65 deletions(-) diff --git a/src/libcore/rt/io/extensions.rs b/src/libcore/rt/io/extensions.rs index addafcf1d99c1..4a5193f086b33 100644 --- a/src/libcore/rt/io/extensions.rs +++ b/src/libcore/rt/io/extensions.rs @@ -14,7 +14,7 @@ // XXX: Iteration should probably be considered separately use vec; -use rt::io::{Reader, read_error, standard_error, EndOfFile}; +use rt::io::{Reader, read_error, standard_error, EndOfFile, DEFAULT_BUF_SIZE}; use option::{Option, Some, None}; use unstable::finally::Finally; use util; @@ -37,9 +37,8 @@ pub trait ReaderUtil { /// # Failure /// /// Raises the same conditions as `read`. Additionally raises `read_error` - /// on EOF. If `read_error` is handled then `push_bytes` returns without - /// pushing any bytes onto `buf` - that is, `buf` has the same length - /// upon exit as it did on entry. + /// on EOF. If `read_error` is handled then `push_bytes` may push less + /// than the requested number of bytes. fn push_bytes(&mut self, buf: &mut ~[u8], len: uint); /// Reads `len` bytes and gives you back a new vector of length `len` @@ -47,8 +46,8 @@ pub trait ReaderUtil { /// # Failure /// /// Raises the same conditions as `read`. Additionally raises `read_error` - /// on EOF. If `read_error` is handled then the returned vector has - /// length 0. + /// on EOF. If `read_error` is handled then the returned vector may + /// contain less than the requested number of bytes. fn read_bytes(&mut self, len: uint) -> ~[u8]; /// Reads all remaining bytes from the stream. @@ -60,60 +59,6 @@ pub trait ReaderUtil { } -impl ReaderUtil for T { - fn read_byte(&mut self) -> Option { - let mut buf = [0]; - match self.read(buf) { - Some(0) => { - debug!("read 0 bytes. trying again"); - self.read_byte() - } - Some(1) => Some(buf[0]), - Some(_) => util::unreachable(), - None => None - } - } - - fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) { - unsafe { - let start_len = buf.len(); - let mut total_read = 0; - - vec::reserve_at_least(buf, start_len + len); - vec::raw::set_len(buf, start_len + len); - - do (|| { - while total_read < len { - let slice = vec::mut_slice(*buf, start_len + total_read, buf.len()); - match self.read(slice) { - Some(nread) => { - total_read += nread; - } - None => { - read_error::cond.raise(standard_error(EndOfFile)); - // Reset the vector length as though we didn't read anything - total_read = 0; - break; - } - } - } - }).finally { - vec::raw::set_len(buf, start_len + total_read); - } - } - } - - fn read_bytes(&mut self, len: uint) -> ~[u8] { - let mut buf = vec::with_capacity(len); - self.push_bytes(&mut buf, len); - return buf; - } - - fn read_to_end(&mut self) -> ~[u8] { - fail!() - } -} - pub trait ReaderByteConversions { /// Reads `n` little-endian unsigned integer bytes. /// @@ -323,6 +268,71 @@ pub trait WriterByteConversions { fn write_i8(&mut self, n: i8); } +impl ReaderUtil for T { + fn read_byte(&mut self) -> Option { + let mut buf = [0]; + match self.read(buf) { + Some(0) => { + debug!("read 0 bytes. trying again"); + self.read_byte() + } + Some(1) => Some(buf[0]), + Some(_) => util::unreachable(), + None => None + } + } + + fn push_bytes(&mut self, buf: &mut ~[u8], len: uint) { + unsafe { + let start_len = buf.len(); + let mut total_read = 0; + + vec::reserve_at_least(buf, start_len + len); + vec::raw::set_len(buf, start_len + len); + + do (|| { + while total_read < len { + let slice = vec::mut_slice(*buf, start_len + total_read, buf.len()); + match self.read(slice) { + Some(nread) => { + total_read += nread; + } + None => { + read_error::cond.raise(standard_error(EndOfFile)); + break; + } + } + } + }).finally { + vec::raw::set_len(buf, start_len + total_read); + } + } + } + + fn read_bytes(&mut self, len: uint) -> ~[u8] { + let mut buf = vec::with_capacity(len); + self.push_bytes(&mut buf, len); + return buf; + } + + fn read_to_end(&mut self) -> ~[u8] { + let mut buf = vec::with_capacity(DEFAULT_BUF_SIZE); + let mut keep_reading = true; + do read_error::cond.trap(|e| { + if e.kind == EndOfFile { + keep_reading = false; + } else { + read_error::cond.raise(e) + } + }).in { + while keep_reading { + self.push_bytes(&mut buf, DEFAULT_BUF_SIZE) + } + } + return buf; + } +} + #[cfg(test)] mod test { use super::*; @@ -414,7 +424,7 @@ mod test { let mut reader = MemReader::new(~[10, 11]); do read_error::cond.trap(|_| { }).in { - assert!(reader.read_bytes(4) == ~[]); + assert!(reader.read_bytes(4) == ~[10, 11]); } } @@ -456,7 +466,7 @@ mod test { do read_error::cond.trap(|_| { }).in { reader.push_bytes(&mut buf, 4); - assert!(buf == ~[8, 9]); + assert!(buf == ~[8, 9, 10, 11]); } } @@ -480,7 +490,7 @@ mod test { do read_error::cond.trap(|_| { } ).in { reader.push_bytes(&mut buf, 4); } - assert!(buf == ~[8, 9]); + assert!(buf == ~[8, 9, 10]); } #[test] @@ -514,4 +524,52 @@ mod test { } } + #[test] + fn read_to_end() { + let mut reader = MockReader::new(); + let count = Cell(0); + reader.read = |buf| { + do count.with_mut_ref |count| { + if *count == 0 { + *count = 1; + buf[0] = 10; + buf[1] = 11; + Some(2) + } else if *count == 1 { + *count = 2; + buf[0] = 12; + buf[1] = 13; + Some(2) + } else { + None + } + } + }; + let buf = reader.read_to_end(); + assert!(buf == ~[10, 11, 12, 13]); + } + + #[test] + #[should_fail] + #[ignore(cfg(windows))] + fn read_to_end_error() { + let mut reader = MockReader::new(); + let count = Cell(0); + reader.read = |buf| { + do count.with_mut_ref |count| { + if *count == 0 { + *count = 1; + buf[0] = 10; + buf[1] = 11; + Some(2) + } else { + read_error::cond.raise(placeholder_error()); + None + } + } + }; + let buf = reader.read_to_end(); + assert!(buf == ~[10, 11]); + } + } diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index 7e611a0b8bc91..14784fa95672e 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -187,7 +187,7 @@ In particular code written to ignore errors and expect conditions to be unhandle will start passing around null or zero objects when wrapped in a condition handler. * XXX: How should we use condition handlers that return values? - +* XXX: Should EOF raise default conditions when EOF is not an error? # Issues withi/o scheduler affinity, work stealing, task pinning @@ -323,6 +323,10 @@ pub mod native { /// Mock implementations for testing mod mock; +/// The default buffer size for various I/O operations +/// XXX: Not pub +pub static DEFAULT_BUF_SIZE: uint = 1024 * 64; + /// The type passed to I/O condition handlers to indicate error /// /// # XXX @@ -375,7 +379,7 @@ pub trait Reader { /// /// # XXX /// - /// * Should raise error on eof + /// * Should raise_default error on eof? /// * If the condition is handled it should still return the bytes read, /// in which case there's no need to return Option - but then you *have* /// to install a handler to detect eof. From 2bc1e6ba606e3f08a49bbadc556558cb42b7ea32 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 13 May 2013 19:14:14 -0700 Subject: [PATCH 049/248] core::rt: Copy many of the old io extensions to the new io Some resolve problem is keeping the tests from working --- src/libcore/rt/io/extensions.rs | 340 +++++++++++++++++++++++++++++++- 1 file changed, 334 insertions(+), 6 deletions(-) diff --git a/src/libcore/rt/io/extensions.rs b/src/libcore/rt/io/extensions.rs index 4a5193f086b33..a3804d2d6ef1a 100644 --- a/src/libcore/rt/io/extensions.rs +++ b/src/libcore/rt/io/extensions.rs @@ -13,11 +13,16 @@ // XXX: Not sure how this should be structured // XXX: Iteration should probably be considered separately +use uint; +use int; use vec; -use rt::io::{Reader, read_error, standard_error, EndOfFile, DEFAULT_BUF_SIZE}; +use rt::io::{Reader, Writer}; +use rt::io::{read_error, standard_error, EndOfFile, DEFAULT_BUF_SIZE}; use option::{Option, Some, None}; use unstable::finally::Finally; use util; +use cast; +use io::{u64_to_le_bytes, u64_to_be_bytes}; pub trait ReaderUtil { @@ -212,7 +217,7 @@ pub trait WriterByteConversions { fn write_be_int(&mut self, n: int); /// Write a big-endian u64 (8 bytes). - fn write_be_u64(&mut self, n: u64); + fn write_be_u64_(&mut self, n: u64); /// Write a big-endian u32 (4 bytes). fn write_be_u32(&mut self, n: u32); @@ -236,7 +241,7 @@ pub trait WriterByteConversions { fn write_be_f32(&mut self, f: f32); /// Write a little-endian u64 (8 bytes). - fn write_le_u64(&mut self, n: u64); + fn write_le_u64_(&mut self, n: u64); /// Write a little-endian u32 (4 bytes). fn write_le_u32(&mut self, n: u32); @@ -333,13 +338,262 @@ impl ReaderUtil for T { } } +impl ReaderByteConversions for T { + fn read_le_uint_n(&mut self, nbytes: uint) -> u64 { + assert!(nbytes > 0 && nbytes <= 8); + + let mut val = 0u64, pos = 0, i = nbytes; + while i > 0 { + val += (self.read_u8() as u64) << pos; + pos += 8; + i -= 1; + } + val + } + + fn read_le_int_n(&mut self, nbytes: uint) -> i64 { + extend_sign(self.read_le_uint_n(nbytes), nbytes) + } + + fn read_be_uint_n(&mut self, nbytes: uint) -> u64 { + assert!(nbytes > 0 && nbytes <= 8); + + let mut val = 0u64, i = nbytes; + while i > 0 { + i -= 1; + val += (self.read_u8() as u64) << i * 8; + } + val + } + + fn read_be_int_n(&mut self, nbytes: uint) -> i64 { + extend_sign(self.read_be_uint_n(nbytes), nbytes) + } + + fn read_le_uint(&mut self) -> uint { + self.read_le_uint_n(uint::bytes) as uint + } + + fn read_le_int(&mut self) -> int { + self.read_le_int_n(int::bytes) as int + } + + fn read_be_uint(&mut self) -> uint { + self.read_be_uint_n(uint::bytes) as uint + } + + fn read_be_int(&mut self) -> int { + self.read_be_int_n(int::bytes) as int + } + + fn read_be_u64(&mut self) -> u64 { + self.read_be_uint_n(8) as u64 + } + + fn read_be_u32(&mut self) -> u32 { + self.read_be_uint_n(4) as u32 + } + + fn read_be_u16(&mut self) -> u16 { + self.read_be_uint_n(2) as u16 + } + + fn read_be_i64(&mut self) -> i64 { + self.read_be_int_n(8) as i64 + } + + fn read_be_i32(&mut self) -> i32 { + self.read_be_int_n(4) as i32 + } + + fn read_be_i16(&mut self) -> i16 { + self.read_be_int_n(2) as i16 + } + + fn read_be_f64(&mut self) -> f64 { + unsafe { + cast::transmute::(self.read_be_u64()) + } + } + + fn read_be_f32(&mut self) -> f32 { + unsafe { + cast::transmute::(self.read_be_u32()) + } + } + + fn read_le_u64(&mut self) -> u64 { + self.read_le_uint_n(8) as u64 + } + + fn read_le_u32(&mut self) -> u32 { + self.read_le_uint_n(4) as u32 + } + + fn read_le_u16(&mut self) -> u16 { + self.read_le_uint_n(2) as u16 + } + + fn read_le_i64(&mut self) -> i64 { + self.read_le_int_n(8) as i64 + } + + fn read_le_i32(&mut self) -> i32 { + self.read_le_int_n(4) as i32 + } + + fn read_le_i16(&mut self) -> i16 { + self.read_le_int_n(2) as i16 + } + + fn read_le_f64(&mut self) -> f64 { + unsafe { + cast::transmute::(self.read_le_u64()) + } + } + + fn read_le_f32(&mut self) -> f32 { + unsafe { + cast::transmute::(self.read_le_u32()) + } + } + + fn read_u8(&mut self) -> u8 { + match self.read_byte() { + Some(b) => b as u8, + None => 0 + } + } + + fn read_i8(&mut self) -> i8 { + match self.read_byte() { + Some(b) => b as i8, + None => 0 + } + } + +} + +impl WriterByteConversions for T { + fn write_int(&mut self, n: int) { + int::to_str_bytes(n, 10u, |bytes| self.write(bytes)) + } + + fn write_uint(&mut self, n: uint) { + uint::to_str_bytes(n, 10u, |bytes| self.write(bytes)) + } + + fn write_le_uint(&mut self, n: uint) { + u64_to_le_bytes(n as u64, uint::bytes, |v| self.write(v)) + } + + fn write_le_int(&mut self, n: int) { + u64_to_le_bytes(n as u64, int::bytes, |v| self.write(v)) + } + + fn write_be_uint(&mut self, n: uint) { + u64_to_be_bytes(n as u64, uint::bytes, |v| self.write(v)) + } + + fn write_be_int(&mut self, n: int) { + u64_to_be_bytes(n as u64, int::bytes, |v| self.write(v)) + } + + fn write_be_u64_(&mut self, n: u64) { + u64_to_be_bytes(n, 8u, |v| self.write(v)) + } + + fn write_be_u32(&mut self, n: u32) { + u64_to_be_bytes(n as u64, 4u, |v| self.write(v)) + } + + fn write_be_u16(&mut self, n: u16) { + u64_to_be_bytes(n as u64, 2u, |v| self.write(v)) + } + + fn write_be_i64(&mut self, n: i64) { + u64_to_be_bytes(n as u64, 8u, |v| self.write(v)) + } + + fn write_be_i32(&mut self, n: i32) { + u64_to_be_bytes(n as u64, 4u, |v| self.write(v)) + } + + fn write_be_i16(&mut self, n: i16) { + u64_to_be_bytes(n as u64, 2u, |v| self.write(v)) + } + + fn write_be_f64(&mut self, f: f64) { + unsafe { + self.write_be_u64_(cast::transmute(f)) + } + } + + fn write_be_f32(&mut self, f: f32) { + unsafe { + self.write_be_u32(cast::transmute(f)) + } + } + + fn write_le_u64_(&mut self, n: u64) { + u64_to_le_bytes(n, 8u, |v| self.write(v)) + } + + fn write_le_u32(&mut self, n: u32) { + u64_to_le_bytes(n as u64, 4u, |v| self.write(v)) + } + + fn write_le_u16(&mut self, n: u16) { + u64_to_le_bytes(n as u64, 2u, |v| self.write(v)) + } + + fn write_le_i64(&mut self, n: i64) { + u64_to_le_bytes(n as u64, 8u, |v| self.write(v)) + } + + fn write_le_i32(&mut self, n: i32) { + u64_to_le_bytes(n as u64, 4u, |v| self.write(v)) + } + + fn write_le_i16(&mut self, n: i16) { + u64_to_le_bytes(n as u64, 2u, |v| self.write(v)) + } + + fn write_le_f64(&mut self, f: f64) { + unsafe { + self.write_le_u64_(cast::transmute(f)) + } + } + + fn write_le_f32(&mut self, f: f32) { + unsafe { + self.write_le_u32(cast::transmute(f)) + } + } + + fn write_u8(&mut self, n: u8) { + self.write([n]) + } + + fn write_i8(&mut self, n: i8) { + self.write([n as u8]) + } +} + +fn extend_sign(val: u64, nbytes: uint) -> i64 { + let shift = (8 - nbytes) * 8; + (val << shift) as i64 >> shift +} + #[cfg(test)] mod test { - use super::*; + use super::{ReaderUtil, ReaderByteConversions, WriterByteConversions}; + use u64; + use i32; use option::{Some, None}; use cell::Cell; - use rt::io::mem::MemReader; - use rt::io::mock::*; + use rt::io::mem::{MemReader, MemWriter}; + use rt::io::mock::MockReader; use rt::io::{read_error, placeholder_error}; #[test] @@ -572,4 +826,78 @@ mod test { assert!(buf == ~[10, 11]); } + // XXX: Some problem with resolve here + /*#[test] + fn test_read_write_le() { + let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value]; + + let mut writer = MemWriter::new(); + for uints.each |i| { + writer.write_le_u64(*i); + } + + let mut reader = MemReader::new(writer.inner()); + for uints.each |i| { + assert!(reader.read_le_u64() == *i); + } + } + + #[test] + fn test_read_write_be() { + let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value]; + + let mut writer = MemWriter::new(); + for uints.each |i| { + writer.write_be_u64(*i); + } + + let mut reader = MemReader::new(writer.inner()); + for uints.each |i| { + assert!(reader.read_be_u64() == *i); + } + } + + #[test] + fn test_read_be_int_n() { + let ints = [i32::min_value, -123456, -42, -5, 0, 1, i32::max_value]; + + let mut writer = MemWriter::new(); + for ints.each |i| { + writer.write_be_i32(*i); + } + + let mut reader = MemReader::new(writer.inner()); + for ints.each |i| { + // this tests that the sign extension is working + // (comparing the values as i32 would not test this) + assert!(reader.read_be_int_n(4) == *i as i64); + } + } + + #[test] + fn test_read_f32() { + //big-endian floating-point 8.1250 + let buf = ~[0x41, 0x02, 0x00, 0x00]; + + let mut writer = MemWriter::new(); + writer.write(buf); + + let mut reader = MemReader::new(writer.inner()); + let f = reader.read_be_f32(); + assert!(f == 8.1250); + } + + #[test] + fn test_read_write_f32() { + let f:f32 = 8.1250; + + let mut writer = MemWriter::new(); + writer.write_be_f32(f); + writer.write_le_f32(f); + + let mut reader = MemReader::new(writer.inner()); + assert!(reader.read_be_f32() == 8.1250); + assert!(reader.read_le_f32() == 8.1250); + }*/ + } From d951da82768685cacba7444dae10ede2a71efedb Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Tue, 14 May 2013 21:18:47 -0700 Subject: [PATCH 050/248] core::rt: Fix TCP test on mac --- src/libcore/rt/io/mod.rs | 3 ++- src/libcore/rt/io/net/tcp.rs | 3 ++- src/libcore/rt/uv/mod.rs | 4 +++- src/libcore/rt/uv/uvll.rs | 1 + 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index 14784fa95672e..802e069a738f0 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -348,7 +348,8 @@ pub enum IoErrorKind { ConnectionFailed, Closed, ConnectionRefused, - ConnectionReset + ConnectionReset, + BrokenPipe } // XXX: Can't put doc comments on macros diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index 04f4edd7e39f5..eec3614d12978 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -233,7 +233,8 @@ mod test { loop { let mut stop = false; do io_error::cond.trap(|e| { - assert!(e.kind == ConnectionReset); + // NB: ECONNRESET on linux, EPIPE on mac + assert!(e.kind == ConnectionReset || e.kind == BrokenPipe); stop = true; }).in { stream.write(buf); diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index ee3c5ceffd236..93cafb835884a 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -272,7 +272,9 @@ pub fn uv_error_to_io_error(uverr: UvError) -> IoError { EACCES => PermissionDenied, ECONNREFUSED => ConnectionRefused, ECONNRESET => ConnectionReset, - _ => { + EPIPE => BrokenPipe, + e => { + rtdebug!("e %u", e as uint); // XXX: Need to map remaining uv error types OtherIoError } diff --git a/src/libcore/rt/uv/uvll.rs b/src/libcore/rt/uv/uvll.rs index 94e6b82ab8fa9..02659ab1eb910 100644 --- a/src/libcore/rt/uv/uvll.rs +++ b/src/libcore/rt/uv/uvll.rs @@ -40,6 +40,7 @@ pub static EADDRINFO: c_int = 2; pub static EACCES: c_int = 3; pub static ECONNREFUSED: c_int = 12; pub static ECONNRESET: c_int = 13; +pub static EPIPE: c_int = 36; pub struct uv_err_t { code: c_int, From 018dfaf9a6a25f5dba0ac642ff6c426c549bc4d7 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 15 May 2013 13:57:08 -0700 Subject: [PATCH 051/248] core::rt: Unignore a fixed TCP test --- src/libcore/rt/io/net/tcp.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index eec3614d12978..a833e92fc1088 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -314,7 +314,7 @@ mod test { } } - #[test] #[ignore(reason = "hangs on mac")] + #[test] fn multiple_connect_interleaved_lazy_schedule() { do run_in_newsched_task { let addr = next_test_ip4(); From f7e58ebe84513ed65b1694311f8c4f35e53e8c0e Mon Sep 17 00:00:00 2001 From: gifnksm Date: Fri, 17 May 2013 22:54:32 +0900 Subject: [PATCH 052/248] libcore: Add `IteratorUtil::to_vec()` method --- src/libcore/iterator.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 40c9637f692bc..3811d28b0302d 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -45,6 +45,7 @@ pub trait IteratorUtil { fn advance(&mut self, f: &fn(A) -> bool); #[cfg(not(stage0))] fn advance(&mut self, f: &fn(A) -> bool) -> bool; + fn to_vec(self) -> ~[A]; } /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also @@ -131,6 +132,14 @@ impl> IteratorUtil for T { } } } + + #[inline(always)] + fn to_vec(self) -> ~[A] { + let mut v = ~[]; + let mut it = self; + for it.advance() |x| { v.push(x); } + return v; + } } pub struct ChainIterator { From 9ffbe69234317859ca910fe5c419cacf4089d60b Mon Sep 17 00:00:00 2001 From: gifnksm Date: Fri, 17 May 2013 23:00:48 +0900 Subject: [PATCH 053/248] libcore: Add `IteratorUtil::filter_map` method --- src/libcore/iterator.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 3811d28b0302d..685b4fcac7fc3 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -34,6 +34,7 @@ pub trait IteratorUtil { // FIXME: #5898: should be called map fn transform<'r, B>(self, f: &'r fn(A) -> B) -> MapIterator<'r, A, B, Self>; fn filter<'r>(self, predicate: &'r fn(&A) -> bool) -> FilterIterator<'r, A, Self>; + fn filter_map<'r, B>(self, f: &'r fn(A) -> Option) -> FilterMapIterator<'r, A, B, Self>; fn enumerate(self) -> EnumerateIterator; fn skip_while<'r>(self, predicate: &'r fn(&A) -> bool) -> SkipWhileIterator<'r, A, Self>; fn take_while<'r>(self, predicate: &'r fn(&A) -> bool) -> TakeWhileIterator<'r, A, Self>; @@ -74,6 +75,11 @@ impl> IteratorUtil for T { FilterIterator{iter: self, predicate: predicate} } + #[inline(always)] + fn filter_map<'r, B>(self, f: &'r fn(A) -> Option) -> FilterMapIterator<'r, A, B, T> { + FilterMapIterator { iter: self, f: f } + } + #[inline(always)] fn enumerate(self) -> EnumerateIterator { EnumerateIterator{iter: self, count: 0} @@ -213,6 +219,28 @@ impl<'self, A, T: Iterator> Iterator for FilterIterator<'self, A, T> { } } +pub struct FilterMapIterator<'self, A, B, T> { + priv iter: T, + priv f: &'self fn(A) -> Option +} + +impl<'self, A, B, T: Iterator> Iterator for FilterMapIterator<'self, A, B, T> { + #[inline] + fn next(&mut self) -> Option { + loop { + match self.iter.next() { + None => { return None; } + Some(a) => { + match (self.f)(a) { + Some(b) => { return Some(b); } + None => { loop; } + } + } + } + } + } +} + pub struct EnumerateIterator { priv iter: T, priv count: uint @@ -432,6 +460,13 @@ mod tests { assert_eq!(i, expected.len()); } + #[test] + fn test_filter_map() { + let it = Counter::new(0u, 1u).take(10) + .filter_map(|x: uint| if x.is_even() { Some(x*x) } else { None }); + assert_eq!(it.to_vec(), ~[0*0, 2*2, 4*4, 6*6, 8*8]); + } + #[test] fn test_iterator_enumerate() { let xs = [0u, 1, 2, 3, 4, 5]; From 02945f1cb1524f5791dd244e63a8d9bb2d61ac77 Mon Sep 17 00:00:00 2001 From: gifnksm Date: Fri, 17 May 2013 23:45:25 +0900 Subject: [PATCH 054/248] libcore: Add `IteratoUtil::nth`, `first`, `last` method --- src/libcore/iterator.rs | 81 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 685b4fcac7fc3..14d6083067a9d 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -47,6 +47,9 @@ pub trait IteratorUtil { #[cfg(not(stage0))] fn advance(&mut self, f: &fn(A) -> bool) -> bool; fn to_vec(self) -> ~[A]; + fn nth(&mut self, n: uint) -> A; + fn first(&mut self) -> A; + fn last(&mut self) -> A; } /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also @@ -146,6 +149,41 @@ impl> IteratorUtil for T { for it.advance() |x| { v.push(x); } return v; } + + /// Get `n`th element of an iterator. + #[inline(always)] + fn nth(&mut self, n: uint) -> A { + let mut i = n; + loop { + match self.next() { + Some(x) => { if i == 0 { return x; }} + None => { fail!("cannot get %uth element", n) } + } + i -= 1; + } + } + + // Get first elemet of an iterator. + #[inline(always)] + fn first(&mut self) -> A { + match self.next() { + Some(x) => x , + None => fail!("cannot get first element") + } + } + + // Get last element of an iterator. + // + // If the iterator have an infinite length, this method won't return. + #[inline(always)] + fn last(&mut self) -> A { + let mut elm = match self.next() { + Some(x) => x, + None => fail!("cannot get last element") + }; + for self.advance |e| { elm = e; } + return elm; + } } pub struct ChainIterator { @@ -567,4 +605,47 @@ mod tests { } assert_eq!(i, 10); } + + #[test] + fn test_iterator_nth() { + let v = &[0, 1, 2, 3, 4]; + for uint::range(0, v.len()) |i| { + assert_eq!(v.iter().nth(i), &v[i]); + } + } + + #[test] + #[should_fail] + fn test_iterator_nth_fail() { + let v = &[0, 1, 2, 3, 4]; + v.iter().nth(5); + } + + #[test] + fn test_iterator_first() { + let v = &[0, 1, 2, 3, 4]; + assert_eq!(v.iter().first(), &0); + assert_eq!(v.slice(2, 5).iter().first(), &2); + } + + #[test] + #[should_fail] + fn test_iterator_first_fail() { + let v: &[uint] = &[]; + v.iter().first(); + } + + #[test] + fn test_iterator_last() { + let v = &[0, 1, 2, 3, 4]; + assert_eq!(v.iter().last(), &4); + assert_eq!(v.slice(0, 1).iter().last(), &0); + } + + #[test] + #[should_fail] + fn test_iterator_last_fail() { + let v: &[uint] = &[]; + v.iter().last(); + } } From b4cea351ba9df84efbff56d7bd79cd52704592d6 Mon Sep 17 00:00:00 2001 From: gifnksm Date: Fri, 17 May 2013 23:54:58 +0900 Subject: [PATCH 055/248] libcore: Add `IteratorUtil::fold`, `count` --- src/libcore/iterator.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 14d6083067a9d..58850190d8b1d 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -50,6 +50,8 @@ pub trait IteratorUtil { fn nth(&mut self, n: uint) -> A; fn first(&mut self) -> A; fn last(&mut self) -> A; + fn fold(&mut self, start: B, f: &fn(B, A) -> B) -> B; + fn count(&mut self) -> uint; } /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also @@ -184,6 +186,23 @@ impl> IteratorUtil for T { for self.advance |e| { elm = e; } return elm; } + + /// Reduce an iterator to an accumulated value + #[inline] + fn fold(&mut self, init: B, f: &fn(B, A) -> B) -> B { + let mut accum = init; + loop { + match self.next() { + Some(x) => { accum = f(accum, x); } + None => { break; } + } + } + return accum; + } + + /// Count the number of an iterator elemenrs + #[inline(always)] + fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) } } pub struct ChainIterator { @@ -648,4 +667,12 @@ mod tests { let v: &[uint] = &[]; v.iter().last(); } + + #[test] + fn test_iterator_count() { + let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().count(), 4); + assert_eq!(v.slice(0, 10).iter().count(), 10); + assert_eq!(v.slice(0, 0).iter().count(), 0); + } } From 54fbac505ed13c4afe193c8c4d6212df708e74d0 Mon Sep 17 00:00:00 2001 From: gifnksm Date: Sat, 18 May 2013 00:18:09 +0900 Subject: [PATCH 056/248] libcore: Add `AdditiveIterator`, `MultiplicativeIterator`, `OrdIterator` --- src/libcore/iterator.rs | 79 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 58850190d8b1d..bf2864702963b 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -18,6 +18,7 @@ implementing the `Iterator` trait. */ use prelude::*; +use num::{Zero, One}; pub trait Iterator { /// Advance the iterator and return the next value. Return `None` when the end is reached. @@ -205,6 +206,51 @@ impl> IteratorUtil for T { fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) } } +pub trait AdditiveIterator { + fn sum(&mut self) -> A; +} + +impl + Zero, T: Iterator> AdditiveIterator for T { + #[inline(always)] + fn sum(&mut self) -> A { self.fold(Zero::zero::(), |s, x| s + x) } +} + +pub trait MultiplicativeIterator { + fn product(&mut self) -> A; +} + +impl + One, T: Iterator> MultiplicativeIterator for T { + #[inline(always)] + fn product(&mut self) -> A { self.fold(One::one::(), |p, x| p * x) } +} + +pub trait OrdIterator { + fn max(&mut self) -> Option; + fn min(&mut self) -> Option; +} + +impl> OrdIterator for T { + #[inline(always)] + fn max(&mut self) -> Option { + self.fold(None, |max, x| { + match max { + None => Some(x), + Some(y) => Some(cmp::max(x, y)) + } + }) + } + + #[inline(always)] + fn min(&mut self) -> Option { + self.fold(None, |min, x| { + match min { + None => Some(x), + Some(y) => Some(cmp::min(x, y)) + } + }) + } +} + pub struct ChainIterator { priv a: T, priv b: U, @@ -675,4 +721,37 @@ mod tests { assert_eq!(v.slice(0, 10).iter().count(), 10); assert_eq!(v.slice(0, 0).iter().count(), 0); } + + #[test] + fn test_iterator_sum() { + let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().transform(|&x| x).sum(), 6); + assert_eq!(v.iter().transform(|&x| x).sum(), 55); + assert_eq!(v.slice(0, 0).iter().transform(|&x| x).sum(), 0); + } + + #[test] + fn test_iterator_product() { + let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().transform(|&x| x).product(), 0); + assert_eq!(v.slice(1, 5).iter().transform(|&x| x).product(), 24); + assert_eq!(v.slice(0, 0).iter().transform(|&x| x).product(), 1); + } + + #[test] + fn test_iterator_max() { + let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().transform(|&x| x).max(), Some(3)); + assert_eq!(v.iter().transform(|&x| x).max(), Some(10)); + assert_eq!(v.slice(0, 0).iter().transform(|&x| x).max(), None); + } + + #[test] + fn test_iterator_min() { + let v = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().transform(|&x| x).min(), Some(0)); + assert_eq!(v.iter().transform(|&x| x).min(), Some(0)); + assert_eq!(v.slice(0, 0).iter().transform(|&x| x).min(), None); + } + } From 3122d8027bfb38b76a916ef0e7be850da62f6e0b Mon Sep 17 00:00:00 2001 From: gifnksm Date: Sat, 18 May 2013 00:24:43 +0900 Subject: [PATCH 057/248] libcore: Add `IteratorUtil::all`, `any` method --- src/libcore/iterator.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index bf2864702963b..588bd0bde5343 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -53,6 +53,8 @@ pub trait IteratorUtil { fn last(&mut self) -> A; fn fold(&mut self, start: B, f: &fn(B, A) -> B) -> B; fn count(&mut self) -> uint; + fn all(&mut self, f: &fn(&A) -> bool) -> bool; + fn any(&mut self, f: &fn(&A) -> bool) -> bool; } /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also @@ -204,6 +206,18 @@ impl> IteratorUtil for T { /// Count the number of an iterator elemenrs #[inline(always)] fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) } + + #[inline(always)] + fn all(&mut self, f: &fn(&A) -> bool) -> bool { + for self.advance |x| { if !f(&x) { return false; } } + return true; + } + + #[inline(always)] + fn any(&mut self, f: &fn(&A) -> bool) -> bool { + for self.advance |x| { if f(&x) { return true; } } + return false; + } } pub trait AdditiveIterator { @@ -754,4 +768,21 @@ mod tests { assert_eq!(v.slice(0, 0).iter().transform(|&x| x).min(), None); } + #[test] + fn test_all() { + let v = ~&[1, 2, 3, 4, 5]; + assert!(v.iter().all(|&x| *x < 10)); + assert!(!v.iter().all(|&x| x.is_even())); + assert!(!v.iter().all(|&x| *x > 100)); + assert!(v.slice(0, 0).iter().all(|_| fail!())); + } + + #[test] + fn test_any() { + let v = ~&[1, 2, 3, 4, 5]; + assert!(v.iter().any(|&x| *x < 10)); + assert!(v.iter().any(|&x| x.is_even())); + assert!(!v.iter().any(|&x| *x > 100)); + assert!(!v.slice(0, 0).iter().any(|_| fail!())); + } } From 7dc466f91f3f6bf44d72430bf760277cd4eebf3a Mon Sep 17 00:00:00 2001 From: Olivier Saut Date: Fri, 17 May 2013 23:11:18 +0200 Subject: [PATCH 058/248] Correct the example given for a future, add punctuation where necessary --- src/libstd/future.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/src/libstd/future.rs b/src/libstd/future.rs index be33c0f4663ed..2ae61293a8fdd 100644 --- a/src/libstd/future.rs +++ b/src/libstd/future.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -15,9 +15,11 @@ * # Example * * ~~~ - * let delayed_fib = future::spawn {|| fib(5000) }; + * # fn fib(n: uint) -> uint {42}; + * # fn make_a_sandwich() {}; + * let mut delayed_fib = std::future::spawn (|| fib(5000) ); * make_a_sandwich(); - * io::println(fmt!("fib(5000) = %?", delayed_fib.get())) + * println(fmt!("fib(5000) = %?", delayed_fib.get())) * ~~~ */ @@ -51,7 +53,7 @@ priv enum FutureState { /// Methods on the `future` type pub impl Future { fn get(&mut self) -> A { - //! Get the value of the future + //! Get the value of the future. *(self.get_ref()) } } @@ -87,7 +89,7 @@ pub impl Future { pub fn from_value(val: A) -> Future { /*! - * Create a future from a value + * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. @@ -117,7 +119,7 @@ pub fn from_fn(f: ~fn() -> A) -> Future { /*! * Create a future from a function. * - * The first time that the value is requested it will be retreived by + * The first time that the value is requested it will be retrieved by * calling the function. Note that this function is a local * function. It is not spawned into another task. */ From 3e41639a5ee24695559a41c5079ed2d36d9b8789 Mon Sep 17 00:00:00 2001 From: Olivier Saut Date: Fri, 17 May 2013 23:11:49 +0200 Subject: [PATCH 059/248] Add a small section on futures to the tutorial --- doc/tutorial-tasks.md | 73 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 60 insertions(+), 13 deletions(-) diff --git a/doc/tutorial-tasks.md b/doc/tutorial-tasks.md index 402cfa84afcba..c9e0377dd132c 100644 --- a/doc/tutorial-tasks.md +++ b/doc/tutorial-tasks.md @@ -43,15 +43,16 @@ in the core and standard libraries, which are still under development and do not always present a consistent or complete interface. For your reference, these are the standard modules involved in Rust -concurrency at this writing. +concurrency at this writing: -* [`core::task`] - All code relating to tasks and task scheduling -* [`core::comm`] - The message passing interface -* [`core::pipes`] - The underlying messaging infrastructure -* [`std::comm`] - Additional messaging types based on `core::pipes` -* [`std::sync`] - More exotic synchronization tools, including locks +* [`core::task`] - All code relating to tasks and task scheduling, +* [`core::comm`] - The message passing interface, +* [`core::pipes`] - The underlying messaging infrastructure, +* [`std::comm`] - Additional messaging types based on `core::pipes`, +* [`std::sync`] - More exotic synchronization tools, including locks, * [`std::arc`] - The ARC (atomically reference counted) type, - for safely sharing immutable data + for safely sharing immutable data, +* [`std::future`] - A type representing values that may be computed concurrently and retrieved at a later time. [`core::task`]: core/task.html [`core::comm`]: core/comm.html @@ -59,6 +60,7 @@ concurrency at this writing. [`std::comm`]: std/comm.html [`std::sync`]: std/sync.html [`std::arc`]: std/arc.html +[`std::future`]: std/future.html # Basics @@ -70,7 +72,7 @@ closure in the new task. ~~~~ # use core::io::println; -use core::task::spawn; +# use core::task::spawn; // Print something profound in a different task using a named function fn print_message() { println("I am running in a different task!"); } @@ -145,8 +147,8 @@ endpoint. Consider the following example of calculating two results concurrently: ~~~~ -use core::task::spawn; -use core::comm::{stream, Port, Chan}; +# use core::task::spawn; +# use core::comm::{stream, Port, Chan}; let (port, chan): (Port, Chan) = stream(); @@ -233,7 +235,7 @@ Instead we can use a `SharedChan`, a type that allows a single ~~~ # use core::task::spawn; -use core::comm::{stream, SharedChan}; +# use core::comm::{stream, SharedChan}; let (port, chan) = stream(); let chan = SharedChan::new(chan); @@ -282,6 +284,51 @@ let result = ports.foldl(0, |accum, port| *accum + port.recv() ); # fn some_expensive_computation(_i: uint) -> int { 42 } ~~~ +## Futures +With `std::future`, rust has a mechanism for requesting a computation and getting the result +later. + +The basic example below illustrates this. +~~~ +# fn make_a_sandwich() {}; +fn fib(n: uint) -> uint { + // lengthy computation returning an uint + 12586269025 +} + +let mut delayed_fib = std::future::spawn (|| fib(50) ); +make_a_sandwich(); +println(fmt!("fib(50) = %?", delayed_fib.get())) +~~~ + +The call to `future::spawn` returns immediately a `future` object regardless of how long it +takes to run `fib(50)`. You can then make yourself a sandwich while the computation of `fib` is +running. The result of the execution of the method is obtained by calling `get` on the future. +This call will block until the value is available (*i.e.* the computation is complete). Note that +the future needs to be mutable so that it can save the result for next time `get` is called. + +Here is another example showing how futures allow you to background computations. The workload will +be distributed on the available cores. +~~~ +fn partial_sum(start: uint) -> f64 { + let mut local_sum = 0f64; + for uint::range(start*100000, (start+1)*100000) |num| { + local_sum += (num as f64 + 1.0).pow(-2.0); + } + local_sum +} + +fn main() { + let mut futures = vec::from_fn(1000, |ind| do std::future::spawn { partial_sum(ind) }); + + let mut final_res = 0f64; + for futures.each_mut |ft| { + final_res += ft.get(); + } + println(fmt!("π^2/6 is not far from : %?", final_res)); +} +~~~ + # Handling task failure Rust has a built-in mechanism for raising exceptions. The `fail!()` macro @@ -363,8 +410,8 @@ either task fails, it kills the other one. ~~~ # fn sleep_forever() { loop { task::yield() } } # do task::try { -do task::spawn { - do task::spawn { +do spawn { + do spawn { fail!(); // All three tasks will fail. } sleep_forever(); // Will get woken up by force, then fail From f5987b03b8d65a2b885519b7b9a0ea33cda33bc5 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 15 May 2013 17:20:48 -0700 Subject: [PATCH 060/248] core::rt: implement `oneshot` and `stream`. --- src/libcore/rt/comm.rs | 599 ++++++++++++++++++++++++++++++++++++++++ src/libcore/rt/mod.rs | 3 + src/libcore/rt/sched.rs | 11 + src/libcore/rt/test.rs | 33 ++- 4 files changed, 645 insertions(+), 1 deletion(-) create mode 100644 src/libcore/rt/comm.rs diff --git a/src/libcore/rt/comm.rs b/src/libcore/rt/comm.rs new file mode 100644 index 0000000000000..9fcb70cfc7d66 --- /dev/null +++ b/src/libcore/rt/comm.rs @@ -0,0 +1,599 @@ +// 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. + +use option::*; +use cast; +use util; +use ops::Drop; +use kinds::Owned; +use rt::sched::Coroutine; +use rt::local_sched; +#[cfg(stage0)] +use unstable::intrinsics::{atomic_xchg}; +#[cfg(not(stage0))] +use unstable::intrinsics::{atomic_xchg, atomic_load}; +use util::Void; +use comm::{GenericChan, GenericSmartChan, GenericPort, Peekable}; +use cell::Cell; + +/// A combined refcount / ~Task pointer. +/// +/// Can be equal to the following values: +/// +/// * 2 - both endpoints are alive +/// * 1 - either the sender or the receiver is dead, determined by context +/// * - A pointer to a Task that can be transmuted to ~Task +type State = int; + +static STATE_BOTH: State = 2; +static STATE_ONE: State = 1; + +struct Packet { + state: State, + payload: Option, +} + +pub struct PortOne { + // XXX: Hack extra allocation to make by-val self work + inner: ~PortOneHack +} + +pub struct ChanOne { + // XXX: Hack extra allocation to make by-val self work + inner: ~ChanOneHack +} + +pub struct PortOneHack { + void_packet: *mut Void, + suppress_finalize: bool +} + +pub struct ChanOneHack { + void_packet: *mut Void, + suppress_finalize: bool +} + +pub fn oneshot() -> (PortOne, ChanOne) { + let packet: ~Packet = ~Packet { + state: STATE_BOTH, + payload: None + }; + + unsafe { + let packet: *mut Void = cast::transmute(packet); + let port = PortOne { + inner: ~PortOneHack { + void_packet: packet, + suppress_finalize: false + } + }; + let chan = ChanOne { + inner: ~ChanOneHack { + void_packet: packet, + suppress_finalize: false + } + }; + return (port, chan); + } +} + +impl PortOne { + pub fn recv(self) -> T { + match self.try_recv() { + Some(val) => val, + None => { + fail!("receiving on closed channel"); + } + } + } + + pub fn try_recv(self) -> Option { + let mut this = self; + + { + let self_ptr: *mut PortOne = &mut this; + + // XXX: Optimize this to not require the two context switches when data is available + + // Switch to the scheduler + let sched = local_sched::take(); + do sched.deschedule_running_task_and_then |task| { + unsafe { + let task_as_state: State = cast::transmute(task); + let oldstate = atomic_xchg(&mut (*(*self_ptr).inner.packet()).state, task_as_state); + match oldstate { + STATE_BOTH => { + // Data has not been sent. Now we're blocked. + } + STATE_ONE => { + // Channel is closed. Switch back and check the data. + let task: ~Coroutine = cast::transmute(task_as_state); + let sched = local_sched::take(); + sched.resume_task_immediately(task); + } + _ => util::unreachable() + } + } + } + } + + // Task resumes. + + // No further memory barrier is needed here to access the + // payload. Some scenarios: + // + // 1) We encountered STATE_ONE above - the atomic_xchg was the acq barrier. We're fine. + // 2) We encountered STATE_BOTH above and blocked. The sending task work-stole us + // and ran on its thread. The work stealing had a memory barrier. + // 3) We encountered STATE_BOTH above and blocked, but the receiving task (this task) + // is pinned to some other scheduler, so the sending task had to give us to + // a different scheduler for resuming. That send synchronized memory. + + unsafe { + let payload = util::replace(&mut (*this.inner.packet()).payload, None); + + // The sender has closed up shop. Drop the packet. + let _packet: ~Packet = cast::transmute(this.inner.void_packet); + // Supress the finalizer. We're done here. + this.inner.suppress_finalize = true; + + return payload; + } + } +} + +impl Peekable for PortOne { + #[cfg(stage0)] + fn peek(&self) -> bool { fail!() } + + #[cfg(not(stage0))] + fn peek(&self) -> bool { + unsafe { + let packet: *mut Packet = self.inner.packet(); + let oldstate = atomic_load(&mut (*packet).state); + match oldstate { + STATE_BOTH => false, + STATE_ONE => (*packet).payload.is_some(), + _ => util::unreachable() + } + } + } +} + +impl ChanOne { + + pub fn send(self, val: T) { + self.try_send(val); + } + + pub fn try_send(self, val: T) -> bool { + let mut this = self; + let mut recvr_active = true; + + unsafe { + assert!((*this.inner.packet()).payload.is_none()); + (*this.inner.packet()).payload = Some(val); + + let oldstate = atomic_xchg(&mut (*this.inner.packet()).state, STATE_ONE); + match oldstate { + STATE_BOTH => { + // Port is not recving yet. Nothing to do + } + STATE_ONE => { + // Port has closed. Need to clean up. + let _packet: ~Packet = cast::transmute(this.inner.void_packet); + recvr_active = false; + } + _ => { + // Port is blocked. Wake it up. + let recvr: ~Coroutine = cast::transmute(oldstate); + let sched = local_sched::take(); + sched.schedule_task(recvr); + } + } + } + + // Suppress the finalizer. We're done here. + this.inner.suppress_finalize = true; + return recvr_active; + } +} + +#[unsafe_destructor] +impl Drop for PortOneHack { + fn finalize(&self) { + if self.suppress_finalize { return } + + unsafe { + let this = cast::transmute_mut(self); + let oldstate = atomic_xchg(&mut (*this.packet()).state, STATE_ONE); + match oldstate { + STATE_BOTH => { + /* cleanup is the chan's responsibility */ + }, + STATE_ONE => { + let _packet: ~Packet = cast::transmute(this.void_packet); + } + _ => { + util::unreachable() + } + } + } + } +} + +#[unsafe_destructor] +impl Drop for ChanOneHack { + fn finalize(&self) { + if self.suppress_finalize { return } + + unsafe { + let this = cast::transmute_mut(self); + let oldstate = atomic_xchg(&mut (*this.packet()).state, STATE_ONE); + match oldstate { + STATE_BOTH => { + /* cleanup is the port's responsibility */ + }, + STATE_ONE => { + let _packet: ~Packet = cast::transmute(this.void_packet); + }, + _ => { + // The port is blocked recving for a message we will never send. Wake it. + assert!((*this.packet()).payload.is_none()); + let recvr: ~Coroutine = cast::transmute(oldstate); + let sched = local_sched::take(); + sched.schedule_task(recvr); + } + } + } + } +} + +impl PortOneHack { + fn packet(&self) -> *mut Packet { + unsafe { + let p: *mut ~Packet = cast::transmute(&self.void_packet); + let p: *mut Packet = &mut **p; + return p; + } + } +} + +impl ChanOneHack { + fn packet(&self) -> *mut Packet { + unsafe { + let p: *mut ~Packet = cast::transmute(&self.void_packet); + let p: *mut Packet = &mut **p; + return p; + } + } +} + +struct StreamPayload(T, PortOne>); + +pub struct Port { + // FIXME #5372. Using Cell because we don't take &mut self + next: Cell>> +} + +pub struct Chan { + // FIXME #5372. Using Cell because we don't take &mut self + next: Cell>> +} + +pub fn stream() -> (Port, Chan) { + let (pone, cone) = oneshot(); + let port = Port { next: Cell(pone) }; + let chan = Chan { next: Cell(cone) }; + return (port, chan); +} + +impl GenericPort for Port { + fn recv(&self) -> T { + match self.try_recv() { + Some(val) => val, + None => { + fail!("receiving on closed channel"); + } + } + } + + fn try_recv(&self) -> Option { + let pone = self.next.take(); + match pone.try_recv() { + Some(StreamPayload(val, next)) => { + self.next.put_back(next); + Some(val) + } + None => None + } + } +} + +impl Peekable for Port { + fn peek(&self) -> bool { + self.next.with_mut_ref(|p| p.peek()) + } +} + +impl GenericChan for Chan { + fn send(&self, val: T) { + self.try_send(val); + } +} + +impl GenericSmartChan for Chan { + fn try_send(&self, val: T) -> bool { + let (next_pone, next_cone) = oneshot(); + let cone = self.next.take(); + self.next.put_back(next_cone); + cone.try_send(StreamPayload(val, next_pone)) + } +} + +#[cfg(test)] +mod test { + use super::*; + use option::*; + use rt::test::*; + use cell::Cell; + use iter::Times; + + #[test] + fn oneshot_single_thread_close_port_first() { + // Simple test of closing without sending + do run_in_newsched_task { + let (port, _chan) = oneshot::(); + { let _p = port; } + } + } + + #[test] + fn oneshot_single_thread_close_chan_first() { + // Simple test of closing without sending + do run_in_newsched_task { + let (_port, chan) = oneshot::(); + { let _c = chan; } + } + } + + #[test] + fn oneshot_single_thread_send_port_close() { + // Testing that the sender cleans up the payload if receiver is closed + do run_in_newsched_task { + let (port, chan) = oneshot::<~int>(); + { let _p = port; } + chan.send(~0); + } + } + + #[test] + fn oneshot_single_thread_recv_chan_close() { + // Receiving on a closed chan will fail + do run_in_newsched_task { + let res = do spawntask_try { + let (port, chan) = oneshot::<~int>(); + { let _c = chan; } + port.recv(); + }; + assert!(res.is_err()); + } + } + + #[test] + fn oneshot_single_thread_send_then_recv() { + do run_in_newsched_task { + let (port, chan) = oneshot::<~int>(); + chan.send(~10); + assert!(port.recv() == ~10); + } + } + + #[test] + fn oneshot_single_thread_try_send_open() { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + assert!(chan.try_send(10)); + assert!(port.recv() == 10); + } + } + + #[test] + fn oneshot_single_thread_try_send_closed() { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + { let _p = port; } + assert!(!chan.try_send(10)); + } + } + + #[test] + fn oneshot_single_thread_try_recv_open() { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + chan.send(10); + assert!(port.try_recv() == Some(10)); + } + } + + #[test] + fn oneshot_single_thread_try_recv_closed() { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + { let _c = chan; } + assert!(port.try_recv() == None); + } + } + + #[test] + fn oneshot_single_thread_peek_data() { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + assert!(!port.peek()); + chan.send(10); + assert!(port.peek()); + } + } + + #[test] + fn oneshot_single_thread_peek_close() { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + { let _c = chan; } + assert!(!port.peek()); + assert!(!port.peek()); + } + } + + #[test] + fn oneshot_single_thread_peek_open() { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + assert!(!port.peek()); + } + } + + #[test] + fn oneshot_multi_task_recv_then_send() { + do run_in_newsched_task { + let (port, chan) = oneshot::<~int>(); + let port_cell = Cell(port); + do spawntask_immediately { + assert!(port_cell.take().recv() == ~10); + } + + chan.send(~10); + } + } + + #[test] + fn oneshot_multi_task_recv_then_close() { + do run_in_newsched_task { + let (port, chan) = oneshot::<~int>(); + let port_cell = Cell(port); + let chan_cell = Cell(chan); + do spawntask_later { + let _cell = chan_cell.take(); + } + let res = do spawntask_try { + assert!(port_cell.take().recv() == ~10); + }; + assert!(res.is_err()); + } + } + + #[test] + fn oneshot_multi_thread_close_stress() { + for stress_factor().times { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + let port_cell = Cell(port); + let _thread = do spawntask_thread { + let _p = port_cell.take(); + }; + let _chan = chan; + } + } + } + + #[test] + fn oneshot_multi_thread_send_close_stress() { + for stress_factor().times { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + let chan_cell = Cell(chan); + let port_cell = Cell(port); + let _thread1 = do spawntask_thread { + let _p = port_cell.take(); + }; + let _thread2 = do spawntask_thread { + let c = chan_cell.take(); + c.send(1); + }; + } + } + } + + #[test] + fn oneshot_multi_thread_recv_close_stress() { + for stress_factor().times { + do run_in_newsched_task { + let (port, chan) = oneshot::(); + let chan_cell = Cell(chan); + let port_cell = Cell(port); + let _thread1 = do spawntask_thread { + let port_cell = Cell(port_cell.take()); + let res = do spawntask_try { + port_cell.take().recv(); + }; + assert!(res.is_err()); + }; + let _thread2 = do spawntask_thread { + let chan_cell = Cell(chan_cell.take()); + do spawntask { + chan_cell.take(); + } + }; + } + } + } + + #[test] + fn oneshot_multi_thread_send_recv_stress() { + for stress_factor().times { + do run_in_newsched_task { + let (port, chan) = oneshot::<~int>(); + let chan_cell = Cell(chan); + let port_cell = Cell(port); + let _thread1 = do spawntask_thread { + chan_cell.take().send(~10); + }; + let _thread2 = do spawntask_thread { + assert!(port_cell.take().recv() == ~10); + }; + } + } + } + + #[test] + fn stream_send_recv() { + for stress_factor().times { + do run_in_newsched_task { + let (port, chan) = stream::<~int>(); + + send(chan, 0); + recv(port, 0); + + fn send(chan: Chan<~int>, i: int) { + if i == 10 { return } + + let chan_cell = Cell(chan); + let _thread = do spawntask_thread { + let chan = chan_cell.take(); + chan.send(~i); + send(chan, i + 1); + }; + } + + fn recv(port: Port<~int>, i: int) { + if i == 10 { return } + + let port_cell = Cell(port); + let _thread = do spawntask_thread { + let port = port_cell.take(); + assert!(port.recv() == ~i); + recv(port, i + 1); + }; + } + } + } + } +} + diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 7a772ff0f3b96..dab627188d0f5 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -122,6 +122,9 @@ pub mod rc; /// scheduler and task context pub mod tube; +/// Simple reimplementation of core::comm +pub mod comm; + /// Set up a default runtime configuration, given compiler-supplied arguments. /// /// This is invoked by the `start` _language item_ (unstable::lang) to diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 5c1a3410087c4..c66f20e01b2d7 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -171,6 +171,17 @@ pub impl Scheduler { } } + fn schedule_task(~self, task: ~Coroutine) { + assert!(self.in_task_context()); + + do self.switch_running_tasks_and_then(task) |last_task| { + let last_task = Cell(last_task); + do local_sched::borrow |sched| { + sched.enqueue_task(last_task.take()); + } + } + } + // Core scheduling ops fn resume_task_immediately(~self, task: ~Coroutine) { diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index 1294b9bcf4765..d739d0110ba35 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -8,17 +8,20 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use uint; +use option::*; use cell::Cell; use result::{Result, Ok, Err}; use super::io::net::ip::{IpAddr, Ipv4}; use rt::local_services::LocalServices; +use rt::thread::Thread; /// Creates a new scheduler in a new thread and runs a task in it, /// then waits for the scheduler to exit. Failure of the task /// will abort the process. pub fn run_in_newsched_task(f: ~fn()) { + use super::sched::*; use unstable::run_in_bare_thread; - use super::sched::Coroutine; use rt::uv::uvio::UvEventLoop; let f = Cell(f); @@ -144,6 +147,23 @@ pub fn spawntask_try(f: ~fn()) -> Result<(), ()> { if !failed { Ok(()) } else { Err(()) } } +// Spawn a new task in a new scheduler and return a thread handle. +pub fn spawntask_thread(f: ~fn()) -> Thread { + use rt::sched::*; + use rt::uv::uvio::UvEventLoop; + + let f = Cell(f); + let thread = do Thread::start { + let mut sched = ~UvEventLoop::new_scheduler(); + let task = ~Coroutine::with_local(&mut sched.stack_pool, + LocalServices::without_unwinding(), + f.take()); + sched.enqueue_task(task); + sched.run(); + }; + return thread; +} + /// Get a port number, starting at 9600, for use in tests pub fn next_test_port() -> u16 { unsafe { @@ -158,3 +178,14 @@ pub fn next_test_port() -> u16 { pub fn next_test_ip4() -> IpAddr { Ipv4(127, 0, 0, 1, next_test_port()) } + +/// Get a constant that represents the number of times to repeat stress tests. Default 1. +pub fn stress_factor() -> uint { + use os::getenv; + + match getenv("RUST_RT_STRESS") { + Some(val) => uint::from_str(val).get(), + None => 1 + } +} + From 26becc308e4b9a0f5be1c7c2895c7761b778e01f Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 16 May 2013 23:12:22 -0700 Subject: [PATCH 061/248] core: Wire up oneshot pipes to newsched --- src/libcore/comm.rs | 350 ++++++++++++++++++++----------- src/libcore/rt/local_services.rs | 22 ++ src/libstd/future.rs | 10 +- src/libstd/workcache.rs | 7 +- 4 files changed, 253 insertions(+), 136 deletions(-) diff --git a/src/libcore/comm.rs b/src/libcore/comm.rs index 34c60202b3f12..da3ae0e6c5dfe 100644 --- a/src/libcore/comm.rs +++ b/src/libcore/comm.rs @@ -22,6 +22,8 @@ use vec; use vec::OwnedVector; use util::replace; use unstable::sync::{Exclusive, exclusive}; +use rtcomm = rt::comm; +use rt; use pipes::{recv, try_recv, wait_many, peek, PacketHeader}; @@ -335,180 +337,280 @@ impl ::clone::Clone for SharedChan { } } -/*proto! oneshot ( - Oneshot:send { - send(T) -> ! +pub struct PortOne { + inner: Either, rtcomm::PortOne> +} + +pub struct ChanOne { + inner: Either, rtcomm::ChanOne> +} + +pub fn oneshot() -> (PortOne, ChanOne) { + let (port, chan) = match rt::context() { + rt::OldTaskContext => match pipesy::oneshot() { + (p, c) => (Left(p), Left(c)), + }, + _ => match rtcomm::oneshot() { + (p, c) => (Right(p), Right(c)) + } + }; + let port = PortOne { + inner: port + }; + let chan = ChanOne { + inner: chan + }; + return (port, chan); +} + +impl PortOne { + pub fn recv(self) -> T { + let PortOne { inner } = self; + match inner { + Left(p) => p.recv(), + Right(p) => p.recv() + } } -)*/ -#[allow(non_camel_case_types)] -pub mod oneshot { - priv use core::kinds::Owned; - use ptr::to_mut_unsafe_ptr; + pub fn try_recv(self) -> Option { + let PortOne { inner } = self; + match inner { + Left(p) => p.try_recv(), + Right(p) => p.try_recv() + } + } +} - pub fn init() -> (client::Oneshot, server::Oneshot) { - pub use core::pipes::HasBuffer; +impl ChanOne { + pub fn send(self, data: T) { + let ChanOne { inner } = self; + match inner { + Left(p) => p.send(data), + Right(p) => p.send(data) + } + } - let buffer = ~::core::pipes::Buffer { - header: ::core::pipes::BufferHeader(), - data: __Buffer { - Oneshot: ::core::pipes::mk_packet::>() - }, - }; - do ::core::pipes::entangle_buffer(buffer) |buffer, data| { - data.Oneshot.set_buffer(buffer); - to_mut_unsafe_ptr(&mut data.Oneshot) + pub fn try_send(self, data: T) -> bool { + let ChanOne { inner } = self; + match inner { + Left(p) => p.try_send(data), + Right(p) => p.try_send(data) } } - #[allow(non_camel_case_types)] - pub enum Oneshot { pub send(T), } - #[allow(non_camel_case_types)] - pub struct __Buffer { - Oneshot: ::core::pipes::Packet>, +} + +pub fn recv_one(port: PortOne) -> T { + let PortOne { inner } = port; + match inner { + Left(p) => pipesy::recv_one(p), + Right(p) => p.recv() } +} - #[allow(non_camel_case_types)] - pub mod client { +pub fn try_recv_one(port: PortOne) -> Option { + let PortOne { inner } = port; + match inner { + Left(p) => pipesy::try_recv_one(p), + Right(p) => p.try_recv() + } +} + +pub fn send_one(chan: ChanOne, data: T) { + let ChanOne { inner } = chan; + match inner { + Left(c) => pipesy::send_one(c, data), + Right(c) => c.send(data) + } +} + +pub fn try_send_one(chan: ChanOne, data: T) -> bool { + let ChanOne { inner } = chan; + match inner { + Left(c) => pipesy::try_send_one(c, data), + Right(c) => c.try_send(data) + } +} +mod pipesy { + + use kinds::Owned; + use option::{Option, Some, None}; + use pipes::{recv, try_recv}; + + /*proto! oneshot ( + Oneshot:send { + send(T) -> ! + } + )*/ + + #[allow(non_camel_case_types)] + pub mod oneshot { priv use core::kinds::Owned; + use ptr::to_mut_unsafe_ptr; - #[allow(non_camel_case_types)] - pub fn try_send(pipe: Oneshot, x_0: T) -> - ::core::option::Option<()> { - { - use super::send; - let message = send(x_0); - if ::core::pipes::send(pipe, message) { - ::core::pipes::rt::make_some(()) - } else { ::core::pipes::rt::make_none() } + pub fn init() -> (client::Oneshot, server::Oneshot) { + pub use core::pipes::HasBuffer; + + let buffer = ~::core::pipes::Buffer { + header: ::core::pipes::BufferHeader(), + data: __Buffer { + Oneshot: ::core::pipes::mk_packet::>() + }, + }; + do ::core::pipes::entangle_buffer(buffer) |buffer, data| { + data.Oneshot.set_buffer(buffer); + to_mut_unsafe_ptr(&mut data.Oneshot) } } + #[allow(non_camel_case_types)] + pub enum Oneshot { pub send(T), } + #[allow(non_camel_case_types)] + pub struct __Buffer { + Oneshot: ::core::pipes::Packet>, + } #[allow(non_camel_case_types)] - pub fn send(pipe: Oneshot, x_0: T) { - { - use super::send; - let message = send(x_0); - ::core::pipes::send(pipe, message); + pub mod client { + + priv use core::kinds::Owned; + + #[allow(non_camel_case_types)] + pub fn try_send(pipe: Oneshot, x_0: T) -> + ::core::option::Option<()> { + { + use super::send; + let message = send(x_0); + if ::core::pipes::send(pipe, message) { + ::core::pipes::rt::make_some(()) + } else { ::core::pipes::rt::make_none() } + } } + + #[allow(non_camel_case_types)] + pub fn send(pipe: Oneshot, x_0: T) { + { + use super::send; + let message = send(x_0); + ::core::pipes::send(pipe, message); + } + } + + #[allow(non_camel_case_types)] + pub type Oneshot = + ::core::pipes::SendPacketBuffered, + super::__Buffer>; } #[allow(non_camel_case_types)] - pub type Oneshot = - ::core::pipes::SendPacketBuffered, - super::__Buffer>; + pub mod server { + #[allow(non_camel_case_types)] + pub type Oneshot = + ::core::pipes::RecvPacketBuffered, + super::__Buffer>; + } } - #[allow(non_camel_case_types)] - pub mod server { - #[allow(non_camel_case_types)] - pub type Oneshot = - ::core::pipes::RecvPacketBuffered, - super::__Buffer>; + /// The send end of a oneshot pipe. + pub struct ChanOne { + contents: oneshot::client::Oneshot } -} - -/// The send end of a oneshot pipe. -pub struct ChanOne { - contents: oneshot::client::Oneshot -} -impl ChanOne { - pub fn new(contents: oneshot::client::Oneshot) -> ChanOne { - ChanOne { - contents: contents + impl ChanOne { + pub fn new(contents: oneshot::client::Oneshot) -> ChanOne { + ChanOne { + contents: contents + } } } -} -/// The receive end of a oneshot pipe. -pub struct PortOne { - contents: oneshot::server::Oneshot -} + /// The receive end of a oneshot pipe. + pub struct PortOne { + contents: oneshot::server::Oneshot + } -impl PortOne { - pub fn new(contents: oneshot::server::Oneshot) -> PortOne { - PortOne { - contents: contents + impl PortOne { + pub fn new(contents: oneshot::server::Oneshot) -> PortOne { + PortOne { + contents: contents + } } } -} -/// Initialiase a (send-endpoint, recv-endpoint) oneshot pipe pair. -pub fn oneshot() -> (PortOne, ChanOne) { - let (chan, port) = oneshot::init(); - (PortOne::new(port), ChanOne::new(chan)) -} + /// Initialiase a (send-endpoint, recv-endpoint) oneshot pipe pair. + pub fn oneshot() -> (PortOne, ChanOne) { + let (chan, port) = oneshot::init(); + (PortOne::new(port), ChanOne::new(chan)) + } -pub impl PortOne { - fn recv(self) -> T { recv_one(self) } - fn try_recv(self) -> Option { try_recv_one(self) } - fn unwrap(self) -> oneshot::server::Oneshot { - match self { - PortOne { contents: s } => s + pub impl PortOne { + fn recv(self) -> T { recv_one(self) } + fn try_recv(self) -> Option { try_recv_one(self) } + fn unwrap(self) -> oneshot::server::Oneshot { + match self { + PortOne { contents: s } => s + } } } -} -pub impl ChanOne { - fn send(self, data: T) { send_one(self, data) } - fn try_send(self, data: T) -> bool { try_send_one(self, data) } - fn unwrap(self) -> oneshot::client::Oneshot { - match self { - ChanOne { contents: s } => s + pub impl ChanOne { + fn send(self, data: T) { send_one(self, data) } + fn try_send(self, data: T) -> bool { try_send_one(self, data) } + fn unwrap(self) -> oneshot::client::Oneshot { + match self { + ChanOne { contents: s } => s + } } } -} -/** - * Receive a message from a oneshot pipe, failing if the connection was - * closed. - */ -pub fn recv_one(port: PortOne) -> T { - match port { - PortOne { contents: port } => { - let oneshot::send(message) = recv(port); - message + /** + * Receive a message from a oneshot pipe, failing if the connection was + * closed. + */ + pub fn recv_one(port: PortOne) -> T { + match port { + PortOne { contents: port } => { + let oneshot::send(message) = recv(port); + message + } } } -} -/// Receive a message from a oneshot pipe unless the connection was closed. -pub fn try_recv_one (port: PortOne) -> Option { - match port { - PortOne { contents: port } => { - let message = try_recv(port); + /// Receive a message from a oneshot pipe unless the connection was closed. + pub fn try_recv_one (port: PortOne) -> Option { + match port { + PortOne { contents: port } => { + let message = try_recv(port); - if message.is_none() { - None - } else { - let oneshot::send(message) = message.unwrap(); - Some(message) + if message.is_none() { + None + } else { + let oneshot::send(message) = message.unwrap(); + Some(message) + } } } } -} -/// Send a message on a oneshot pipe, failing if the connection was closed. -pub fn send_one(chan: ChanOne, data: T) { - match chan { - ChanOne { contents: chan } => oneshot::client::send(chan, data), + /// Send a message on a oneshot pipe, failing if the connection was closed. + pub fn send_one(chan: ChanOne, data: T) { + match chan { + ChanOne { contents: chan } => oneshot::client::send(chan, data), + } } -} -/** - * Send a message on a oneshot pipe, or return false if the connection was - * closed. - */ -pub fn try_send_one(chan: ChanOne, data: T) -> bool { - match chan { - ChanOne { contents: chan } => { - oneshot::client::try_send(chan, data).is_some() + /** + * Send a message on a oneshot pipe, or return false if the connection was + * closed. + */ + pub fn try_send_one(chan: ChanOne, data: T) -> bool { + match chan { + ChanOne { contents: chan } => { + oneshot::client::try_send(chan, data).is_some() + } } } -} - +} /// Returns the index of an endpoint that is ready to receive. pub fn selecti(endpoints: &mut [T]) -> uint { diff --git a/src/libcore/rt/local_services.rs b/src/libcore/rt/local_services.rs index 98bfc2fa1686f..35c703bb35074 100644 --- a/src/libcore/rt/local_services.rs +++ b/src/libcore/rt/local_services.rs @@ -244,5 +244,27 @@ mod test { info!("here i am. logging in a newsched task"); } } + + #[test] + fn comm_oneshot() { + use comm::*; + + do run_in_newsched_task { + let (port, chan) = oneshot(); + send_one(chan, 10); + assert!(recv_one(port) == 10); + } + } + + #[test] + fn comm_stream() { + use comm::*; + + do run_in_newsched_task() { + let (port, chan) = oneshot(); + chan.send(10); + assert!(port.recv() == 10); + } + } } diff --git a/src/libstd/future.rs b/src/libstd/future.rs index be33c0f4663ed..b8ae03c0f2bfe 100644 --- a/src/libstd/future.rs +++ b/src/libstd/future.rs @@ -23,8 +23,7 @@ use core::cast; use core::cell::Cell; -use core::comm::{PortOne, oneshot, send_one}; -use core::pipes::recv; +use core::comm::{PortOne, oneshot, send_one, recv_one}; use core::task; use core::util::replace; @@ -105,11 +104,8 @@ pub fn from_port(port: PortOne) -> Future { */ let port = Cell(port); - do from_fn || { - let port = port.take().unwrap(); - match recv(port) { - oneshot::send(data) => data - } + do from_fn { + recv_one(port.take()) } } diff --git a/src/libstd/workcache.rs b/src/libstd/workcache.rs index f173df60df893..3889650d012e0 100644 --- a/src/libstd/workcache.rs +++ b/src/libstd/workcache.rs @@ -15,11 +15,10 @@ use sort; use core::cell::Cell; use core::cmp; -use core::comm::{PortOne, oneshot, send_one}; +use core::comm::{PortOne, oneshot, send_one, recv_one}; use core::either::{Either, Left, Right}; use core::hashmap::HashMap; use core::io; -use core::pipes::recv; use core::run; use core::to_bytes; use core::util::replace; @@ -389,9 +388,7 @@ fn unwrap fail!(), Some(Left(v)) => v, Some(Right(port)) => { - let (exe, v) = match recv(port.unwrap()) { - oneshot::send(data) => data - }; + let (exe, v) = recv_one(port); let s = json_encode(&v); From df9e41278eb1e3e653ccd6b4dfab4d7303f64c02 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 17 May 2013 17:47:10 -0700 Subject: [PATCH 062/248] core: Wire up `stream` to newsched --- src/libcore/comm.rs | 349 +++++++++++++++++++------------ src/libcore/rt/comm.rs | 248 ++++++++++++---------- src/libcore/rt/local_services.rs | 2 +- 3 files changed, 357 insertions(+), 242 deletions(-) diff --git a/src/libcore/comm.rs b/src/libcore/comm.rs index da3ae0e6c5dfe..59eb915c239fe 100644 --- a/src/libcore/comm.rs +++ b/src/libcore/comm.rs @@ -25,7 +25,7 @@ use unstable::sync::{Exclusive, exclusive}; use rtcomm = rt::comm; use rt; -use pipes::{recv, try_recv, wait_many, peek, PacketHeader}; +use pipes::{wait_many, PacketHeader}; // FIXME #5160: Making this public exposes some plumbing from // pipes. Needs some refactoring @@ -61,76 +61,14 @@ pub trait Peekable { fn peek(&self) -> bool; } - -// Streams - Make pipes a little easier in general. - -/*proto! streamp ( - Open:send { - data(T) -> Open - } -)*/ - -#[allow(non_camel_case_types)] -pub mod streamp { - priv use core::kinds::Owned; - - pub fn init() -> (client::Open, server::Open) { - pub use core::pipes::HasBuffer; - ::core::pipes::entangle() - } - - #[allow(non_camel_case_types)] - pub enum Open { pub data(T, server::Open), } - - #[allow(non_camel_case_types)] - pub mod client { - priv use core::kinds::Owned; - - #[allow(non_camel_case_types)] - pub fn try_data(pipe: Open, x_0: T) -> - ::core::option::Option> { - { - use super::data; - let (c, s) = ::core::pipes::entangle(); - let message = data(x_0, s); - if ::core::pipes::send(pipe, message) { - ::core::pipes::rt::make_some(c) - } else { ::core::pipes::rt::make_none() } - } - } - - #[allow(non_camel_case_types)] - pub fn data(pipe: Open, x_0: T) -> Open { - { - use super::data; - let (c, s) = ::core::pipes::entangle(); - let message = data(x_0, s); - ::core::pipes::send(pipe, message); - c - } - } - - #[allow(non_camel_case_types)] - pub type Open = ::core::pipes::SendPacket>; - } - - #[allow(non_camel_case_types)] - pub mod server { - #[allow(non_camel_case_types)] - pub type Open = ::core::pipes::RecvPacket>; - } -} - /// An endpoint that can send many messages. -#[unsafe_mut_field(endp)] pub struct Chan { - endp: Option> + inner: Either, rtcomm::Chan> } /// An endpoint that can receive many messages. -#[unsafe_mut_field(endp)] pub struct Port { - endp: Option>, + inner: Either, rtcomm::Port> } /** Creates a `(Port, Chan)` pair. @@ -139,100 +77,75 @@ These allow sending or receiving an unlimited number of messages. */ pub fn stream() -> (Port, Chan) { - let (c, s) = streamp::init(); - - (Port { - endp: Some(s) - }, Chan { - endp: Some(c) - }) + let (port, chan) = match rt::context() { + rt::OldTaskContext => match pipesy::stream() { + (p, c) => (Left(p), Left(c)) + }, + _ => match rtcomm::stream() { + (p, c) => (Right(p), Right(c)) + } + }; + let port = Port { inner: port }; + let chan = Chan { inner: chan }; + return (port, chan); } impl GenericChan for Chan { - #[inline(always)] fn send(&self, x: T) { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - *self_endp = Some(streamp::client::data(endp.unwrap(), x)) + match self.inner { + Left(ref chan) => chan.send(x), + Right(ref chan) => chan.send(x) } } } impl GenericSmartChan for Chan { - #[inline(always)] fn try_send(&self, x: T) -> bool { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - match streamp::client::try_data(endp.unwrap(), x) { - Some(next) => { - *self_endp = Some(next); - true - } - None => false - } + match self.inner { + Left(ref chan) => chan.try_send(x), + Right(ref chan) => chan.try_send(x) } } } impl GenericPort for Port { - #[inline(always)] fn recv(&self) -> T { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - let streamp::data(x, endp) = recv(endp.unwrap()); - *self_endp = Some(endp); - x + match self.inner { + Left(ref port) => port.recv(), + Right(ref port) => port.recv() } } - #[inline(always)] fn try_recv(&self) -> Option { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - match try_recv(endp.unwrap()) { - Some(streamp::data(x, endp)) => { - *self_endp = Some(endp); - Some(x) - } - None => None - } + match self.inner { + Left(ref port) => port.try_recv(), + Right(ref port) => port.try_recv() } } } impl Peekable for Port { - #[inline(always)] fn peek(&self) -> bool { - unsafe { - let self_endp = transmute_mut(&self.endp); - let mut endp = replace(self_endp, None); - let peek = match endp { - Some(ref mut endp) => peek(endp), - None => fail!("peeking empty stream") - }; - *self_endp = endp; - peek + match self.inner { + Left(ref port) => port.peek(), + Right(ref port) => port.peek() } } } impl Selectable for Port { fn header(&mut self) -> *mut PacketHeader { - match self.endp { - Some(ref mut endp) => endp.header(), - None => fail!("peeking empty stream") - } + match self.inner { + Left(ref mut port) => port.header(), + Right(_) => fail!("can't select on newsched ports") + } } } /// Treat many ports as one. #[unsafe_mut_field(ports)] pub struct PortSet { - ports: ~[Port], + ports: ~[pipesy::Port], } pub impl PortSet { @@ -243,6 +156,11 @@ pub impl PortSet { } fn add(&self, port: Port) { + let Port { inner } = port; + let port = match inner { + Left(p) => p, + Right(_) => fail!("PortSet not implemented") + }; unsafe { let self_ports = transmute_mut(&self.ports); self_ports.push(port) @@ -290,7 +208,7 @@ impl Peekable for PortSet { // It'd be nice to use self.port.each, but that version isn't // pure. for uint::range(0, vec::uniq_len(&const self.ports)) |i| { - let port: &Port = &self.ports[i]; + let port: &pipesy::Port = &self.ports[i]; if port.peek() { return true; } @@ -301,12 +219,17 @@ impl Peekable for PortSet { /// A channel that can be shared between many senders. pub struct SharedChan { - ch: Exclusive> + ch: Exclusive> } impl SharedChan { /// Converts a `chan` into a `shared_chan`. pub fn new(c: Chan) -> SharedChan { + let Chan { inner } = c; + let c = match inner { + Left(c) => c, + Right(_) => fail!("SharedChan not implemented") + }; SharedChan { ch: exclusive(c) } } } @@ -354,12 +277,8 @@ pub fn oneshot() -> (PortOne, ChanOne) { (p, c) => (Right(p), Right(c)) } }; - let port = PortOne { - inner: port - }; - let chan = ChanOne { - inner: chan - }; + let port = PortOne { inner: port }; + let chan = ChanOne { inner: chan }; return (port, chan); } @@ -435,7 +354,10 @@ mod pipesy { use kinds::Owned; use option::{Option, Some, None}; - use pipes::{recv, try_recv}; + use pipes::{recv, try_recv, peek, PacketHeader}; + use super::{GenericChan, GenericSmartChan, GenericPort, Peekable, Selectable}; + use cast::transmute_mut; + use util::replace; /*proto! oneshot ( Oneshot:send { @@ -610,6 +532,173 @@ mod pipesy { } } + // Streams - Make pipes a little easier in general. + + /*proto! streamp ( + Open:send { + data(T) -> Open + } + )*/ + + #[allow(non_camel_case_types)] + pub mod streamp { + priv use core::kinds::Owned; + + pub fn init() -> (client::Open, server::Open) { + pub use core::pipes::HasBuffer; + ::core::pipes::entangle() + } + + #[allow(non_camel_case_types)] + pub enum Open { pub data(T, server::Open), } + + #[allow(non_camel_case_types)] + pub mod client { + priv use core::kinds::Owned; + + #[allow(non_camel_case_types)] + pub fn try_data(pipe: Open, x_0: T) -> + ::core::option::Option> { + { + use super::data; + let (c, s) = ::core::pipes::entangle(); + let message = data(x_0, s); + if ::core::pipes::send(pipe, message) { + ::core::pipes::rt::make_some(c) + } else { ::core::pipes::rt::make_none() } + } + } + + #[allow(non_camel_case_types)] + pub fn data(pipe: Open, x_0: T) -> Open { + { + use super::data; + let (c, s) = ::core::pipes::entangle(); + let message = data(x_0, s); + ::core::pipes::send(pipe, message); + c + } + } + + #[allow(non_camel_case_types)] + pub type Open = ::core::pipes::SendPacket>; + } + + #[allow(non_camel_case_types)] + pub mod server { + #[allow(non_camel_case_types)] + pub type Open = ::core::pipes::RecvPacket>; + } + } + + /// An endpoint that can send many messages. + #[unsafe_mut_field(endp)] + pub struct Chan { + endp: Option> + } + + /// An endpoint that can receive many messages. + #[unsafe_mut_field(endp)] + pub struct Port { + endp: Option>, + } + + /** Creates a `(Port, Chan)` pair. + + These allow sending or receiving an unlimited number of messages. + + */ + pub fn stream() -> (Port, Chan) { + let (c, s) = streamp::init(); + + (Port { + endp: Some(s) + }, Chan { + endp: Some(c) + }) + } + + impl GenericChan for Chan { + #[inline(always)] + fn send(&self, x: T) { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + *self_endp = Some(streamp::client::data(endp.unwrap(), x)) + } + } + } + + impl GenericSmartChan for Chan { + #[inline(always)] + fn try_send(&self, x: T) -> bool { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + match streamp::client::try_data(endp.unwrap(), x) { + Some(next) => { + *self_endp = Some(next); + true + } + None => false + } + } + } + } + + impl GenericPort for Port { + #[inline(always)] + fn recv(&self) -> T { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + let streamp::data(x, endp) = recv(endp.unwrap()); + *self_endp = Some(endp); + x + } + } + + #[inline(always)] + fn try_recv(&self) -> Option { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + match try_recv(endp.unwrap()) { + Some(streamp::data(x, endp)) => { + *self_endp = Some(endp); + Some(x) + } + None => None + } + } + } + } + + impl Peekable for Port { + #[inline(always)] + fn peek(&self) -> bool { + unsafe { + let self_endp = transmute_mut(&self.endp); + let mut endp = replace(self_endp, None); + let peek = match endp { + Some(ref mut endp) => peek(endp), + None => fail!("peeking empty stream") + }; + *self_endp = endp; + peek + } + } + } + + impl Selectable for Port { + fn header(&mut self) -> *mut PacketHeader { + match self.endp { + Some(ref mut endp) => endp.header(), + None => fail!("peeking empty stream") + } + } +} + } /// Returns the index of an endpoint that is ready to receive. diff --git a/src/libcore/rt/comm.rs b/src/libcore/rt/comm.rs index 9fcb70cfc7d66..4b5732b2d3aec 100644 --- a/src/libcore/rt/comm.rs +++ b/src/libcore/rt/comm.rs @@ -8,6 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +//! Ports and channels. +//! +//! XXX: Carefully consider whether the sequentially consistent +//! atomics here can be converted to acq/rel. I'm not sure they can, +//! because there is data being transerred in both directions (the payload +//! goes from sender to receiver and the task pointer goes the other way). + use option::*; use cast; use util; @@ -29,33 +36,37 @@ use cell::Cell; /// /// * 2 - both endpoints are alive /// * 1 - either the sender or the receiver is dead, determined by context -/// * - A pointer to a Task that can be transmuted to ~Task +/// * - A pointer to a blocked Task that can be transmuted to ~Task type State = int; static STATE_BOTH: State = 2; static STATE_ONE: State = 1; +/// The heap-allocated structure shared between two endpoints. struct Packet { state: State, payload: Option, } -pub struct PortOne { +/// A one-shot channel. +pub struct ChanOne { // XXX: Hack extra allocation to make by-val self work - inner: ~PortOneHack + inner: ~ChanOneHack } -pub struct ChanOne { + +/// A one-shot port. +pub struct PortOne { // XXX: Hack extra allocation to make by-val self work - inner: ~ChanOneHack + inner: ~PortOneHack } -pub struct PortOneHack { +pub struct ChanOneHack { void_packet: *mut Void, suppress_finalize: bool } -pub struct ChanOneHack { +pub struct PortOneHack { void_packet: *mut Void, suppress_finalize: bool } @@ -84,6 +95,54 @@ pub fn oneshot() -> (PortOne, ChanOne) { } } +impl ChanOne { + + pub fn send(self, val: T) { + self.try_send(val); + } + + pub fn try_send(self, val: T) -> bool { + let mut this = self; + let mut recvr_active = true; + let packet = this.inner.packet(); + + unsafe { + + // Install the payload + assert!((*packet).payload.is_none()); + (*packet).payload = Some(val); + + // Atomically swap out the old state to figure out what + // the port's up to, issuing a release barrier to prevent + // reordering of the payload write. This also issues an + // acquire barrier that keeps the subsequent access of the + // ~Task pointer from being reordered. + let oldstate = atomic_xchg(&mut (*packet).state, STATE_ONE); + match oldstate { + STATE_BOTH => { + // Port is not waiting yet. Nothing to do + } + STATE_ONE => { + // Port has closed. Need to clean up. + let _packet: ~Packet = cast::transmute(this.inner.void_packet); + recvr_active = false; + } + task_as_state => { + // Port is blocked. Wake it up. + let recvr: ~Coroutine = cast::transmute(task_as_state); + let sched = local_sched::take(); + sched.schedule_task(recvr); + } + } + } + + // Suppress the synchronizing actions in the finalizer. We're done with the packet. + this.inner.suppress_finalize = true; + return recvr_active; + } +} + + impl PortOne { pub fn recv(self) -> T { match self.try_recv() { @@ -96,30 +155,31 @@ impl PortOne { pub fn try_recv(self) -> Option { let mut this = self; - - { - let self_ptr: *mut PortOne = &mut this; - - // XXX: Optimize this to not require the two context switches when data is available - - // Switch to the scheduler - let sched = local_sched::take(); - do sched.deschedule_running_task_and_then |task| { - unsafe { - let task_as_state: State = cast::transmute(task); - let oldstate = atomic_xchg(&mut (*(*self_ptr).inner.packet()).state, task_as_state); - match oldstate { - STATE_BOTH => { - // Data has not been sent. Now we're blocked. - } - STATE_ONE => { - // Channel is closed. Switch back and check the data. - let task: ~Coroutine = cast::transmute(task_as_state); - let sched = local_sched::take(); - sched.resume_task_immediately(task); - } - _ => util::unreachable() + let packet = this.inner.packet(); + + // XXX: Optimize this to not require the two context switches when data is available + + // Switch to the scheduler to put the ~Task into the Packet state. + let sched = local_sched::take(); + do sched.deschedule_running_task_and_then |task| { + unsafe { + // Atomically swap the task pointer into the Packet state, issuing + // an acquire barrier to prevent reordering of the subsequent read + // of the payload. Also issues a release barrier to prevent reordering + // of any previous writes to the task structure. + let task_as_state: State = cast::transmute(task); + let oldstate = atomic_xchg(&mut (*packet).state, task_as_state); + match oldstate { + STATE_BOTH => { + // Data has not been sent. Now we're blocked. + } + STATE_ONE => { + // Channel is closed. Switch back and check the data. + let task: ~Coroutine = cast::transmute(task_as_state); + let sched = local_sched::take(); + sched.resume_task_immediately(task); } + _ => util::unreachable() } } } @@ -130,20 +190,20 @@ impl PortOne { // payload. Some scenarios: // // 1) We encountered STATE_ONE above - the atomic_xchg was the acq barrier. We're fine. - // 2) We encountered STATE_BOTH above and blocked. The sending task work-stole us - // and ran on its thread. The work stealing had a memory barrier. + // 2) We encountered STATE_BOTH above and blocked. The sending task then ran us + // and ran on its thread. The sending task issued a read barrier when taking the + // pointer to the receiving task. // 3) We encountered STATE_BOTH above and blocked, but the receiving task (this task) // is pinned to some other scheduler, so the sending task had to give us to // a different scheduler for resuming. That send synchronized memory. unsafe { - let payload = util::replace(&mut (*this.inner.packet()).payload, None); + let payload = util::replace(&mut (*packet).payload, None); // The sender has closed up shop. Drop the packet. let _packet: ~Packet = cast::transmute(this.inner.void_packet); - // Supress the finalizer. We're done here. + // Suppress the synchronizing actions in the finalizer. We're done with the packet. this.inner.suppress_finalize = true; - return payload; } } @@ -167,47 +227,8 @@ impl Peekable for PortOne { } } -impl ChanOne { - - pub fn send(self, val: T) { - self.try_send(val); - } - - pub fn try_send(self, val: T) -> bool { - let mut this = self; - let mut recvr_active = true; - - unsafe { - assert!((*this.inner.packet()).payload.is_none()); - (*this.inner.packet()).payload = Some(val); - - let oldstate = atomic_xchg(&mut (*this.inner.packet()).state, STATE_ONE); - match oldstate { - STATE_BOTH => { - // Port is not recving yet. Nothing to do - } - STATE_ONE => { - // Port has closed. Need to clean up. - let _packet: ~Packet = cast::transmute(this.inner.void_packet); - recvr_active = false; - } - _ => { - // Port is blocked. Wake it up. - let recvr: ~Coroutine = cast::transmute(oldstate); - let sched = local_sched::take(); - sched.schedule_task(recvr); - } - } - } - - // Suppress the finalizer. We're done here. - this.inner.suppress_finalize = true; - return recvr_active; - } -} - #[unsafe_destructor] -impl Drop for PortOneHack { +impl Drop for ChanOneHack { fn finalize(&self) { if self.suppress_finalize { return } @@ -216,13 +237,17 @@ impl Drop for PortOneHack { let oldstate = atomic_xchg(&mut (*this.packet()).state, STATE_ONE); match oldstate { STATE_BOTH => { - /* cleanup is the chan's responsibility */ + // Port still active. It will destroy the Packet. }, STATE_ONE => { let _packet: ~Packet = cast::transmute(this.void_packet); - } - _ => { - util::unreachable() + }, + task_as_state => { + // The port is blocked waiting for a message we will never send. Wake it. + assert!((*this.packet()).payload.is_none()); + let recvr: ~Coroutine = cast::transmute(task_as_state); + let sched = local_sched::take(); + sched.schedule_task(recvr); } } } @@ -230,7 +255,7 @@ impl Drop for PortOneHack { } #[unsafe_destructor] -impl Drop for ChanOneHack { +impl Drop for PortOneHack { fn finalize(&self) { if self.suppress_finalize { return } @@ -239,24 +264,20 @@ impl Drop for ChanOneHack { let oldstate = atomic_xchg(&mut (*this.packet()).state, STATE_ONE); match oldstate { STATE_BOTH => { - /* cleanup is the port's responsibility */ + // Chan still active. It will destroy the packet. }, STATE_ONE => { let _packet: ~Packet = cast::transmute(this.void_packet); - }, + } _ => { - // The port is blocked recving for a message we will never send. Wake it. - assert!((*this.packet()).payload.is_none()); - let recvr: ~Coroutine = cast::transmute(oldstate); - let sched = local_sched::take(); - sched.schedule_task(recvr); + util::unreachable() } } } } } -impl PortOneHack { +impl ChanOneHack { fn packet(&self) -> *mut Packet { unsafe { let p: *mut ~Packet = cast::transmute(&self.void_packet); @@ -266,7 +287,7 @@ impl PortOneHack { } } -impl ChanOneHack { +impl PortOneHack { fn packet(&self) -> *mut Packet { unsafe { let p: *mut ~Packet = cast::transmute(&self.void_packet); @@ -276,18 +297,23 @@ impl ChanOneHack { } } -struct StreamPayload(T, PortOne>); - -pub struct Port { - // FIXME #5372. Using Cell because we don't take &mut self - next: Cell>> +struct StreamPayload { + val: T, + next: PortOne> } +/// A channel with unbounded size. pub struct Chan { // FIXME #5372. Using Cell because we don't take &mut self next: Cell>> } +/// An port with unbounded size. +pub struct Port { + // FIXME #5372. Using Cell because we don't take &mut self + next: Cell>> +} + pub fn stream() -> (Port, Chan) { let (pone, cone) = oneshot(); let port = Port { next: Cell(pone) }; @@ -295,6 +321,21 @@ pub fn stream() -> (Port, Chan) { return (port, chan); } +impl GenericChan for Chan { + fn send(&self, val: T) { + self.try_send(val); + } +} + +impl GenericSmartChan for Chan { + fn try_send(&self, val: T) -> bool { + let (next_pone, next_cone) = oneshot(); + let cone = self.next.take(); + self.next.put_back(next_cone); + cone.try_send(StreamPayload { val: val, next: next_pone }) + } +} + impl GenericPort for Port { fn recv(&self) -> T { match self.try_recv() { @@ -308,7 +349,7 @@ impl GenericPort for Port { fn try_recv(&self) -> Option { let pone = self.next.take(); match pone.try_recv() { - Some(StreamPayload(val, next)) => { + Some(StreamPayload { val, next }) => { self.next.put_back(next); Some(val) } @@ -323,21 +364,6 @@ impl Peekable for Port { } } -impl GenericChan for Chan { - fn send(&self, val: T) { - self.try_send(val); - } -} - -impl GenericSmartChan for Chan { - fn try_send(&self, val: T) -> bool { - let (next_pone, next_cone) = oneshot(); - let cone = self.next.take(); - self.next.put_back(next_cone); - cone.try_send(StreamPayload(val, next_pone)) - } -} - #[cfg(test)] mod test { use super::*; @@ -563,7 +589,7 @@ mod test { } #[test] - fn stream_send_recv() { + fn stream_send_recv_stress() { for stress_factor().times { do run_in_newsched_task { let (port, chan) = stream::<~int>(); diff --git a/src/libcore/rt/local_services.rs b/src/libcore/rt/local_services.rs index 35c703bb35074..8d6873be8cd56 100644 --- a/src/libcore/rt/local_services.rs +++ b/src/libcore/rt/local_services.rs @@ -261,7 +261,7 @@ mod test { use comm::*; do run_in_newsched_task() { - let (port, chan) = oneshot(); + let (port, chan) = stream(); chan.send(10); assert!(port.recv() == 10); } From 633af4c8abeeb8b7c65b1a504276da72e4f4234c Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Fri, 17 May 2013 18:11:47 -0700 Subject: [PATCH 063/248] Whitespace --- src/libcore/rt/io/extensions.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/rt/io/extensions.rs b/src/libcore/rt/io/extensions.rs index a3804d2d6ef1a..ceff2ecd77de0 100644 --- a/src/libcore/rt/io/extensions.rs +++ b/src/libcore/rt/io/extensions.rs @@ -572,11 +572,11 @@ impl WriterByteConversions for T { } fn write_u8(&mut self, n: u8) { - self.write([n]) + self.write([n]) } fn write_i8(&mut self, n: i8) { - self.write([n as u8]) + self.write([n as u8]) } } From 5ca383b777d3fd406ff9ded4681d385f0668b2df Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Fri, 17 May 2013 21:12:50 -0400 Subject: [PATCH 064/248] Distinguish tuple elements by index in mem_categorization. Fixes #5362. --- src/librustc/middle/borrowck/check_loans.rs | 1 + .../middle/borrowck/gather_loans/lifetime.rs | 3 + .../borrowck/gather_loans/restrictions.rs | 19 +-- src/librustc/middle/borrowck/mod.rs | 28 +-- src/librustc/middle/mem_categorization.rs | 161 ++++++++++++------ .../borrowck-anon-fields-struct.rs | 37 ++++ .../borrowck-anon-fields-tuple.rs | 35 ++++ .../borrowck-anon-fields-variant.rs | 43 +++++ 8 files changed, 246 insertions(+), 81 deletions(-) create mode 100644 src/test/compile-fail/borrowck-anon-fields-struct.rs create mode 100644 src/test/compile-fail/borrowck-anon-fields-tuple.rs create mode 100644 src/test/compile-fail/borrowck-anon-fields-variant.rs diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index 2f24a8ceb2465..24414bc800667 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -400,6 +400,7 @@ pub impl<'self> CheckLoanCtxt<'self> { cmt = b; } + mc::cat_downcast(b) | mc::cat_interior(b, _) => { if cmt.mutbl == mc::McInherited { cmt = b; diff --git a/src/librustc/middle/borrowck/gather_loans/lifetime.rs b/src/librustc/middle/borrowck/gather_loans/lifetime.rs index e377bebcc2697..870e581ae49fa 100644 --- a/src/librustc/middle/borrowck/gather_loans/lifetime.rs +++ b/src/librustc/middle/borrowck/gather_loans/lifetime.rs @@ -105,6 +105,7 @@ impl GuaranteeLifetimeContext { } } + mc::cat_downcast(base) | mc::cat_deref(base, _, mc::uniq_ptr(*)) | mc::cat_interior(base, _) => { self.check(base, discr_scope) @@ -303,6 +304,7 @@ impl GuaranteeLifetimeContext { mc::cat_deref(*) => { false } + r @ mc::cat_downcast(*) | r @ mc::cat_interior(*) | r @ mc::cat_stack_upvar(*) | r @ mc::cat_discr(*) => { @@ -340,6 +342,7 @@ impl GuaranteeLifetimeContext { mc::cat_deref(_, _, mc::region_ptr(_, r)) => { r } + mc::cat_downcast(cmt) | mc::cat_deref(cmt, _, mc::uniq_ptr(*)) | mc::cat_deref(cmt, _, mc::gc_ptr(*)) | mc::cat_interior(cmt, _) | diff --git a/src/librustc/middle/borrowck/gather_loans/restrictions.rs b/src/librustc/middle/borrowck/gather_loans/restrictions.rs index 0be4c67a9bc91..00b0a41d706db 100644 --- a/src/librustc/middle/borrowck/gather_loans/restrictions.rs +++ b/src/librustc/middle/borrowck/gather_loans/restrictions.rs @@ -80,24 +80,17 @@ impl RestrictionsContext { set: restrictions}]) } - mc::cat_interior(cmt_base, i @ mc::interior_variant(_)) => { + mc::cat_downcast(cmt_base) => { // When we borrow the interior of an enum, we have to // ensure the enum itself is not mutated, because that // could cause the type of the memory to change. - let result = self.compute(cmt_base, restrictions | RESTR_MUTATE); - self.extend(result, cmt.mutbl, LpInterior(i), restrictions) + self.compute(cmt_base, restrictions | RESTR_MUTATE) } - mc::cat_interior(cmt_base, i @ mc::interior_tuple) | - mc::cat_interior(cmt_base, i @ mc::interior_anon_field) | - mc::cat_interior(cmt_base, i @ mc::interior_field(*)) | - mc::cat_interior(cmt_base, i @ mc::interior_index(*)) => { - // For all of these cases, overwriting the base would - // not change the type of the memory, so no additional - // restrictions are needed. - // - // FIXME(#5397) --- Mut fields are not treated soundly - // (hopefully they will just get phased out) + mc::cat_interior(cmt_base, i) => { + // Overwriting the base would not change the type of + // the memory, so no additional restrictions are + // needed. let result = self.compute(cmt_base, restrictions); self.extend(result, cmt.mutbl, LpInterior(i), restrictions) } diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 0f01b2b1e418e..3824e83e1ce70 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -236,8 +236,8 @@ pub enum LoanPath { #[deriving(Eq)] pub enum LoanPathElem { - LpDeref, // `*LV` in doc.rs - LpInterior(mc::interior_kind) // `LV.f` in doc.rs + LpDeref, // `*LV` in doc.rs + LpInterior(mc::InteriorKind) // `LV.f` in doc.rs } pub impl LoanPath { @@ -280,6 +280,7 @@ pub fn opt_loan_path(cmt: mc::cmt) -> Option<@LoanPath> { |&lp| @LpExtend(lp, cmt.mutbl, LpInterior(ik))) } + mc::cat_downcast(cmt_base) | mc::cat_stack_upvar(cmt_base) | mc::cat_discr(cmt_base, _) => { opt_loan_path(cmt_base) @@ -616,24 +617,25 @@ pub impl BorrowckCtxt { } } - LpExtend(lp_base, _, LpInterior(mc::interior_field(fld))) => { + LpExtend(lp_base, _, LpInterior(mc::InteriorField(fname))) => { self.append_loan_path_to_str_from_interior(lp_base, out); - str::push_char(out, '.'); - str::push_str(out, *self.tcx.sess.intr().get(fld)); + match fname { + mc::NamedField(fname) => { + str::push_char(out, '.'); + str::push_str(out, *self.tcx.sess.intr().get(fname)); + } + mc::PositionalField(idx) => { + str::push_char(out, '#'); // invent a notation here + str::push_str(out, idx.to_str()); + } + } } - LpExtend(lp_base, _, LpInterior(mc::interior_index(*))) => { + LpExtend(lp_base, _, LpInterior(mc::InteriorElement(_))) => { self.append_loan_path_to_str_from_interior(lp_base, out); str::push_str(out, "[]"); } - LpExtend(lp_base, _, LpInterior(mc::interior_tuple)) | - LpExtend(lp_base, _, LpInterior(mc::interior_anon_field)) | - LpExtend(lp_base, _, LpInterior(mc::interior_variant(_))) => { - self.append_loan_path_to_str_from_interior(lp_base, out); - str::push_str(out, ".(tuple)"); - } - LpExtend(lp_base, _, LpDeref) => { str::push_char(out, '*'); self.append_loan_path_to_str(lp_base, out); diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 91c0b8e61cc7b..c9ec10ed30aa4 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -66,9 +66,12 @@ pub enum categorization { cat_local(ast::node_id), // local variable cat_arg(ast::node_id), // formal argument cat_deref(cmt, uint, ptr_kind), // deref of a ptr - cat_interior(cmt, interior_kind), // something interior + cat_interior(cmt, InteriorKind), // something interior: field, tuple, etc + cat_downcast(cmt), // selects a particular enum variant (*) cat_discr(cmt, ast::node_id), // match discriminant (see preserve()) cat_self(ast::node_id), // explicit `self` + + // (*) downcast is only required if the enum has more than one variant } #[deriving(Eq)] @@ -89,14 +92,15 @@ pub enum ptr_kind { // We use the term "interior" to mean "something reachable from the // base without a pointer dereference", e.g. a field #[deriving(Eq)] -pub enum interior_kind { - interior_tuple, // elt in a tuple - interior_anon_field, // anonymous field (in e.g. - // struct Foo(int, int); - interior_variant(ast::def_id), // internals to a variant of given enum - interior_field(ast::ident), // name of field - interior_index(ty::t, // type of vec/str/etc being deref'd - ast::mutability) // mutability of vec content +pub enum InteriorKind { + InteriorField(FieldName), + InteriorElement(ty::t), // ty::t is the type of the vec/str +} + +#[deriving(Eq)] +pub enum FieldName { + NamedField(ast::ident), + PositionalField(uint) } #[deriving(Eq)] @@ -134,7 +138,10 @@ pub type cmt = @cmt_; // We pun on *T to mean both actual deref of a ptr as well // as accessing of components: -pub enum deref_kind {deref_ptr(ptr_kind), deref_interior(interior_kind)} +pub enum deref_kind { + deref_ptr(ptr_kind), + deref_interior(InteriorKind), +} // Categorizes a derefable type. Note that we include vectors and strings as // derefable (we model an index as the combination of a deref and then a @@ -176,20 +183,14 @@ pub fn opt_deref_kind(t: ty::t) -> Option { Some(deref_ptr(unsafe_ptr)) } - ty::ty_enum(did, _) => { - Some(deref_interior(interior_variant(did))) - } - - ty::ty_struct(_, _) => { - Some(deref_interior(interior_anon_field)) - } - - ty::ty_evec(mt, ty::vstore_fixed(_)) => { - Some(deref_interior(interior_index(t, mt.mutbl))) + ty::ty_enum(*) | + ty::ty_struct(*) => { // newtype + Some(deref_interior(InteriorField(PositionalField(0)))) } + ty::ty_evec(_, ty::vstore_fixed(_)) | ty::ty_estr(ty::vstore_fixed(_)) => { - Some(deref_interior(interior_index(t, m_imm))) + Some(deref_interior(InteriorElement(t))) } _ => None @@ -579,7 +580,7 @@ pub impl mem_categorization_ctxt { @cmt_ { id: node.id(), span: node.span(), - cat: cat_interior(base_cmt, interior_field(f_name)), + cat: cat_interior(base_cmt, InteriorField(NamedField(f_name))), mutbl: base_cmt.mutbl.inherit(), ty: f_ty } @@ -737,15 +738,16 @@ pub impl mem_categorization_ctxt { } }; - fn interior(elt: N, of_cmt: cmt, - vect: ty::t, mutbl: MutabilityCategory, + fn interior(elt: N, + of_cmt: cmt, + vec_ty: ty::t, + mutbl: MutabilityCategory, mt: ty::mt) -> cmt { - let interior = interior_index(vect, mt.mutbl); @cmt_ { id:elt.id(), span:elt.span(), - cat:cat_interior(of_cmt, interior), + cat:cat_interior(of_cmt, InteriorElement(vec_ty)), mutbl:mutbl, ty:mt.ty } @@ -756,7 +758,7 @@ pub impl mem_categorization_ctxt { node: N, base_cmt: cmt, interior_ty: ty::t, - interior: interior_kind) -> cmt { + interior: InteriorKind) -> cmt { @cmt_ { id: node.id(), span: node.span(), @@ -766,6 +768,19 @@ pub impl mem_categorization_ctxt { } } + fn cat_downcast(&self, + node: N, + base_cmt: cmt, + downcast_ty: ty::t) -> cmt { + @cmt_ { + id: node.id(), + span: node.span(), + cat: cat_downcast(base_cmt), + mutbl: base_cmt.mutbl.inherit(), + ty: downcast_ty + } + } + fn cat_pattern(&self, cmt: cmt, pat: @ast::pat, @@ -835,21 +850,34 @@ pub impl mem_categorization_ctxt { match self.tcx.def_map.find(&pat.id) { Some(&ast::def_variant(enum_did, _)) => { // variant(x, y, z) - for subpats.each |&subpat| { + + let downcast_cmt = { + if ty::enum_is_univariant(tcx, enum_did) { + cmt // univariant, no downcast needed + } else { + self.cat_downcast(pat, cmt, cmt.ty) + } + }; + + for subpats.eachi |i, &subpat| { let subpat_ty = self.pat_ty(subpat); // see (*) + let subcmt = - self.cat_imm_interior(pat, cmt, subpat_ty, - interior_variant(enum_did)); + self.cat_imm_interior( + pat, downcast_cmt, subpat_ty, + InteriorField(PositionalField(i))); + self.cat_pattern(subcmt, subpat, op); } } Some(&ast::def_fn(*)) | Some(&ast::def_struct(*)) => { - for subpats.each |&subpat| { + for subpats.eachi |i, &subpat| { let subpat_ty = self.pat_ty(subpat); // see (*) let cmt_field = - self.cat_imm_interior(pat, cmt, subpat_ty, - interior_anon_field); + self.cat_imm_interior( + pat, cmt, subpat_ty, + InteriorField(PositionalField(i))); self.cat_pattern(cmt_field, subpat, op); } } @@ -885,10 +913,12 @@ pub impl mem_categorization_ctxt { ast::pat_tup(ref subpats) => { // (p1, ..., pN) - for subpats.each |&subpat| { + for subpats.eachi |i, &subpat| { let subpat_ty = self.pat_ty(subpat); // see (*) - let subcmt = self.cat_imm_interior(pat, cmt, subpat_ty, - interior_tuple); + let subcmt = + self.cat_imm_interior( + pat, cmt, subpat_ty, + InteriorField(PositionalField(i))); self.cat_pattern(subcmt, subpat, op); } } @@ -931,22 +961,37 @@ pub impl mem_categorization_ctxt { fn cmt_to_str(&self, cmt: cmt) -> ~str { match cmt.cat { - cat_static_item => ~"static item", - cat_implicit_self => ~"self reference", + cat_static_item => { + ~"static item" + } + cat_implicit_self => { + ~"self reference" + } cat_copied_upvar(_) => { ~"captured outer variable in a heap closure" } - cat_rvalue => ~"non-lvalue", - cat_local(_) => ~"local variable", - cat_self(_) => ~"self value", - cat_arg(*) => ~"argument", - cat_deref(_, _, pk) => fmt!("dereference of %s pointer", - ptr_sigil(pk)), - cat_interior(_, interior_field(*)) => ~"field", - cat_interior(_, interior_tuple) => ~"tuple content", - cat_interior(_, interior_anon_field) => ~"anonymous field", - cat_interior(_, interior_variant(_)) => ~"enum content", - cat_interior(_, interior_index(t, _)) => { + cat_rvalue => { + ~"non-lvalue" + } + cat_local(_) => { + ~"local variable" + } + cat_self(_) => { + ~"self value" + } + cat_arg(*) => { + ~"argument" + } + cat_deref(_, _, pk) => { + fmt!("dereference of %s pointer", ptr_sigil(pk)) + } + cat_interior(_, InteriorField(NamedField(_))) => { + ~"field" + } + cat_interior(_, InteriorField(PositionalField(_))) => { + ~"anonymous field" + } + cat_interior(_, InteriorElement(t)) => { match ty::get(t).sty { ty::ty_evec(*) => ~"vec content", ty::ty_estr(*) => ~"str content", @@ -959,6 +1004,9 @@ pub impl mem_categorization_ctxt { cat_discr(cmt, _) => { self.cmt_to_str(cmt) } + cat_downcast(cmt) => { + self.cmt_to_str(cmt) + } } } @@ -1027,6 +1075,7 @@ pub impl cmt_ { cat_deref(_, _, region_ptr(*)) => { self } + cat_downcast(b) | cat_stack_upvar(b) | cat_discr(b, _) | cat_interior(b, _) | @@ -1075,6 +1124,7 @@ pub impl cmt_ { Some(AliasableBorrowed(m)) } + cat_downcast(b) | cat_stack_upvar(b) | cat_deref(b, _, uniq_ptr(*)) | cat_interior(b, _) | @@ -1114,6 +1164,9 @@ impl Repr for categorization { cmt.cat.repr(tcx), interior.repr(tcx)) } + cat_downcast(cmt) => { + fmt!("%s->(enum)", cmt.cat.repr(tcx)) + } cat_stack_upvar(cmt) | cat_discr(cmt, _) => cmt.cat.repr(tcx) } @@ -1129,14 +1182,12 @@ pub fn ptr_sigil(ptr: ptr_kind) -> ~str { } } -impl Repr for interior_kind { +impl Repr for InteriorKind { fn repr(&self, tcx: ty::ctxt) -> ~str { match *self { - interior_field(fld) => copy *tcx.sess.str_of(fld), - interior_index(*) => ~"[]", - interior_tuple => ~"()", - interior_anon_field => ~"", - interior_variant(_) => ~"" + InteriorField(NamedField(fld)) => copy *tcx.sess.str_of(fld), + InteriorField(PositionalField(i)) => fmt!("#%?", i), + InteriorElement(_) => ~"[]", } } } diff --git a/src/test/compile-fail/borrowck-anon-fields-struct.rs b/src/test/compile-fail/borrowck-anon-fields-struct.rs new file mode 100644 index 0000000000000..45a26068d8285 --- /dev/null +++ b/src/test/compile-fail/borrowck-anon-fields-struct.rs @@ -0,0 +1,37 @@ +// Tests that we are able to distinguish when loans borrow different +// anonymous fields of an tuple vs the same anonymous field. + +struct Y(uint, uint); + +fn distinct_variant() { + let mut y = Y(1, 2); + + let a = match y { + Y(ref mut a, _) => a + }; + + let b = match y { + Y(_, ref mut b) => b + }; + + *a += 1; + *b += 1; +} + +fn same_variant() { + let mut y = Y(1, 2); + + let a = match y { + Y(ref mut a, _) => a + }; + + let b = match y { + Y(ref mut b, _) => b //~ ERROR cannot borrow + }; + + *a += 1; + *b += 1; +} + +fn main() { +} \ No newline at end of file diff --git a/src/test/compile-fail/borrowck-anon-fields-tuple.rs b/src/test/compile-fail/borrowck-anon-fields-tuple.rs new file mode 100644 index 0000000000000..ae02245c97f52 --- /dev/null +++ b/src/test/compile-fail/borrowck-anon-fields-tuple.rs @@ -0,0 +1,35 @@ +// Tests that we are able to distinguish when loans borrow different +// anonymous fields of a tuple vs the same anonymous field. + +fn distinct_variant() { + let mut y = (1, 2); + + let a = match y { + (ref mut a, _) => a + }; + + let b = match y { + (_, ref mut b) => b + }; + + *a += 1; + *b += 1; +} + +fn same_variant() { + let mut y = (1, 2); + + let a = match y { + (ref mut a, _) => a + }; + + let b = match y { + (ref mut b, _) => b //~ ERROR cannot borrow + }; + + *a += 1; + *b += 1; +} + +fn main() { +} \ No newline at end of file diff --git a/src/test/compile-fail/borrowck-anon-fields-variant.rs b/src/test/compile-fail/borrowck-anon-fields-variant.rs new file mode 100644 index 0000000000000..3d9738df059ca --- /dev/null +++ b/src/test/compile-fail/borrowck-anon-fields-variant.rs @@ -0,0 +1,43 @@ +// Tests that we are able to distinguish when loans borrow different +// anonymous fields of an enum variant vs the same anonymous field. + +enum Foo { + X, Y(uint, uint) +} + +fn distinct_variant() { + let mut y = Y(1, 2); + + let a = match y { + Y(ref mut a, _) => a, + X => fail!() + }; + + let b = match y { + Y(_, ref mut b) => b, + X => fail!() + }; + + *a += 1; + *b += 1; +} + +fn same_variant() { + let mut y = Y(1, 2); + + let a = match y { + Y(ref mut a, _) => a, + X => fail!() + }; + + let b = match y { + Y(ref mut b, _) => b, //~ ERROR cannot borrow + X => fail!() + }; + + *a += 1; + *b += 1; +} + +fn main() { +} \ No newline at end of file From f21fb3aff5c0dbc1129c99ef827150343b425da0 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Fri, 17 May 2013 17:27:44 -0700 Subject: [PATCH 065/248] rustc: Cleaning up bad copies and other XXXes --- src/librustc/middle/trans/build.rs | 2 +- src/librustc/middle/trans/closure.rs | 5 ++--- src/librustc/middle/trans/common.rs | 2 +- src/librustc/middle/trans/datum.rs | 2 +- src/librustc/middle/trans/expr.rs | 12 ++++++------ src/librustc/middle/trans/foreign.rs | 3 +-- src/librustc/middle/trans/glue.rs | 5 ++--- src/librustc/middle/trans/meth.rs | 13 ++++++------- src/librustc/middle/trans/monomorphize.rs | 10 ++++------ src/librustc/middle/trans/reflect.rs | 11 +++++------ src/librustc/middle/trans/type_of.rs | 7 +++---- src/librustc/middle/ty.rs | 4 ---- src/librustc/middle/typeck/check/method.rs | 4 ++-- src/librustc/middle/typeck/check/mod.rs | 1 - src/librustc/middle/typeck/infer/combine.rs | 4 +++- 15 files changed, 37 insertions(+), 48 deletions(-) diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index e8853fd20e98b..38f8d271f08b3 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -602,7 +602,7 @@ pub fn GEP(cx: block, Pointer: ValueRef, Indices: &[ValueRef]) -> ValueRef { // Simple wrapper around GEP that takes an array of ints and wraps them // in C_i32() // -// XXX: Use a small-vector optimization to avoid allocations here. +// FIXME #6571: Use a small-vector optimization to avoid allocations here. pub fn GEPi(cx: block, base: ValueRef, ixs: &[uint]) -> ValueRef { let v = do vec::map(ixs) |i| { C_i32(*i as i32) }; count_insn(cx, "gepi"); diff --git a/src/librustc/middle/trans/closure.rs b/src/librustc/middle/trans/closure.rs index 0651d3443b56a..c6fa42cb8cbd3 100644 --- a/src/librustc/middle/trans/closure.rs +++ b/src/librustc/middle/trans/closure.rs @@ -137,7 +137,7 @@ pub fn mk_tuplified_uniq_cbox_ty(tcx: ty::ctxt, cdata_ty: ty::t) -> ty::t { // Given a closure ty, emits a corresponding tuple ty pub fn mk_closure_tys(tcx: ty::ctxt, - bound_values: ~[EnvValue]) + bound_values: &[EnvValue]) -> ty::t { // determine the types of the values in the env. Note that this // is the actual types that will be stored in the map, not the @@ -203,8 +203,7 @@ pub fn store_environment(bcx: block, let ccx = bcx.ccx(), tcx = ccx.tcx; // compute the shape of the closure - // XXX: Bad copy. - let cdata_ty = mk_closure_tys(tcx, copy bound_values); + let cdata_ty = mk_closure_tys(tcx, bound_values); // allocate closure in the heap let Result {bcx: bcx, val: llbox} = allocate_cbox(bcx, sigil, cdata_ty); diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 8000484c0550f..547b54a6ef50f 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -1325,7 +1325,7 @@ pub fn is_null(val: ValueRef) -> bool { // Used to identify cached monomorphized functions and vtables #[deriving(Eq)] pub enum mono_param_id { - mono_precise(ty::t, Option<~[mono_id]>), + mono_precise(ty::t, Option<@~[mono_id]>), mono_any, mono_repr(uint /* size */, uint /* align */, diff --git a/src/librustc/middle/trans/datum.rs b/src/librustc/middle/trans/datum.rs index 8055d919ffd9a..13f02b8fcac1d 100644 --- a/src/librustc/middle/trans/datum.rs +++ b/src/librustc/middle/trans/datum.rs @@ -652,7 +652,7 @@ pub impl Datum { ByRef => { // Recast lv.val as a pointer to the newtype rather // than a pointer to the struct type. - // XXX: This isn't correct for structs with + // FIXME #6572: This isn't correct for structs with // destructors. ( Some(Datum { diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 59526ffbe498d..3ed08eade33a4 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -576,7 +576,7 @@ fn trans_rvalue_dps_unadjusted(bcx: block, expr: @ast::expr, }; } ast::expr_struct(_, ref fields, base) => { - return trans_rec_or_struct(bcx, (*fields), base, expr.id, dest); + return trans_rec_or_struct(bcx, (*fields), base, expr.span, expr.id, dest); } ast::expr_tup(ref args) => { let repr = adt::represent_type(bcx.ccx(), expr_ty(bcx, expr)); @@ -721,7 +721,7 @@ fn trans_def_dps_unadjusted(bcx: block, ref_expr: @ast::expr, } ast::def_struct(*) => { // Nothing to do here. - // XXX: May not be true in the case of classes with destructors. + // FIXME #6572: May not be true in the case of classes with destructors. return bcx; } _ => { @@ -1129,6 +1129,7 @@ pub fn with_field_tys(tcx: ty::ctxt, fn trans_rec_or_struct(bcx: block, fields: &[ast::field], base: Option<@ast::expr>, + expr_span: codemap::span, id: ast::node_id, dest: Dest) -> block { @@ -1167,8 +1168,7 @@ fn trans_rec_or_struct(bcx: block, } None => { if need_base.any(|b| *b) { - // XXX should be span bug - tcx.sess.bug(~"missing fields and no base expr") + tcx.sess.span_bug(expr_span, ~"missing fields and no base expr") } None } @@ -1232,8 +1232,8 @@ fn trans_adt(bcx: block, repr: &adt::Repr, discr: int, temp_cleanups.push(dest); } for optbase.each |base| { - // XXX is it sound to use the destination's repr on the base? - // XXX would it ever be reasonable to be here with discr != 0? + // FIXME #6573: is it sound to use the destination's repr on the base? + // And, would it ever be reasonable to be here with discr != 0? let base_datum = unpack_datum!(bcx, trans_to_datum(bcx, base.expr)); for base.fields.each |&(i, t)| { let datum = do base_datum.get_element(bcx, t, ZeroMem) |srcval| { diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index fd545ca2c6ea8..13d8f854fb20f 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -550,14 +550,13 @@ pub fn trans_intrinsic(ccx: @CrateContext, let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, item.id)); - // XXX: Bad copy. let fcx = new_fn_ctxt_w_id(ccx, path, decl, item.id, output_type, None, - Some(copy substs), + Some(substs), Some(item.span)); // Set the fixed stack segment flag if necessary. diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index 585d9d8420cd7..f8aa3eca28476 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -669,7 +669,7 @@ pub fn declare_tydesc(ccx: @CrateContext, t: ty::t) -> @mut tydesc_info { let llsize = llsize_of(ccx, llty); let llalign = llalign_of(ccx, llty); let addrspace = declare_tydesc_addrspace(ccx, t); - //XXX this triggers duplicate LLVM symbols + // FIXME #6574: this triggers duplicate LLVM symbols let name = @(if false /*ccx.sess.opts.debuginfo*/ { mangle_internal_name_by_type_only(ccx, t, "tydesc") } else { @@ -703,14 +703,13 @@ pub fn declare_generic_glue(ccx: @CrateContext, t: ty::t, llfnty: TypeRef, name: ~str) -> ValueRef { let _icx = ccx.insn_ctxt("declare_generic_glue"); let name = name; - //XXX this triggers duplicate LLVM symbols + // FIXME #6574 this triggers duplicate LLVM symbols let fn_nm = @(if false /*ccx.sess.opts.debuginfo*/ { mangle_internal_name_by_type_only(ccx, t, (~"glue_" + name)) } else { mangle_internal_name_by_seq(ccx, (~"glue_" + name)) }); debug!("%s is for type %s", *fn_nm, ppaux::ty_to_str(ccx.tcx, t)); - // XXX: Bad copy. note_unique_llvm_symbol(ccx, fn_nm); let llfn = decl_cdecl_fn(ccx.llmod, *fn_nm, llfnty); set_glue_inlining(llfn, t); diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index 6eb2540f1df65..337e2a13b1fde 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -401,7 +401,7 @@ pub fn method_with_name_or_default(ccx: @CrateContext, Some(pmis) => { for pmis.each |pmi| { if pmi.method_info.ident == name { - debug!("XXX %?", pmi.method_info.did); + debug!("pmi.method_info.did = %?", pmi.method_info.did); return pmi.method_info.did; } } @@ -734,15 +734,15 @@ pub fn trans_trait_callee_from_llval(bcx: block, } pub fn vtable_id(ccx: @CrateContext, - origin: typeck::vtable_origin) + origin: &typeck::vtable_origin) -> mono_id { match origin { - typeck::vtable_static(impl_id, substs, sub_vtables) => { + &typeck::vtable_static(impl_id, ref substs, sub_vtables) => { monomorphize::make_mono_id( ccx, impl_id, - substs, - if (*sub_vtables).len() == 0u { + *substs, + if sub_vtables.is_empty() { None } else { Some(sub_vtables) @@ -759,8 +759,7 @@ pub fn vtable_id(ccx: @CrateContext, pub fn get_vtable(ccx: @CrateContext, origin: typeck::vtable_origin) -> ValueRef { - // XXX: Bad copy. - let hash_id = vtable_id(ccx, copy origin); + let hash_id = vtable_id(ccx, &origin); match ccx.vtables.find(&hash_id) { Some(&val) => val, None => match origin { diff --git a/src/librustc/middle/trans/monomorphize.rs b/src/librustc/middle/trans/monomorphize.rs index ccc906f2ee8af..40b92d336536c 100644 --- a/src/librustc/middle/trans/monomorphize.rs +++ b/src/librustc/middle/trans/monomorphize.rs @@ -70,8 +70,7 @@ pub fn monomorphic_fn(ccx: @CrateContext, for real_substs.each() |s| { assert!(!ty::type_has_params(*s)); } for substs.each() |s| { assert!(!ty::type_has_params(*s)); } let param_uses = type_use::type_uses_for(ccx, fn_id, substs.len()); - // XXX: Bad copy. - let hash_id = make_mono_id(ccx, fn_id, copy substs, vtables, impl_did_opt, + let hash_id = make_mono_id(ccx, fn_id, substs, vtables, impl_did_opt, Some(param_uses)); if vec::any(hash_id.params, |p| match *p { mono_precise(_, _) => false, _ => true }) { @@ -350,10 +349,10 @@ pub fn make_mono_id(ccx: @CrateContext, vec::map_zip(*item_ty.generics.type_param_defs, substs, |type_param_def, subst| { let mut v = ~[]; for type_param_def.bounds.trait_bounds.each |_bound| { - v.push(meth::vtable_id(ccx, /*bad*/copy vts[i])); + v.push(meth::vtable_id(ccx, &vts[i])); i += 1; } - (*subst, if !v.is_empty() { Some(v) } else { None }) + (*subst, if !v.is_empty() { Some(@v) } else { None }) }) } None => { @@ -369,8 +368,7 @@ pub fn make_mono_id(ccx: @CrateContext, } } else { match *id { - // XXX: Bad copy. - (a, copy b@Some(_)) => mono_precise(a, b), + (a, b@Some(_)) => mono_precise(a, b), (subst, None) => { if *uses == 0 { mono_any diff --git a/src/librustc/middle/trans/reflect.rs b/src/librustc/middle/trans/reflect.rs index 1141e0c007fee..0e82de86bc6dd 100644 --- a/src/librustc/middle/trans/reflect.rs +++ b/src/librustc/middle/trans/reflect.rs @@ -84,7 +84,7 @@ pub impl Reflector { self.c_tydesc(mt.ty)] } - fn visit(&mut self, ty_name: ~str, args: ~[ValueRef]) { + fn visit(&mut self, ty_name: ~str, args: &[ValueRef]) { let tcx = self.bcx.tcx(); let mth_idx = ty::method_idx( tcx.sess.ident_of(~"visit_" + ty_name), @@ -121,10 +121,9 @@ pub impl Reflector { fn bracketed(&mut self, bracket_name: ~str, - extra: ~[ValueRef], + extra: &[ValueRef], inner: &fn(&mut Reflector)) { - // XXX: Bad copy. - self.visit(~"enter_" + bracket_name, copy extra); + self.visit(~"enter_" + bracket_name, extra); inner(self); self.visit(~"leave_" + bracket_name, extra); } @@ -226,7 +225,7 @@ pub impl Reflector { self.c_uint(sigilval), self.c_uint(fty.sig.inputs.len()), self.c_uint(retval)]; - self.visit(~"enter_fn", copy extra); // XXX: Bad copy. + self.visit(~"enter_fn", extra); self.visit_sig(retval, &fty.sig); self.visit(~"leave_fn", extra); } @@ -241,7 +240,7 @@ pub impl Reflector { self.c_uint(sigilval), self.c_uint(fty.sig.inputs.len()), self.c_uint(retval)]; - self.visit(~"enter_fn", copy extra); // XXX: Bad copy. + self.visit(~"enter_fn", extra); self.visit_sig(retval, &fty.sig); self.visit(~"leave_fn", extra); } diff --git a/src/librustc/middle/trans/type_of.rs b/src/librustc/middle/trans/type_of.rs index dfbebd90c298b..8d5721aeb6512 100644 --- a/src/librustc/middle/trans/type_of.rs +++ b/src/librustc/middle/trans/type_of.rs @@ -45,7 +45,7 @@ pub fn type_of_fn(cx: @CrateContext, inputs: &[ty::t], output: ty::t) if !output_is_immediate { atys.push(T_ptr(lloutputtype)); } else { - // XXX: Eliminate this. + // FIXME #6575: Eliminate this. atys.push(T_ptr(T_i8())); } @@ -200,7 +200,6 @@ pub fn type_of(cx: @CrateContext, t: ty::t) -> TypeRef { return llty; } - // XXX: This is a terrible terrible copy. let llty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => T_nil(), ty::ty_bool => T_bool(), @@ -219,7 +218,7 @@ pub fn type_of(cx: @CrateContext, t: ty::t) -> TypeRef { common::T_named_struct(llvm_type_name(cx, an_enum, did, - /*bad*/copy substs.tps)) + substs.tps)) } ty::ty_estr(ty::vstore_box) => { T_box_ptr(T_box(cx, T_vec(cx, T_i8()))) @@ -280,7 +279,7 @@ pub fn type_of(cx: @CrateContext, t: ty::t) -> TypeRef { T_named_struct(llvm_type_name(cx, a_struct, did, - /*bad*/ copy substs.tps)) + substs.tps)) } } ty::ty_self(*) => cx.tcx.sess.unimpl(~"type_of: ty_self"), diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index c51fba8a62b71..bb18948ce5d54 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -681,7 +681,6 @@ pub enum type_err { terr_trait_stores_differ(terr_vstore_kind, expected_found), terr_in_field(@type_err, ast::ident), terr_sorts(expected_found), - terr_self_substs, terr_integer_as_char, terr_int_mismatch(expected_found), terr_float_mismatch(expected_found), @@ -3722,9 +3721,6 @@ pub fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str { values.found.user_string(cx)) } } - terr_self_substs => { - ~"inconsistent self substitution" // XXX this is more of a bug - } terr_integer_as_char => { fmt!("expected an integral type but found char") } diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 9e8103f4527f6..7655212d9d64e 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -438,7 +438,7 @@ pub impl<'self> LookupContext<'self> { return; // inapplicable } ast::sty_region(_) => vstore_slice(r) - ast::sty_box(_) => vstore_box, // XXX NDM mutability + ast::sty_box(_) => vstore_box, // NDM mutability, as per #5762 ast::sty_uniq(_) => vstore_uniq } */ @@ -594,7 +594,7 @@ pub impl<'self> LookupContext<'self> { let method = ty::method(self.tcx(), provided_method_info.method_info.did); - // XXX: Needs to support generics. + // FIXME #4099 (?) Needs to support generics. let dummy_substs = substs { self_r: None, self_ty: None, diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 8d32bb7f67756..6e272b9410f49 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -1817,7 +1817,6 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt, let mut class_field_map = HashMap::new(); let mut fields_found = 0; for field_types.each |field| { - // XXX: Check visibility here. class_field_map.insert(field.ident, (field.id, false)); } diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/typeck/infer/combine.rs index 3c337d17f8684..0efecefa3580e 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/typeck/infer/combine.rs @@ -286,7 +286,9 @@ pub fn super_self_tys( // I think it should never happen that we unify two substs and // one of them has a self_ty and one doesn't...? I could be // wrong about this. - Err(ty::terr_self_substs) + this.infcx().tcx.sess.bug( + fmt!("substitution a had a self_ty and substitution b didn't, \ + or vice versa")); } } } From a10974da2db2e483f21e337f0c9a8a1e1c4c81ed Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 15:02:58 +1000 Subject: [PATCH 066/248] Use cond! macro where appropriate --- src/libcore/num/f32.rs | 16 ++++++++++++++-- src/libcore/num/f64.rs | 16 ++++++++++++++-- src/libcore/num/int-template.rs | 12 ++++++++++++ src/libcore/num/uint-template.rs | 12 ++++++++++++ src/libcore/unicode.rs | 28 ++++++++++++++++++++++++++-- 5 files changed, 78 insertions(+), 6 deletions(-) diff --git a/src/libcore/num/f32.rs b/src/libcore/num/f32.rs index 4a3ec3528f28b..d580f7aa26c99 100644 --- a/src/libcore/num/f32.rs +++ b/src/libcore/num/f32.rs @@ -248,8 +248,7 @@ impl Orderable for f32 { if self.is_NaN() || other.is_NaN() { Float::NaN() } else { fmax(*self, *other) } } - /// Returns the number constrained within the range `mn <= self <= mx`. - /// If any of the numbers are `NaN` then `NaN` is returned. + #[cfg(stage0)] #[inline(always)] fn clamp(&self, mn: &f32, mx: &f32) -> f32 { if self.is_NaN() { *self } @@ -257,6 +256,19 @@ impl Orderable for f32 { else if !(*self >= *mn) { *mn } else { *self } } + + /// Returns the number constrained within the range `mn <= self <= mx`. + /// If any of the numbers are `NaN` then `NaN` is returned. + #[cfg(not(stage0))] + #[inline(always)] + fn clamp(&self, mn: &f32, mx: &f32) -> f32 { + cond!( + (self.is_NaN()) { *self } + (!(*self <= *mx)) { *mx } + (!(*self >= *mn)) { *mn } + _ { *self } + ) + } } impl Zero for f32 { diff --git a/src/libcore/num/f64.rs b/src/libcore/num/f64.rs index e370f43a0037e..d140df30c4273 100644 --- a/src/libcore/num/f64.rs +++ b/src/libcore/num/f64.rs @@ -270,8 +270,7 @@ impl Orderable for f64 { if self.is_NaN() || other.is_NaN() { Float::NaN() } else { fmax(*self, *other) } } - /// Returns the number constrained within the range `mn <= self <= mx`. - /// If any of the numbers are `NaN` then `NaN` is returned. + #[cfg(stage0)] #[inline(always)] fn clamp(&self, mn: &f64, mx: &f64) -> f64 { if self.is_NaN() { *self } @@ -279,6 +278,19 @@ impl Orderable for f64 { else if !(*self >= *mn) { *mn } else { *self } } + + /// Returns the number constrained within the range `mn <= self <= mx`. + /// If any of the numbers are `NaN` then `NaN` is returned. + #[cfg(not(stage0))] + #[inline(always)] + fn clamp(&self, mn: &f64, mx: &f64) -> f64 { + cond!( + (self.is_NaN()) { *self } + (!(*self <= *mx)) { *mx } + (!(*self >= *mn)) { *mn } + _ { *self } + ) + } } impl Zero for f64 { diff --git a/src/libcore/num/int-template.rs b/src/libcore/num/int-template.rs index 348f72f9f0a74..d0e6174ec637d 100644 --- a/src/libcore/num/int-template.rs +++ b/src/libcore/num/int-template.rs @@ -187,11 +187,23 @@ impl Orderable for T { if *self > *other { *self } else { *other } } + #[cfg(stage0)] #[inline(always)] fn clamp(&self, mn: &T, mx: &T) -> T { if *self > *mx { *mx } else if *self < *mn { *mn } else { *self } } + + /// Returns the number constrained within the range `mn <= self <= mx`. + #[cfg(not(stage0))] + #[inline(always)] + fn clamp(&self, mn: &T, mx: &T) -> T { + cond!( + (*self > *mx) { *mx } + (*self < *mn) { *mn } + _ { *self } + ) + } } impl Zero for T { diff --git a/src/libcore/num/uint-template.rs b/src/libcore/num/uint-template.rs index da0815c264b06..f3e140945057c 100644 --- a/src/libcore/num/uint-template.rs +++ b/src/libcore/num/uint-template.rs @@ -153,11 +153,23 @@ impl Orderable for T { if *self > *other { *self } else { *other } } + #[cfg(stage0)] #[inline(always)] fn clamp(&self, mn: &T, mx: &T) -> T { if *self > *mx { *mx } else if *self < *mn { *mn } else { *self } } + + /// Returns the number constrained within the range `mn <= self <= mx`. + #[cfg(not(stage0))] + #[inline(always)] + fn clamp(&self, mn: &T, mx: &T) -> T { + cond!( + (*self > *mx) { *mx } + (*self < *mn) { *mn } + _ { *self } + ) + } } impl Zero for T { diff --git a/src/libcore/unicode.rs b/src/libcore/unicode.rs index d6e2c5eee6aca..3b7fdcc85be2f 100644 --- a/src/libcore/unicode.rs +++ b/src/libcore/unicode.rs @@ -14,6 +14,7 @@ pub mod general_category { + #[cfg(stage0)] fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { use cmp::{Equal, Less, Greater}; use vec::bsearch; @@ -25,6 +26,18 @@ pub mod general_category { }) != None } + #[cfg(not(stage0))] + fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use cmp::{Equal, Less, Greater}; + use vec::bsearch; + use option::None; + (do bsearch(r) |&(lo,hi)| { cond!( + (lo <= c && c <= hi) { Equal } + (hi < c) { Less } + _ { Greater } + )}) != None + } + static Cc_table : &'static [(char,char)] = &[ ('\x00', '\x1f'), ('\x7f', '\x9f') @@ -1449,8 +1462,7 @@ pub mod general_category { } pub mod derived_property { - - + #[cfg(stage0)] fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { use cmp::{Equal, Less, Greater}; use vec::bsearch; @@ -1462,6 +1474,18 @@ pub mod derived_property { }) != None } + #[cfg(not(stage0))] + fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use cmp::{Equal, Less, Greater}; + use vec::bsearch; + use option::None; + (do bsearch(r) |&(lo,hi)| { cond!( + (lo <= c && c <= hi) { Equal } + (hi < c) { Less } + _ { Greater } + )}) != None + } + static Alphabetic_table : &'static [(char,char)] = &[ ('\x41', '\x5a'), ('\x61', '\x7a'), From 728fe775a28b780d2bb26982992d5aab7623ba13 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 16:27:54 +1000 Subject: [PATCH 067/248] Use pattern-matching instead of conditionals where appropriate to improve code clarity --- src/libcore/bool.rs | 10 ++--- src/libcore/path.rs | 100 +++++++++++++++++++------------------------- src/libcore/str.rs | 84 ++++++++++++++++--------------------- 3 files changed, 81 insertions(+), 113 deletions(-) diff --git a/src/libcore/bool.rs b/src/libcore/bool.rs index 76a8f456cd5f3..b3c0b8cad7a4e 100644 --- a/src/libcore/bool.rs +++ b/src/libcore/bool.rs @@ -49,12 +49,10 @@ pub fn is_false(v: bool) -> bool { !v } /// Parse logic value from `s` impl FromStr for bool { fn from_str(s: &str) -> Option { - if s == "true" { - Some(true) - } else if s == "false" { - Some(false) - } else { - None + match s { + "true" => Some(true), + "false" => Some(false), + _ => None, } } } diff --git a/src/libcore/path.rs b/src/libcore/path.rs index 2015c5474be32..c359b657cd3d7 100644 --- a/src/libcore/path.rs +++ b/src/libcore/path.rs @@ -311,9 +311,10 @@ pub impl Path { unsafe { do str::as_c_str(self.to_str()) |buf| { let mut st = stat::arch::default_stat(); - let r = libc::stat(buf, &mut st); - - if r == 0 { Some(st) } else { None } + match libc::stat(buf, &mut st) { + 0 => Some(st), + _ => None, + } } } } @@ -323,9 +324,10 @@ pub impl Path { unsafe { do str::as_c_str(self.to_str()) |buf| { let mut st = stat::arch::default_stat(); - let r = libc::lstat(buf, &mut st); - - if r == 0 { Some(st) } else { None } + match libc::lstat(buf, &mut st) { + 0 => Some(st), + _ => None, + } } } } @@ -456,10 +458,9 @@ impl GenericPath for PosixPath { fn dirname(&self) -> ~str { let s = self.dir_path().to_str(); - if s.len() == 0 { - ~"." - } else { - s + match s.len() { + 0 => ~".", + _ => s, } } @@ -515,25 +516,18 @@ impl GenericPath for PosixPath { } fn with_filetype(&self, t: &str) -> PosixPath { - if t.len() == 0 { - match self.filestem() { - None => copy *self, - Some(ref s) => self.with_filename(*s) - } - } else { - let t = ~"." + str::to_owned(t); - match self.filestem() { - None => self.with_filename(t), - Some(ref s) => self.with_filename(*s + t) - } + match (t.len(), self.filestem()) { + (0, None) => copy *self, + (0, Some(ref s)) => self.with_filename(*s), + (_, None) => self.with_filename(fmt!(".%s", t)), + (_, Some(ref s)) => self.with_filename(fmt!("%s.%s", *s, t)), } } fn dir_path(&self) -> PosixPath { - if self.components.len() != 0 { - self.pop() - } else { - copy *self + match self.components.len() { + 0 => copy *self, + _ => self.pop(), } } @@ -638,26 +632,25 @@ impl GenericPath for WindowsPath { let device; let rest; - match windows::extract_drive_prefix(s) { - Some((ref d, ref r)) => { - host = None; - device = Some(copy *d); - rest = copy *r; - } - None => { - match windows::extract_unc_prefix(s) { - Some((ref h, ref r)) => { + match ( + windows::extract_drive_prefix(s), + windows::extract_unc_prefix(s), + ) { + (Some((ref d, ref r)), _) => { + host = None; + device = Some(copy *d); + rest = copy *r; + } + (None, Some((ref h, ref r))) => { host = Some(copy *h); device = None; rest = copy *r; - } - None => { + } + (None, None) => { host = None; device = None; rest = str::to_owned(s); - } } - } } let mut components = ~[]; @@ -673,10 +666,9 @@ impl GenericPath for WindowsPath { fn dirname(&self) -> ~str { let s = self.dir_path().to_str(); - if s.len() == 0 { - ~"." - } else { - s + match s.len() { + 0 => ~".", + _ => s, } } @@ -732,26 +724,18 @@ impl GenericPath for WindowsPath { } fn with_filetype(&self, t: &str) -> WindowsPath { - if t.len() == 0 { - match self.filestem() { - None => copy *self, - Some(ref s) => self.with_filename(*s) - } - } else { - let t = ~"." + str::to_owned(t); - match self.filestem() { - None => self.with_filename(t), - Some(ref s) => - self.with_filename(*s + t) - } + match (t.len(), self.filestem()) { + (0, None) => copy *self, + (0, Some(ref s)) => self.with_filename(*s), + (_, None) => self.with_filename(fmt!(".%s", t)), + (_, Some(ref s)) => self.with_filename(fmt!("%s.%s", *s, t)), } } fn dir_path(&self) -> WindowsPath { - if self.components.len() != 0 { - self.pop() - } else { - copy *self + match self.components.len() { + 0 => copy *self, + _ => self.pop(), } } diff --git a/src/libcore/str.rs b/src/libcore/str.rs index ec7177e52114e..59f769fd92d42 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -128,57 +128,43 @@ pub fn push_char(s: &mut ~str, ch: char) { let off = len; do as_buf(*s) |buf, _len| { let buf: *mut u8 = ::cast::transmute(buf); - if nb == 1u { - *ptr::mut_offset(buf, off) = - code as u8; - } else if nb == 2u { - *ptr::mut_offset(buf, off) = - (code >> 6u & 31u | tag_two_b) as u8; - *ptr::mut_offset(buf, off + 1u) = - (code & 63u | tag_cont) as u8; - } else if nb == 3u { - *ptr::mut_offset(buf, off) = - (code >> 12u & 15u | tag_three_b) as u8; - *ptr::mut_offset(buf, off + 1u) = - (code >> 6u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 2u) = - (code & 63u | tag_cont) as u8; - } else if nb == 4u { - *ptr::mut_offset(buf, off) = - (code >> 18u & 7u | tag_four_b) as u8; - *ptr::mut_offset(buf, off + 1u) = - (code >> 12u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 2u) = - (code >> 6u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 3u) = - (code & 63u | tag_cont) as u8; - } else if nb == 5u { - *ptr::mut_offset(buf, off) = - (code >> 24u & 3u | tag_five_b) as u8; - *ptr::mut_offset(buf, off + 1u) = - (code >> 18u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 2u) = - (code >> 12u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 3u) = - (code >> 6u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 4u) = - (code & 63u | tag_cont) as u8; - } else if nb == 6u { - *ptr::mut_offset(buf, off) = - (code >> 30u & 1u | tag_six_b) as u8; - *ptr::mut_offset(buf, off + 1u) = - (code >> 24u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 2u) = - (code >> 18u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 3u) = - (code >> 12u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 4u) = - (code >> 6u & 63u | tag_cont) as u8; - *ptr::mut_offset(buf, off + 5u) = - (code & 63u | tag_cont) as u8; + match nb { + 1u => { + *ptr::mut_offset(buf, off) = code as u8; + } + 2u => { + *ptr::mut_offset(buf, off) = (code >> 6u & 31u | tag_two_b) as u8; + *ptr::mut_offset(buf, off + 1u) = (code & 63u | tag_cont) as u8; + } + 3u => { + *ptr::mut_offset(buf, off) = (code >> 12u & 15u | tag_three_b) as u8; + *ptr::mut_offset(buf, off + 1u) = (code >> 6u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 2u) = (code & 63u | tag_cont) as u8; + } + 4u => { + *ptr::mut_offset(buf, off) = (code >> 18u & 7u | tag_four_b) as u8; + *ptr::mut_offset(buf, off + 1u) = (code >> 12u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 2u) = (code >> 6u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 3u) = (code & 63u | tag_cont) as u8; + } + 5u => { + *ptr::mut_offset(buf, off) = (code >> 24u & 3u | tag_five_b) as u8; + *ptr::mut_offset(buf, off + 1u) = (code >> 18u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 2u) = (code >> 12u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 3u) = (code >> 6u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 4u) = (code & 63u | tag_cont) as u8; + } + 6u => { + *ptr::mut_offset(buf, off) = (code >> 30u & 1u | tag_six_b) as u8; + *ptr::mut_offset(buf, off + 1u) = (code >> 24u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 2u) = (code >> 18u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 3u) = (code >> 12u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 4u) = (code >> 6u & 63u | tag_cont) as u8; + *ptr::mut_offset(buf, off + 5u) = (code & 63u | tag_cont) as u8; + } + _ => {} } } - raw::set_len(s, new_len); } } From 60ea6d6957697ac6ced355e8a1db5ab6be439765 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 16:50:23 +1000 Subject: [PATCH 068/248] Convert various inner doc-comments to outer doc-comments --- src/libcore/cmp.rs | 3 +- src/libcore/either.rs | 62 +++++++++++++++--------------------------- src/libcore/managed.rs | 4 +-- src/libcore/option.rs | 16 ++++------- 4 files changed, 30 insertions(+), 55 deletions(-) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 80f1f05961a5d..ca9c49b2c0682 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -127,12 +127,11 @@ totalord_impl!(uint) totalord_impl!(char) +/// Compares (a1, b1) against (a2, b2), where the a values are more significant. pub fn cmp2( a1: &A, b1: &B, a2: &A, b2: &B) -> Ordering { - //! Compares (a1, b1) against (a2, b2), where the a values are more significant. - match a1.cmp(a2) { Less => Less, Greater => Greater, diff --git a/src/libcore/either.rs b/src/libcore/either.rs index 8c16f5c64824f..ab52822849cfb 100644 --- a/src/libcore/either.rs +++ b/src/libcore/either.rs @@ -26,26 +26,22 @@ pub enum Either { Right(U) } +/// Applies a function based on the given either value +/// +/// If `value` is left(T) then `f_left` is applied to its contents, if +/// `value` is right(U) then `f_right` is applied to its contents, and the +/// result is returned. #[inline(always)] pub fn either(f_left: &fn(&T) -> V, f_right: &fn(&U) -> V, value: &Either) -> V { - /*! - * Applies a function based on the given either value - * - * If `value` is left(T) then `f_left` is applied to its contents, if - * `value` is right(U) then `f_right` is applied to its contents, and the - * result is returned. - */ - match *value { Left(ref l) => f_left(l), Right(ref r) => f_right(r) } } +/// Extracts from a vector of either all the left values pub fn lefts(eithers: &[Either]) -> ~[T] { - //! Extracts from a vector of either all the left values - do vec::build_sized(eithers.len()) |push| { for eithers.each |elt| { match *elt { @@ -56,9 +52,8 @@ pub fn lefts(eithers: &[Either]) -> ~[T] { } } +/// Extracts from a vector of either all the right values pub fn rights(eithers: &[Either]) -> ~[U] { - //! Extracts from a vector of either all the right values - do vec::build_sized(eithers.len()) |push| { for eithers.each |elt| { match *elt { @@ -69,15 +64,11 @@ pub fn rights(eithers: &[Either]) -> ~[U] { } } -pub fn partition(eithers: ~[Either]) - -> (~[T], ~[U]) { - /*! - * Extracts from a vector of either all the left values and right values - * - * Returns a structure containing a vector of left values and a vector of - * right values. - */ - +/// Extracts from a vector of either all the left values and right values +/// +/// Returns a structure containing a vector of left values and a vector of +/// right values. +pub fn partition(eithers: ~[Either]) -> (~[T], ~[U]) { let mut lefts: ~[T] = ~[]; let mut rights: ~[U] = ~[]; do vec::consume(eithers) |_i, elt| { @@ -89,60 +80,51 @@ pub fn partition(eithers: ~[Either]) return (lefts, rights); } +/// Flips between left and right of a given either #[inline(always)] pub fn flip(eith: Either) -> Either { - //! Flips between left and right of a given either - match eith { Right(r) => Left(r), Left(l) => Right(l) } } +/// Converts either::t to a result::t +/// +/// Converts an `either` type to a `result` type, making the "right" choice +/// an ok result, and the "left" choice a fail #[inline(always)] -pub fn to_result(eith: Either) - -> Result { - /*! - * Converts either::t to a result::t - * - * Converts an `either` type to a `result` type, making the "right" choice - * an ok result, and the "left" choice a fail - */ - +pub fn to_result(eith: Either) -> Result { match eith { Right(r) => result::Ok(r), Left(l) => result::Err(l) } } +/// Checks whether the given value is a left #[inline(always)] pub fn is_left(eith: &Either) -> bool { - //! Checks whether the given value is a left - match *eith { Left(_) => true, _ => false } } +/// Checks whether the given value is a right #[inline(always)] pub fn is_right(eith: &Either) -> bool { - //! Checks whether the given value is a right - match *eith { Right(_) => true, _ => false } } +/// Retrieves the value in the left branch. Fails if the either is Right. #[inline(always)] pub fn unwrap_left(eith: Either) -> T { - //! Retrieves the value in the left branch. Fails if the either is Right. - match eith { Left(x) => x, Right(_) => fail!("either::unwrap_left Right") } } +/// Retrieves the value in the right branch. Fails if the either is Left. #[inline(always)] pub fn unwrap_right(eith: Either) -> U { - //! Retrieves the value in the right branch. Fails if the either is Left. - match eith { Right(x) => x, Left(_) => fail!("either::unwrap_right Left") diff --git a/src/libcore/managed.rs b/src/libcore/managed.rs index d2bb88ca30202..ecde1eb19179d 100644 --- a/src/libcore/managed.rs +++ b/src/libcore/managed.rs @@ -35,16 +35,16 @@ pub mod raw { } +/// Determine if two shared boxes point to the same object #[inline(always)] pub fn ptr_eq(a: @T, b: @T) -> bool { - //! Determine if two shared boxes point to the same object let a_ptr: *T = to_unsafe_ptr(&*a), b_ptr: *T = to_unsafe_ptr(&*b); a_ptr == b_ptr } +/// Determine if two mutable shared boxes point to the same object #[inline(always)] pub fn mut_ptr_eq(a: @mut T, b: @mut T) -> bool { - //! Determine if two mutable shared boxes point to the same object let a_ptr: *T = to_unsafe_ptr(&*a), b_ptr: *T = to_unsafe_ptr(&*b); a_ptr == b_ptr } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 5aee3077e4866..e1bd72f67f16f 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -182,12 +182,10 @@ pub impl Option { #[inline(always)] fn is_some(&const self) -> bool { !self.is_none() } + /// Update an optional value by optionally running its content through a + /// function that returns an option. #[inline(always)] fn chain(self, f: &fn(t: T) -> Option) -> Option { - /*! - * Update an optional value by optionally running its content through a - * function that returns an option. - */ match self { Some(t) => f(t), @@ -195,21 +193,17 @@ pub impl Option { } } + /// Returns the leftmost Some() value, or None if both are None. #[inline(always)] fn or(self, optb: Option) -> Option { - /*! - * Returns the leftmost Some() value, or None if both are None. - */ match self { Some(opta) => Some(opta), _ => optb } } - /** - * Update an optional value by optionally running its content by reference - * through a function that returns an option. - */ + /// Update an optional value by optionally running its content by reference + /// through a function that returns an option. #[inline(always)] fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option) -> Option { match *self { Some(ref x) => f(x), None => None } From ad6ee5f4e5f779d987ac7a35ce6f149039a45b15 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 16:52:11 +1000 Subject: [PATCH 069/248] Use four-space indentation, add trailing commas, and remove unnecessary uses of the return keyword --- src/libcore/either.rs | 26 +++++--- src/libcore/option.rs | 4 +- src/libcore/path.rs | 145 ++++++++++++++++++++++-------------------- 3 files changed, 95 insertions(+), 80 deletions(-) diff --git a/src/libcore/either.rs b/src/libcore/either.rs index ab52822849cfb..f89bb3b2f9064 100644 --- a/src/libcore/either.rs +++ b/src/libcore/either.rs @@ -35,8 +35,8 @@ pub enum Either { pub fn either(f_left: &fn(&T) -> V, f_right: &fn(&U) -> V, value: &Either) -> V { match *value { - Left(ref l) => f_left(l), - Right(ref r) => f_right(r) + Left(ref l) => f_left(l), + Right(ref r) => f_right(r) } } @@ -73,8 +73,8 @@ pub fn partition(eithers: ~[Either]) -> (~[T], ~[U]) { let mut rights: ~[U] = ~[]; do vec::consume(eithers) |_i, elt| { match elt { - Left(l) => lefts.push(l), - Right(r) => rights.push(r) + Left(l) => lefts.push(l), + Right(r) => rights.push(r) } } return (lefts, rights); @@ -84,8 +84,8 @@ pub fn partition(eithers: ~[Either]) -> (~[T], ~[U]) { #[inline(always)] pub fn flip(eith: Either) -> Either { match eith { - Right(r) => Left(r), - Left(l) => Right(l) + Right(r) => Left(r), + Left(l) => Right(l) } } @@ -96,21 +96,27 @@ pub fn flip(eith: Either) -> Either { #[inline(always)] pub fn to_result(eith: Either) -> Result { match eith { - Right(r) => result::Ok(r), - Left(l) => result::Err(l) + Right(r) => result::Ok(r), + Left(l) => result::Err(l) } } /// Checks whether the given value is a left #[inline(always)] pub fn is_left(eith: &Either) -> bool { - match *eith { Left(_) => true, _ => false } + match *eith { + Left(_) => true, + _ => false + } } /// Checks whether the given value is a right #[inline(always)] pub fn is_right(eith: &Either) -> bool { - match *eith { Right(_) => true, _ => false } + match *eith { + Right(_) => true, + _ => false + } } /// Retrieves the value in the left branch. Fails if the either is Right. diff --git a/src/libcore/option.rs b/src/libcore/option.rs index e1bd72f67f16f..0212d4abd29d6 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -89,11 +89,11 @@ impl Ord for Option { } fn ge(&self, other: &Option) -> bool { - ! (self < other) + !(self < other) } fn gt(&self, other: &Option) -> bool { - ! (self <= other) + !(self <= other) } } diff --git a/src/libcore/path.rs b/src/libcore/path.rs index c359b657cd3d7..8a5d9c0416d07 100644 --- a/src/libcore/path.rs +++ b/src/libcore/path.rs @@ -452,8 +452,10 @@ impl GenericPath for PosixPath { components.push(s.to_owned()) } let is_absolute = (s.len() != 0 && s[0] == '/' as u8); - return PosixPath { is_absolute: is_absolute, - components: components } + PosixPath { + is_absolute: is_absolute, + components: components, + } } fn dirname(&self) -> ~str { @@ -466,40 +468,40 @@ impl GenericPath for PosixPath { fn filename(&self) -> Option<~str> { match self.components.len() { - 0 => None, - n => Some(copy self.components[n - 1]) + 0 => None, + n => Some(copy self.components[n - 1]), } } fn filestem(&self) -> Option<~str> { match self.filename() { - None => None, - Some(ref f) => { - match str::rfind_char(*f, '.') { - Some(p) => Some(f.slice(0, p).to_owned()), - None => Some(copy *f) + None => None, + Some(ref f) => { + match str::rfind_char(*f, '.') { + Some(p) => Some(f.slice(0, p).to_owned()), + None => Some(copy *f), + } } - } } } fn filetype(&self) -> Option<~str> { match self.filename() { - None => None, - Some(ref f) => { - match str::rfind_char(*f, '.') { - Some(p) if p < f.len() => Some(f.slice(p, f.len()).to_owned()), - _ => None + None => None, + Some(ref f) => { + match str::rfind_char(*f, '.') { + Some(p) if p < f.len() => Some(f.slice(p, f.len()).to_owned()), + _ => None, + } } - } } } fn with_dirname(&self, d: &str) -> PosixPath { let dpath = PosixPath(d); match self.filename() { - Some(ref f) => dpath.push(*f), - None => dpath + Some(ref f) => dpath.push(*f), + None => dpath, } } @@ -510,8 +512,8 @@ impl GenericPath for PosixPath { fn with_filestem(&self, s: &str) -> PosixPath { match self.filetype() { - None => self.with_filename(s), - Some(ref t) => self.with_filename(str::to_owned(s) + *t) + None => self.with_filename(s), + Some(ref t) => self.with_filename(str::to_owned(s) + *t), } } @@ -536,8 +538,10 @@ impl GenericPath for PosixPath { None => ~[], Some(ref f) => ~[copy *f] }; - return PosixPath { is_absolute: false, - components: cs } + PosixPath { + is_absolute: false, + components: cs, + } } fn push_rel(&self, other: &PosixPath) -> PosixPath { @@ -547,8 +551,10 @@ impl GenericPath for PosixPath { fn unsafe_join(&self, other: &PosixPath) -> PosixPath { if other.is_absolute { - PosixPath { is_absolute: true, - components: copy other.components } + PosixPath { + is_absolute: true, + components: copy other.components, + } } else { self.push_rel(other) } @@ -567,8 +573,10 @@ impl GenericPath for PosixPath { } v.push_all_move(ss); } - PosixPath { is_absolute: self.is_absolute, - components: v } + PosixPath { + is_absolute: self.is_absolute, + components: v, + } } fn push(&self, s: &str) -> PosixPath { @@ -586,19 +594,17 @@ impl GenericPath for PosixPath { if cs.len() != 0 { cs.pop(); } - return PosixPath { + PosixPath { is_absolute: self.is_absolute, - components: cs - } - //..self } + components: cs, + } //..self } } fn normalize(&self) -> PosixPath { - return PosixPath { + PosixPath { is_absolute: self.is_absolute, - components: normalize(self.components) - // ..self - } + components: normalize(self.components), + } // ..self } } fn is_absolute(&self) -> bool { @@ -658,10 +664,12 @@ impl GenericPath for WindowsPath { components.push(s.to_owned()) } let is_absolute = (rest.len() != 0 && windows::is_sep(rest[0])); - return WindowsPath { host: host, - device: device, - is_absolute: is_absolute, - components: components } + WindowsPath { + host: host, + device: device, + is_absolute: is_absolute, + components: components, + } } fn dirname(&self) -> ~str { @@ -674,20 +682,20 @@ impl GenericPath for WindowsPath { fn filename(&self) -> Option<~str> { match self.components.len() { - 0 => None, - n => Some(copy self.components[n - 1]) + 0 => None, + n => Some(copy self.components[n - 1]), } } fn filestem(&self) -> Option<~str> { match self.filename() { - None => None, - Some(ref f) => { - match str::rfind_char(*f, '.') { - Some(p) => Some(f.slice(0, p).to_owned()), - None => Some(copy *f) + None => None, + Some(ref f) => { + match str::rfind_char(*f, '.') { + Some(p) => Some(f.slice(0, p).to_owned()), + None => Some(copy *f), + } } - } } } @@ -696,8 +704,8 @@ impl GenericPath for WindowsPath { None => None, Some(ref f) => { match str::rfind_char(*f, '.') { - Some(p) if p < f.len() => Some(f.slice(p, f.len()).to_owned()), - _ => None + Some(p) if p < f.len() => Some(f.slice(p, f.len()).to_owned()), + _ => None, } } } @@ -706,8 +714,8 @@ impl GenericPath for WindowsPath { fn with_dirname(&self, d: &str) -> WindowsPath { let dpath = WindowsPath(d); match self.filename() { - Some(ref f) => dpath.push(*f), - None => dpath + Some(ref f) => dpath.push(*f), + None => dpath, } } @@ -718,8 +726,8 @@ impl GenericPath for WindowsPath { fn with_filestem(&self, s: &str) -> WindowsPath { match self.filetype() { - None => self.with_filename(s), - Some(ref t) => self.with_filename(str::to_owned(s) + *t) + None => self.with_filename(s), + Some(ref t) => self.with_filename(str::to_owned(s) + *t), } } @@ -740,14 +748,15 @@ impl GenericPath for WindowsPath { } fn file_path(&self) -> WindowsPath { - let cs = match self.filename() { - None => ~[], - Some(ref f) => ~[copy *f] - }; - return WindowsPath { host: None, - device: None, - is_absolute: false, - components: cs } + WindowsPath { + host: None, + device: None, + is_absolute: false, + components: match self.filename() { + None => ~[], + Some(ref f) => ~[copy *f], + } + } } fn push_rel(&self, other: &WindowsPath) -> WindowsPath { @@ -768,7 +777,7 @@ impl GenericPath for WindowsPath { host: Some(host), device: copy other.device, is_absolute: true, - components: copy other.components + components: copy other.components, }; } _ => {} @@ -781,7 +790,7 @@ impl GenericPath for WindowsPath { host: None, device: Some(device), is_absolute: true, - components: copy other.components + components: copy other.components, }; } _ => {} @@ -793,7 +802,7 @@ impl GenericPath for WindowsPath { host: copy self.host, device: copy self.device, is_absolute: self.is_absolute || other.is_absolute, - components: copy other.components + components: copy other.components, } } @@ -822,7 +831,7 @@ impl GenericPath for WindowsPath { v.push_all_move(ss); } // tedious, but as-is, we can't use ..self - return WindowsPath { + WindowsPath { host: copy self.host, device: copy self.device, is_absolute: self.is_absolute, @@ -837,7 +846,7 @@ impl GenericPath for WindowsPath { ss.push(s.to_owned()) } v.push_all_move(ss); - return WindowsPath { components: v, ..copy *self } + WindowsPath { components: v, ..copy *self } } fn pop(&self) -> WindowsPath { @@ -845,16 +854,16 @@ impl GenericPath for WindowsPath { if cs.len() != 0 { cs.pop(); } - return WindowsPath { + WindowsPath { host: copy self.host, device: copy self.device, is_absolute: self.is_absolute, - components: cs + components: cs, } } fn normalize(&self) -> WindowsPath { - return WindowsPath { + WindowsPath { host: copy self.host, device: match self.device { None => None, From a9c465ce1f1caaae58a31c57f665217ee58bb876 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 18 May 2013 04:20:01 -0400 Subject: [PATCH 070/248] iterator: remove `first` it's the same as `next.unwrap()`, but there's no way to check the length of an iterator so this isn't a good pattern --- src/libcore/iterator.rs | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 588bd0bde5343..68281526e6f94 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -49,7 +49,6 @@ pub trait IteratorUtil { fn advance(&mut self, f: &fn(A) -> bool) -> bool; fn to_vec(self) -> ~[A]; fn nth(&mut self, n: uint) -> A; - fn first(&mut self) -> A; fn last(&mut self) -> A; fn fold(&mut self, start: B, f: &fn(B, A) -> B) -> B; fn count(&mut self) -> uint; @@ -168,15 +167,6 @@ impl> IteratorUtil for T { } } - // Get first elemet of an iterator. - #[inline(always)] - fn first(&mut self) -> A { - match self.next() { - Some(x) => x , - None => fail!("cannot get first element") - } - } - // Get last element of an iterator. // // If the iterator have an infinite length, this method won't return. @@ -700,20 +690,6 @@ mod tests { v.iter().nth(5); } - #[test] - fn test_iterator_first() { - let v = &[0, 1, 2, 3, 4]; - assert_eq!(v.iter().first(), &0); - assert_eq!(v.slice(2, 5).iter().first(), &2); - } - - #[test] - #[should_fail] - fn test_iterator_first_fail() { - let v: &[uint] = &[]; - v.iter().first(); - } - #[test] fn test_iterator_last() { let v = &[0, 1, 2, 3, 4]; From ea8a55b821460ef7b3b58052f99673674fca8f96 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 18 May 2013 04:27:58 -0400 Subject: [PATCH 071/248] iterator: make nth and last return Option There isn't a way to take the length of any iterator, so failing on a zero length would make these much less useful. --- src/libcore/iterator.rs | 50 +++++++++++++---------------------------- 1 file changed, 15 insertions(+), 35 deletions(-) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 68281526e6f94..65c36b122c766 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -48,8 +48,8 @@ pub trait IteratorUtil { #[cfg(not(stage0))] fn advance(&mut self, f: &fn(A) -> bool) -> bool; fn to_vec(self) -> ~[A]; - fn nth(&mut self, n: uint) -> A; - fn last(&mut self) -> A; + fn nth(&mut self, n: uint) -> Option; + fn last(&mut self) -> Option; fn fold(&mut self, start: B, f: &fn(B, A) -> B) -> B; fn count(&mut self) -> uint; fn all(&mut self, f: &fn(&A) -> bool) -> bool; @@ -154,30 +154,24 @@ impl> IteratorUtil for T { return v; } - /// Get `n`th element of an iterator. + /// Return the `n`th item yielded by an iterator. #[inline(always)] - fn nth(&mut self, n: uint) -> A { - let mut i = n; + fn nth(&mut self, mut n: uint) -> Option { loop { match self.next() { - Some(x) => { if i == 0 { return x; }} - None => { fail!("cannot get %uth element", n) } + Some(x) => if n == 0 { return Some(x) }, + None => return None } - i -= 1; + n -= 1; } } - // Get last element of an iterator. - // - // If the iterator have an infinite length, this method won't return. + /// Return the last item yielded by an iterator. #[inline(always)] - fn last(&mut self) -> A { - let mut elm = match self.next() { - Some(x) => x, - None => fail!("cannot get last element") - }; - for self.advance |e| { elm = e; } - return elm; + fn last(&mut self) -> Option { + let mut last = None; + for self.advance |x| { last = Some(x); } + last } /// Reduce an iterator to an accumulated value @@ -679,29 +673,15 @@ mod tests { fn test_iterator_nth() { let v = &[0, 1, 2, 3, 4]; for uint::range(0, v.len()) |i| { - assert_eq!(v.iter().nth(i), &v[i]); + assert_eq!(v.iter().nth(i).unwrap(), &v[i]); } } - #[test] - #[should_fail] - fn test_iterator_nth_fail() { - let v = &[0, 1, 2, 3, 4]; - v.iter().nth(5); - } - #[test] fn test_iterator_last() { let v = &[0, 1, 2, 3, 4]; - assert_eq!(v.iter().last(), &4); - assert_eq!(v.slice(0, 1).iter().last(), &0); - } - - #[test] - #[should_fail] - fn test_iterator_last_fail() { - let v: &[uint] = &[]; - v.iter().last(); + assert_eq!(v.iter().last().unwrap(), &4); + assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0); } #[test] From 883d583faa9f33e69dce4b913f47a2d09e8b584d Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 18 May 2013 04:32:53 -0400 Subject: [PATCH 072/248] iterator: reuse iter::to_vec, and use &mut self --- src/libcore/iterator.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 65c36b122c766..0b0df4a5d70b7 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -47,7 +47,7 @@ pub trait IteratorUtil { fn advance(&mut self, f: &fn(A) -> bool); #[cfg(not(stage0))] fn advance(&mut self, f: &fn(A) -> bool) -> bool; - fn to_vec(self) -> ~[A]; + fn to_vec(&mut self) -> ~[A]; fn nth(&mut self, n: uint) -> Option; fn last(&mut self) -> Option; fn fold(&mut self, start: B, f: &fn(B, A) -> B) -> B; @@ -147,11 +147,8 @@ impl> IteratorUtil for T { } #[inline(always)] - fn to_vec(self) -> ~[A] { - let mut v = ~[]; - let mut it = self; - for it.advance() |x| { v.push(x); } - return v; + fn to_vec(&mut self) -> ~[A] { + iter::to_vec::(|f| self.advance(f)) } /// Return the `n`th item yielded by an iterator. @@ -563,7 +560,7 @@ mod tests { #[test] fn test_filter_map() { - let it = Counter::new(0u, 1u).take(10) + let mut it = Counter::new(0u, 1u).take(10) .filter_map(|x: uint| if x.is_even() { Some(x*x) } else { None }); assert_eq!(it.to_vec(), ~[0*0, 2*2, 4*4, 6*6, 8*8]); } From 073225572a1c7c7dc9f7c2740514557105950807 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 18 May 2013 04:44:44 -0400 Subject: [PATCH 073/248] iterator: reword docstring --- src/libcore/iterator.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 0b0df4a5d70b7..0bf61b66f7532 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -184,7 +184,7 @@ impl> IteratorUtil for T { return accum; } - /// Count the number of an iterator elemenrs + /// Count the number of items yielded by an iterator #[inline(always)] fn count(&mut self) -> uint { self.fold(0, |cnt, _x| cnt + 1) } From fc656262a905a50eff2be54a87295d2952d29106 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 18 May 2013 04:48:22 -0400 Subject: [PATCH 074/248] iterator: use advance to implement FilterMapIterator --- src/libcore/iterator.rs | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 0bf61b66f7532..41f916f2d1557 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -325,17 +325,13 @@ pub struct FilterMapIterator<'self, A, B, T> { impl<'self, A, B, T: Iterator> Iterator for FilterMapIterator<'self, A, B, T> { #[inline] fn next(&mut self) -> Option { - loop { - match self.iter.next() { - None => { return None; } - Some(a) => { - match (self.f)(a) { - Some(b) => { return Some(b); } - None => { loop; } - } - } + for self.iter.advance |x| { + match (self.f)(x) { + Some(y) => return Some(y), + None => () } } + None } } From d953a5ce43ba2adecb50780c7debd3fea6248996 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Mon, 29 Apr 2013 00:03:55 -0400 Subject: [PATCH 075/248] replace old_iter::repeat with the Times trait --- doc/tutorial.md | 2 +- src/libcore/old_iter.rs | 20 -------------------- src/libcore/task/mod.rs | 19 +++++++++---------- src/librustdoc/markdown_pass.rs | 4 ++-- src/libstd/base64.rs | 6 +----- src/libstd/timer.rs | 13 ++++++------- src/libstd/uv_global_loop.rs | 4 ++-- src/libstd/uv_iotask.rs | 4 ++-- src/test/bench/task-perf-alloc-unwind.rs | 2 +- src/test/run-fail/extern-fail.rs | 2 +- src/test/run-pass/bitv-perf-test.rs | 2 +- src/test/run-pass/extern-stress.rs | 2 +- src/test/run-pass/extern-yield.rs | 2 +- 13 files changed, 28 insertions(+), 54 deletions(-) diff --git a/doc/tutorial.md b/doc/tutorial.md index a01423d3fd3fc..cb7caeeb8109f 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1977,7 +1977,7 @@ struct TimeBomb { impl Drop for TimeBomb { fn finalize(&self) { - for old_iter::repeat(self.explosivity) { + for self.explosivity.times { println("blam!"); } } diff --git a/src/libcore/old_iter.rs b/src/libcore/old_iter.rs index 7cffcb10a5321..12b7ce1eb6ebb 100644 --- a/src/libcore/old_iter.rs +++ b/src/libcore/old_iter.rs @@ -238,26 +238,6 @@ pub fn position>(this: &IA, f: &fn(&A) -> bool) // iter interface, such as would provide "reach" in addition to "each". As is, // it would have to be implemented with foldr, which is too inefficient. -#[inline(always)] -#[cfg(stage0)] -pub fn repeat(times: uint, blk: &fn() -> bool) { - let mut i = 0; - while i < times { - if !blk() { break } - i += 1; - } -} -#[inline(always)] -#[cfg(not(stage0))] -pub fn repeat(times: uint, blk: &fn() -> bool) -> bool { - let mut i = 0; - while i < times { - if !blk() { return false; } - i += 1; - } - return true; -} - #[inline(always)] pub fn min>(this: &IA) -> A { match do foldl::,IA>(this, None) |a, b| { diff --git a/src/libcore/task/mod.rs b/src/libcore/task/mod.rs index d57bd5528bce4..8eb166c6ef233 100644 --- a/src/libcore/task/mod.rs +++ b/src/libcore/task/mod.rs @@ -619,7 +619,7 @@ fn test_spawn_unlinked_unsup_no_fail_down() { // grandchild sends on a port let ch = ch.clone(); do spawn_unlinked { // Give middle task a chance to fail-but-not-kill-us. - for old_iter::repeat(16) { task::yield(); } + for 16.times { task::yield(); } ch.send(()); // If killed first, grandparent hangs. } fail!(); // Shouldn't kill either (grand)parent or (grand)child. @@ -634,7 +634,7 @@ fn test_spawn_unlinked_unsup_no_fail_up() { // child unlinked fails fn test_spawn_unlinked_sup_no_fail_up() { // child unlinked fails do spawn_supervised { fail!(); } // Give child a chance to fail-but-not-kill-us. - for old_iter::repeat(16) { task::yield(); } + for 16.times { task::yield(); } } #[test] #[should_fail] #[ignore(cfg(windows))] fn test_spawn_unlinked_sup_fail_down() { @@ -709,7 +709,7 @@ fn test_spawn_failure_propagate_grandchild() { loop { task::yield(); } } } - for old_iter::repeat(16) { task::yield(); } + for 16.times { task::yield(); } fail!(); } @@ -721,7 +721,7 @@ fn test_spawn_failure_propagate_secondborn() { loop { task::yield(); } } } - for old_iter::repeat(16) { task::yield(); } + for 16.times { task::yield(); } fail!(); } @@ -733,7 +733,7 @@ fn test_spawn_failure_propagate_nephew_or_niece() { loop { task::yield(); } } } - for old_iter::repeat(16) { task::yield(); } + for 16.times { task::yield(); } fail!(); } @@ -745,7 +745,7 @@ fn test_spawn_linked_sup_propagate_sibling() { loop { task::yield(); } } } - for old_iter::repeat(16) { task::yield(); } + for 16.times { task::yield(); } fail!(); } @@ -904,8 +904,7 @@ fn test_spawn_sched_blocking() { // Testing that a task in one scheduler can block in foreign code // without affecting other schedulers - for old_iter::repeat(20u) { - + for 20u.times { let (start_po, start_ch) = stream(); let (fin_po, fin_ch) = stream(); @@ -1024,7 +1023,7 @@ fn test_unkillable() { // We want to do this after failing do spawn_unlinked { - for old_iter::repeat(10) { yield() } + for 10.times { yield() } ch.send(()); } @@ -1059,7 +1058,7 @@ fn test_unkillable_nested() { // We want to do this after failing do spawn_unlinked || { - for old_iter::repeat(10) { yield() } + for 10.times { yield() } ch.send(()); } diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index a42c4738b2de7..1eac09ea2056f 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -629,7 +629,7 @@ mod test { let doc = (page_pass::mk_pass(config::DocPerMod).f)(srv, doc); write_markdown(doc, writer_factory); // We expect two pages to have been written - for old_iter::repeat(2) { + for 2.times { po.recv(); } } @@ -641,7 +641,7 @@ mod test { ~"#[link(name = \"core\")]; mod a { }"); let doc = (page_pass::mk_pass(config::DocPerMod).f)(srv, doc); write_markdown(doc, writer_factory); - for old_iter::repeat(2) { + for 2.times { let (page, markdown) = po.recv(); match page { doc::CratePage(_) => { diff --git a/src/libstd/base64.rs b/src/libstd/base64.rs index 68242f88fae5e..57833e607ae0a 100644 --- a/src/libstd/base64.rs +++ b/src/libstd/base64.rs @@ -10,10 +10,6 @@ //! Base64 binary-to-text encoding -use core::old_iter; -use core::str; -use core::vec; - pub trait ToBase64 { fn to_base64(&self) -> ~str; } @@ -152,7 +148,7 @@ impl FromBase64 for ~[u8] { while i < len { let mut n = 0u; - for old_iter::repeat(4u) { + for 4u.times { let ch = self[i] as char; n <<= 6u; diff --git a/src/libstd/timer.rs b/src/libstd/timer.rs index e9fd0414244e8..52dc095b092dd 100644 --- a/src/libstd/timer.rs +++ b/src/libstd/timer.rs @@ -188,7 +188,7 @@ mod test { #[test] fn test_gl_timer_sleep_stress1() { let hl_loop = &uv::global_loop::get(); - for old_iter::repeat(50u) { + for 50u.times { sleep(hl_loop, 1u); } } @@ -208,8 +208,7 @@ mod test { }; - for old_iter::repeat(repeat) { - + for repeat.times { let ch = ch.clone(); for spec.each |spec| { let (times, maxms) = *spec; @@ -218,7 +217,7 @@ mod test { do task::spawn { use core::rand::*; let mut rng = rng(); - for old_iter::repeat(times) { + for times.times { sleep(&hl_loop_clone, rng.next() as uint % maxms); } ch.send(()); @@ -226,7 +225,7 @@ mod test { } } - for old_iter::repeat(repeat * spec.len()) { + for (repeat * spec.len()).times { po.recv() } } @@ -244,7 +243,7 @@ mod test { let mut failures = 0; let hl_loop = uv::global_loop::get(); - for old_iter::repeat(times as uint) { + for (times as uint).times { task::yield(); let expected = rand::rng().gen_str(16u); @@ -273,7 +272,7 @@ mod test { let mut failures = 0; let hl_loop = uv::global_loop::get(); - for old_iter::repeat(times as uint) { + for (times as uint).times { let mut rng = rand::rng(); let expected = Cell(rng.gen_str(16u)); let (test_po, test_ch) = stream::<~str>(); diff --git a/src/libstd/uv_global_loop.rs b/src/libstd/uv_global_loop.rs index c7b5d9eef726b..d1471ba1e7705 100644 --- a/src/libstd/uv_global_loop.rs +++ b/src/libstd/uv_global_loop.rs @@ -215,7 +215,7 @@ mod test { let (exit_po, exit_ch) = stream::<()>(); let exit_ch = SharedChan::new(exit_ch); let cycles = 5000u; - for old_iter::repeat(cycles) { + for cycles.times { let exit_ch_clone = exit_ch.clone(); task::spawn_sched(task::ManualThreads(1u), || { let hl_loop = &get_gl(); @@ -223,7 +223,7 @@ mod test { exit_ch_clone.send(()); }); }; - for old_iter::repeat(cycles) { + for cycles.times { exit_po.recv(); }; debug!(~"test_stress_gl_uv_global_loop_high_level_global_timer"+ diff --git a/src/libstd/uv_iotask.rs b/src/libstd/uv_iotask.rs index 2922f403f34a6..b40f657ad7f07 100644 --- a/src/libstd/uv_iotask.rs +++ b/src/libstd/uv_iotask.rs @@ -284,7 +284,7 @@ fn test_uv_iotask_async() { // impl_uv_hl_async() runs have been called, at least. let (work_exit_po, work_exit_ch) = stream::<()>(); let work_exit_ch = SharedChan::new(work_exit_ch); - for old_iter::repeat(7u) { + for 7u.times { let iotask_clone = iotask.clone(); let work_exit_ch_clone = work_exit_ch.clone(); do task::spawn_sched(task::ManualThreads(1u)) { @@ -294,7 +294,7 @@ fn test_uv_iotask_async() { work_exit_ch_clone.send(()); }; }; - for old_iter::repeat(7u) { + for 7u.times { debug!("waiting"); work_exit_po.recv(); }; diff --git a/src/test/bench/task-perf-alloc-unwind.rs b/src/test/bench/task-perf-alloc-unwind.rs index 2588916705045..4a07193d8cd1d 100644 --- a/src/test/bench/task-perf-alloc-unwind.rs +++ b/src/test/bench/task-perf-alloc-unwind.rs @@ -30,7 +30,7 @@ fn main() { } fn run(repeat: int, depth: int) { - for old_iter::repeat(repeat as uint) { + for (repeat as uint).times { debug!("starting %.4f", precise_time_s()); do task::try { recurse_or_fail(depth, None) diff --git a/src/test/run-fail/extern-fail.rs b/src/test/run-fail/extern-fail.rs index 2deee10527cc9..d7ec9f088653f 100644 --- a/src/test/run-fail/extern-fail.rs +++ b/src/test/run-fail/extern-fail.rs @@ -37,7 +37,7 @@ fn count(n: uint) -> uint { } fn main() { - for old_iter::repeat(10u) { + for 10u.times { do task::spawn { let result = count(5u); debug!("result = %?", result); diff --git a/src/test/run-pass/bitv-perf-test.rs b/src/test/run-pass/bitv-perf-test.rs index bf2285480b477..2d47916d05040 100644 --- a/src/test/run-pass/bitv-perf-test.rs +++ b/src/test/run-pass/bitv-perf-test.rs @@ -21,5 +21,5 @@ fn bitv_test() -> bool { } pub fn main() { - do old_iter::repeat(10000) || {bitv_test()}; + do 10000.times || {bitv_test()}; } diff --git a/src/test/run-pass/extern-stress.rs b/src/test/run-pass/extern-stress.rs index 0b640c8c62360..379d88fbd7675 100644 --- a/src/test/run-pass/extern-stress.rs +++ b/src/test/run-pass/extern-stress.rs @@ -34,7 +34,7 @@ fn count(n: uint) -> uint { } pub fn main() { - for old_iter::repeat(100u) { + for 100u.times { do task::spawn { assert!(count(5u) == 16u); }; diff --git a/src/test/run-pass/extern-yield.rs b/src/test/run-pass/extern-yield.rs index bde3f5dd52ff6..e2f23de6b6827 100644 --- a/src/test/run-pass/extern-yield.rs +++ b/src/test/run-pass/extern-yield.rs @@ -31,7 +31,7 @@ fn count(n: uint) -> uint { } pub fn main() { - for old_iter::repeat(10u) { + for 10u.times { do task::spawn { let result = count(5u); debug!("result = %?", result); From 6742f91192da67324b33cf882383a283a2599f7b Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 18:59:16 +1000 Subject: [PATCH 076/248] Create tuple element accessor traits --- src/libcore/prelude.rs | 2 + src/libcore/tuple.rs | 165 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 167 insertions(+) diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index 4ed648161fc22..77371b6336848 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -52,6 +52,8 @@ pub use from_str::{FromStr}; pub use to_bytes::IterBytes; pub use to_str::{ToStr, ToStrConsume}; pub use tuple::{CopyableTuple, ImmutableTuple, ExtendedTupleOps}; +pub use tuple::{Tuple2, Tuple3, Tuple4, Tuple5, Tuple6, Tuple7, Tuple8, Tuple9}; +pub use tuple::{Tuple10, Tuple11, Tuple12}; pub use vec::{CopyableVector, ImmutableVector}; pub use vec::{ImmutableEqVector, ImmutableCopyableVector}; pub use vec::{OwnedVector, OwnedCopyableVector, MutableVector}; diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index b29a4e55426df..810ef75ad6a31 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -246,6 +246,154 @@ impl Ord for (A, B, C) { fn gt(&self, other: &(A, B, C)) -> bool { (*other).lt(&(*self)) } } +// Tuple element accessor traits + +macro_rules! n_tuple( + ($name:ident: $($method:ident : $T:ident),+) => ( + pub trait $name<$($T),+> { + $(fn $method(&self) -> $T;)+ + } + ) +) + +n_tuple!(Tuple2: _0:A, _1:B) +n_tuple!(Tuple3: _0:A, _1:B, _2:C) +n_tuple!(Tuple4: _0:A, _1:B, _2:C, _3:D) +n_tuple!(Tuple5: _0:A, _1:B, _2:C, _3:D, _4:E) +n_tuple!(Tuple6: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F) +n_tuple!(Tuple7: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G) +n_tuple!(Tuple8: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H) +n_tuple!(Tuple9: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I) +n_tuple!(Tuple10: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I, _9:J) +n_tuple!(Tuple11: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I, _9:J, _10:K) +n_tuple!(Tuple12: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I, _9:J, _10:K, _11:L) + +// Tuple element accessor trait implementations + +macro_rules! impl_n_tuple( + ($name:ident: $($method:ident -> $T:ident { $accessor:pat => $t:expr })+) => ( + impl<$($T:Copy),+> $name<$($T),+> for ($($T),+) { + $( + fn $method(&self) -> $T { + match *self { + $accessor => $t + } + } + )+ + } + ) +) + +impl_n_tuple!(Tuple2: + _0 -> A { (a,_) => a } + _1 -> B { (_,b) => b } +) + +impl_n_tuple!(Tuple3: + _0 -> A { (a,_,_) => a } + _1 -> B { (_,b,_) => b } + _2 -> C { (_,_,c) => c } +) + +impl_n_tuple!(Tuple4: + _0 -> A { (a,_,_,_) => a } + _1 -> B { (_,b,_,_) => b } + _2 -> C { (_,_,c,_) => c } + _3 -> D { (_,_,_,d) => d } +) + +impl_n_tuple!(Tuple5: + _0 -> A { (a,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_) => b } + _2 -> C { (_,_,c,_,_) => c } + _3 -> D { (_,_,_,d,_) => d } + _4 -> E { (_,_,_,_,e) => e } +) + +impl_n_tuple!(Tuple6: + _0 -> A { (a,_,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_,_) => b } + _2 -> C { (_,_,c,_,_,_) => c } + _3 -> D { (_,_,_,d,_,_) => d } + _4 -> E { (_,_,_,_,e,_) => e } + _5 -> F { (_,_,_,_,_,f) => f } +) + +impl_n_tuple!(Tuple7: + _0 -> A { (a,_,_,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_,_,_) => b } + _2 -> C { (_,_,c,_,_,_,_) => c } + _3 -> D { (_,_,_,d,_,_,_) => d } + _4 -> E { (_,_,_,_,e,_,_) => e } + _5 -> F { (_,_,_,_,_,f,_) => f } + _6 -> G { (_,_,_,_,_,_,g) => g } +) + +impl_n_tuple!(Tuple8: + _0 -> A { (a,_,_,_,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_,_,_,_) => b } + _2 -> C { (_,_,c,_,_,_,_,_) => c } + _3 -> D { (_,_,_,d,_,_,_,_) => d } + _4 -> E { (_,_,_,_,e,_,_,_) => e } + _5 -> F { (_,_,_,_,_,f,_,_) => f } + _6 -> G { (_,_,_,_,_,_,g,_) => g } + _7 -> H { (_,_,_,_,_,_,_,h) => h } +) + +impl_n_tuple!(Tuple9: + _0 -> A { (a,_,_,_,_,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_,_,_,_,_) => b } + _2 -> C { (_,_,c,_,_,_,_,_,_) => c } + _3 -> D { (_,_,_,d,_,_,_,_,_) => d } + _4 -> E { (_,_,_,_,e,_,_,_,_) => e } + _5 -> F { (_,_,_,_,_,f,_,_,_) => f } + _6 -> G { (_,_,_,_,_,_,g,_,_) => g } + _7 -> H { (_,_,_,_,_,_,_,h,_) => h } + _8 -> I { (_,_,_,_,_,_,_,_,i) => i } +) + +impl_n_tuple!(Tuple10: + _0 -> A { (a,_,_,_,_,_,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_,_,_,_,_,_) => b } + _2 -> C { (_,_,c,_,_,_,_,_,_,_) => c } + _3 -> D { (_,_,_,d,_,_,_,_,_,_) => d } + _4 -> E { (_,_,_,_,e,_,_,_,_,_) => e } + _5 -> F { (_,_,_,_,_,f,_,_,_,_) => f } + _6 -> G { (_,_,_,_,_,_,g,_,_,_) => g } + _7 -> H { (_,_,_,_,_,_,_,h,_,_) => h } + _8 -> I { (_,_,_,_,_,_,_,_,i,_) => i } + _9 -> J { (_,_,_,_,_,_,_,_,_,j) => j } +) + +impl_n_tuple!(Tuple11: + _0 -> A { (a,_,_,_,_,_,_,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_,_,_,_,_,_,_) => b } + _2 -> C { (_,_,c,_,_,_,_,_,_,_,_) => c } + _3 -> D { (_,_,_,d,_,_,_,_,_,_,_) => d } + _4 -> E { (_,_,_,_,e,_,_,_,_,_,_) => e } + _5 -> F { (_,_,_,_,_,f,_,_,_,_,_) => f } + _6 -> G { (_,_,_,_,_,_,g,_,_,_,_) => g } + _7 -> H { (_,_,_,_,_,_,_,h,_,_,_) => h } + _8 -> I { (_,_,_,_,_,_,_,_,i,_,_) => i } + _9 -> J { (_,_,_,_,_,_,_,_,_,j,_) => j } + _10 -> K { (_,_,_,_,_,_,_,_,_,_,k) => k } +) + +impl_n_tuple!(Tuple12: + _0 -> A { (a,_,_,_,_,_,_,_,_,_,_,_) => a } + _1 -> B { (_,b,_,_,_,_,_,_,_,_,_,_) => b } + _2 -> C { (_,_,c,_,_,_,_,_,_,_,_,_) => c } + _3 -> D { (_,_,_,d,_,_,_,_,_,_,_,_) => d } + _4 -> E { (_,_,_,_,e,_,_,_,_,_,_,_) => e } + _5 -> F { (_,_,_,_,_,f,_,_,_,_,_,_) => f } + _6 -> G { (_,_,_,_,_,_,g,_,_,_,_,_) => g } + _7 -> H { (_,_,_,_,_,_,_,h,_,_,_,_) => h } + _8 -> I { (_,_,_,_,_,_,_,_,i,_,_,_) => i } + _9 -> J { (_,_,_,_,_,_,_,_,_,j,_,_) => j } + _10 -> K { (_,_,_,_,_,_,_,_,_,_,k,_) => k } + _11 -> L { (_,_,_,_,_,_,_,_,_,_,_,l) => l } +) + #[test] fn test_tuple_ref() { let x = (~"foo", ~"bar"); @@ -268,3 +416,20 @@ fn test_clone() { assert!(a.first() == b.first()); assert!(a.second() == b.second()); } + +#[test] +fn test_n_tuple() { + let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); + assert_eq!(t._0(), 0u8); + assert_eq!(t._1(), 1u16); + assert_eq!(t._2(), 2u32); + assert_eq!(t._3(), 3u64); + assert_eq!(t._4(), 4u); + assert_eq!(t._5(), 5i8); + assert_eq!(t._6(), 6i16); + assert_eq!(t._7(), 7i32); + assert_eq!(t._8(), 8i64); + assert_eq!(t._9(), 9i); + assert_eq!(t._10(), 10f32); + assert_eq!(t._11(), 11f64); +} From 96cb0dc8a0804256c8620dfabaa415be99562ccc Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 19:10:12 +1000 Subject: [PATCH 077/248] use n{0..11} instead of _{0..12} for accessor method names --- src/libcore/tuple.rs | 200 +++++++++++++++++++++---------------------- 1 file changed, 100 insertions(+), 100 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 810ef75ad6a31..7c58385948371 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -256,17 +256,17 @@ macro_rules! n_tuple( ) ) -n_tuple!(Tuple2: _0:A, _1:B) -n_tuple!(Tuple3: _0:A, _1:B, _2:C) -n_tuple!(Tuple4: _0:A, _1:B, _2:C, _3:D) -n_tuple!(Tuple5: _0:A, _1:B, _2:C, _3:D, _4:E) -n_tuple!(Tuple6: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F) -n_tuple!(Tuple7: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G) -n_tuple!(Tuple8: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H) -n_tuple!(Tuple9: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I) -n_tuple!(Tuple10: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I, _9:J) -n_tuple!(Tuple11: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I, _9:J, _10:K) -n_tuple!(Tuple12: _0:A, _1:B, _2:C, _3:D, _4:E, _5:F, _6:G, _7:H, _8:I, _9:J, _10:K, _11:L) +n_tuple!(Tuple2: n0:A, n1:B) +n_tuple!(Tuple3: n0:A, n1:B, n2:C) +n_tuple!(Tuple4: n0:A, n1:B, n2:C, n3:D) +n_tuple!(Tuple5: n0:A, n1:B, n2:C, n3:D, n4:E) +n_tuple!(Tuple6: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F) +n_tuple!(Tuple7: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G) +n_tuple!(Tuple8: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H) +n_tuple!(Tuple9: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I) +n_tuple!(Tuple10: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I, n9:J) +n_tuple!(Tuple11: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I, n9:J, n10:K) +n_tuple!(Tuple12: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I, n9:J, n10:K, n11:L) // Tuple element accessor trait implementations @@ -285,113 +285,113 @@ macro_rules! impl_n_tuple( ) impl_n_tuple!(Tuple2: - _0 -> A { (a,_) => a } - _1 -> B { (_,b) => b } + n0 -> A { (a,_) => a } + n1 -> B { (_,b) => b } ) impl_n_tuple!(Tuple3: - _0 -> A { (a,_,_) => a } - _1 -> B { (_,b,_) => b } - _2 -> C { (_,_,c) => c } + n0 -> A { (a,_,_) => a } + n1 -> B { (_,b,_) => b } + n2 -> C { (_,_,c) => c } ) impl_n_tuple!(Tuple4: - _0 -> A { (a,_,_,_) => a } - _1 -> B { (_,b,_,_) => b } - _2 -> C { (_,_,c,_) => c } - _3 -> D { (_,_,_,d) => d } + n0 -> A { (a,_,_,_) => a } + n1 -> B { (_,b,_,_) => b } + n2 -> C { (_,_,c,_) => c } + n3 -> D { (_,_,_,d) => d } ) impl_n_tuple!(Tuple5: - _0 -> A { (a,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_) => b } - _2 -> C { (_,_,c,_,_) => c } - _3 -> D { (_,_,_,d,_) => d } - _4 -> E { (_,_,_,_,e) => e } + n0 -> A { (a,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_) => b } + n2 -> C { (_,_,c,_,_) => c } + n3 -> D { (_,_,_,d,_) => d } + n4 -> E { (_,_,_,_,e) => e } ) impl_n_tuple!(Tuple6: - _0 -> A { (a,_,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_,_) => b } - _2 -> C { (_,_,c,_,_,_) => c } - _3 -> D { (_,_,_,d,_,_) => d } - _4 -> E { (_,_,_,_,e,_) => e } - _5 -> F { (_,_,_,_,_,f) => f } + n0 -> A { (a,_,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_,_) => b } + n2 -> C { (_,_,c,_,_,_) => c } + n3 -> D { (_,_,_,d,_,_) => d } + n4 -> E { (_,_,_,_,e,_) => e } + n5 -> F { (_,_,_,_,_,f) => f } ) impl_n_tuple!(Tuple7: - _0 -> A { (a,_,_,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_,_,_) => b } - _2 -> C { (_,_,c,_,_,_,_) => c } - _3 -> D { (_,_,_,d,_,_,_) => d } - _4 -> E { (_,_,_,_,e,_,_) => e } - _5 -> F { (_,_,_,_,_,f,_) => f } - _6 -> G { (_,_,_,_,_,_,g) => g } + n0 -> A { (a,_,_,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_,_,_) => b } + n2 -> C { (_,_,c,_,_,_,_) => c } + n3 -> D { (_,_,_,d,_,_,_) => d } + n4 -> E { (_,_,_,_,e,_,_) => e } + n5 -> F { (_,_,_,_,_,f,_) => f } + n6 -> G { (_,_,_,_,_,_,g) => g } ) impl_n_tuple!(Tuple8: - _0 -> A { (a,_,_,_,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_,_,_,_) => b } - _2 -> C { (_,_,c,_,_,_,_,_) => c } - _3 -> D { (_,_,_,d,_,_,_,_) => d } - _4 -> E { (_,_,_,_,e,_,_,_) => e } - _5 -> F { (_,_,_,_,_,f,_,_) => f } - _6 -> G { (_,_,_,_,_,_,g,_) => g } - _7 -> H { (_,_,_,_,_,_,_,h) => h } + n0 -> A { (a,_,_,_,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_,_,_,_) => b } + n2 -> C { (_,_,c,_,_,_,_,_) => c } + n3 -> D { (_,_,_,d,_,_,_,_) => d } + n4 -> E { (_,_,_,_,e,_,_,_) => e } + n5 -> F { (_,_,_,_,_,f,_,_) => f } + n6 -> G { (_,_,_,_,_,_,g,_) => g } + n7 -> H { (_,_,_,_,_,_,_,h) => h } ) impl_n_tuple!(Tuple9: - _0 -> A { (a,_,_,_,_,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_,_,_,_,_) => b } - _2 -> C { (_,_,c,_,_,_,_,_,_) => c } - _3 -> D { (_,_,_,d,_,_,_,_,_) => d } - _4 -> E { (_,_,_,_,e,_,_,_,_) => e } - _5 -> F { (_,_,_,_,_,f,_,_,_) => f } - _6 -> G { (_,_,_,_,_,_,g,_,_) => g } - _7 -> H { (_,_,_,_,_,_,_,h,_) => h } - _8 -> I { (_,_,_,_,_,_,_,_,i) => i } + n0 -> A { (a,_,_,_,_,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_,_,_,_,_) => b } + n2 -> C { (_,_,c,_,_,_,_,_,_) => c } + n3 -> D { (_,_,_,d,_,_,_,_,_) => d } + n4 -> E { (_,_,_,_,e,_,_,_,_) => e } + n5 -> F { (_,_,_,_,_,f,_,_,_) => f } + n6 -> G { (_,_,_,_,_,_,g,_,_) => g } + n7 -> H { (_,_,_,_,_,_,_,h,_) => h } + n8 -> I { (_,_,_,_,_,_,_,_,i) => i } ) impl_n_tuple!(Tuple10: - _0 -> A { (a,_,_,_,_,_,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_,_,_,_,_,_) => b } - _2 -> C { (_,_,c,_,_,_,_,_,_,_) => c } - _3 -> D { (_,_,_,d,_,_,_,_,_,_) => d } - _4 -> E { (_,_,_,_,e,_,_,_,_,_) => e } - _5 -> F { (_,_,_,_,_,f,_,_,_,_) => f } - _6 -> G { (_,_,_,_,_,_,g,_,_,_) => g } - _7 -> H { (_,_,_,_,_,_,_,h,_,_) => h } - _8 -> I { (_,_,_,_,_,_,_,_,i,_) => i } - _9 -> J { (_,_,_,_,_,_,_,_,_,j) => j } + n0 -> A { (a,_,_,_,_,_,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_,_,_,_,_,_) => b } + n2 -> C { (_,_,c,_,_,_,_,_,_,_) => c } + n3 -> D { (_,_,_,d,_,_,_,_,_,_) => d } + n4 -> E { (_,_,_,_,e,_,_,_,_,_) => e } + n5 -> F { (_,_,_,_,_,f,_,_,_,_) => f } + n6 -> G { (_,_,_,_,_,_,g,_,_,_) => g } + n7 -> H { (_,_,_,_,_,_,_,h,_,_) => h } + n8 -> I { (_,_,_,_,_,_,_,_,i,_) => i } + n9 -> J { (_,_,_,_,_,_,_,_,_,j) => j } ) impl_n_tuple!(Tuple11: - _0 -> A { (a,_,_,_,_,_,_,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_,_,_,_,_,_,_) => b } - _2 -> C { (_,_,c,_,_,_,_,_,_,_,_) => c } - _3 -> D { (_,_,_,d,_,_,_,_,_,_,_) => d } - _4 -> E { (_,_,_,_,e,_,_,_,_,_,_) => e } - _5 -> F { (_,_,_,_,_,f,_,_,_,_,_) => f } - _6 -> G { (_,_,_,_,_,_,g,_,_,_,_) => g } - _7 -> H { (_,_,_,_,_,_,_,h,_,_,_) => h } - _8 -> I { (_,_,_,_,_,_,_,_,i,_,_) => i } - _9 -> J { (_,_,_,_,_,_,_,_,_,j,_) => j } - _10 -> K { (_,_,_,_,_,_,_,_,_,_,k) => k } + n0 -> A { (a,_,_,_,_,_,_,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_,_,_,_,_,_,_) => b } + n2 -> C { (_,_,c,_,_,_,_,_,_,_,_) => c } + n3 -> D { (_,_,_,d,_,_,_,_,_,_,_) => d } + n4 -> E { (_,_,_,_,e,_,_,_,_,_,_) => e } + n5 -> F { (_,_,_,_,_,f,_,_,_,_,_) => f } + n6 -> G { (_,_,_,_,_,_,g,_,_,_,_) => g } + n7 -> H { (_,_,_,_,_,_,_,h,_,_,_) => h } + n8 -> I { (_,_,_,_,_,_,_,_,i,_,_) => i } + n9 -> J { (_,_,_,_,_,_,_,_,_,j,_) => j } + n10 -> K { (_,_,_,_,_,_,_,_,_,_,k) => k } ) impl_n_tuple!(Tuple12: - _0 -> A { (a,_,_,_,_,_,_,_,_,_,_,_) => a } - _1 -> B { (_,b,_,_,_,_,_,_,_,_,_,_) => b } - _2 -> C { (_,_,c,_,_,_,_,_,_,_,_,_) => c } - _3 -> D { (_,_,_,d,_,_,_,_,_,_,_,_) => d } - _4 -> E { (_,_,_,_,e,_,_,_,_,_,_,_) => e } - _5 -> F { (_,_,_,_,_,f,_,_,_,_,_,_) => f } - _6 -> G { (_,_,_,_,_,_,g,_,_,_,_,_) => g } - _7 -> H { (_,_,_,_,_,_,_,h,_,_,_,_) => h } - _8 -> I { (_,_,_,_,_,_,_,_,i,_,_,_) => i } - _9 -> J { (_,_,_,_,_,_,_,_,_,j,_,_) => j } - _10 -> K { (_,_,_,_,_,_,_,_,_,_,k,_) => k } - _11 -> L { (_,_,_,_,_,_,_,_,_,_,_,l) => l } + n0 -> A { (a,_,_,_,_,_,_,_,_,_,_,_) => a } + n1 -> B { (_,b,_,_,_,_,_,_,_,_,_,_) => b } + n2 -> C { (_,_,c,_,_,_,_,_,_,_,_,_) => c } + n3 -> D { (_,_,_,d,_,_,_,_,_,_,_,_) => d } + n4 -> E { (_,_,_,_,e,_,_,_,_,_,_,_) => e } + n5 -> F { (_,_,_,_,_,f,_,_,_,_,_,_) => f } + n6 -> G { (_,_,_,_,_,_,g,_,_,_,_,_) => g } + n7 -> H { (_,_,_,_,_,_,_,h,_,_,_,_) => h } + n8 -> I { (_,_,_,_,_,_,_,_,i,_,_,_) => i } + n9 -> J { (_,_,_,_,_,_,_,_,_,j,_,_) => j } + n10 -> K { (_,_,_,_,_,_,_,_,_,_,k,_) => k } + n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,l) => l } ) #[test] @@ -420,16 +420,16 @@ fn test_clone() { #[test] fn test_n_tuple() { let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); - assert_eq!(t._0(), 0u8); - assert_eq!(t._1(), 1u16); - assert_eq!(t._2(), 2u32); - assert_eq!(t._3(), 3u64); - assert_eq!(t._4(), 4u); - assert_eq!(t._5(), 5i8); - assert_eq!(t._6(), 6i16); - assert_eq!(t._7(), 7i32); - assert_eq!(t._8(), 8i64); - assert_eq!(t._9(), 9i); - assert_eq!(t._10(), 10f32); - assert_eq!(t._11(), 11f64); + assert_eq!(t.n0(), 0u8); + assert_eq!(t.n1(), 1u16); + assert_eq!(t.n2(), 2u32); + assert_eq!(t.n3(), 3u64); + assert_eq!(t.n4(), 4u); + assert_eq!(t.n5(), 5i8); + assert_eq!(t.n6(), 6i16); + assert_eq!(t.n7(), 7i32); + assert_eq!(t.n8(), 8i64); + assert_eq!(t.n9(), 9i); + assert_eq!(t.n10(), 10f32); + assert_eq!(t.n11(), 11f64); } From c1eb539e124771a3e7618d9879345ea6a6cf3ed9 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 19:10:49 +1000 Subject: [PATCH 078/248] Use assert_eq! instead of assert! --- src/libcore/tuple.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 7c58385948371..334c576ba665b 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -397,24 +397,24 @@ impl_n_tuple!(Tuple12: #[test] fn test_tuple_ref() { let x = (~"foo", ~"bar"); - assert!(x.first_ref() == &~"foo"); - assert!(x.second_ref() == &~"bar"); + assert_eq!(x.first_ref(), &~"foo"); + assert_eq!(x.second_ref(), &~"bar"); } #[test] #[allow(non_implicitly_copyable_typarams)] fn test_tuple() { - assert!((948, 4039.48).first() == 948); - assert!((34.5, ~"foo").second() == ~"foo"); - assert!(('a', 2).swap() == (2, 'a')); + assert_eq!((948, 4039.48).first(), 948); + assert_eq!((34.5, ~"foo").second(), ~"foo"); + assert_eq!(('a', 2).swap(), (2, 'a')); } #[test] fn test_clone() { let a = (1, ~"2"); let b = a.clone(); - assert!(a.first() == b.first()); - assert!(a.second() == b.second()); + assert_eq!(a.first(), b.first()); + assert_eq!(a.second(), b.second()); } #[test] From 5242464d543f0a7e811bcfd7fe8943b62842148a Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 19:43:14 +1000 Subject: [PATCH 079/248] Merge trait and impl macros by using an inner module --- src/libcore/tuple.rs | 253 +++++++++++++++++++++---------------------- 1 file changed, 124 insertions(+), 129 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 334c576ba665b..1dfdb42c30310 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -16,6 +16,8 @@ use vec; #[cfg(not(test))] use cmp::{Eq, Ord}; +pub use self::getters::*; + pub trait CopyableTuple { fn first(&self) -> T; fn second(&self) -> U; @@ -246,152 +248,145 @@ impl Ord for (A, B, C) { fn gt(&self, other: &(A, B, C)) -> bool { (*other).lt(&(*self)) } } -// Tuple element accessor traits +// Tuple element getters -macro_rules! n_tuple( - ($name:ident: $($method:ident : $T:ident),+) => ( - pub trait $name<$($T),+> { - $(fn $method(&self) -> $T;)+ +macro_rules! tuple_getters( + ($( + $name:ident { + $(fn $method:ident -> $T:ident { $accessor:pat => $t:expr })+ } - ) -) - -n_tuple!(Tuple2: n0:A, n1:B) -n_tuple!(Tuple3: n0:A, n1:B, n2:C) -n_tuple!(Tuple4: n0:A, n1:B, n2:C, n3:D) -n_tuple!(Tuple5: n0:A, n1:B, n2:C, n3:D, n4:E) -n_tuple!(Tuple6: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F) -n_tuple!(Tuple7: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G) -n_tuple!(Tuple8: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H) -n_tuple!(Tuple9: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I) -n_tuple!(Tuple10: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I, n9:J) -n_tuple!(Tuple11: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I, n9:J, n10:K) -n_tuple!(Tuple12: n0:A, n1:B, n2:C, n3:D, n4:E, n5:F, n6:G, n7:H, n8:I, n9:J, n10:K, n11:L) - -// Tuple element accessor trait implementations - -macro_rules! impl_n_tuple( - ($name:ident: $($method:ident -> $T:ident { $accessor:pat => $t:expr })+) => ( - impl<$($T:Copy),+> $name<$($T),+> for ($($T),+) { - $( - fn $method(&self) -> $T { - match *self { - $accessor => $t + )+) => ( + pub mod getters { + use kinds::Copy; + + $(pub trait $name<$($T),+> { + $(fn $method(&self) -> $T;)+ + })+ + + $(impl<$($T:Copy),+> $name<$($T),+> for ($($T),+) { + $( + #[inline(always)] + fn $method(&self) -> $T { + match *self { + $accessor => $t + } } - } - )+ + )+ + })+ } ) ) -impl_n_tuple!(Tuple2: - n0 -> A { (a,_) => a } - n1 -> B { (_,b) => b } -) +tuple_getters!( + Tuple2 { + fn n0 -> A { (a,_) => a } + fn n1 -> B { (_,b) => b } + } -impl_n_tuple!(Tuple3: - n0 -> A { (a,_,_) => a } - n1 -> B { (_,b,_) => b } - n2 -> C { (_,_,c) => c } -) + Tuple3 { + fn n0 -> A { (a,_,_) => a } + fn n1 -> B { (_,b,_) => b } + fn n2 -> C { (_,_,c) => c } + } -impl_n_tuple!(Tuple4: - n0 -> A { (a,_,_,_) => a } - n1 -> B { (_,b,_,_) => b } - n2 -> C { (_,_,c,_) => c } - n3 -> D { (_,_,_,d) => d } -) + Tuple4 { + fn n0 -> A { (a,_,_,_) => a } + fn n1 -> B { (_,b,_,_) => b } + fn n2 -> C { (_,_,c,_) => c } + fn n3 -> D { (_,_,_,d) => d } + } -impl_n_tuple!(Tuple5: - n0 -> A { (a,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_) => b } - n2 -> C { (_,_,c,_,_) => c } - n3 -> D { (_,_,_,d,_) => d } - n4 -> E { (_,_,_,_,e) => e } -) + Tuple5 { + fn n0 -> A { (a,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_) => c } + fn n3 -> D { (_,_,_,d,_) => d } + fn n4 -> E { (_,_,_,_,e) => e } + } -impl_n_tuple!(Tuple6: - n0 -> A { (a,_,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_,_) => b } - n2 -> C { (_,_,c,_,_,_) => c } - n3 -> D { (_,_,_,d,_,_) => d } - n4 -> E { (_,_,_,_,e,_) => e } - n5 -> F { (_,_,_,_,_,f) => f } -) + Tuple6 { + fn n0 -> A { (a,_,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_,_) => c } + fn n3 -> D { (_,_,_,d,_,_) => d } + fn n4 -> E { (_,_,_,_,e,_) => e } + fn n5 -> F { (_,_,_,_,_,f) => f } + } -impl_n_tuple!(Tuple7: - n0 -> A { (a,_,_,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_,_,_) => b } - n2 -> C { (_,_,c,_,_,_,_) => c } - n3 -> D { (_,_,_,d,_,_,_) => d } - n4 -> E { (_,_,_,_,e,_,_) => e } - n5 -> F { (_,_,_,_,_,f,_) => f } - n6 -> G { (_,_,_,_,_,_,g) => g } -) + Tuple7 { + fn n0 -> A { (a,_,_,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_,_,_) => c } + fn n3 -> D { (_,_,_,d,_,_,_) => d } + fn n4 -> E { (_,_,_,_,e,_,_) => e } + fn n5 -> F { (_,_,_,_,_,f,_) => f } + fn n6 -> G { (_,_,_,_,_,_,g) => g } + } -impl_n_tuple!(Tuple8: - n0 -> A { (a,_,_,_,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_,_,_,_) => b } - n2 -> C { (_,_,c,_,_,_,_,_) => c } - n3 -> D { (_,_,_,d,_,_,_,_) => d } - n4 -> E { (_,_,_,_,e,_,_,_) => e } - n5 -> F { (_,_,_,_,_,f,_,_) => f } - n6 -> G { (_,_,_,_,_,_,g,_) => g } - n7 -> H { (_,_,_,_,_,_,_,h) => h } -) + Tuple8 { + fn n0 -> A { (a,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,d,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,e,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,f,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,g,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,h) => h } + } -impl_n_tuple!(Tuple9: - n0 -> A { (a,_,_,_,_,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_,_,_,_,_) => b } - n2 -> C { (_,_,c,_,_,_,_,_,_) => c } - n3 -> D { (_,_,_,d,_,_,_,_,_) => d } - n4 -> E { (_,_,_,_,e,_,_,_,_) => e } - n5 -> F { (_,_,_,_,_,f,_,_,_) => f } - n6 -> G { (_,_,_,_,_,_,g,_,_) => g } - n7 -> H { (_,_,_,_,_,_,_,h,_) => h } - n8 -> I { (_,_,_,_,_,_,_,_,i) => i } -) + Tuple9 { + fn n0 -> A { (a,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,d,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,e,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,f,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,g,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,h,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,i) => i } + } -impl_n_tuple!(Tuple10: - n0 -> A { (a,_,_,_,_,_,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_,_,_,_,_,_) => b } - n2 -> C { (_,_,c,_,_,_,_,_,_,_) => c } - n3 -> D { (_,_,_,d,_,_,_,_,_,_) => d } - n4 -> E { (_,_,_,_,e,_,_,_,_,_) => e } - n5 -> F { (_,_,_,_,_,f,_,_,_,_) => f } - n6 -> G { (_,_,_,_,_,_,g,_,_,_) => g } - n7 -> H { (_,_,_,_,_,_,_,h,_,_) => h } - n8 -> I { (_,_,_,_,_,_,_,_,i,_) => i } - n9 -> J { (_,_,_,_,_,_,_,_,_,j) => j } -) + Tuple10 { + fn n0 -> A { (a,_,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,d,_,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,e,_,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,f,_,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,g,_,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,h,_,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,i,_) => i } + fn n9 -> J { (_,_,_,_,_,_,_,_,_,j) => j } + } -impl_n_tuple!(Tuple11: - n0 -> A { (a,_,_,_,_,_,_,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_,_,_,_,_,_,_) => b } - n2 -> C { (_,_,c,_,_,_,_,_,_,_,_) => c } - n3 -> D { (_,_,_,d,_,_,_,_,_,_,_) => d } - n4 -> E { (_,_,_,_,e,_,_,_,_,_,_) => e } - n5 -> F { (_,_,_,_,_,f,_,_,_,_,_) => f } - n6 -> G { (_,_,_,_,_,_,g,_,_,_,_) => g } - n7 -> H { (_,_,_,_,_,_,_,h,_,_,_) => h } - n8 -> I { (_,_,_,_,_,_,_,_,i,_,_) => i } - n9 -> J { (_,_,_,_,_,_,_,_,_,j,_) => j } - n10 -> K { (_,_,_,_,_,_,_,_,_,_,k) => k } -) + Tuple11 { + fn n0 -> A { (a,_,_,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,d,_,_,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,e,_,_,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,f,_,_,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,g,_,_,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,h,_,_,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,i,_,_) => i } + fn n9 -> J { (_,_,_,_,_,_,_,_,_,j,_) => j } + fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,k) => k } + } -impl_n_tuple!(Tuple12: - n0 -> A { (a,_,_,_,_,_,_,_,_,_,_,_) => a } - n1 -> B { (_,b,_,_,_,_,_,_,_,_,_,_) => b } - n2 -> C { (_,_,c,_,_,_,_,_,_,_,_,_) => c } - n3 -> D { (_,_,_,d,_,_,_,_,_,_,_,_) => d } - n4 -> E { (_,_,_,_,e,_,_,_,_,_,_,_) => e } - n5 -> F { (_,_,_,_,_,f,_,_,_,_,_,_) => f } - n6 -> G { (_,_,_,_,_,_,g,_,_,_,_,_) => g } - n7 -> H { (_,_,_,_,_,_,_,h,_,_,_,_) => h } - n8 -> I { (_,_,_,_,_,_,_,_,i,_,_,_) => i } - n9 -> J { (_,_,_,_,_,_,_,_,_,j,_,_) => j } - n10 -> K { (_,_,_,_,_,_,_,_,_,_,k,_) => k } - n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,l) => l } + Tuple12 { + fn n0 -> A { (a,_,_,_,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,b,_,_,_,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,c,_,_,_,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,d,_,_,_,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,e,_,_,_,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,f,_,_,_,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,g,_,_,_,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,h,_,_,_,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,i,_,_,_) => i } + fn n9 -> J { (_,_,_,_,_,_,_,_,_,j,_,_) => j } + fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,k,_) => k } + fn n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,l) => l } + } ) #[test] From 4b13895c2f43024b2b0986d4c2ddcb742926c3c6 Mon Sep 17 00:00:00 2001 From: Olivier Saut Date: Sat, 18 May 2013 11:53:51 +0200 Subject: [PATCH 080/248] Remove trailing whitespaces --- src/libstd/future.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/future.rs b/src/libstd/future.rs index 2ae61293a8fdd..ef9318e8d3de1 100644 --- a/src/libstd/future.rs +++ b/src/libstd/future.rs @@ -16,7 +16,7 @@ * * ~~~ * # fn fib(n: uint) -> uint {42}; - * # fn make_a_sandwich() {}; + * # fn make_a_sandwich() {}; * let mut delayed_fib = std::future::spawn (|| fib(5000) ); * make_a_sandwich(); * println(fmt!("fib(5000) = %?", delayed_fib.get())) From b6038b76339deefc340fa709009a7bea069270e4 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 20:05:40 +1000 Subject: [PATCH 081/248] Return a reference to the tuple elements instead of copying --- src/libcore/tuple.rs | 186 +++++++++++++++++++++---------------------- 1 file changed, 92 insertions(+), 94 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 1dfdb42c30310..c872839146ab0 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -257,16 +257,14 @@ macro_rules! tuple_getters( } )+) => ( pub mod getters { - use kinds::Copy; - $(pub trait $name<$($T),+> { - $(fn $method(&self) -> $T;)+ + $(fn $method<'a>(&'a self) -> &'a $T;)+ })+ - $(impl<$($T:Copy),+> $name<$($T),+> for ($($T),+) { + $(impl<$($T),+> $name<$($T),+> for ($($T),+) { $( #[inline(always)] - fn $method(&self) -> $T { + fn $method<'a>(&'a self) -> &'a $T { match *self { $accessor => $t } @@ -279,113 +277,113 @@ macro_rules! tuple_getters( tuple_getters!( Tuple2 { - fn n0 -> A { (a,_) => a } - fn n1 -> B { (_,b) => b } + fn n0 -> A { (ref a,_) => a } + fn n1 -> B { (_,ref b) => b } } Tuple3 { - fn n0 -> A { (a,_,_) => a } - fn n1 -> B { (_,b,_) => b } - fn n2 -> C { (_,_,c) => c } + fn n0 -> A { (ref a,_,_) => a } + fn n1 -> B { (_,ref b,_) => b } + fn n2 -> C { (_,_,ref c) => c } } Tuple4 { - fn n0 -> A { (a,_,_,_) => a } - fn n1 -> B { (_,b,_,_) => b } - fn n2 -> C { (_,_,c,_) => c } - fn n3 -> D { (_,_,_,d) => d } + fn n0 -> A { (ref a,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_) => b } + fn n2 -> C { (_,_,ref c,_) => c } + fn n3 -> D { (_,_,_,ref d) => d } } Tuple5 { - fn n0 -> A { (a,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_) => c } - fn n3 -> D { (_,_,_,d,_) => d } - fn n4 -> E { (_,_,_,_,e) => e } + fn n0 -> A { (ref a,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_) => d } + fn n4 -> E { (_,_,_,_,ref e) => e } } Tuple6 { - fn n0 -> A { (a,_,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_,_) => c } - fn n3 -> D { (_,_,_,d,_,_) => d } - fn n4 -> E { (_,_,_,_,e,_) => e } - fn n5 -> F { (_,_,_,_,_,f) => f } + fn n0 -> A { (ref a,_,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_,_) => d } + fn n4 -> E { (_,_,_,_,ref e,_) => e } + fn n5 -> F { (_,_,_,_,_,ref f) => f } } Tuple7 { - fn n0 -> A { (a,_,_,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_,_,_) => c } - fn n3 -> D { (_,_,_,d,_,_,_) => d } - fn n4 -> E { (_,_,_,_,e,_,_) => e } - fn n5 -> F { (_,_,_,_,_,f,_) => f } - fn n6 -> G { (_,_,_,_,_,_,g) => g } + fn n0 -> A { (ref a,_,_,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_,_,_) => d } + fn n4 -> E { (_,_,_,_,ref e,_,_) => e } + fn n5 -> F { (_,_,_,_,_,ref f,_) => f } + fn n6 -> G { (_,_,_,_,_,_,ref g) => g } } Tuple8 { - fn n0 -> A { (a,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,d,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,e,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,f,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,g,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,h) => h } + fn n0 -> A { (ref a,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,ref e,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,ref f,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,ref g,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,ref h) => h } } Tuple9 { - fn n0 -> A { (a,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,d,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,e,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,f,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,g,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,h,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,i) => i } + fn n0 -> A { (ref a,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,ref e,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,ref f,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,ref g,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,ref h,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,ref i) => i } } Tuple10 { - fn n0 -> A { (a,_,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,d,_,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,e,_,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,f,_,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,g,_,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,h,_,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,i,_) => i } - fn n9 -> J { (_,_,_,_,_,_,_,_,_,j) => j } + fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_) => i } + fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j) => j } } Tuple11 { - fn n0 -> A { (a,_,_,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,d,_,_,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,e,_,_,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,f,_,_,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,g,_,_,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,h,_,_,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,i,_,_) => i } - fn n9 -> J { (_,_,_,_,_,_,_,_,_,j,_) => j } - fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,k) => k } + fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_) => i } + fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_) => j } + fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k) => k } } Tuple12 { - fn n0 -> A { (a,_,_,_,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,b,_,_,_,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,c,_,_,_,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,d,_,_,_,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,e,_,_,_,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,f,_,_,_,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,g,_,_,_,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,h,_,_,_,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,i,_,_,_) => i } - fn n9 -> J { (_,_,_,_,_,_,_,_,_,j,_,_) => j } - fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,k,_) => k } - fn n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,l) => l } + fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_,_) => a } + fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_,_) => b } + fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_,_) => c } + fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_,_) => d } + fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_,_) => e } + fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_,_) => f } + fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_,_) => g } + fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_,_) => h } + fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_,_) => i } + fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_,_) => j } + fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k,_) => k } + fn n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,ref l) => l } } ) @@ -415,16 +413,16 @@ fn test_clone() { #[test] fn test_n_tuple() { let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); - assert_eq!(t.n0(), 0u8); - assert_eq!(t.n1(), 1u16); - assert_eq!(t.n2(), 2u32); - assert_eq!(t.n3(), 3u64); - assert_eq!(t.n4(), 4u); - assert_eq!(t.n5(), 5i8); - assert_eq!(t.n6(), 6i16); - assert_eq!(t.n7(), 7i32); - assert_eq!(t.n8(), 8i64); - assert_eq!(t.n9(), 9i); - assert_eq!(t.n10(), 10f32); - assert_eq!(t.n11(), 11f64); + assert_eq!(*t.n0(), 0u8); + assert_eq!(*t.n1(), 1u16); + assert_eq!(*t.n2(), 2u32); + assert_eq!(*t.n3(), 3u64); + assert_eq!(*t.n4(), 4u); + assert_eq!(*t.n5(), 5i8); + assert_eq!(*t.n6(), 6i16); + assert_eq!(*t.n7(), 7i32); + assert_eq!(*t.n8(), 8i64); + assert_eq!(*t.n9(), 9i); + assert_eq!(*t.n10(), 10f32); + assert_eq!(*t.n11(), 11f64); } From ce1e211eeb607fdc131cedc764ccb7d824b28b70 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 21:38:06 +1000 Subject: [PATCH 082/248] Adapt the getter macro to implement Clone, Eq and Ord for n-ary tuples --- src/libcore/tuple.rs | 200 ++++++++++++------------------------------- 1 file changed, 55 insertions(+), 145 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index c872839146ab0..27632acf4e8f3 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -10,13 +10,10 @@ //! Operations on tuples -use clone::Clone; use kinds::Copy; use vec; -#[cfg(not(test))] use cmp::{Eq, Ord}; - -pub use self::getters::*; +pub use self::inner::*; pub trait CopyableTuple { fn first(&self) -> T; @@ -46,16 +43,6 @@ impl CopyableTuple for (T, U) { let (t, u) = *self; return (u, t); } - -} - -impl Clone for (T, U) { - fn clone(&self) -> (T, U) { - let (a, b) = match *self { - (ref a, ref b) => (a, b) - }; - (a.clone(), b.clone()) - } } pub trait ImmutableTuple { @@ -124,158 +111,81 @@ impl ExtendedTupleOps for (~[A], ~[B]) { } } -#[cfg(not(test))] -impl Eq for (A,) { - #[inline(always)] - fn eq(&self, other: &(A,)) -> bool { - match (*self) { - (ref self_a,) => match other { - &(ref other_a,) => { - (*self_a).eq(other_a) - } - } +// macro for implementing n-ary tuple functions and operations + +macro_rules! tuple_impls( + ($( + $name:ident { + $(fn $get_fn:ident -> $T:ident { $get_pattern:pat => $ret:expr })+ } - } - #[inline(always)] - fn ne(&self, other: &(A,)) -> bool { !(*self).eq(other) } -} + )+) => ( + pub mod inner { + use clone::Clone; + #[cfg(not(test))] use cmp::{Eq, Ord}; -#[cfg(not(test))] -impl Ord for (A,) { - #[inline(always)] - fn lt(&self, other: &(A,)) -> bool { - match (*self) { - (ref self_a,) => { - match (*other) { - (ref other_a,) => { - if (*self_a).lt(other_a) { return true; } - return false; - } + $( + pub trait $name<$($T),+> { + $(fn $get_fn<'a>(&'a self) -> &'a $T;)+ } - } - } - } - #[inline(always)] - fn le(&self, other: &(A,)) -> bool { !other.lt(&(*self)) } - #[inline(always)] - fn ge(&self, other: &(A,)) -> bool { !self.lt(other) } - #[inline(always)] - fn gt(&self, other: &(A,)) -> bool { other.lt(&(*self)) } -} -#[cfg(not(test))] -impl Eq for (A, B) { - #[inline(always)] - fn eq(&self, other: &(A, B)) -> bool { - match (*self) { - (ref self_a, ref self_b) => match other { - &(ref other_a, ref other_b) => { - (*self_a).eq(other_a) && (*self_b).eq(other_b) + impl<$($T),+> $name<$($T),+> for ($($T),+) { + $( + #[inline(always)] + fn $get_fn<'a>(&'a self) -> &'a $T { + match *self { + $get_pattern => $ret + } + } + )+ } - } - } - } - #[inline(always)] - fn ne(&self, other: &(A, B)) -> bool { !(*self).eq(other) } -} -#[cfg(not(test))] -impl Ord for (A, B) { - #[inline(always)] - fn lt(&self, other: &(A, B)) -> bool { - match (*self) { - (ref self_a, ref self_b) => { - match (*other) { - (ref other_a, ref other_b) => { - if (*self_a).lt(other_a) { return true; } - if (*other_a).lt(self_a) { return false; } - if (*self_b).lt(other_b) { return true; } - return false; + impl<$($T:Clone),+> Clone for ($($T),+) { + fn clone(&self) -> ($($T),+) { + ($(self.$get_fn().clone()),+) } } - } - } - } - #[inline(always)] - fn le(&self, other: &(A, B)) -> bool { !(*other).lt(&(*self)) } - #[inline(always)] - fn ge(&self, other: &(A, B)) -> bool { !(*self).lt(other) } - #[inline(always)] - fn gt(&self, other: &(A, B)) -> bool { (*other).lt(&(*self)) } -} -#[cfg(not(test))] -impl Eq for (A, B, C) { - #[inline(always)] - fn eq(&self, other: &(A, B, C)) -> bool { - match (*self) { - (ref self_a, ref self_b, ref self_c) => match other { - &(ref other_a, ref other_b, ref other_c) => { - (*self_a).eq(other_a) && (*self_b).eq(other_b) - && (*self_c).eq(other_c) - } - } - } - } - #[inline(always)] - fn ne(&self, other: &(A, B, C)) -> bool { !(*self).eq(other) } -} + #[cfg(not(test))] + impl<$($T:Eq),+> Eq for ($($T),+) { + #[inline(always)] + fn eq(&self, other: &($($T),+)) -> bool { + $(*self.$get_fn() == *other.$get_fn())&&+ + } -#[cfg(not(test))] -impl Ord for (A, B, C) { - #[inline(always)] - fn lt(&self, other: &(A, B, C)) -> bool { - match (*self) { - (ref self_a, ref self_b, ref self_c) => { - match (*other) { - (ref other_a, ref other_b, ref other_c) => { - if (*self_a).lt(other_a) { return true; } - if (*other_a).lt(self_a) { return false; } - if (*self_b).lt(other_b) { return true; } - if (*other_b).lt(self_b) { return false; } - if (*self_c).lt(other_c) { return true; } - return false; + #[inline(always)] + fn ne(&self, other: &($($T),+)) -> bool { + !(*self == *other) } } - } - } - } - #[inline(always)] - fn le(&self, other: &(A, B, C)) -> bool { !(*other).lt(&(*self)) } - #[inline(always)] - fn ge(&self, other: &(A, B, C)) -> bool { !(*self).lt(other) } - #[inline(always)] - fn gt(&self, other: &(A, B, C)) -> bool { (*other).lt(&(*self)) } -} -// Tuple element getters + #[cfg(not(test))] + impl<$($T:Ord),+> Ord for ($($T),+) { + #[inline(always)] + fn lt(&self, other: &($($T),+)) -> bool { + $(*self.$get_fn() < *other.$get_fn())&&+ + } -macro_rules! tuple_getters( - ($( - $name:ident { - $(fn $method:ident -> $T:ident { $accessor:pat => $t:expr })+ - } - )+) => ( - pub mod getters { - $(pub trait $name<$($T),+> { - $(fn $method<'a>(&'a self) -> &'a $T;)+ - })+ + #[inline(always)] + fn le(&self, other: &($($T),+)) -> bool { + $(*self.$get_fn() <= *other.$get_fn())&&+ + } - $(impl<$($T),+> $name<$($T),+> for ($($T),+) { - $( #[inline(always)] - fn $method<'a>(&'a self) -> &'a $T { - match *self { - $accessor => $t - } + fn ge(&self, other: &($($T),+)) -> bool { + $(*self.$get_fn() >= *other.$get_fn())&&+ } - )+ - })+ + + #[inline(always)] + fn gt(&self, other: &($($T),+)) -> bool { + $(*self.$get_fn() > *other.$get_fn())&&+ + } + } + )+ } ) ) -tuple_getters!( +tuple_impls!( Tuple2 { fn n0 -> A { (ref a,_) => a } fn n1 -> B { (_,ref b) => b } From ee4d11f37ea3f1bff8103c0e6b369a972f4b1bf2 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 22:18:23 +1000 Subject: [PATCH 083/248] Use match instead of intermediate variable --- src/libcore/tuple.rs | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 27632acf4e8f3..d5187c55730f1 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -22,26 +22,28 @@ pub trait CopyableTuple { } impl CopyableTuple for (T, U) { - /// Return the first element of self #[inline(always)] fn first(&self) -> T { - let (t, _) = *self; - return t; + match *self { + (t, _) => t, + } } /// Return the second element of self #[inline(always)] fn second(&self) -> U { - let (_, u) = *self; - return u; + match *self { + (_, u) => u, + } } /// Return the results of swapping the two elements of self #[inline(always)] fn swap(&self) -> (U, T) { - let (t, u) = *self; - return (u, t); + match *self { + (t, u) => (u, t), + } } } From db453ec0e507382b4ac1bb9eae4654957b8a7e76 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sat, 18 May 2013 22:46:02 +1000 Subject: [PATCH 084/248] Replace Tuple{2..12} trait with CloneableTuple{2..12} and ImmutableTuple{2..12} Make n{0..11} methods return cloned values, and create n{0..12}_ref methods for returning references --- src/libcore/prelude.rs | 8 +- src/libcore/tuple.rs | 257 ++++++++++++++++++++++------------------- 2 files changed, 147 insertions(+), 118 deletions(-) diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index 77371b6336848..684c4c7a27178 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -52,8 +52,12 @@ pub use from_str::{FromStr}; pub use to_bytes::IterBytes; pub use to_str::{ToStr, ToStrConsume}; pub use tuple::{CopyableTuple, ImmutableTuple, ExtendedTupleOps}; -pub use tuple::{Tuple2, Tuple3, Tuple4, Tuple5, Tuple6, Tuple7, Tuple8, Tuple9}; -pub use tuple::{Tuple10, Tuple11, Tuple12}; +pub use tuple::{CloneableTuple2, CloneableTuple3, CloneableTuple4, CloneableTuple5}; +pub use tuple::{CloneableTuple6, CloneableTuple7, CloneableTuple8, CloneableTuple9}; +pub use tuple::{CloneableTuple10, CloneableTuple11, CloneableTuple12}; +pub use tuple::{ImmutableTuple2, ImmutableTuple3, ImmutableTuple4, ImmutableTuple5}; +pub use tuple::{ImmutableTuple6, ImmutableTuple7, ImmutableTuple8, ImmutableTuple9}; +pub use tuple::{ImmutableTuple10, ImmutableTuple11, ImmutableTuple12}; pub use vec::{CopyableVector, ImmutableVector}; pub use vec::{ImmutableEqVector, ImmutableCopyableVector}; pub use vec::{OwnedVector, OwnedCopyableVector, MutableVector}; diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index d5187c55730f1..dd42afe646ddc 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -93,7 +93,6 @@ impl<'self,A:Copy,B:Copy> ExtendedTupleOps for (&'self [A], &'self [B]) { } impl ExtendedTupleOps for (~[A], ~[B]) { - #[inline(always)] fn zip(&self) -> ~[(A, B)] { match *self { @@ -117,8 +116,10 @@ impl ExtendedTupleOps for (~[A], ~[B]) { macro_rules! tuple_impls( ($( - $name:ident { - $(fn $get_fn:ident -> $T:ident { $get_pattern:pat => $ret:expr })+ + ($cloneable_trait:ident, $immutable_trait:ident) { + $(($get_fn:ident, $get_ref_fn:ident) -> $T:ident { + $get_pattern:pat => $ret:expr + })+ } )+) => ( pub mod inner { @@ -126,24 +127,35 @@ macro_rules! tuple_impls( #[cfg(not(test))] use cmp::{Eq, Ord}; $( - pub trait $name<$($T),+> { - $(fn $get_fn<'a>(&'a self) -> &'a $T;)+ + pub trait $cloneable_trait<$($T),+> { + $(fn $get_fn(&self) -> $T;)+ + } + + impl<$($T:Clone),+> $cloneable_trait<$($T),+> for ($($T),+) { + $( + #[inline(always)] + fn $get_fn(&self) -> $T { + self.$get_ref_fn().clone() + } + )+ + } + + pub trait $immutable_trait<$($T),+> { + $(fn $get_ref_fn<'a>(&'a self) -> &'a $T;)+ } - impl<$($T),+> $name<$($T),+> for ($($T),+) { + impl<$($T),+> $immutable_trait<$($T),+> for ($($T),+) { $( #[inline(always)] - fn $get_fn<'a>(&'a self) -> &'a $T { - match *self { - $get_pattern => $ret - } + fn $get_ref_fn<'a>(&'a self) -> &'a $T { + match *self { $get_pattern => $ret } } )+ } impl<$($T:Clone),+> Clone for ($($T),+) { fn clone(&self) -> ($($T),+) { - ($(self.$get_fn().clone()),+) + ($(self.$get_ref_fn().clone()),+) } } @@ -151,7 +163,7 @@ macro_rules! tuple_impls( impl<$($T:Eq),+> Eq for ($($T),+) { #[inline(always)] fn eq(&self, other: &($($T),+)) -> bool { - $(*self.$get_fn() == *other.$get_fn())&&+ + $(*self.$get_ref_fn() == *other.$get_ref_fn())&&+ } #[inline(always)] @@ -164,22 +176,22 @@ macro_rules! tuple_impls( impl<$($T:Ord),+> Ord for ($($T),+) { #[inline(always)] fn lt(&self, other: &($($T),+)) -> bool { - $(*self.$get_fn() < *other.$get_fn())&&+ + $(*self.$get_ref_fn() < *other.$get_ref_fn())&&+ } #[inline(always)] fn le(&self, other: &($($T),+)) -> bool { - $(*self.$get_fn() <= *other.$get_fn())&&+ + $(*self.$get_ref_fn() <= *other.$get_ref_fn())&&+ } #[inline(always)] fn ge(&self, other: &($($T),+)) -> bool { - $(*self.$get_fn() >= *other.$get_fn())&&+ + $(*self.$get_ref_fn() >= *other.$get_ref_fn())&&+ } #[inline(always)] fn gt(&self, other: &($($T),+)) -> bool { - $(*self.$get_fn() > *other.$get_fn())&&+ + $(*self.$get_ref_fn() > *other.$get_ref_fn())&&+ } } )+ @@ -188,114 +200,114 @@ macro_rules! tuple_impls( ) tuple_impls!( - Tuple2 { - fn n0 -> A { (ref a,_) => a } - fn n1 -> B { (_,ref b) => b } + (CloneableTuple2, ImmutableTuple2) { + (n0, n0_ref) -> A { (ref a,_) => a } + (n1, n1_ref) -> B { (_,ref b) => b } } - Tuple3 { - fn n0 -> A { (ref a,_,_) => a } - fn n1 -> B { (_,ref b,_) => b } - fn n2 -> C { (_,_,ref c) => c } + (CloneableTuple3, ImmutableTuple3) { + (n0, n0_ref) -> A { (ref a,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_) => b } + (n2, n2_ref) -> C { (_,_,ref c) => c } } - Tuple4 { - fn n0 -> A { (ref a,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_) => b } - fn n2 -> C { (_,_,ref c,_) => c } - fn n3 -> D { (_,_,_,ref d) => d } + (CloneableTuple4, ImmutableTuple4) { + (n0, n0_ref) -> A { (ref a,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d) => d } } - Tuple5 { - fn n0 -> A { (ref a,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_) => d } - fn n4 -> E { (_,_,_,_,ref e) => e } + (CloneableTuple5, ImmutableTuple5) { + (n0, n0_ref) -> A { (ref a,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e) => e } } - Tuple6 { - fn n0 -> A { (ref a,_,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_,_) => d } - fn n4 -> E { (_,_,_,_,ref e,_) => e } - fn n5 -> F { (_,_,_,_,_,ref f) => f } + (CloneableTuple6, ImmutableTuple6) { + (n0, n0_ref) -> A { (ref a,_,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e,_) => e } + (n5, n5_ref) -> F { (_,_,_,_,_,ref f) => f } } - Tuple7 { - fn n0 -> A { (ref a,_,_,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_,_,_) => d } - fn n4 -> E { (_,_,_,_,ref e,_,_) => e } - fn n5 -> F { (_,_,_,_,_,ref f,_) => f } - fn n6 -> G { (_,_,_,_,_,_,ref g) => g } + (CloneableTuple7, ImmutableTuple7) { + (n0, n0_ref) -> A { (ref a,_,_,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_,_,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e,_,_) => e } + (n5, n5_ref) -> F { (_,_,_,_,_,ref f,_) => f } + (n6, n6_ref) -> G { (_,_,_,_,_,_,ref g) => g } } - Tuple8 { - fn n0 -> A { (ref a,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,ref e,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,ref f,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,ref g,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,ref h) => h } + (CloneableTuple8, ImmutableTuple8) { + (n0, n0_ref) -> A { (ref a,_,_,_,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_,_,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_,_,_,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e,_,_,_) => e } + (n5, n5_ref) -> F { (_,_,_,_,_,ref f,_,_) => f } + (n6, n6_ref) -> G { (_,_,_,_,_,_,ref g,_) => g } + (n7, n7_ref) -> H { (_,_,_,_,_,_,_,ref h) => h } } - Tuple9 { - fn n0 -> A { (ref a,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,ref e,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,ref f,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,ref g,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,ref h,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,ref i) => i } + (CloneableTuple9, ImmutableTuple9) { + (n0, n0_ref) -> A { (ref a,_,_,_,_,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_,_,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_,_,_,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_,_,_,_,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e,_,_,_,_) => e } + (n5, n5_ref) -> F { (_,_,_,_,_,ref f,_,_,_) => f } + (n6, n6_ref) -> G { (_,_,_,_,_,_,ref g,_,_) => g } + (n7, n7_ref) -> H { (_,_,_,_,_,_,_,ref h,_) => h } + (n8, n8_ref) -> I { (_,_,_,_,_,_,_,_,ref i) => i } } - Tuple10 { - fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_) => i } - fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j) => j } + (CloneableTuple10, ImmutableTuple10) { + (n0, n0_ref) -> A { (ref a,_,_,_,_,_,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_,_,_,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_,_,_,_,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_,_,_,_,_,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e,_,_,_,_,_) => e } + (n5, n5_ref) -> F { (_,_,_,_,_,ref f,_,_,_,_) => f } + (n6, n6_ref) -> G { (_,_,_,_,_,_,ref g,_,_,_) => g } + (n7, n7_ref) -> H { (_,_,_,_,_,_,_,ref h,_,_) => h } + (n8, n8_ref) -> I { (_,_,_,_,_,_,_,_,ref i,_) => i } + (n9, n9_ref) -> J { (_,_,_,_,_,_,_,_,_,ref j) => j } } - Tuple11 { - fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_) => i } - fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_) => j } - fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k) => k } + (CloneableTuple11, ImmutableTuple11) { + (n0, n0_ref) -> A { (ref a,_,_,_,_,_,_,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_,_,_,_,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_,_,_,_,_,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_,_,_,_,_,_,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e,_,_,_,_,_,_) => e } + (n5, n5_ref) -> F { (_,_,_,_,_,ref f,_,_,_,_,_) => f } + (n6, n6_ref) -> G { (_,_,_,_,_,_,ref g,_,_,_,_) => g } + (n7, n7_ref) -> H { (_,_,_,_,_,_,_,ref h,_,_,_) => h } + (n8, n8_ref) -> I { (_,_,_,_,_,_,_,_,ref i,_,_) => i } + (n9, n9_ref) -> J { (_,_,_,_,_,_,_,_,_,ref j,_) => j } + (n10, n10_ref) -> K { (_,_,_,_,_,_,_,_,_,_,ref k) => k } } - Tuple12 { - fn n0 -> A { (ref a,_,_,_,_,_,_,_,_,_,_,_) => a } - fn n1 -> B { (_,ref b,_,_,_,_,_,_,_,_,_,_) => b } - fn n2 -> C { (_,_,ref c,_,_,_,_,_,_,_,_,_) => c } - fn n3 -> D { (_,_,_,ref d,_,_,_,_,_,_,_,_) => d } - fn n4 -> E { (_,_,_,_,ref e,_,_,_,_,_,_,_) => e } - fn n5 -> F { (_,_,_,_,_,ref f,_,_,_,_,_,_) => f } - fn n6 -> G { (_,_,_,_,_,_,ref g,_,_,_,_,_) => g } - fn n7 -> H { (_,_,_,_,_,_,_,ref h,_,_,_,_) => h } - fn n8 -> I { (_,_,_,_,_,_,_,_,ref i,_,_,_) => i } - fn n9 -> J { (_,_,_,_,_,_,_,_,_,ref j,_,_) => j } - fn n10 -> K { (_,_,_,_,_,_,_,_,_,_,ref k,_) => k } - fn n11 -> L { (_,_,_,_,_,_,_,_,_,_,_,ref l) => l } + (CloneableTuple12, ImmutableTuple12) { + (n0, n0_ref) -> A { (ref a,_,_,_,_,_,_,_,_,_,_,_) => a } + (n1, n1_ref) -> B { (_,ref b,_,_,_,_,_,_,_,_,_,_) => b } + (n2, n2_ref) -> C { (_,_,ref c,_,_,_,_,_,_,_,_,_) => c } + (n3, n3_ref) -> D { (_,_,_,ref d,_,_,_,_,_,_,_,_) => d } + (n4, n4_ref) -> E { (_,_,_,_,ref e,_,_,_,_,_,_,_) => e } + (n5, n5_ref) -> F { (_,_,_,_,_,ref f,_,_,_,_,_,_) => f } + (n6, n6_ref) -> G { (_,_,_,_,_,_,ref g,_,_,_,_,_) => g } + (n7, n7_ref) -> H { (_,_,_,_,_,_,_,ref h,_,_,_,_) => h } + (n8, n8_ref) -> I { (_,_,_,_,_,_,_,_,ref i,_,_,_) => i } + (n9, n9_ref) -> J { (_,_,_,_,_,_,_,_,_,ref j,_,_) => j } + (n10, n10_ref) -> K { (_,_,_,_,_,_,_,_,_,_,ref k,_) => k } + (n11, n11_ref) -> L { (_,_,_,_,_,_,_,_,_,_,_,ref l) => l } } ) @@ -325,16 +337,29 @@ fn test_clone() { #[test] fn test_n_tuple() { let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); - assert_eq!(*t.n0(), 0u8); - assert_eq!(*t.n1(), 1u16); - assert_eq!(*t.n2(), 2u32); - assert_eq!(*t.n3(), 3u64); - assert_eq!(*t.n4(), 4u); - assert_eq!(*t.n5(), 5i8); - assert_eq!(*t.n6(), 6i16); - assert_eq!(*t.n7(), 7i32); - assert_eq!(*t.n8(), 8i64); - assert_eq!(*t.n9(), 9i); - assert_eq!(*t.n10(), 10f32); - assert_eq!(*t.n11(), 11f64); + assert_eq!(t.n0(), 0u8); + assert_eq!(t.n1(), 1u16); + assert_eq!(t.n2(), 2u32); + assert_eq!(t.n3(), 3u64); + assert_eq!(t.n4(), 4u); + assert_eq!(t.n5(), 5i8); + assert_eq!(t.n6(), 6i16); + assert_eq!(t.n7(), 7i32); + assert_eq!(t.n8(), 8i64); + assert_eq!(t.n9(), 9i); + assert_eq!(t.n10(), 10f32); + assert_eq!(t.n11(), 11f64); + + assert_eq!(t.n0_ref(), &0u8); + assert_eq!(t.n1_ref(), &1u16); + assert_eq!(t.n2_ref(), &2u32); + assert_eq!(t.n3_ref(), &3u64); + assert_eq!(t.n4_ref(), &4u); + assert_eq!(t.n5_ref(), &5i8); + assert_eq!(t.n6_ref(), &6i16); + assert_eq!(t.n7_ref(), &7i32); + assert_eq!(t.n8_ref(), &8i64); + assert_eq!(t.n9_ref(), &9i); + assert_eq!(t.n10_ref(), &10f32); + assert_eq!(t.n11_ref(), &11f64); } From d9eec664fd812dda88c349d092f327c9be8a7558 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sun, 19 May 2013 01:11:50 +1000 Subject: [PATCH 085/248] Fix Ord implementation to use lexical ordering --- src/libcore/tuple.rs | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index dd42afe646ddc..b07bb2bb1e6a5 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -165,7 +165,6 @@ macro_rules! tuple_impls( fn eq(&self, other: &($($T),+)) -> bool { $(*self.$get_ref_fn() == *other.$get_ref_fn())&&+ } - #[inline(always)] fn ne(&self, other: &($($T),+)) -> bool { !(*self == *other) @@ -176,29 +175,30 @@ macro_rules! tuple_impls( impl<$($T:Ord),+> Ord for ($($T),+) { #[inline(always)] fn lt(&self, other: &($($T),+)) -> bool { - $(*self.$get_ref_fn() < *other.$get_ref_fn())&&+ + lexical_lt!($(*self.$get_ref_fn(), *other.$get_ref_fn()),+) } - #[inline(always)] - fn le(&self, other: &($($T),+)) -> bool { - $(*self.$get_ref_fn() <= *other.$get_ref_fn())&&+ - } - + fn le(&self, other: &($($T),+)) -> bool { !(*other).lt(&(*self)) } #[inline(always)] - fn ge(&self, other: &($($T),+)) -> bool { - $(*self.$get_ref_fn() >= *other.$get_ref_fn())&&+ - } - + fn ge(&self, other: &($($T),+)) -> bool { !(*self).lt(other) } #[inline(always)] - fn gt(&self, other: &($($T),+)) -> bool { - $(*self.$get_ref_fn() > *other.$get_ref_fn())&&+ - } + fn gt(&self, other: &($($T),+)) -> bool { (*other).lt(&(*self)) } } )+ } ) ) +// Constructs an expression that performs a lexical less-than ordering. +// The values are interleaved, so the macro invocation for +// `(a1, a2, a3) < (b1, b2, b3)` would be `lexical_lt!(a1, b1, a2, b2, a3, b3)` +macro_rules! lexical_lt( + ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => ( + if $a < $b { true } else { lexical_lt!($($rest_a, $rest_b),+) } + ); + ($a:expr, $b:expr) => ($a < $b); +) + tuple_impls!( (CloneableTuple2, ImmutableTuple2) { (n0, n0_ref) -> A { (ref a,_) => a } From 7103c39dbb32f5bc1452f8abaa3de5d68b47053b Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sun, 19 May 2013 02:23:52 +1000 Subject: [PATCH 086/248] Move tuple tests into submodule --- src/libcore/tuple.rs | 102 +++++++++++++++++++++++-------------------- 1 file changed, 54 insertions(+), 48 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index b07bb2bb1e6a5..e8796147ef8f6 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -311,55 +311,61 @@ tuple_impls!( } ) -#[test] -fn test_tuple_ref() { - let x = (~"foo", ~"bar"); - assert_eq!(x.first_ref(), &~"foo"); - assert_eq!(x.second_ref(), &~"bar"); -} +#[cfg(test)] +mod tests { + use super::*; + use clone::Clone; + + #[test] + fn test_tuple_ref() { + let x = (~"foo", ~"bar"); + assert_eq!(x.first_ref(), &~"foo"); + assert_eq!(x.second_ref(), &~"bar"); + } -#[test] -#[allow(non_implicitly_copyable_typarams)] -fn test_tuple() { - assert_eq!((948, 4039.48).first(), 948); - assert_eq!((34.5, ~"foo").second(), ~"foo"); - assert_eq!(('a', 2).swap(), (2, 'a')); -} + #[test] + #[allow(non_implicitly_copyable_typarams)] + fn test_tuple() { + assert_eq!((948, 4039.48).first(), 948); + assert_eq!((34.5, ~"foo").second(), ~"foo"); + assert_eq!(('a', 2).swap(), (2, 'a')); + } -#[test] -fn test_clone() { - let a = (1, ~"2"); - let b = a.clone(); - assert_eq!(a.first(), b.first()); - assert_eq!(a.second(), b.second()); -} + #[test] + fn test_clone() { + let a = (1, ~"2"); + let b = a.clone(); + assert_eq!(a.first(), b.first()); + assert_eq!(a.second(), b.second()); + } -#[test] -fn test_n_tuple() { - let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); - assert_eq!(t.n0(), 0u8); - assert_eq!(t.n1(), 1u16); - assert_eq!(t.n2(), 2u32); - assert_eq!(t.n3(), 3u64); - assert_eq!(t.n4(), 4u); - assert_eq!(t.n5(), 5i8); - assert_eq!(t.n6(), 6i16); - assert_eq!(t.n7(), 7i32); - assert_eq!(t.n8(), 8i64); - assert_eq!(t.n9(), 9i); - assert_eq!(t.n10(), 10f32); - assert_eq!(t.n11(), 11f64); - - assert_eq!(t.n0_ref(), &0u8); - assert_eq!(t.n1_ref(), &1u16); - assert_eq!(t.n2_ref(), &2u32); - assert_eq!(t.n3_ref(), &3u64); - assert_eq!(t.n4_ref(), &4u); - assert_eq!(t.n5_ref(), &5i8); - assert_eq!(t.n6_ref(), &6i16); - assert_eq!(t.n7_ref(), &7i32); - assert_eq!(t.n8_ref(), &8i64); - assert_eq!(t.n9_ref(), &9i); - assert_eq!(t.n10_ref(), &10f32); - assert_eq!(t.n11_ref(), &11f64); + #[test] + fn test_n_tuple() { + let t = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); + assert_eq!(t.n0(), 0u8); + assert_eq!(t.n1(), 1u16); + assert_eq!(t.n2(), 2u32); + assert_eq!(t.n3(), 3u64); + assert_eq!(t.n4(), 4u); + assert_eq!(t.n5(), 5i8); + assert_eq!(t.n6(), 6i16); + assert_eq!(t.n7(), 7i32); + assert_eq!(t.n8(), 8i64); + assert_eq!(t.n9(), 9i); + assert_eq!(t.n10(), 10f32); + assert_eq!(t.n11(), 11f64); + + assert_eq!(t.n0_ref(), &0u8); + assert_eq!(t.n1_ref(), &1u16); + assert_eq!(t.n2_ref(), &2u32); + assert_eq!(t.n3_ref(), &3u64); + assert_eq!(t.n4_ref(), &4u); + assert_eq!(t.n5_ref(), &5i8); + assert_eq!(t.n6_ref(), &6i16); + assert_eq!(t.n7_ref(), &7i32); + assert_eq!(t.n8_ref(), &8i64); + assert_eq!(t.n9_ref(), &9i); + assert_eq!(t.n10_ref(), &10f32); + assert_eq!(t.n11_ref(), &11f64); + } } From d73f31b31d1b9f14a6b5288ba5b9cb5277b08f3a Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sun, 19 May 2013 05:50:02 +1000 Subject: [PATCH 087/248] Create Char trait --- src/libcore/char.rs | 157 ++++++++++++++++++++++++++--------------- src/libcore/prelude.rs | 1 + 2 files changed, 102 insertions(+), 56 deletions(-) diff --git a/src/libcore/char.rs b/src/libcore/char.rs index 68f283f1ad848..a3957e1bbfc97 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -244,6 +244,53 @@ pub fn len_utf8_bytes(c: char) -> uint { else { fail!("invalid character!") } } +pub trait Char { + fn is_alphabetic(&self) -> bool; + fn is_XID_start(&self) -> bool; + fn is_XID_continue(&self) -> bool; + fn is_lowercase(&self) -> bool; + fn is_uppercase(&self) -> bool; + fn is_whitespace(&self) -> bool; + fn is_alphanumeric(&self) -> bool; + fn is_digit(&self) -> bool; + fn is_digit_radix(&self, radix: uint) -> bool; + fn to_digit(&self, radix: uint) -> Option; + fn from_digit(num: uint, radix: uint) -> Option; + fn escape_unicode(&self) -> ~str; + fn escape_default(&self) -> ~str; + fn len_utf8_bytes(&self) -> uint; +} + +impl Char for char { + fn is_alphabetic(&self) -> bool { is_alphabetic(*self) } + + fn is_XID_start(&self) -> bool { is_XID_start(*self) } + + fn is_XID_continue(&self) -> bool { is_XID_continue(*self) } + + fn is_lowercase(&self) -> bool { is_lowercase(*self) } + + fn is_uppercase(&self) -> bool { is_uppercase(*self) } + + fn is_whitespace(&self) -> bool { is_whitespace(*self) } + + fn is_alphanumeric(&self) -> bool { is_alphanumeric(*self) } + + fn is_digit(&self) -> bool { is_digit(*self) } + + fn is_digit_radix(&self, radix: uint) -> bool { is_digit_radix(*self, radix) } + + fn to_digit(&self, radix: uint) -> Option { to_digit(*self, radix) } + + fn from_digit(num: uint, radix: uint) -> Option { from_digit(num, radix) } + + fn escape_unicode(&self) -> ~str { escape_unicode(*self) } + + fn escape_default(&self) -> ~str { escape_default(*self) } + + fn len_utf8_bytes(&self) -> uint { len_utf8_bytes(*self) } +} + #[cfg(not(test))] impl Eq for char { #[inline(always)] @@ -266,84 +313,82 @@ impl Ord for char { #[test] fn test_is_lowercase() { - assert!(is_lowercase('a')); - assert!(is_lowercase('ö')); - assert!(is_lowercase('ß')); - assert!(!is_lowercase('Ü')); - assert!(!is_lowercase('P')); + assert!('a'.is_lowercase()); + assert!('ö'.is_lowercase()); + assert!('ß'.is_lowercase()); + assert!(!'Ü'.is_lowercase()); + assert!(!'P'.is_lowercase()); } #[test] fn test_is_uppercase() { - assert!(!is_uppercase('h')); - assert!(!is_uppercase('ä')); - assert!(!is_uppercase('ß')); - assert!(is_uppercase('Ö')); - assert!(is_uppercase('T')); + assert!(!'h'.is_uppercase()); + assert!(!'ä'.is_uppercase()); + assert!(!'ß'.is_uppercase()); + assert!('Ö'.is_uppercase()); + assert!('T'.is_uppercase()); } #[test] fn test_is_whitespace() { - assert!(is_whitespace(' ')); - assert!(is_whitespace('\u2007')); - assert!(is_whitespace('\t')); - assert!(is_whitespace('\n')); - - assert!(!is_whitespace('a')); - assert!(!is_whitespace('_')); - assert!(!is_whitespace('\u0000')); + assert!(' '.is_whitespace()); + assert!('\u2007'.is_whitespace()); + assert!('\t'.is_whitespace()); + assert!('\n'.is_whitespace()); + assert!(!'a'.is_whitespace()); + assert!(!'_'.is_whitespace()); + assert!(!'\u0000'.is_whitespace()); } #[test] fn test_to_digit() { - assert_eq!(to_digit('0', 10u), Some(0u)); - assert_eq!(to_digit('1', 2u), Some(1u)); - assert_eq!(to_digit('2', 3u), Some(2u)); - assert_eq!(to_digit('9', 10u), Some(9u)); - assert_eq!(to_digit('a', 16u), Some(10u)); - assert_eq!(to_digit('A', 16u), Some(10u)); - assert_eq!(to_digit('b', 16u), Some(11u)); - assert_eq!(to_digit('B', 16u), Some(11u)); - assert_eq!(to_digit('z', 36u), Some(35u)); - assert_eq!(to_digit('Z', 36u), Some(35u)); - - assert!(to_digit(' ', 10u).is_none()); - assert!(to_digit('$', 36u).is_none()); + assert_eq!('0'.to_digit(10u), Some(0u)); + assert_eq!('1'.to_digit(2u), Some(1u)); + assert_eq!('2'.to_digit(3u), Some(2u)); + assert_eq!('9'.to_digit(10u), Some(9u)); + assert_eq!('a'.to_digit(16u), Some(10u)); + assert_eq!('A'.to_digit(16u), Some(10u)); + assert_eq!('b'.to_digit(16u), Some(11u)); + assert_eq!('B'.to_digit(16u), Some(11u)); + assert_eq!('z'.to_digit(36u), Some(35u)); + assert_eq!('Z'.to_digit(36u), Some(35u)); + assert_eq!(' '.to_digit(10u), None); + assert_eq!('$'.to_digit(36u), None); } #[test] fn test_is_digit() { - assert!(is_digit('2')); - assert!(is_digit('7')); - assert!(! is_digit('c')); - assert!(! is_digit('i')); - assert!(! is_digit('z')); - assert!(! is_digit('Q')); + assert!('2'.is_digit()); + assert!('7'.is_digit()); + assert!(!'c'.is_digit()); + assert!(!'i'.is_digit()); + assert!(!'z'.is_digit()); + assert!(!'Q'.is_digit()); } #[test] fn test_escape_default() { - assert_eq!(escape_default('\n'), ~"\\n"); - assert_eq!(escape_default('\r'), ~"\\r"); - assert_eq!(escape_default('\''), ~"\\'"); - assert_eq!(escape_default('"'), ~"\\\""); - assert_eq!(escape_default(' '), ~" "); - assert_eq!(escape_default('a'), ~"a"); - assert_eq!(escape_default('~'), ~"~"); - assert_eq!(escape_default('\x00'), ~"\\x00"); - assert_eq!(escape_default('\x1f'), ~"\\x1f"); - assert_eq!(escape_default('\x7f'), ~"\\x7f"); - assert_eq!(escape_default('\xff'), ~"\\xff"); - assert_eq!(escape_default('\u011b'), ~"\\u011b"); - assert_eq!(escape_default('\U0001d4b6'), ~"\\U0001d4b6"); + assert_eq!('\n'.escape_default(), ~"\\n"); + assert_eq!('\r'.escape_default(), ~"\\r"); + assert_eq!('\''.escape_default(), ~"\\'"); + assert_eq!('"'.escape_default(), ~"\\\""); + assert_eq!(' '.escape_default(), ~" "); + assert_eq!('a'.escape_default(), ~"a"); + assert_eq!('~'.escape_default(), ~"~"); + assert_eq!('\x00'.escape_default(), ~"\\x00"); + assert_eq!('\x1f'.escape_default(), ~"\\x1f"); + assert_eq!('\x7f'.escape_default(), ~"\\x7f"); + assert_eq!('\xff'.escape_default(), ~"\\xff"); + assert_eq!('\u011b'.escape_default(), ~"\\u011b"); + assert_eq!('\U0001d4b6'.escape_default(), ~"\\U0001d4b6"); } #[test] fn test_escape_unicode() { - assert_eq!(escape_unicode('\x00'), ~"\\x00"); - assert_eq!(escape_unicode('\n'), ~"\\x0a"); - assert_eq!(escape_unicode(' '), ~"\\x20"); - assert_eq!(escape_unicode('a'), ~"\\x61"); - assert_eq!(escape_unicode('\u011b'), ~"\\u011b"); - assert_eq!(escape_unicode('\U0001d4b6'), ~"\\U0001d4b6"); + assert_eq!('\x00'.escape_unicode(), ~"\\x00"); + assert_eq!('\n'.escape_unicode(), ~"\\x0a"); + assert_eq!(' '.escape_unicode(), ~"\\x20"); + assert_eq!('a'.escape_unicode(), ~"\\x61"); + assert_eq!('\u011b'.escape_unicode(), ~"\\u011b"); + assert_eq!('\U0001d4b6'.escape_unicode(), ~"\\U0001d4b6"); } diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index 77371b6336848..78273c51b526a 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -29,6 +29,7 @@ pub use io::{print, println}; pub use clone::{Clone, DeepClone}; pub use cmp::{Eq, ApproxEq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater, Equiv}; +pub use char::Char; pub use container::{Container, Mutable, Map, Set}; pub use hash::Hash; pub use old_iter::{BaseIter, ReverseIter, MutableIter, ExtendedIter, EqIter}; From efe6564a0e650e5a784e8883c8836068e0a13e15 Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sun, 19 May 2013 05:53:30 +1000 Subject: [PATCH 088/248] Code modernisation and cleanup --- src/libcore/char.rs | 164 +++++++++++++++++++++++++++----------------- 1 file changed, 100 insertions(+), 64 deletions(-) diff --git a/src/libcore/char.rs b/src/libcore/char.rs index a3957e1bbfc97..3a0e7bd063988 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -10,47 +10,50 @@ //! Utilities for manipulating the char type -#[cfg(not(test))] -use cmp::Ord; use option::{None, Option, Some}; use str; +#[cfg(stage0)] +use str::StrSlice; +#[cfg(not(stage0))] +use str::{StrSlice, OwnedStr}; use u32; use uint; use unicode::{derived_property, general_category}; -#[cfg(not(test))] use cmp::Eq; +#[cfg(not(test))] +use cmp::{Eq, Ord}; /* - Lu Uppercase_Letter an uppercase letter - Ll Lowercase_Letter a lowercase letter - Lt Titlecase_Letter a digraphic character, with first part uppercase - Lm Modifier_Letter a modifier letter - Lo Other_Letter other letters, including syllables and ideographs - Mn Nonspacing_Mark a nonspacing combining mark (zero advance width) - Mc Spacing_Mark a spacing combining mark (positive advance width) - Me Enclosing_Mark an enclosing combining mark - Nd Decimal_Number a decimal digit - Nl Letter_Number a letterlike numeric character - No Other_Number a numeric character of other type + Lu Uppercase_Letter an uppercase letter + Ll Lowercase_Letter a lowercase letter + Lt Titlecase_Letter a digraphic character, with first part uppercase + Lm Modifier_Letter a modifier letter + Lo Other_Letter other letters, including syllables and ideographs + Mn Nonspacing_Mark a nonspacing combining mark (zero advance width) + Mc Spacing_Mark a spacing combining mark (positive advance width) + Me Enclosing_Mark an enclosing combining mark + Nd Decimal_Number a decimal digit + Nl Letter_Number a letterlike numeric character + No Other_Number a numeric character of other type Pc Connector_Punctuation a connecting punctuation mark, like a tie - Pd Dash_Punctuation a dash or hyphen punctuation mark - Ps Open_Punctuation an opening punctuation mark (of a pair) - Pe Close_Punctuation a closing punctuation mark (of a pair) + Pd Dash_Punctuation a dash or hyphen punctuation mark + Ps Open_Punctuation an opening punctuation mark (of a pair) + Pe Close_Punctuation a closing punctuation mark (of a pair) Pi Initial_Punctuation an initial quotation mark - Pf Final_Punctuation a final quotation mark - Po Other_Punctuation a punctuation mark of other type - Sm Math_Symbol a symbol of primarily mathematical use - Sc Currency_Symbol a currency sign - Sk Modifier_Symbol a non-letterlike modifier symbol - So Other_Symbol a symbol of other type - Zs Space_Separator a space character (of various non-zero widths) - Zl Line_Separator U+2028 LINE SEPARATOR only + Pf Final_Punctuation a final quotation mark + Po Other_Punctuation a punctuation mark of other type + Sm Math_Symbol a symbol of primarily mathematical use + Sc Currency_Symbol a currency sign + Sk Modifier_Symbol a non-letterlike modifier symbol + So Other_Symbol a symbol of other type + Zs Space_Separator a space character (of various non-zero widths) + Zl Line_Separator U+2028 LINE SEPARATOR only Zp Paragraph_Separator U+2029 PARAGRAPH SEPARATOR only - Cc Control a C0 or C1 control code - Cf Format a format control character - Cs Surrogate a surrogate code point - Co Private_Use a private-use character - Cn Unassigned a reserved unassigned code point or a noncharacter + Cc Control a C0 or C1 control code + Cf Format a format control character + Cs Surrogate a surrogate code point + Co Private_Use a private-use character + Cn Unassigned a reserved unassigned code point or a noncharacter */ pub fn is_alphabetic(c: char) -> bool { derived_property::Alphabetic(c) } @@ -62,18 +65,14 @@ pub fn is_XID_continue(c: char) -> bool { derived_property::XID_Continue(c) } * in terms of the Unicode General Category 'Ll' */ #[inline(always)] -pub fn is_lowercase(c: char) -> bool { - return general_category::Ll(c); -} +pub fn is_lowercase(c: char) -> bool { general_category::Ll(c) } /** * Indicates whether a character is in upper case, defined * in terms of the Unicode General Category 'Lu'. */ #[inline(always)] -pub fn is_uppercase(c: char) -> bool { - return general_category::Lu(c); -} +pub fn is_uppercase(c: char) -> bool { general_category::Lu(c) } /** * Indicates whether a character is whitespace. Whitespace is defined in @@ -82,10 +81,10 @@ pub fn is_uppercase(c: char) -> bool { */ #[inline(always)] pub fn is_whitespace(c: char) -> bool { - return ('\x09' <= c && c <= '\x0d') + ('\x09' <= c && c <= '\x0d') || general_category::Zs(c) || general_category::Zl(c) - || general_category::Zp(c); + || general_category::Zp(c) } /** @@ -95,18 +94,18 @@ pub fn is_whitespace(c: char) -> bool { */ #[inline(always)] pub fn is_alphanumeric(c: char) -> bool { - return derived_property::Alphabetic(c) || - general_category::Nd(c) || - general_category::Nl(c) || - general_category::No(c); + derived_property::Alphabetic(c) + || general_category::Nd(c) + || general_category::Nl(c) + || general_category::No(c) } /// Indicates whether the character is numeric (Nd, Nl, or No) #[inline(always)] pub fn is_digit(c: char) -> bool { - return general_category::Nd(c) || - general_category::Nl(c) || - general_category::No(c); + general_category::Nd(c) + || general_category::Nl(c) + || general_category::No(c) } /** @@ -125,7 +124,7 @@ pub fn is_digit(c: char) -> bool { pub fn is_digit_radix(c: char, radix: uint) -> bool { match to_digit(c, radix) { Some(_) => true, - None => false + None => false, } } @@ -151,7 +150,7 @@ pub fn to_digit(c: char, radix: uint) -> Option { '0' .. '9' => c as uint - ('0' as uint), 'a' .. 'z' => c as uint + 10u - ('a' as uint), 'A' .. 'Z' => c as uint + 10u - ('A' as uint), - _ => return None + _ => return None, }; if val < radix { Some(val) } else { None } @@ -181,6 +180,21 @@ pub fn from_digit(num: uint, radix: uint) -> Option { } } +#[cfg(stage0)] +pub fn escape_unicode(c: char) -> ~str { + let s = u32::to_str_radix(c as u32, 16u); + let (c, pad) = (if c <= '\xff' { ('x', 2u) } + else if c <= '\uffff' { ('u', 4u) } + else { ('U', 8u) }); + assert!(str::len(s) <= pad); + let mut out = ~"\\"; + str::push_str(&mut out, str::from_char(c)); + for uint::range(str::len(s), pad) |_i| + { str::push_str(&mut out, ~"0"); } + str::push_str(&mut out, s); + out +} + /** * Return the hexadecimal unicode escape of a char. * @@ -190,17 +204,21 @@ pub fn from_digit(num: uint, radix: uint) -> Option { * - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN` * - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN` */ +#[cfg(not(stage0))] pub fn escape_unicode(c: char) -> ~str { let s = u32::to_str_radix(c as u32, 16u); - let (c, pad) = (if c <= '\xff' { ('x', 2u) } - else if c <= '\uffff' { ('u', 4u) } - else { ('U', 8u) }); - assert!(str::len(s) <= pad); + let (c, pad) = cond!( + (c <= '\xff') { ('x', 2u) } + (c <= '\uffff') { ('u', 4u) } + _ { ('U', 8u) } + ); + assert!(s.len() <= pad); let mut out = ~"\\"; - str::push_str(&mut out, str::from_char(c)); - for uint::range(str::len(s), pad) |_i| - { str::push_str(&mut out, ~"0"); } - str::push_str(&mut out, s); + out.push_str(str::from_char(c)); + for uint::range(s.len(), pad) |_| { + out.push_str("0"); + } + out.push_str(s); out } @@ -218,18 +236,18 @@ pub fn escape_unicode(c: char) -> ~str { */ pub fn escape_default(c: char) -> ~str { match c { - '\t' => ~"\\t", - '\r' => ~"\\r", - '\n' => ~"\\n", - '\\' => ~"\\\\", - '\'' => ~"\\'", - '"' => ~"\\\"", - '\x20' .. '\x7e' => str::from_char(c), - _ => escape_unicode(c) + '\t' => ~"\\t", + '\r' => ~"\\r", + '\n' => ~"\\n", + '\\' => ~"\\\\", + '\'' => ~"\\'", + '"' => ~"\\\"", + '\x20' .. '\x7e' => str::from_char(c), + _ => c.escape_unicode(), } } -/// Returns the amount of bytes this character would need if encoded in utf8 +#[cfg(stage0)] pub fn len_utf8_bytes(c: char) -> uint { static max_one_b: uint = 128u; static max_two_b: uint = 2048u; @@ -244,6 +262,24 @@ pub fn len_utf8_bytes(c: char) -> uint { else { fail!("invalid character!") } } +/// Returns the amount of bytes this character would need if encoded in utf8 +#[cfg(not(stage0))] +pub fn len_utf8_bytes(c: char) -> uint { + static MAX_ONE_B: uint = 128u; + static MAX_TWO_B: uint = 2048u; + static MAX_THREE_B: uint = 65536u; + static MAX_FOUR_B: uint = 2097152u; + + let code = c as uint; + cond!( + (code < MAX_ONE_B) { 1u } + (code < MAX_TWO_B) { 2u } + (code < MAX_THREE_B) { 3u } + (code < MAX_FOUR_B) { 4u } + _ { fail!("invalid character!") } + ) +} + pub trait Char { fn is_alphabetic(&self) -> bool; fn is_XID_start(&self) -> bool; From f687b9d771fce39d1102ff13042a6dfc45f4bf8d Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sun, 19 May 2013 06:03:40 +1000 Subject: [PATCH 089/248] Use `///` style doc-comments and add missing headings --- src/libcore/char.rs | 155 ++++++++++++++++++++++++-------------------- 1 file changed, 83 insertions(+), 72 deletions(-) diff --git a/src/libcore/char.rs b/src/libcore/char.rs index 3a0e7bd063988..f977845eb8a58 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -60,25 +60,25 @@ pub fn is_alphabetic(c: char) -> bool { derived_property::Alphabetic(c) } pub fn is_XID_start(c: char) -> bool { derived_property::XID_Start(c) } pub fn is_XID_continue(c: char) -> bool { derived_property::XID_Continue(c) } -/** - * Indicates whether a character is in lower case, defined - * in terms of the Unicode General Category 'Ll' - */ +/// +/// Indicates whether a character is in lower case, defined +/// in terms of the Unicode General Category 'Ll' +/// #[inline(always)] pub fn is_lowercase(c: char) -> bool { general_category::Ll(c) } -/** - * Indicates whether a character is in upper case, defined - * in terms of the Unicode General Category 'Lu'. - */ +/// +/// Indicates whether a character is in upper case, defined +/// in terms of the Unicode General Category 'Lu'. +/// #[inline(always)] pub fn is_uppercase(c: char) -> bool { general_category::Lu(c) } -/** - * Indicates whether a character is whitespace. Whitespace is defined in - * terms of the Unicode General Categories 'Zs', 'Zl', 'Zp' - * additional 'Cc'-category control codes in the range [0x09, 0x0d] - */ +/// +/// Indicates whether a character is whitespace. Whitespace is defined in +/// terms of the Unicode General Categories 'Zs', 'Zl', 'Zp' +/// additional 'Cc'-category control codes in the range [0x09, 0x0d] +/// #[inline(always)] pub fn is_whitespace(c: char) -> bool { ('\x09' <= c && c <= '\x0d') @@ -87,11 +87,11 @@ pub fn is_whitespace(c: char) -> bool { || general_category::Zp(c) } -/** - * Indicates whether a character is alphanumeric. Alphanumericness is - * defined in terms of the Unicode General Categories 'Nd', 'Nl', 'No' - * and the Derived Core Property 'Alphabetic'. - */ +/// +/// Indicates whether a character is alphanumeric. Alphanumericness is +/// defined in terms of the Unicode General Categories 'Nd', 'Nl', 'No' +/// and the Derived Core Property 'Alphabetic'. +/// #[inline(always)] pub fn is_alphanumeric(c: char) -> bool { derived_property::Alphabetic(c) @@ -108,18 +108,24 @@ pub fn is_digit(c: char) -> bool { || general_category::No(c) } -/** - * Checks if a character parses as a numeric digit in the given radix. - * Compared to `is_digit()`, this function only recognizes the - * characters `0-9`, `a-z` and `A-Z`. - * - * Returns `true` if `c` is a valid digit under `radix`, and `false` - * otherwise. - * - * Fails if given a `radix` > 36. - * - * Note: This just wraps `to_digit()`. - */ +/// +/// Checks if a character parses as a numeric digit in the given radix. +/// Compared to `is_digit()`, this function only recognizes the +/// characters `0-9`, `a-z` and `A-Z`. +/// +/// # Return value +/// +/// Returns `true` if `c` is a valid digit under `radix`, and `false` +/// otherwise. +/// +/// # Failure +/// +/// Fails if given a `radix` > 36. +/// +/// # Note +/// +/// This just wraps `to_digit()`. +/// #[inline(always)] pub fn is_digit_radix(c: char, radix: uint) -> bool { match to_digit(c, radix) { @@ -128,19 +134,20 @@ pub fn is_digit_radix(c: char, radix: uint) -> bool { } } -/** - * Convert a char to the corresponding digit. - * - * # Return value - * - * If `c` is between '0' and '9', the corresponding value - * between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is - * 'b' or 'B', 11, etc. Returns none if the char does not - * refer to a digit in the given radix. - * - * # Failure - * Fails if given a `radix` outside the range `[0..36]`. - */ +/// +/// Convert a char to the corresponding digit. +/// +/// # Return value +/// +/// If `c` is between '0' and '9', the corresponding value +/// between 0 and 9. If `c` is 'a' or 'A', 10. If `c` is +/// 'b' or 'B', 11, etc. Returns none if the char does not +/// refer to a digit in the given radix. +/// +/// # Failure +/// +/// Fails if given a `radix` outside the range `[0..36]`. +/// #[inline] pub fn to_digit(c: char, radix: uint) -> Option { if radix > 36 { @@ -156,14 +163,18 @@ pub fn to_digit(c: char, radix: uint) -> Option { else { None } } -/** - * Converts a number to the character representing it. - * - * Returns `Some(char)` if `num` represents one digit under `radix`, - * using one character of `0-9` or `a-z`, or `None` if it doesn't. - * - * Fails if given an `radix` > 36. - */ +/// +/// Converts a number to the character representing it. +/// +/// # Return value +/// +/// Returns `Some(char)` if `num` represents one digit under `radix`, +/// using one character of `0-9` or `a-z`, or `None` if it doesn't. +/// +/// # Failure +/// +/// Fails if given an `radix` > 36. +/// #[inline] pub fn from_digit(num: uint, radix: uint) -> Option { if radix > 36 { @@ -195,15 +206,15 @@ pub fn escape_unicode(c: char) -> ~str { out } -/** - * Return the hexadecimal unicode escape of a char. - * - * The rules are as follows: - * - * - chars in [0,0xff] get 2-digit escapes: `\\xNN` - * - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN` - * - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN` - */ +/// +/// Return the hexadecimal unicode escape of a char. +/// +/// The rules are as follows: +/// +/// - chars in [0,0xff] get 2-digit escapes: `\\xNN` +/// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN` +/// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN` +/// #[cfg(not(stage0))] pub fn escape_unicode(c: char) -> ~str { let s = u32::to_str_radix(c as u32, 16u); @@ -222,18 +233,18 @@ pub fn escape_unicode(c: char) -> ~str { out } -/** - * Return a 'default' ASCII and C++11-like char-literal escape of a char. - * - * The default is chosen with a bias toward producing literals that are - * legal in a variety of languages, including C++11 and similar C-family - * languages. The exact rules are: - * - * - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. - * - Single-quote, double-quote and backslash chars are backslash-escaped. - * - Any other chars in the range [0x20,0x7e] are not escaped. - * - Any other chars are given hex unicode escapes; see `escape_unicode`. - */ +/// +/// Return a 'default' ASCII and C++11-like char-literal escape of a char. +/// +/// The default is chosen with a bias toward producing literals that are +/// legal in a variety of languages, including C++11 and similar C-family +/// languages. The exact rules are: +/// +/// - Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively. +/// - Single-quote, double-quote and backslash chars are backslash-escaped. +/// - Any other chars in the range [0x20,0x7e] are not escaped. +/// - Any other chars are given hex unicode escapes; see `escape_unicode`. +/// pub fn escape_default(c: char) -> ~str { match c { '\t' => ~"\\t", From 8daa5ec9eac7148674cd63e5281c56925a3bc7b7 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 18 May 2013 16:35:58 -0700 Subject: [PATCH 090/248] xfail-fast run-pass/core-rt-smoke --- src/test/run-pass/core-rt-smoke.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/test/run-pass/core-rt-smoke.rs b/src/test/run-pass/core-rt-smoke.rs index fb08cda3b2577..3a0b4b6d40da9 100644 --- a/src/test/run-pass/core-rt-smoke.rs +++ b/src/test/run-pass/core-rt-smoke.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// xfail-fast + // A simple test of starting the runtime manually #[start] From 9b6b0e1e646b42de7205a21bf73e5c4c2b203a6b Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 18 May 2013 22:10:56 -0400 Subject: [PATCH 091/248] fix stage0 compile --- src/libcore/iterator.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index 41f916f2d1557..ecf76a39fcdb5 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -47,6 +47,7 @@ pub trait IteratorUtil { fn advance(&mut self, f: &fn(A) -> bool); #[cfg(not(stage0))] fn advance(&mut self, f: &fn(A) -> bool) -> bool; + #[cfg(not(stage0))] fn to_vec(&mut self) -> ~[A]; fn nth(&mut self, n: uint) -> Option; fn last(&mut self) -> Option; @@ -146,6 +147,7 @@ impl> IteratorUtil for T { } } + #[cfg(not(stage0))] #[inline(always)] fn to_vec(&mut self) -> ~[A] { iter::to_vec::(|f| self.advance(f)) From 1789174541d36bad270b3e27584db53516c93912 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sat, 18 May 2013 22:40:12 -0400 Subject: [PATCH 092/248] minor automated whitespace fixes --- src/librustc/middle/borrowck/check_loans.rs | 1 - src/librustc/middle/borrowck/gather_loans/mod.rs | 1 - src/librustc/middle/borrowck/gather_loans/restrictions.rs | 1 - src/librustc/middle/dataflow.rs | 1 - src/librustc/middle/trans/write_guard.rs | 1 - src/librustpkg/rustpkg.rc | 1 - src/libsyntax/fold.rs | 1 - src/test/auxiliary/mod_trait_with_static_methods_lib.rs | 1 - .../compile-fail/regions-infer-borrow-scope-within-loop.rs | 4 ++-- src/test/run-pass/intrinsic-atomics.rs | 4 ++-- src/test/run-pass/issue-5353.rs | 2 -- src/test/run-pass/match-range-static.rs | 1 - 12 files changed, 4 insertions(+), 15 deletions(-) diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index 2f24a8ceb2465..b33b64921b406 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -816,4 +816,3 @@ fn check_loans_in_block<'a>(blk: &ast::blk, visit::visit_block(blk, this, vt); this.check_for_conflicting_loans(blk.node.id); } - diff --git a/src/librustc/middle/borrowck/gather_loans/mod.rs b/src/librustc/middle/borrowck/gather_loans/mod.rs index 64d32d713d0da..0db7b4880e758 100644 --- a/src/librustc/middle/borrowck/gather_loans/mod.rs +++ b/src/librustc/middle/borrowck/gather_loans/mod.rs @@ -634,4 +634,3 @@ fn add_stmt_to_map(stmt: @ast::stmt, } visit::visit_stmt(stmt, this, vt); } - diff --git a/src/librustc/middle/borrowck/gather_loans/restrictions.rs b/src/librustc/middle/borrowck/gather_loans/restrictions.rs index 0be4c67a9bc91..3760350dc268c 100644 --- a/src/librustc/middle/borrowck/gather_loans/restrictions.rs +++ b/src/librustc/middle/borrowck/gather_loans/restrictions.rs @@ -246,4 +246,3 @@ impl RestrictionsContext { } } } - diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 31d22b76800c1..648daaf3cd1d3 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -1062,4 +1062,3 @@ fn reslice<'a>(v: &'a mut [uint]) -> &'a [uint] { cast::transmute(v) } } - diff --git a/src/librustc/middle/trans/write_guard.rs b/src/librustc/middle/trans/write_guard.rs index 18f21b489b0b8..8a6b4acac8eab 100644 --- a/src/librustc/middle/trans/write_guard.rs +++ b/src/librustc/middle/trans/write_guard.rs @@ -198,4 +198,3 @@ fn perform_write_guard(datum: &Datum, line], expr::Ignore) } - diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index a69613776efdc..c5531fbd1158b 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -676,4 +676,3 @@ impl PkgSrc { self.build_crates(maybe_sysroot, dst_dir, &dir, self.benchs, cfgs, Bench); } } - diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 275a7b963a4bf..8b657b13fa9d2 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -858,4 +858,3 @@ impl AstFoldExtensions for @ast_fold { pub fn make_fold(afp: ast_fold_fns) -> @ast_fold { afp as @ast_fold } - diff --git a/src/test/auxiliary/mod_trait_with_static_methods_lib.rs b/src/test/auxiliary/mod_trait_with_static_methods_lib.rs index b060c7aee49a2..2099c6a2f2f2f 100644 --- a/src/test/auxiliary/mod_trait_with_static_methods_lib.rs +++ b/src/test/auxiliary/mod_trait_with_static_methods_lib.rs @@ -19,4 +19,3 @@ pub mod sub_foo { pub fn foo() -> int { 42 } } } - diff --git a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs b/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs index 50ac5f65772fc..3b88c634598b1 100644 --- a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs +++ b/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs @@ -15,8 +15,8 @@ fn foo(cond: &fn() -> bool, box: &fn() -> @int) { loop { let x = box(); - // Here we complain because the resulting region - // of this borrow is the fn body as a whole. + // Here we complain because the resulting region + // of this borrow is the fn body as a whole. y = borrow(x); //~ ERROR cannot root assert!(*x == *y); diff --git a/src/test/run-pass/intrinsic-atomics.rs b/src/test/run-pass/intrinsic-atomics.rs index d4701f74488c8..4105e6003b55c 100644 --- a/src/test/run-pass/intrinsic-atomics.rs +++ b/src/test/run-pass/intrinsic-atomics.rs @@ -17,7 +17,7 @@ mod rusti { pub fn atomic_load(src: &int) -> int; pub fn atomic_load_acq(src: &int) -> int; - + pub fn atomic_store(dst: &mut int, val: int); pub fn atomic_store_rel(dst: &mut int, val: int); @@ -42,7 +42,7 @@ pub fn main() { assert!(rusti::atomic_load(x) == 1); *x = 5; assert!(rusti::atomic_load_acq(x) == 5); - + rusti::atomic_store(x,3); assert!(*x == 3); rusti::atomic_store_rel(x,1); diff --git a/src/test/run-pass/issue-5353.rs b/src/test/run-pass/issue-5353.rs index f933b616119fa..cc1bb2dd03738 100644 --- a/src/test/run-pass/issue-5353.rs +++ b/src/test/run-pass/issue-5353.rs @@ -22,5 +22,3 @@ fn gl_err_str(err: u32) -> ~str } fn main() {} - - diff --git a/src/test/run-pass/match-range-static.rs b/src/test/run-pass/match-range-static.rs index 3eefc386250ed..aa216b8d05487 100644 --- a/src/test/run-pass/match-range-static.rs +++ b/src/test/run-pass/match-range-static.rs @@ -7,4 +7,3 @@ fn main() { _ => (), } } - From d1e091a27a6ee0d32fcda0830ec5f9a7ad585d9e Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Sun, 19 May 2013 14:08:27 +1000 Subject: [PATCH 093/248] Add Ptr::to_option method --- src/libcore/ptr.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index e116dc0194310..6254d3349d3d9 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -13,6 +13,7 @@ use cast; use libc; use libc::{c_void, size_t}; +use option::{Option, Some, None}; use sys; #[cfg(not(test))] use cmp::{Eq, Ord}; @@ -209,6 +210,7 @@ pub unsafe fn array_each(arr: **T, cb: &fn(*T)) { pub trait Ptr { fn is_null(&const self) -> bool; fn is_not_null(&const self) -> bool; + fn to_option(&const self) -> Option; fn offset(&self, count: uint) -> Self; } @@ -222,6 +224,14 @@ impl Ptr for *T { #[inline(always)] fn is_not_null(&const self) -> bool { is_not_null(*self) } + /// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`. + #[inline(always)] + fn to_option(&const self) -> Option { + if self.is_null() { None } else { + Some(unsafe { **self }) + } + } + /// Calculates the offset from a pointer. #[inline(always)] fn offset(&self, count: uint) -> *T { offset(*self, count) } @@ -237,6 +247,14 @@ impl Ptr for *mut T { #[inline(always)] fn is_not_null(&const self) -> bool { is_not_null(*self) } + /// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`. + #[inline(always)] + fn to_option(&const self) -> Option { + if self.is_null() { None } else { + Some(unsafe { **self }) + } + } + /// Calculates the offset from a mutable pointer. #[inline(always)] fn offset(&self, count: uint) -> *mut T { mut_offset(*self, count) } @@ -423,6 +441,21 @@ pub mod ptr_tests { assert!(mq.is_not_null()); } + #[test] + #[allow(unused_mut)] + fn test_to_option() { + let p: *int = null(); + assert_eq!(p.to_option(), None); + + let q: *int = &2; + assert_eq!(q.to_option(), Some(2)); + + let p: *mut int = mut_null(); + assert_eq!(p.to_option(), None); + + let q: *mut int = &mut 2; + assert_eq!(q.to_option(), Some(2)); + } #[test] fn test_ptr_array_each_with_len() { From 20ef4238bb63686d5af951acfba5468959be861d Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Sun, 19 May 2013 00:21:41 -0400 Subject: [PATCH 094/248] reduce the usage of explicit version markers --- src/compiletest/compiletest.rc | 2 +- src/driver/driver.rs | 12 ++++++------ src/libcore/core.rc | 2 +- src/libfuzzer/fuzzer.rc | 4 ++-- src/librust/rust.rc | 8 ++++---- src/librustc/rustc.rc | 5 ++--- src/librustdoc/rustdoc.rc | 6 +++--- src/librusti/rusti.rc | 6 +++--- src/librustpkg/rustpkg.rc | 6 +++--- src/libsyntax/syntax.rc | 2 +- 10 files changed, 26 insertions(+), 27 deletions(-) diff --git a/src/compiletest/compiletest.rc b/src/compiletest/compiletest.rc index dedf465b56d8b..5d703f6721314 100644 --- a/src/compiletest/compiletest.rc +++ b/src/compiletest/compiletest.rc @@ -12,7 +12,7 @@ #[allow(non_camel_case_types)]; -extern mod std(vers = "0.7-pre"); +extern mod std; use core::*; diff --git a/src/driver/driver.rs b/src/driver/driver.rs index 70dc9e895c01e..b8bd79eedbb86 100644 --- a/src/driver/driver.rs +++ b/src/driver/driver.rs @@ -9,21 +9,21 @@ // except according to those terms. #[cfg(rustpkg)] -extern mod this(name = "rustpkg", vers = "0.7-pre"); +extern mod this(name = "rustpkg"); #[cfg(fuzzer)] -extern mod this(name = "fuzzer", vers = "0.7-pre"); +extern mod this(name = "fuzzer"); #[cfg(rustdoc)] -extern mod this(name = "rustdoc", vers = "0.7-pre"); +extern mod this(name = "rustdoc"); #[cfg(rusti)] -extern mod this(name = "rusti", vers = "0.7-pre"); +extern mod this(name = "rusti"); #[cfg(rust)] -extern mod this(name = "rust", vers = "0.7-pre"); +extern mod this(name = "rust"); #[cfg(rustc)] -extern mod this(name = "rustc", vers = "0.7-pre"); +extern mod this(name = "rustc"); fn main() { this::main() } diff --git a/src/libcore/core.rc b/src/libcore/core.rc index eb94e9ca02869..60093ff96bb26 100644 --- a/src/libcore/core.rc +++ b/src/libcore/core.rc @@ -63,7 +63,7 @@ they contained the following prologue: #[deny(non_camel_case_types)]; // Make core testable by not duplicating lang items. See #2912 -#[cfg(test)] extern mod realcore(name = "core", vers = "0.7-pre"); +#[cfg(test)] extern mod realcore(name = "core"); #[cfg(test)] pub use kinds = realcore::kinds; #[cfg(test)] pub use ops = realcore::ops; #[cfg(test)] pub use cmp = realcore::cmp; diff --git a/src/libfuzzer/fuzzer.rc b/src/libfuzzer/fuzzer.rc index 59a715e7f9062..6662af3b5965a 100644 --- a/src/libfuzzer/fuzzer.rc +++ b/src/libfuzzer/fuzzer.rc @@ -20,8 +20,8 @@ #[allow(non_camel_case_types)]; -extern mod std(vers = "0.7-pre"); -extern mod syntax(vers = "0.7-pre"); +extern mod std; +extern mod syntax; use core::run; diff --git a/src/librust/rust.rc b/src/librust/rust.rc index 92510be56c3a8..7b3585af9b4ab 100644 --- a/src/librust/rust.rc +++ b/src/librust/rust.rc @@ -20,10 +20,10 @@ #[license = "MIT/ASL2"]; #[crate_type = "lib"]; -extern mod rustpkg(vers = "0.7-pre"); -extern mod rustdoc(vers = "0.7-pre"); -extern mod rusti(vers = "0.7-pre"); -extern mod rustc(vers = "0.7-pre"); +extern mod rustpkg; +extern mod rustdoc; +extern mod rusti; +extern mod rustc; use core::run; diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index 6027a04454180..e3d19e3855925 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -21,9 +21,8 @@ #[allow(non_camel_case_types)]; #[deny(deprecated_pattern)]; -extern mod std(vers = "0.7-pre"); -extern mod syntax(vers = "0.7-pre"); - +extern mod std; +extern mod syntax; use driver::driver::{host_triple, optgroups, early_error}; use driver::driver::{str_input, file_input, build_session_options}; diff --git a/src/librustdoc/rustdoc.rc b/src/librustdoc/rustdoc.rc index 333ea5bce2fde..fed8bc0e97209 100644 --- a/src/librustdoc/rustdoc.rc +++ b/src/librustdoc/rustdoc.rc @@ -21,9 +21,9 @@ #[allow(non_implicitly_copyable_typarams)]; -extern mod std(vers = "0.7-pre"); -extern mod rustc(vers = "0.7-pre"); -extern mod syntax(vers = "0.7-pre"); +extern mod std; +extern mod rustc; +extern mod syntax; use config::Config; use doc::Item; diff --git a/src/librusti/rusti.rc b/src/librusti/rusti.rc index 4a03d31e5dba1..3ec19ce1a1476 100644 --- a/src/librusti/rusti.rc +++ b/src/librusti/rusti.rc @@ -18,9 +18,9 @@ #[license = "MIT/ASL2"]; #[crate_type = "lib"]; -extern mod std(vers = "0.7-pre"); -extern mod rustc(vers = "0.7-pre"); -extern mod syntax(vers = "0.7-pre"); +extern mod std; +extern mod rustc; +extern mod syntax; use core::*; use core::cell::Cell; diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index a69613776efdc..f1ba759acd775 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -18,9 +18,9 @@ #[license = "MIT/ASL2"]; #[crate_type = "lib"]; -extern mod std(vers = "0.7-pre"); -extern mod rustc(vers = "0.7-pre"); -extern mod syntax(vers = "0.7-pre"); +extern mod std; +extern mod rustc; +extern mod syntax; use core::*; pub use core::path::Path; diff --git a/src/libsyntax/syntax.rc b/src/libsyntax/syntax.rc index 565a8a18c6fad..0d9b7ca429eae 100644 --- a/src/libsyntax/syntax.rc +++ b/src/libsyntax/syntax.rc @@ -23,7 +23,7 @@ #[allow(non_camel_case_types)]; #[deny(deprecated_pattern)]; -extern mod std(vers = "0.7-pre"); +extern mod std; // allow the interner_key macro // to escape this module: From 3a11ddb1b2a0807e1c3dc9a9a6afc1d578286bae Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sun, 19 May 2013 18:51:14 +1000 Subject: [PATCH 095/248] Correct tuple Ord impl, add Total{Eq,Ord} impls and add some tests. --- src/libcore/tuple.rs | 106 +++++++++++++++++++++++++++++++++++-------- 1 file changed, 87 insertions(+), 19 deletions(-) diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index e8796147ef8f6..639df89a3776f 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -114,17 +114,17 @@ impl ExtendedTupleOps for (~[A], ~[B]) { // macro for implementing n-ary tuple functions and operations -macro_rules! tuple_impls( +macro_rules! tuple_impls { ($( ($cloneable_trait:ident, $immutable_trait:ident) { $(($get_fn:ident, $get_ref_fn:ident) -> $T:ident { $get_pattern:pat => $ret:expr })+ } - )+) => ( + )+) => { pub mod inner { use clone::Clone; - #[cfg(not(test))] use cmp::{Eq, Ord}; + #[cfg(not(test))] use cmp::*; $( pub trait $cloneable_trait<$($T),+> { @@ -171,11 +171,19 @@ macro_rules! tuple_impls( } } + #[cfg(not(test))] + impl<$($T:TotalEq),+> TotalEq for ($($T),+) { + #[inline(always)] + fn equals(&self, other: &($($T),+)) -> bool { + $(self.$get_ref_fn().equals(other.$get_ref_fn()))&&+ + } + } + #[cfg(not(test))] impl<$($T:Ord),+> Ord for ($($T),+) { #[inline(always)] fn lt(&self, other: &($($T),+)) -> bool { - lexical_lt!($(*self.$get_ref_fn(), *other.$get_ref_fn()),+) + lexical_lt!($(self.$get_ref_fn(), other.$get_ref_fn()),+) } #[inline(always)] fn le(&self, other: &($($T),+)) -> bool { !(*other).lt(&(*self)) } @@ -184,22 +192,44 @@ macro_rules! tuple_impls( #[inline(always)] fn gt(&self, other: &($($T),+)) -> bool { (*other).lt(&(*self)) } } + + #[cfg(not(test))] + impl<$($T:TotalOrd),+> TotalOrd for ($($T),+) { + #[inline] + fn cmp(&self, other: &($($T),+)) -> Ordering { + lexical_cmp!($(self.$get_ref_fn(), other.$get_ref_fn()),+) + } + } )+ } - ) -) - -// Constructs an expression that performs a lexical less-than ordering. -// The values are interleaved, so the macro invocation for -// `(a1, a2, a3) < (b1, b2, b3)` would be `lexical_lt!(a1, b1, a2, b2, a3, b3)` -macro_rules! lexical_lt( - ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => ( - if $a < $b { true } else { lexical_lt!($($rest_a, $rest_b),+) } - ); - ($a:expr, $b:expr) => ($a < $b); -) - -tuple_impls!( + } +} + +// Constructs an expression that performs a lexical less-than +// ordering. The values are interleaved, so the macro invocation for +// `(a1, a2, a3) < (b1, b2, b3)` would be `lexical_lt!(a1, b1, a2, b2, +// a3, b3)` (and similarly for `lexical_cmp`) +macro_rules! lexical_lt { + ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => { + if *$a < *$b { true } + else if !(*$b < *$a) { lexical_lt!($($rest_a, $rest_b),+) } + else { false } + }; + ($a:expr, $b:expr) => { *$a < *$b }; +} + +macro_rules! lexical_cmp { + ($a:expr, $b:expr, $($rest_a:expr, $rest_b:expr),+) => { + match ($a).cmp($b) { + Equal => lexical_cmp!($($rest_a, $rest_b),+), + ordering => ordering + } + }; + ($a:expr, $b:expr) => { ($a).cmp($b) }; +} + + +tuple_impls! { (CloneableTuple2, ImmutableTuple2) { (n0, n0_ref) -> A { (ref a,_) => a } (n1, n1_ref) -> B { (_,ref b) => b } @@ -309,12 +339,13 @@ tuple_impls!( (n10, n10_ref) -> K { (_,_,_,_,_,_,_,_,_,_,ref k,_) => k } (n11, n11_ref) -> L { (_,_,_,_,_,_,_,_,_,_,_,ref l) => l } } -) +} #[cfg(test)] mod tests { use super::*; use clone::Clone; + use cmp::*; #[test] fn test_tuple_ref() { @@ -368,4 +399,41 @@ mod tests { assert_eq!(t.n10_ref(), &10f32); assert_eq!(t.n11_ref(), &11f64); } + + #[test] + fn test_tuple_cmp() { + let small = (1u, 2u, 3u), big = (3u, 2u, 1u); + + // Eq + assert_eq!(small, small); + assert_eq!(big, big); + assert!(small != big); + assert!(big != small); + + // Ord + assert!(small < big); + assert!(!(small < small)); + assert!(!(big < small)); + assert!(!(big < big)); + + assert!(small <= small); + assert!(big <= big); + + assert!(big > small); + assert!(small >= small); + assert!(big >= small); + assert!(big >= big); + + // TotalEq + assert!(small.equals(&small)); + assert!(big.equals(&big)); + assert!(!small.equals(&big)); + assert!(!big.equals(&small)); + + // TotalOrd + assert_eq!(small.cmp(&small), Equal); + assert_eq!(big.cmp(&big), Equal); + assert_eq!(small.cmp(&big), Less); + assert_eq!(big.cmp(&small), Greater); + } } From cc57ca012a1f49875e19b1b089c91928dc339979 Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Sat, 18 May 2013 22:02:45 -0400 Subject: [PATCH 096/248] Use assert_eq! rather than assert! where possible --- src/libcore/at_vec.rs | 26 +- src/libcore/bool.rs | 6 +- src/libcore/cast.rs | 4 +- src/libcore/cell.rs | 4 +- src/libcore/clone.rs | 8 +- src/libcore/hash.rs | 8 +- src/libcore/hashmap.rs | 62 +- src/libcore/io.rs | 34 +- src/libcore/num/int-template/int.rs | 18 +- src/libcore/num/uint-template/uint.rs | 90 +-- src/libcore/option.rs | 14 +- src/libcore/os.rs | 30 +- src/libcore/path.rs | 26 +- src/libcore/pipes.rs | 6 +- src/libcore/ptr.rs | 24 +- src/libcore/rand.rs | 42 +- src/libcore/repr.rs | 4 +- src/libcore/result.rs | 14 +- src/libcore/rt/io/flate.rs | 4 +- src/libcore/rt/io/mem.rs | 32 +- src/libcore/rt/io/net/tcp.rs | 2 +- src/libcore/rt/io/option.rs | 12 +- src/libcore/rt/mod.rs | 8 +- src/libcore/rt/sched.rs | 6 +- src/libcore/rt/thread_local_storage.rs | 8 +- src/libcore/rt/uv/mod.rs | 4 +- src/libcore/rt/uv/net.rs | 8 +- src/libcore/rt/uv/uvio.rs | 10 +- src/libcore/rt/uv/uvll.rs | 4 +- src/libcore/run.rs | 4 +- src/libcore/str.rs | 358 +++++------ src/libcore/sys.rs | 40 +- src/libcore/task/mod.rs | 16 +- src/libcore/task/spawn.rs | 4 +- src/libcore/to_str.rs | 34 +- src/libcore/trie.rs | 32 +- src/libcore/unstable/at_exit.rs | 4 +- src/libcore/unstable/extfmt.rs | 8 +- src/libcore/unstable/finally.rs | 12 +- src/libcore/unstable/global.rs | 2 +- src/libcore/unstable/mod.rs | 2 +- src/libcore/unstable/sync.rs | 4 +- src/libcore/util.rs | 4 +- src/libcore/vec.rs | 576 +++++++++--------- src/librustc/back/rpath.rs | 30 +- src/librustc/driver/driver.rs | 2 +- src/librustc/metadata/decoder.rs | 2 +- src/librustc/metadata/encoder.rs | 4 +- src/librustc/metadata/tydecode.rs | 42 +- src/librustc/middle/astencode.rs | 2 +- .../middle/borrowck/gather_loans/mod.rs | 2 +- src/librustc/middle/entry.rs | 2 +- src/librustc/middle/region.rs | 4 +- src/librustc/middle/resolve.rs | 4 +- src/librustc/middle/resolve_stage0.rs | 4 +- src/librustc/middle/trans/adt.rs | 20 +- src/librustc/middle/trans/base.rs | 2 +- src/librustc/middle/trans/build.rs | 2 +- src/librustc/middle/trans/callee.rs | 2 +- src/librustc/middle/trans/closure.rs | 2 +- src/librustc/middle/trans/consts.rs | 8 +- src/librustc/middle/trans/datum.rs | 2 +- src/librustc/middle/trans/expr.rs | 2 +- src/librustc/middle/trans/glue.rs | 2 +- src/librustc/middle/ty.rs | 2 +- src/librustc/middle/typeck/coherence.rs | 2 +- .../middle/typeck/infer/region_inference.rs | 4 +- src/librustc/middle/typeck/infer/unify.rs | 2 +- src/librustdoc/astsrv.rs | 2 +- src/librustdoc/desc_to_brief_pass.rs | 10 +- src/librustdoc/escape_pass.rs | 2 +- src/librustdoc/fold.rs | 8 +- src/librustdoc/markdown_index_pass.rs | 2 +- src/librustdoc/markdown_writer.rs | 6 +- src/librustdoc/page_pass.rs | 4 +- src/librustdoc/pass.rs | 2 +- src/librustdoc/path_pass.rs | 2 +- src/librustdoc/prune_private_pass.rs | 10 +- src/librustdoc/sectionalize_pass.rs | 6 +- src/librustdoc/sort_item_name_pass.rs | 4 +- src/librustdoc/sort_item_type_pass.rs | 16 +- src/librustdoc/sort_pass.rs | 16 +- src/librustdoc/text_pass.rs | 16 +- src/librustdoc/trim_pass.rs | 2 +- src/librustdoc/unindent_pass.rs | 10 +- src/librustpkg/tests.rs | 8 +- .../testsuite/pass/src/install-paths/test.rs | 2 +- src/librustpkg/util.rs | 2 +- src/libstd/arc.rs | 46 +- src/libstd/base64.rs | 20 +- src/libstd/bitv.rs | 38 +- src/libstd/c_vec.rs | 8 +- src/libstd/comm.rs | 4 +- src/libstd/deque.rs | 110 ++-- src/libstd/dlist.rs | 4 +- src/libstd/ebml.rs | 10 +- src/libstd/flate.rs | 2 +- src/libstd/flatpipes.rs | 8 +- src/libstd/future.rs | 14 +- src/libstd/getopts.rs | 72 +-- src/libstd/list.rs | 24 +- src/libstd/md4.rs | 6 +- src/libstd/net_ip.rs | 2 +- src/libstd/net_tcp.rs | 2 +- src/libstd/net_url.rs | 272 ++++----- src/libstd/num/bigint.rs | 44 +- src/libstd/par.rs | 6 +- src/libstd/priority_queue.rs | 68 +-- src/libstd/rc.rs | 2 +- src/libstd/rope.rs | 10 +- src/libstd/semver.rs | 24 +- src/libstd/serialize.rs | 8 +- src/libstd/sha1.rs | 20 +- src/libstd/smallintmap.rs | 24 +- src/libstd/sort.rs | 24 +- src/libstd/sort_stage0.rs | 28 +- src/libstd/sync.rs | 10 +- src/libstd/test.rs | 14 +- src/libstd/time.rs | 94 +-- src/libstd/timer.rs | 2 +- src/libstd/treemap.rs | 72 +-- src/libstd/uv_iotask.rs | 2 +- src/libsyntax/codemap.rs | 4 +- src/libsyntax/parse/mod.rs | 2 +- src/libsyntax/print/pp.rs | 6 +- src/libsyntax/print/pprust.rs | 2 +- src/test/bench/core-map.rs | 6 +- src/test/bench/graph500-bfs.rs | 2 +- src/test/bench/msgsend-pipes-shared.rs | 2 +- src/test/bench/msgsend-pipes.rs | 2 +- src/test/bench/shootout-pfib.rs | 2 +- src/test/bench/std-smallintmap.rs | 2 +- src/test/bench/sudoku.rs | 42 +- src/test/bench/task-perf-linked-failure.rs | 2 +- src/test/compile-fail/autoderef-full-lval.rs | 4 +- .../block-arg-as-stmt-with-value.rs | 2 +- .../borrowck-loan-blocks-mut-uniq.rs | 4 +- .../compile-fail/borrowck-ref-mut-of-imm.rs | 2 +- src/test/compile-fail/issue-1896-1.rs | 2 +- src/test/compile-fail/issue-2467.rs | 2 +- src/test/compile-fail/issue-2548.rs | 4 +- src/test/compile-fail/issue-2969.rs | 2 +- .../compile-fail/kindck-owned-trait-scoped.rs | 2 +- src/test/compile-fail/mod_file_not_exist.rs | 2 +- .../compile-fail/mod_file_with_path_attr.rs | 2 +- src/test/compile-fail/no-capture-arc.rs | 4 +- src/test/compile-fail/no-reuse-move-arc.rs | 2 +- .../compile-fail/regions-glb-free-free.rs | 2 +- .../regions-infer-borrow-scope-too-big.rs | 2 +- .../regions-infer-borrow-scope-within-loop.rs | 2 +- src/test/compile-fail/regions-trait-1.rs | 2 +- .../regions-var-type-out-of-scope.rs | 2 +- .../compile-fail/vtable-res-trait-param.rs | 2 +- src/test/pretty/record-trailing-comma.rs | 2 +- src/test/run-fail/str-overrun.rs | 2 +- src/test/run-fail/unwind-alt.rs | 2 +- src/test/run-fail/vec-overrun.rs | 4 +- src/test/run-fail/vec-underrun.rs | 4 +- src/test/run-pass-fulldeps/qquote.rs | 2 +- src/test/run-pass/alignment-gep-tup-like-1.rs | 4 +- src/test/run-pass/alignment-gep-tup-like-2.rs | 4 +- .../run-pass/alt-ref-binding-mut-option.rs | 2 +- src/test/run-pass/alt-ref-binding-mut.rs | 2 +- src/test/run-pass/alt-ref-binding.rs | 2 +- src/test/run-pass/alt-str.rs | 2 +- src/test/run-pass/alt-tag.rs | 6 +- src/test/run-pass/alt-unique-bind.rs | 2 +- src/test/run-pass/alt-with-ret-arm.rs | 2 +- src/test/run-pass/argument-passing.rs | 10 +- src/test/run-pass/arith-0.rs | 2 +- src/test/run-pass/arith-1.rs | 32 +- src/test/run-pass/arith-unsigned.rs | 12 +- src/test/run-pass/assign-assign.rs | 12 +- src/test/run-pass/assignability-trait.rs | 6 +- src/test/run-pass/auto-loop.rs | 2 +- src/test/run-pass/auto-ref-newtype.rs | 2 +- src/test/run-pass/auto-ref-sliceable.rs | 2 +- src/test/run-pass/autobind.rs | 4 +- src/test/run-pass/autoderef-method-newtype.rs | 2 +- .../run-pass/autoderef-method-on-trait.rs | 2 +- .../run-pass/autoderef-method-priority.rs | 2 +- .../autoderef-method-twice-but-not-thrice.rs | 2 +- src/test/run-pass/autoderef-method-twice.rs | 2 +- src/test/run-pass/autoderef-method.rs | 2 +- .../autoref-intermediate-types-issue-3585.rs | 2 +- src/test/run-pass/big-literals.rs | 12 +- .../run-pass/binary-minus-without-space.rs | 2 +- src/test/run-pass/binops.rs | 48 +- src/test/run-pass/bitwise.rs | 20 +- src/test/run-pass/block-arg-call-as.rs | 6 +- .../block-arg-can-be-followed-by-binop.rs | 2 +- .../block-arg-can-be-followed-by-block-arg.rs | 2 +- .../block-arg-can-be-followed-by-call.rs | 2 +- src/test/run-pass/block-arg-in-parentheses.rs | 8 +- src/test/run-pass/block-arg-used-as-any.rs | 2 +- src/test/run-pass/block-arg-used-as-lambda.rs | 4 +- src/test/run-pass/block-arg.rs | 4 +- src/test/run-pass/block-expr-precedence.rs | 4 +- src/test/run-pass/block-fn-coerce.rs | 4 +- src/test/run-pass/block-iter-1.rs | 2 +- src/test/run-pass/block-iter-2.rs | 2 +- src/test/run-pass/block-vec-map_zip.rs | 2 +- .../run-pass/borrowck-borrow-from-at-vec.rs | 2 +- .../borrowck-borrow-from-expr-block.rs | 2 +- .../run-pass/borrowck-fixed-length-vecs.rs | 2 +- .../run-pass/borrowck-mut-vec-as-imm-slice.rs | 2 +- .../borrowck-preserve-box-in-discr.rs | 6 +- .../borrowck-preserve-box-in-field.rs | 8 +- .../run-pass/borrowck-preserve-box-in-pat.rs | 6 +- .../run-pass/borrowck-preserve-box-in-uniq.rs | 8 +- src/test/run-pass/borrowck-preserve-box.rs | 8 +- .../run-pass/borrowck-preserve-cond-box.rs | 4 +- .../run-pass/borrowck-preserve-expl-deref.rs | 8 +- src/test/run-pass/borrowck-univariant-enum.rs | 2 +- .../borrowed-ptr-pattern-infallible.rs | 6 +- .../run-pass/borrowed-ptr-pattern-option.rs | 2 +- src/test/run-pass/borrowed-ptr-pattern.rs | 6 +- src/test/run-pass/box-unbox.rs | 2 +- src/test/run-pass/break.rs | 4 +- src/test/run-pass/c-stack-returning-int64.rs | 2 +- .../call-closure-from-overloaded-op.rs | 2 +- src/test/run-pass/cap-clause-move.rs | 8 +- src/test/run-pass/cast.rs | 16 +- src/test/run-pass/cci_borrow.rs | 2 +- src/test/run-pass/cci_nested_exe.rs | 8 +- src/test/run-pass/cfgs-on-items.rs | 4 +- src/test/run-pass/char.rs | 14 +- .../class-cast-to-trait-cross-crate-2.rs | 2 +- .../class-cast-to-trait-cross-crate.rs | 2 +- .../class-cast-to-trait-multiple-types.rs | 4 +- src/test/run-pass/class-exports.rs | 2 +- .../class-impl-very-parameterized-trait.rs | 8 +- .../class-implements-multiple-traits.rs | 2 +- src/test/run-pass/class-method-cross-crate.rs | 4 +- .../run-pass/class-methods-cross-crate.rs | 6 +- src/test/run-pass/class-methods.rs | 6 +- .../class-poly-methods-cross-crate.rs | 8 +- src/test/run-pass/class-poly-methods.rs | 8 +- src/test/run-pass/class-separate-impl.rs | 2 +- .../run-pass/class-trait-bounded-param.rs | 2 +- .../run-pass/classes-simple-cross-crate.rs | 4 +- src/test/run-pass/classes-simple-method.rs | 4 +- src/test/run-pass/classes-simple.rs | 4 +- src/test/run-pass/clone-with-exterior.rs | 4 +- .../close-over-big-then-small-data.rs | 4 +- src/test/run-pass/closure-inference.rs | 2 +- src/test/run-pass/closure-inference2.rs | 4 +- .../run-pass/coerce-reborrow-imm-ptr-rcvr.rs | 2 +- .../run-pass/coerce-reborrow-imm-vec-rcvr.rs | 6 +- .../run-pass/coerce-reborrow-mut-vec-arg.rs | 2 +- .../run-pass/coerce-reborrow-mut-vec-rcvr.rs | 2 +- src/test/run-pass/comm.rs | 2 +- src/test/run-pass/conditional-compile.rs | 2 +- src/test/run-pass/const-autoderef-newtype.rs | 2 +- src/test/run-pass/const-autoderef.rs | 4 +- src/test/run-pass/const-big-enum.rs | 4 +- src/test/run-pass/const-cast-ptr-int.rs | 2 +- src/test/run-pass/const-cast.rs | 4 +- src/test/run-pass/const-const.rs | 2 +- src/test/run-pass/const-contents.rs | 12 +- src/test/run-pass/const-cross-crate-const.rs | 8 +- src/test/run-pass/const-cross-crate-extern.rs | 2 +- src/test/run-pass/const-deref.rs | 4 +- src/test/run-pass/const-enum-cast.rs | 16 +- src/test/run-pass/const-enum-struct.rs | 2 +- src/test/run-pass/const-enum-struct2.rs | 2 +- src/test/run-pass/const-enum-tuple.rs | 2 +- src/test/run-pass/const-enum-tuple2.rs | 2 +- src/test/run-pass/const-enum-tuplestruct.rs | 2 +- src/test/run-pass/const-enum-tuplestruct2.rs | 2 +- src/test/run-pass/const-extern-function.rs | 4 +- .../run-pass/const-fields-and-indexing.rs | 6 +- src/test/run-pass/const-fn-val.rs | 2 +- src/test/run-pass/const-negative.rs | 2 +- .../run-pass/const-nullary-univariant-enum.rs | 4 +- src/test/run-pass/const-rec-and-tup.rs | 2 +- .../run-pass/const-region-ptrs-noncopy.rs | 2 +- src/test/run-pass/const-region-ptrs.rs | 4 +- src/test/run-pass/const-str-ptr.rs | 6 +- src/test/run-pass/const-struct.rs | 6 +- src/test/run-pass/const-tuple-struct.rs | 4 +- src/test/run-pass/const-vecs-and-slices.rs | 6 +- src/test/run-pass/consts-in-patterns.rs | 2 +- src/test/run-pass/crateresolve1.rs | 2 +- src/test/run-pass/crateresolve6.rs | 4 +- src/test/run-pass/crateresolve7.rs | 4 +- .../run-pass/deriving-via-extension-c-enum.rs | 2 +- .../run-pass/deriving-via-extension-enum.rs | 2 +- .../deriving-via-extension-struct-empty.rs | 2 +- ...-via-extension-struct-like-enum-variant.rs | 2 +- .../deriving-via-extension-struct-tuple.rs | 4 +- .../run-pass/deriving-via-extension-struct.rs | 2 +- .../deriving-via-extension-type-params.rs | 2 +- src/test/run-pass/div-mod.rs | 20 +- src/test/run-pass/do2.rs | 2 +- src/test/run-pass/do3.rs | 2 +- src/test/run-pass/empty-tag.rs | 2 +- src/test/run-pass/estr-slice.rs | 6 +- src/test/run-pass/estr-uniq.rs | 4 +- src/test/run-pass/evec-internal-boxes.rs | 4 +- src/test/run-pass/evec-internal.rs | 4 +- src/test/run-pass/evec-slice.rs | 4 +- src/test/run-pass/exec-env.rs | 2 +- src/test/run-pass/explicit-self-generic.rs | 2 +- .../run-pass/explicit-self-objects-box.rs | 2 +- .../run-pass/explicit-self-objects-simple.rs | 2 +- .../run-pass/explicit-self-objects-uniq.rs | 2 +- src/test/run-pass/explicit-self.rs | 10 +- src/test/run-pass/expr-alt-box.rs | 4 +- src/test/run-pass/expr-alt-fail.rs | 4 +- src/test/run-pass/expr-alt-struct.rs | 4 +- src/test/run-pass/expr-alt-unique.rs | 2 +- src/test/run-pass/expr-block-slot.rs | 4 +- src/test/run-pass/expr-block.rs | 2 +- src/test/run-pass/expr-copy.rs | 4 +- src/test/run-pass/expr-elseif-ref.rs | 2 +- src/test/run-pass/expr-fn.rs | 16 +- src/test/run-pass/expr-if-box.rs | 4 +- src/test/run-pass/expr-if-fail.rs | 4 +- src/test/run-pass/expr-if-struct.rs | 4 +- src/test/run-pass/expr-if-unique.rs | 2 +- src/test/run-pass/exterior.rs | 6 +- src/test/run-pass/extern-call-deep.rs | 2 +- src/test/run-pass/extern-call-deep2.rs | 2 +- src/test/run-pass/extern-call-scrub.rs | 2 +- src/test/run-pass/extern-call.rs | 2 +- src/test/run-pass/extern-crosscrate.rs | 2 +- src/test/run-pass/extern-pass-TwoU16s.rs | 2 +- src/test/run-pass/extern-pass-TwoU32s.rs | 2 +- src/test/run-pass/extern-pass-TwoU64s-ref.rs | 2 +- src/test/run-pass/extern-pass-TwoU64s.rs | 2 +- src/test/run-pass/extern-pass-TwoU8s.rs | 2 +- src/test/run-pass/extern-pass-char.rs | 2 +- src/test/run-pass/extern-pass-double.rs | 2 +- src/test/run-pass/extern-pass-u32.rs | 2 +- src/test/run-pass/extern-pass-u64.rs | 2 +- src/test/run-pass/extern-return-TwoU16s.rs | 4 +- src/test/run-pass/extern-return-TwoU32s.rs | 4 +- src/test/run-pass/extern-return-TwoU64s.rs | 4 +- src/test/run-pass/extern-return-TwoU8s.rs | 4 +- src/test/run-pass/extern-stress.rs | 2 +- src/test/run-pass/extern-take-value.rs | 2 +- src/test/run-pass/extern-yield.rs | 2 +- src/test/run-pass/fact.rs | 2 +- src/test/run-pass/fixed-point-bind-box.rs | 4 +- src/test/run-pass/fixed-point-bind-unique.rs | 4 +- src/test/run-pass/fixed_length_copy.rs | 4 +- src/test/run-pass/fixed_length_vec_glue.rs | 2 +- src/test/run-pass/float-nan.rs | 20 +- src/test/run-pass/float2.rs | 8 +- .../run-pass/fn-assign-managed-to-bare-1.rs | 4 +- .../run-pass/fn-assign-managed-to-bare-2.rs | 8 +- src/test/run-pass/fn-bare-assign.rs | 4 +- src/test/run-pass/fn-bare-spawn.rs | 2 +- src/test/run-pass/fn-pattern-expected-type.rs | 4 +- src/test/run-pass/for-destruct.rs | 2 +- src/test/run-pass/foreach-nested.rs | 8 +- src/test/run-pass/foreach-put-structured.rs | 4 +- .../run-pass/foreach-simple-outer-slot.rs | 2 +- src/test/run-pass/foreign-call-no-runtime.rs | 2 +- src/test/run-pass/foreign-fn-linkname.rs | 2 +- src/test/run-pass/foreign-lib-path.rs | 2 +- src/test/run-pass/fun-call-variants.rs | 2 +- src/test/run-pass/fun-indirect-call.rs | 2 +- src/test/run-pass/generic-alias-box.rs | 2 +- src/test/run-pass/generic-alias-unique.rs | 2 +- src/test/run-pass/generic-box.rs | 2 +- src/test/run-pass/generic-derived-type.rs | 4 +- src/test/run-pass/generic-exterior-box.rs | 2 +- src/test/run-pass/generic-exterior-unique.rs | 2 +- src/test/run-pass/generic-fn.rs | 6 +- src/test/run-pass/generic-object.rs | 2 +- src/test/run-pass/generic-tag-values.rs | 4 +- src/test/run-pass/generic-tup.rs | 4 +- src/test/run-pass/generic-type.rs | 4 +- src/test/run-pass/generic-unique.rs | 2 +- src/test/run-pass/guards-not-exhaustive.rs | 2 +- src/test/run-pass/guards.rs | 4 +- src/test/run-pass/i8-incr.rs | 2 +- src/test/run-pass/import-glob-crate.rs | 2 +- .../inferred-suffix-in-pattern-range.rs | 6 +- src/test/run-pass/init-res-into-things.rs | 12 +- src/test/run-pass/int-conversion-coherence.rs | 2 +- src/test/run-pass/integral-indexing.rs | 20 +- src/test/run-pass/intrinsic-alignment.rs | 16 +- src/test/run-pass/intrinsic-atomics-cc.rs | 2 +- src/test/run-pass/intrinsic-atomics.rs | 48 +- src/test/run-pass/intrinsic-move-val.rs | 2 +- src/test/run-pass/intrinsics-integer.rs | 156 ++--- src/test/run-pass/issue-1112.rs | 12 +- src/test/run-pass/issue-1458.rs | 2 +- src/test/run-pass/issue-1701.rs | 8 +- src/test/run-pass/issue-2214.rs | 2 +- src/test/run-pass/issue-2216.rs | 2 +- src/test/run-pass/issue-2428.rs | 2 +- src/test/run-pass/issue-2718.rs | 2 +- src/test/run-pass/issue-2748-b.rs | 4 +- src/test/run-pass/issue-2895.rs | 8 +- src/test/run-pass/issue-2936.rs | 2 +- src/test/run-pass/issue-2989.rs | 2 +- src/test/run-pass/issue-3091.rs | 2 +- src/test/run-pass/issue-3211.rs | 2 +- src/test/run-pass/issue-3683.rs | 2 +- src/test/run-pass/issue-3979-generics.rs | 2 +- src/test/run-pass/issue-3979-xcrate.rs | 2 +- src/test/run-pass/issue-3979.rs | 2 +- src/test/run-pass/issue-4241.rs | 6 +- src/test/run-pass/issue-4401.rs | 2 +- src/test/run-pass/issue-4448.rs | 2 +- src/test/run-pass/issue-979.rs | 2 +- src/test/run-pass/issue2378c.rs | 2 +- src/test/run-pass/istr.rs | 20 +- src/test/run-pass/iter-contains.rs | 16 +- src/test/run-pass/iter-count.rs | 14 +- src/test/run-pass/iter-eachi.rs | 8 +- src/test/run-pass/iter-filter-to-vec.rs | 10 +- src/test/run-pass/iter-flat-map-to-vec.rs | 20 +- src/test/run-pass/iter-foldl.rs | 10 +- src/test/run-pass/iter-map-to-vec.rs | 10 +- src/test/run-pass/iter-min-max.rs | 12 +- src/test/run-pass/iter-to-vec.rs | 10 +- src/test/run-pass/ivec-add.rs | 8 +- .../run-pass/kindck-owned-trait-contains-1.rs | 2 +- src/test/run-pass/last-use-in-cap-clause.rs | 2 +- src/test/run-pass/lazy-and-or.rs | 2 +- src/test/run-pass/let-destruct-fresh-mem.rs | 8 +- src/test/run-pass/let-destruct.rs | 2 +- src/test/run-pass/linear-for-loop.rs | 4 +- .../log-knows-the-names-of-variants-in-std.rs | 2 +- .../log-knows-the-names-of-variants.rs | 8 +- src/test/run-pass/log-str.rs | 4 +- src/test/run-pass/loop-break-cont.rs | 2 +- src/test/run-pass/loop-scope.rs | 2 +- src/test/run-pass/macro-path.rs | 2 +- src/test/run-pass/macro-stmt.rs | 6 +- src/test/run-pass/mod-inside-fn.rs | 2 +- src/test/run-pass/mod-merge-hack.rs | 4 +- src/test/run-pass/mod_dir_path.rs | 2 +- src/test/run-pass/mod_dir_path2.rs | 2 +- src/test/run-pass/mod_dir_path3.rs | 2 +- src/test/run-pass/mod_dir_path_multi.rs | 4 +- src/test/run-pass/mod_dir_recursive.rs | 2 +- src/test/run-pass/mod_dir_simple.rs | 2 +- src/test/run-pass/mod_file.rs | 2 +- src/test/run-pass/mod_file_with_path_attr.rs | 2 +- src/test/run-pass/monad.rs | 4 +- .../run-pass/monomorphize-trait-in-fn-at.rs | 2 +- src/test/run-pass/morestack3.rs | 20 +- src/test/run-pass/move-1-unique.rs | 8 +- src/test/run-pass/move-1.rs | 8 +- src/test/run-pass/move-3-unique.rs | 4 +- src/test/run-pass/move-3.rs | 4 +- src/test/run-pass/move-4.rs | 2 +- src/test/run-pass/move-scalar.rs | 2 +- src/test/run-pass/mut-function-arguments.rs | 2 +- ...ility-inherits-through-fixed-length-vec.rs | 2 +- src/test/run-pass/mutable-alias-vec.rs | 2 +- src/test/run-pass/nested-class.rs | 4 +- src/test/run-pass/nested-patterns.rs | 4 +- src/test/run-pass/newlambdas.rs | 6 +- src/test/run-pass/newtype-polymorphic.rs | 6 +- src/test/run-pass/newtype.rs | 2 +- src/test/run-pass/non-boolean-pure-fns.rs | 2 +- src/test/run-pass/non-legacy-modes.rs | 2 +- src/test/run-pass/nullable-pointer-size.rs | 4 +- src/test/run-pass/nullary-or-pattern.rs | 4 +- .../run-pass/numeric-method-autoexport.rs | 26 +- src/test/run-pass/one-tuple.rs | 4 +- src/test/run-pass/opeq.rs | 8 +- src/test/run-pass/operator-overloading.rs | 12 +- src/test/run-pass/option-unwrap.rs | 2 +- src/test/run-pass/option_addition.rs | 6 +- src/test/run-pass/or-pattern.rs | 6 +- .../run-pass/pattern-bound-var-in-for-each.rs | 2 +- src/test/run-pass/pipe-select.rs | 4 +- src/test/run-pass/placement-new-arena.rs | 2 +- src/test/run-pass/private-class-field.rs | 2 +- .../propagate-expected-type-through-block.rs | 2 +- src/test/run-pass/rcvr-borrowed-to-region.rs | 10 +- src/test/run-pass/rcvr-borrowed-to-slice.rs | 6 +- src/test/run-pass/rec-align-u32.rs | 6 +- src/test/run-pass/rec-align-u64.rs | 6 +- src/test/run-pass/rec-extend.rs | 12 +- src/test/run-pass/rec-tup.rs | 18 +- src/test/run-pass/rec.rs | 18 +- src/test/run-pass/record-pat.rs | 4 +- src/test/run-pass/region-dependent-addr-of.rs | 18 +- .../region-return-interior-of-option.rs | 4 +- .../run-pass/regions-appearance-constraint.rs | 2 +- src/test/run-pass/regions-borrow-at.rs | 2 +- src/test/run-pass/regions-borrow-estr-uniq.rs | 4 +- src/test/run-pass/regions-borrow-evec-at.rs | 2 +- .../run-pass/regions-borrow-evec-fixed.rs | 2 +- src/test/run-pass/regions-borrow-evec-uniq.rs | 4 +- src/test/run-pass/regions-borrow-uniq.rs | 2 +- src/test/run-pass/regions-copy-closure.rs | 4 +- .../run-pass/regions-escape-into-other-fn.rs | 2 +- ...gions-infer-borrow-scope-within-loop-ok.rs | 2 +- .../run-pass/regions-infer-borrow-scope.rs | 2 +- src/test/run-pass/regions-infer-call-2.rs | 2 +- src/test/run-pass/regions-infer-call.rs | 2 +- ...regions-infer-contravariance-due-to-ret.rs | 2 +- src/test/run-pass/regions-params.rs | 2 +- src/test/run-pass/regions-trait.rs | 2 +- .../run-pass/resource-assign-is-not-copy.rs | 2 +- src/test/run-pass/resource-destruct.rs | 2 +- src/test/run-pass/resource-generic.rs | 2 +- src/test/run-pass/ret-break-cont-in-block.rs | 12 +- src/test/run-pass/rt-sched-1.rs | 2 +- src/test/run-pass/sendfn-is-a-block.rs | 2 +- src/test/run-pass/sendfn-spawn-with-fn-arg.rs | 2 +- src/test/run-pass/seq-compare.rs | 2 +- src/test/run-pass/shift.rs | 42 +- src/test/run-pass/signed-shift-const-eval.rs | 2 +- src/test/run-pass/spawn-types.rs | 2 +- src/test/run-pass/spawn2.rs | 18 +- src/test/run-pass/stable-addr-of.rs | 2 +- src/test/run-pass/stat.rs | 2 +- src/test/run-pass/static-impl.rs | 12 +- ...tic-method-in-trait-with-tps-intracrate.rs | 2 +- src/test/run-pass/static-method-test.rs | 12 +- src/test/run-pass/static-method-xcrate.rs | 6 +- src/test/run-pass/static-methods-in-traits.rs | 4 +- src/test/run-pass/str-append.rs | 6 +- src/test/run-pass/str-concat.rs | 2 +- src/test/run-pass/str-growth.rs | 12 +- src/test/run-pass/str-idx.rs | 2 +- src/test/run-pass/str-multiline.rs | 4 +- src/test/run-pass/string-self-append.rs | 2 +- src/test/run-pass/struct-deref.rs | 2 +- .../struct-destructuring-cross-crate.rs | 4 +- .../run-pass/struct-field-assignability.rs | 2 +- .../run-pass/struct-like-variant-match.rs | 8 +- src/test/run-pass/struct-return.rs | 14 +- src/test/run-pass/structured-compare.rs | 4 +- src/test/run-pass/swap-2.rs | 8 +- src/test/run-pass/syntax-extension-fmt.rs | 14 +- src/test/run-pass/syntax-extension-minor.rs | 2 +- .../run-pass/syntax-extension-source-utils.rs | 6 +- src/test/run-pass/tag-disr-val-shape.rs | 6 +- src/test/run-pass/tag-variant-disr-val.rs | 4 +- src/test/run-pass/task-comm-0.rs | 2 +- src/test/run-pass/task-comm-16.rs | 28 +- src/test/run-pass/task-comm-3.rs | 2 +- src/test/run-pass/task-comm-4.rs | 2 +- src/test/run-pass/task-comm-5.rs | 2 +- src/test/run-pass/task-comm-6.rs | 2 +- src/test/run-pass/task-comm-7.rs | 2 +- src/test/run-pass/task-comm-9.rs | 2 +- src/test/run-pass/task-comm-chan-nil.rs | 2 +- src/test/run-pass/task-spawn-move-and-copy.rs | 2 +- src/test/run-pass/trait-bounds.rs | 2 +- src/test/run-pass/trait-cast.rs | 4 +- .../trait-default-method-bound-subst.rs | 2 +- .../trait-default-method-bound-subst2.rs | 2 +- .../trait-default-method-bound-subst3.rs | 4 +- .../trait-default-method-bound-subst4.rs | 4 +- .../run-pass/trait-default-method-bound.rs | 2 +- src/test/run-pass/trait-generic.rs | 8 +- .../run-pass/trait-inheritance-auto-xc-2.rs | 6 +- .../run-pass/trait-inheritance-auto-xc.rs | 6 +- src/test/run-pass/trait-inheritance-auto.rs | 6 +- .../trait-inheritance-call-bound-inherited.rs | 2 +- ...trait-inheritance-call-bound-inherited2.rs | 2 +- ...ritance-cast-without-call-to-supertrait.rs | 4 +- src/test/run-pass/trait-inheritance-cast.rs | 6 +- .../trait-inheritance-cross-trait-call-xc.rs | 2 +- .../trait-inheritance-cross-trait-call.rs | 2 +- .../run-pass/trait-inheritance-diamond.rs | 8 +- .../trait-inheritance-multiple-inheritors.rs | 6 +- .../trait-inheritance-multiple-params.rs | 10 +- .../trait-inheritance-overloading-simple.rs | 2 +- .../trait-inheritance-overloading-xc-exe.rs | 6 +- .../run-pass/trait-inheritance-overloading.rs | 6 +- src/test/run-pass/trait-inheritance-simple.rs | 4 +- src/test/run-pass/trait-inheritance-static.rs | 2 +- .../run-pass/trait-inheritance-static2.rs | 2 +- src/test/run-pass/trait-inheritance-subst2.rs | 2 +- .../run-pass/trait-inheritance-visibility.rs | 2 +- src/test/run-pass/trait-inheritance2.rs | 6 +- .../run-pass/trait-region-pointer-simple.rs | 2 +- .../trait_with_static_methods_cross_crate.rs | 2 +- .../run-pass/traits-default-method-macro.rs | 2 +- src/test/run-pass/tup.rs | 8 +- .../run-pass/tuple-struct-destructuring.rs | 4 +- src/test/run-pass/tuple-struct-matching.rs | 4 +- src/test/run-pass/type-sizes.rs | 22 +- src/test/run-pass/u32-decr.rs | 2 +- src/test/run-pass/u8-incr-decr.rs | 2 +- src/test/run-pass/u8-incr.rs | 2 +- src/test/run-pass/unique-assign-copy.rs | 4 +- src/test/run-pass/unique-assign-drop.rs | 2 +- src/test/run-pass/unique-assign-generic.rs | 4 +- src/test/run-pass/unique-assign.rs | 2 +- src/test/run-pass/unique-autoderef-field.rs | 2 +- src/test/run-pass/unique-autoderef-index.rs | 2 +- src/test/run-pass/unique-containing-tag.rs | 4 +- src/test/run-pass/unique-copy-box.rs | 2 +- src/test/run-pass/unique-decl-init-copy.rs | 4 +- src/test/run-pass/unique-decl-init.rs | 2 +- src/test/run-pass/unique-decl-move-temp.rs | 2 +- src/test/run-pass/unique-decl-move.rs | 2 +- src/test/run-pass/unique-deref.rs | 2 +- src/test/run-pass/unique-destructure.rs | 2 +- src/test/run-pass/unique-fn-arg-move.rs | 2 +- src/test/run-pass/unique-fn-arg-mut.rs | 2 +- src/test/run-pass/unique-fn-arg.rs | 2 +- src/test/run-pass/unique-fn-ret.rs | 2 +- src/test/run-pass/unique-in-vec-copy.rs | 8 +- src/test/run-pass/unique-kinds.rs | 6 +- src/test/run-pass/unique-move-drop.rs | 2 +- src/test/run-pass/unique-move-temp.rs | 2 +- src/test/run-pass/unique-move.rs | 2 +- src/test/run-pass/unique-mutable.rs | 2 +- src/test/run-pass/unique-object.rs | 2 +- src/test/run-pass/unique-pinned-nocopy-2.rs | 2 +- src/test/run-pass/unique-rec.rs | 2 +- src/test/run-pass/unique-send-2.rs | 2 +- src/test/run-pass/unique-send.rs | 2 +- src/test/run-pass/unique-swap.rs | 4 +- .../run-pass/unsafe-pointer-assignability.rs | 2 +- src/test/run-pass/utf8.rs | 18 +- src/test/run-pass/utf8_chars.rs | 24 +- src/test/run-pass/utf8_idents.rs | 10 +- src/test/run-pass/vec-concat.rs | 6 +- src/test/run-pass/vec-each2_mut.rs | 8 +- src/test/run-pass/vec-growth.rs | 10 +- src/test/run-pass/vec-matching-autoslice.rs | 6 +- src/test/run-pass/vec-matching-fold.rs | 4 +- src/test/run-pass/vec-matching.rs | 26 +- src/test/run-pass/vec-self-append.rs | 38 +- src/test/run-pass/vec-slice-drop.rs | 4 +- src/test/run-pass/vec-slice.rs | 4 +- src/test/run-pass/vec-tail-matching.rs | 6 +- src/test/run-pass/vec-to_str.rs | 12 +- src/test/run-pass/vec-trailing-comma.rs | 4 +- src/test/run-pass/vec.rs | 12 +- src/test/run-pass/while-with-break.rs | 2 +- src/test/run-pass/writealias.rs | 2 +- src/test/run-pass/x86stdcall.rs | 2 +- src/test/run-pass/zip-same-length.rs | 4 +- 641 files changed, 2831 insertions(+), 2831 deletions(-) diff --git a/src/libcore/at_vec.rs b/src/libcore/at_vec.rs index 93bbf8fb66214..44c55563ac57f 100644 --- a/src/libcore/at_vec.rs +++ b/src/libcore/at_vec.rs @@ -294,30 +294,30 @@ mod test { } assert_eq!(seq_range(10, 15), @[10, 11, 12, 13, 14]); - assert!(from_fn(5, |x| x+1) == @[1, 2, 3, 4, 5]); - assert!(from_elem(5, 3.14) == @[3.14, 3.14, 3.14, 3.14, 3.14]); + assert_eq!(from_fn(5, |x| x+1), @[1, 2, 3, 4, 5]); + assert_eq!(from_elem(5, 3.14), @[3.14, 3.14, 3.14, 3.14, 3.14]); } #[test] fn append_test() { - assert!(@[1,2,3] + @[4,5,6] == @[1,2,3,4,5,6]); + assert_eq!(@[1,2,3] + @[4,5,6], @[1,2,3,4,5,6]); } #[test] fn test_to_managed_consume() { - assert!(to_managed_consume::(~[]) == @[]); - assert!(to_managed_consume(~[true]) == @[true]); - assert!(to_managed_consume(~[1, 2, 3, 4, 5]) == @[1, 2, 3, 4, 5]); - assert!(to_managed_consume(~[~"abc", ~"123"]) == @[~"abc", ~"123"]); - assert!(to_managed_consume(~[~[42]]) == @[~[42]]); + assert_eq!(to_managed_consume::(~[]), @[]); + assert_eq!(to_managed_consume(~[true]), @[true]); + assert_eq!(to_managed_consume(~[1, 2, 3, 4, 5]), @[1, 2, 3, 4, 5]); + assert_eq!(to_managed_consume(~[~"abc", ~"123"]), @[~"abc", ~"123"]); + assert_eq!(to_managed_consume(~[~[42]]), @[~[42]]); } #[test] fn test_to_managed() { - assert!(to_managed::([]) == @[]); - assert!(to_managed([true]) == @[true]); - assert!(to_managed([1, 2, 3, 4, 5]) == @[1, 2, 3, 4, 5]); - assert!(to_managed([@"abc", @"123"]) == @[@"abc", @"123"]); - assert!(to_managed([@[42]]) == @[@[42]]); + assert_eq!(to_managed::([]), @[]); + assert_eq!(to_managed([true]), @[true]); + assert_eq!(to_managed([1, 2, 3, 4, 5]), @[1, 2, 3, 4, 5]); + assert_eq!(to_managed([@"abc", @"123"]), @[@"abc", @"123"]); + assert_eq!(to_managed([@[42]]), @[@[42]]); } } diff --git a/src/libcore/bool.rs b/src/libcore/bool.rs index b3c0b8cad7a4e..5ab7f838a57cc 100644 --- a/src/libcore/bool.rs +++ b/src/libcore/bool.rs @@ -113,14 +113,14 @@ mod tests { #[test] fn test_bool_to_str() { - assert!(to_str(false) == ~"false"); - assert!(to_str(true) == ~"true"); + assert_eq!(to_str(false), ~"false"); + assert_eq!(to_str(true), ~"true"); } #[test] fn test_bool_to_bit() { do all_values |v| { - assert!(to_bit(v) == if is_true(v) { 1u8 } else { 0u8 }); + assert_eq!(to_bit(v), if is_true(v) { 1u8 } else { 0u8 }); } } diff --git a/src/libcore/cast.rs b/src/libcore/cast.rs index 7451353458e28..8b48376caac5e 100644 --- a/src/libcore/cast.rs +++ b/src/libcore/cast.rs @@ -145,7 +145,7 @@ mod tests { #[test] fn test_transmute_copy() { - assert!(1u == unsafe { ::cast::transmute_copy(&1) }); + assert_eq!(1u, unsafe { ::cast::transmute_copy(&1) }); } #[test] @@ -177,7 +177,7 @@ mod tests { #[test] fn test_transmute2() { unsafe { - assert!(~[76u8, 0u8] == transmute(~"L")); + assert_eq!(~[76u8, 0u8], transmute(~"L")); } } } diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 87e8d0525e5b0..b707e3bbb9efa 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -122,7 +122,7 @@ fn test_with_ref() { let good = 6; let c = Cell(~[1, 2, 3, 4, 5, 6]); let l = do c.with_ref() |v| { v.len() }; - assert!(l == good); + assert_eq!(l, good); } #[test] @@ -132,5 +132,5 @@ fn test_with_mut_ref() { let c = Cell(v); do c.with_mut_ref() |v| { v.push(3); } let v = c.take(); - assert!(v == good); + assert_eq!(v, good); } diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 4d2b5998b445b..2650b96c4083c 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -146,14 +146,14 @@ deep_clone_impl!(char) fn test_owned_clone() { let a = ~5i; let b: ~int = a.clone(); - assert!(a == b); + assert_eq!(a, b); } #[test] fn test_managed_clone() { let a = @5i; let b: @int = a.clone(); - assert!(a == b); + assert_eq!(a, b); } #[test] @@ -168,9 +168,9 @@ fn test_managed_mut_deep_clone() { fn test_managed_mut_clone() { let a = @mut 5i; let b: @mut int = a.clone(); - assert!(a == b); + assert_eq!(a, b); *b = 10; - assert!(a == b); + assert_eq!(a, b); } #[test] diff --git a/src/libcore/hash.rs b/src/libcore/hash.rs index cb02364d725f8..ebc15174c5c73 100644 --- a/src/libcore/hash.rs +++ b/src/libcore/hash.rs @@ -490,7 +490,7 @@ mod tests { let vec = u8to64_le!(vecs[t], 0); let out = buf.hash_keyed(k0, k1); debug!("got %?, expected %?", out, vec); - assert!(vec == out); + assert_eq!(vec, out); stream_full.reset(); stream_full.input(buf); @@ -512,19 +512,19 @@ mod tests { fn test_hash_uint() { let val = 0xdeadbeef_deadbeef_u64; assert!((val as u64).hash() != (val as uint).hash()); - assert!((val as u32).hash() == (val as uint).hash()); + assert_eq!((val as u32).hash(), (val as uint).hash()); } #[test] #[cfg(target_arch = "x86_64")] fn test_hash_uint() { let val = 0xdeadbeef_deadbeef_u64; - assert!((val as u64).hash() == (val as uint).hash()); + assert_eq!((val as u64).hash(), (val as uint).hash()); assert!((val as u32).hash() != (val as uint).hash()); } #[test] #[cfg(target_arch = "x86")] fn test_hash_uint() { let val = 0xdeadbeef_deadbeef_u64; assert!((val as u64).hash() != (val as uint).hash()); - assert!((val as u32).hash() == (val as uint).hash()); + assert_eq!((val as u32).hash(), (val as uint).hash()); } #[test] diff --git a/src/libcore/hashmap.rs b/src/libcore/hashmap.rs index d9912813cf930..fe44bfba1140d 100644 --- a/src/libcore/hashmap.rs +++ b/src/libcore/hashmap.rs @@ -842,8 +842,8 @@ mod test_map { let mut m = HashMap::new(); assert!(m.insert(1, 2)); assert!(m.insert(2, 4)); - assert!(*m.get(&1) == 2); - assert!(*m.get(&2) == 4); + assert_eq!(*m.get(&1), 2); + assert_eq!(*m.get(&2), 4); } #[test] @@ -863,9 +863,9 @@ mod test_map { fn test_insert_overwrite() { let mut m = HashMap::new(); assert!(m.insert(1, 2)); - assert!(*m.get(&1) == 2); + assert_eq!(*m.get(&1), 2); assert!(!m.insert(1, 3)); - assert!(*m.get(&1) == 3); + assert_eq!(*m.get(&1), 3); } #[test] @@ -874,9 +874,9 @@ mod test_map { assert!(m.insert(1, 2)); assert!(m.insert(5, 3)); assert!(m.insert(9, 4)); - assert!(*m.get(&9) == 4); - assert!(*m.get(&5) == 3); - assert!(*m.get(&1) == 2); + assert_eq!(*m.get(&9), 4); + assert_eq!(*m.get(&5), 3); + assert_eq!(*m.get(&1), 2); } #[test] @@ -886,8 +886,8 @@ mod test_map { assert!(m.insert(5, 3)); assert!(m.insert(9, 4)); assert!(m.remove(&1)); - assert!(*m.get(&9) == 4); - assert!(*m.get(&5) == 3); + assert_eq!(*m.get(&9), 4); + assert_eq!(*m.get(&5), 3); } #[test] @@ -903,30 +903,30 @@ mod test_map { fn test_pop() { let mut m = HashMap::new(); m.insert(1, 2); - assert!(m.pop(&1) == Some(2)); - assert!(m.pop(&1) == None); + assert_eq!(m.pop(&1), Some(2)); + assert_eq!(m.pop(&1), None); } #[test] fn test_swap() { let mut m = HashMap::new(); - assert!(m.swap(1, 2) == None); - assert!(m.swap(1, 3) == Some(2)); - assert!(m.swap(1, 4) == Some(3)); + assert_eq!(m.swap(1, 2), None); + assert_eq!(m.swap(1, 3), Some(2)); + assert_eq!(m.swap(1, 4), Some(3)); } #[test] fn test_find_or_insert() { let mut m = HashMap::new::(); - assert!(m.find_or_insert(1, 2) == &2); - assert!(m.find_or_insert(1, 3) == &2); + assert_eq!(m.find_or_insert(1, 2), &2); + assert_eq!(m.find_or_insert(1, 3), &2); } #[test] fn test_find_or_insert_with() { let mut m = HashMap::new::(); - assert!(m.find_or_insert_with(1, |_| 2) == &2); - assert!(m.find_or_insert_with(1, |_| 3) == &2); + assert_eq!(m.find_or_insert_with(1, |_| 2), &2); + assert_eq!(m.find_or_insert_with(1, |_| 3), &2); } #[test] @@ -938,10 +938,10 @@ mod test_map { do m.consume |k, v| { m2.insert(k, v); } - assert!(m.len() == 0); - assert!(m2.len() == 2); - assert!(m2.get(&1) == &2); - assert!(m2.get(&2) == &3); + assert_eq!(m.len(), 0); + assert_eq!(m2.len(), 2); + assert_eq!(m2.get(&1), &2); + assert_eq!(m2.get(&2), &3); } #[test] @@ -952,10 +952,10 @@ mod test_map { } let mut observed = 0; for m.each |k, v| { - assert!(*v == *k * 2); + assert_eq!(*v, *k * 2); observed |= (1 << *k); } - assert!(observed == 0xFFFF_FFFF); + assert_eq!(observed, 0xFFFF_FFFF); } #[test] @@ -984,14 +984,14 @@ mod test_map { m2.insert(3, 4); - assert!(m1 == m2); + assert_eq!(m1, m2); } #[test] fn test_expand() { let mut m = HashMap::new(); - assert!(m.len() == 0); + assert_eq!(m.len(), 0); assert!(m.is_empty()); let mut i = 0u; @@ -1001,7 +1001,7 @@ mod test_map { i += 1; } - assert!(m.len() == i); + assert_eq!(m.len(), i); assert!(!m.is_empty()); } } @@ -1090,7 +1090,7 @@ mod test_set { assert!(vec::contains(expected, x)); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1113,7 +1113,7 @@ mod test_set { assert!(vec::contains(expected, x)); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1139,7 +1139,7 @@ mod test_set { assert!(vec::contains(expected, x)); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1169,6 +1169,6 @@ mod test_set { assert!(vec::contains(expected, x)); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } } diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 7b7d278380f1a..77b486ca44619 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -635,7 +635,7 @@ impl ReaderUtil for T { let next = bytes[i] as int; i += 1; assert!((next > -1)); - assert!((next & 192 == 128)); + assert_eq!(next & 192, 128); val <<= 6; val += (next & 63) as uint; } @@ -676,7 +676,7 @@ impl ReaderUtil for T { if c.len() == 0 { return -1 as char; // FIXME will this stay valid? // #2004 } - assert!(c.len() == 1); + assert_eq!(c.len(), 1); return c[0]; } @@ -1795,14 +1795,14 @@ mod tests { let inp: @io::Reader = result::get(&io::file_reader(tmpfile)); let frood2: ~str = inp.read_c_str(); debug!(copy frood2); - assert!(frood == frood2); + assert_eq!(frood, frood2); } #[test] fn test_readchars_empty() { do io::with_str_reader(~"") |inp| { let res : ~[char] = inp.read_chars(128); - assert!(res.len() == 0); + assert_eq!(res.len(), 0); } } @@ -1810,18 +1810,18 @@ mod tests { fn test_read_line_utf8() { do io::with_str_reader(~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤") |inp| { let line = inp.read_line(); - assert!(line == ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤"); + assert_eq!(line, ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤"); } } #[test] fn test_read_lines() { do io::with_str_reader(~"a\nb\nc\n") |inp| { - assert!(inp.read_lines() == ~[~"a", ~"b", ~"c"]); + assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]); } do io::with_str_reader(~"a\nb\nc") |inp| { - assert!(inp.read_lines() == ~[~"a", ~"b", ~"c"]); + assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]); } do io::with_str_reader(~"") |inp| { @@ -1842,7 +1842,7 @@ mod tests { do io::with_str_reader(s) |inp| { let res : ~[char] = inp.read_chars(len); if len <= ivals.len() { - assert!(res.len() == len); + assert_eq!(res.len(), len); } assert!(vec::slice(ivals, 0u, res.len()) == vec::map(res, |x| *x as int)); @@ -1861,7 +1861,7 @@ mod tests { fn test_readchar() { do io::with_str_reader(~"生") |inp| { let res : char = inp.read_char(); - assert!((res as int == 29983)); + assert_eq!(res as int, 29983); } } @@ -1869,7 +1869,7 @@ mod tests { fn test_readchar_empty() { do io::with_str_reader(~"") |inp| { let res : char = inp.read_char(); - assert!((res as int == -1)); + assert_eq!(res as int, -1); } } @@ -1877,7 +1877,7 @@ mod tests { fn file_reader_not_exist() { match io::file_reader(&Path("not a file")) { result::Err(copy e) => { - assert!(e == ~"error opening not a file"); + assert_eq!(e, ~"error opening not a file"); } result::Ok(_) => fail!() } @@ -1966,7 +1966,7 @@ mod tests { { let file = io::file_reader(&path).get(); for uints.each |i| { - assert!(file.read_le_u64() == *i); + assert_eq!(file.read_le_u64(), *i); } } } @@ -1988,7 +1988,7 @@ mod tests { { let file = io::file_reader(&path).get(); for uints.each |i| { - assert!(file.read_be_u64() == *i); + assert_eq!(file.read_be_u64(), *i); } } } @@ -2012,7 +2012,7 @@ mod tests { for ints.each |i| { // this tests that the sign extension is working // (comparing the values as i32 would not test this) - assert!(file.read_be_int_n(4) == *i as i64); + assert_eq!(file.read_be_int_n(4), *i as i64); } } } @@ -2031,7 +2031,7 @@ mod tests { { let file = io::file_reader(&path).get(); let f = file.read_be_f32(); - assert!(f == 8.1250); + assert_eq!(f, 8.1250); } } @@ -2048,8 +2048,8 @@ mod tests { { let file = io::file_reader(&path).get(); - assert!(file.read_be_f32() == 8.1250); - assert!(file.read_le_f32() == 8.1250); + assert_eq!(file.read_be_f32(), 8.1250); + assert_eq!(file.read_le_f32(), 8.1250); } } } diff --git a/src/libcore/num/int-template/int.rs b/src/libcore/num/int-template/int.rs index 7a44bfdf16038..64f6f2d2a9a9b 100644 --- a/src/libcore/num/int-template/int.rs +++ b/src/libcore/num/int-template/int.rs @@ -85,20 +85,20 @@ mod inst { #[test] fn test_pow() { - assert!((pow(0, 0u) == 1)); - assert!((pow(0, 1u) == 0)); - assert!((pow(0, 2u) == 0)); - assert!((pow(-1, 0u) == 1)); - assert!((pow(1, 0u) == 1)); - assert!((pow(-3, 2u) == 9)); - assert!((pow(-3, 3u) == -27)); - assert!((pow(4, 9u) == 262144)); + assert_eq!(pow(0, 0u), 1); + assert_eq!(pow(0, 1u), 0); + assert_eq!(pow(0, 2u), 0); + assert_eq!(pow(-1, 0u), 1); + assert_eq!(pow(1, 0u), 1); + assert_eq!(pow(-3, 2u), 9); + assert_eq!(pow(-3, 3u), -27); + assert_eq!(pow(4, 9u), 262144); } #[test] fn test_overflows() { assert!((::int::max_value > 0)); assert!((::int::min_value <= 0)); - assert!((::int::min_value + ::int::max_value + 1 == 0)); + assert_eq!(::int::min_value + ::int::max_value + 1, 0); } } diff --git a/src/libcore/num/uint-template/uint.rs b/src/libcore/num/uint-template/uint.rs index d8a4ec19304f3..b4c9bb653712e 100644 --- a/src/libcore/num/uint-template/uint.rs +++ b/src/libcore/num/uint-template/uint.rs @@ -211,46 +211,46 @@ pub mod inst { #[test] fn test_next_power_of_two() { - assert!((next_power_of_two(0u) == 0u)); - assert!((next_power_of_two(1u) == 1u)); - assert!((next_power_of_two(2u) == 2u)); - assert!((next_power_of_two(3u) == 4u)); - assert!((next_power_of_two(4u) == 4u)); - assert!((next_power_of_two(5u) == 8u)); - assert!((next_power_of_two(6u) == 8u)); - assert!((next_power_of_two(7u) == 8u)); - assert!((next_power_of_two(8u) == 8u)); - assert!((next_power_of_two(9u) == 16u)); - assert!((next_power_of_two(10u) == 16u)); - assert!((next_power_of_two(11u) == 16u)); - assert!((next_power_of_two(12u) == 16u)); - assert!((next_power_of_two(13u) == 16u)); - assert!((next_power_of_two(14u) == 16u)); - assert!((next_power_of_two(15u) == 16u)); - assert!((next_power_of_two(16u) == 16u)); - assert!((next_power_of_two(17u) == 32u)); - assert!((next_power_of_two(18u) == 32u)); - assert!((next_power_of_two(19u) == 32u)); - assert!((next_power_of_two(20u) == 32u)); - assert!((next_power_of_two(21u) == 32u)); - assert!((next_power_of_two(22u) == 32u)); - assert!((next_power_of_two(23u) == 32u)); - assert!((next_power_of_two(24u) == 32u)); - assert!((next_power_of_two(25u) == 32u)); - assert!((next_power_of_two(26u) == 32u)); - assert!((next_power_of_two(27u) == 32u)); - assert!((next_power_of_two(28u) == 32u)); - assert!((next_power_of_two(29u) == 32u)); - assert!((next_power_of_two(30u) == 32u)); - assert!((next_power_of_two(31u) == 32u)); - assert!((next_power_of_two(32u) == 32u)); - assert!((next_power_of_two(33u) == 64u)); - assert!((next_power_of_two(34u) == 64u)); - assert!((next_power_of_two(35u) == 64u)); - assert!((next_power_of_two(36u) == 64u)); - assert!((next_power_of_two(37u) == 64u)); - assert!((next_power_of_two(38u) == 64u)); - assert!((next_power_of_two(39u) == 64u)); + assert_eq!(next_power_of_two(0u), 0u); + assert_eq!(next_power_of_two(1u), 1u); + assert_eq!(next_power_of_two(2u), 2u); + assert_eq!(next_power_of_two(3u), 4u); + assert_eq!(next_power_of_two(4u), 4u); + assert_eq!(next_power_of_two(5u), 8u); + assert_eq!(next_power_of_two(6u), 8u); + assert_eq!(next_power_of_two(7u), 8u); + assert_eq!(next_power_of_two(8u), 8u); + assert_eq!(next_power_of_two(9u), 16u); + assert_eq!(next_power_of_two(10u), 16u); + assert_eq!(next_power_of_two(11u), 16u); + assert_eq!(next_power_of_two(12u), 16u); + assert_eq!(next_power_of_two(13u), 16u); + assert_eq!(next_power_of_two(14u), 16u); + assert_eq!(next_power_of_two(15u), 16u); + assert_eq!(next_power_of_two(16u), 16u); + assert_eq!(next_power_of_two(17u), 32u); + assert_eq!(next_power_of_two(18u), 32u); + assert_eq!(next_power_of_two(19u), 32u); + assert_eq!(next_power_of_two(20u), 32u); + assert_eq!(next_power_of_two(21u), 32u); + assert_eq!(next_power_of_two(22u), 32u); + assert_eq!(next_power_of_two(23u), 32u); + assert_eq!(next_power_of_two(24u), 32u); + assert_eq!(next_power_of_two(25u), 32u); + assert_eq!(next_power_of_two(26u), 32u); + assert_eq!(next_power_of_two(27u), 32u); + assert_eq!(next_power_of_two(28u), 32u); + assert_eq!(next_power_of_two(29u), 32u); + assert_eq!(next_power_of_two(30u), 32u); + assert_eq!(next_power_of_two(31u), 32u); + assert_eq!(next_power_of_two(32u), 32u); + assert_eq!(next_power_of_two(33u), 64u); + assert_eq!(next_power_of_two(34u), 64u); + assert_eq!(next_power_of_two(35u), 64u); + assert_eq!(next_power_of_two(36u), 64u); + assert_eq!(next_power_of_two(37u), 64u); + assert_eq!(next_power_of_two(38u), 64u); + assert_eq!(next_power_of_two(39u), 64u); } #[test] @@ -258,14 +258,14 @@ pub mod inst { use uint; assert!((uint::max_value > 0u)); assert!((uint::min_value <= 0u)); - assert!((uint::min_value + uint::max_value + 1u == 0u)); + assert_eq!(uint::min_value + uint::max_value + 1u, 0u); } #[test] fn test_div() { - assert!((div_floor(3u, 4u) == 0u)); - assert!((div_ceil(3u, 4u) == 1u)); - assert!((div_round(3u, 4u) == 1u)); + assert_eq!(div_floor(3u, 4u), 0u); + assert_eq!(div_ceil(3u, 4u), 1u); + assert_eq!(div_round(3u, 4u), 1u); } #[test] @@ -274,6 +274,6 @@ pub mod inst { let ten = 10 as uint; let mut accum = 0; for ten.times { accum += 1; } - assert!((accum == 10)); + assert_eq!(accum, 10); } } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 0212d4abd29d6..71c242bb69b3c 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -405,7 +405,7 @@ fn test_unwrap_ptr() { let opt = Some(x); let y = opt.unwrap(); let addr_y: *int = ::cast::transmute(&*y); - assert!(addr_x == addr_y); + assert_eq!(addr_x, addr_y); } } @@ -416,7 +416,7 @@ fn test_unwrap_str() { let opt = Some(x); let y = opt.unwrap(); let addr_y = str::as_buf(y, |buf, _len| buf); - assert!(addr_x == addr_y); + assert_eq!(addr_x, addr_y); } #[test] @@ -442,7 +442,7 @@ fn test_unwrap_resource() { let opt = Some(x); let _y = opt.unwrap(); } - assert!(*i == 1); + assert_eq!(*i, 1); } #[test] @@ -453,7 +453,7 @@ fn test_option_dance() { for x.each |_x| { y2 = y.swap_unwrap(); } - assert!(y2 == 5); + assert_eq!(y2, 5); assert!(y.is_none()); } #[test] #[should_fail] #[ignore(cfg(windows))] @@ -474,13 +474,13 @@ fn test_option_while_some() { None } } - assert!(i == 11); + assert_eq!(i, 11); } #[test] fn test_get_or_zero() { let some_stuff = Some(42); - assert!(some_stuff.get_or_zero() == 42); + assert_eq!(some_stuff.get_or_zero(), 42); let no_stuff: Option = None; - assert!(no_stuff.get_or_zero() == 0); + assert_eq!(no_stuff.get_or_zero(), 0); } diff --git a/src/libcore/os.rs b/src/libcore/os.rs index 72e62c8039204..2625d03588be9 100644 --- a/src/libcore/os.rs +++ b/src/libcore/os.rs @@ -221,7 +221,7 @@ pub fn env() -> ~[(~str,~str)] { for str::each_splitn_char(*p, '=', 1) |s| { vs.push(s.to_owned()) } debug!("splitting: len: %u", vs.len()); - assert!(vs.len() == 2); + assert_eq!(vs.len(), 2); pairs.push((copy vs[0], copy vs[1])); } pairs @@ -388,7 +388,7 @@ pub fn pipe() -> Pipe { unsafe { let mut fds = Pipe {in: 0 as c_int, out: 0 as c_int }; - assert!((libc::pipe(&mut fds.in) == (0 as c_int))); + assert_eq!(libc::pipe(&mut fds.in), (0 as c_int)); return Pipe {in: fds.in, out: fds.out}; } } @@ -407,7 +407,7 @@ pub fn pipe() -> Pipe { out: 0 as c_int }; let res = libc::pipe(&mut fds.in, 1024 as ::libc::c_uint, (libc::O_BINARY | libc::O_NOINHERIT) as c_int); - assert!((res == 0 as c_int)); + assert_eq!(res, 0 as c_int); assert!((fds.in != -1 as c_int && fds.in != 0 as c_int)); assert!((fds.out != -1 as c_int && fds.in != 0 as c_int)); return Pipe {in: fds.in, out: fds.out}; @@ -1474,7 +1474,7 @@ mod tests { fn test_setenv() { let n = make_rand_name(); setenv(n, ~"VALUE"); - assert!(getenv(n) == option::Some(~"VALUE")); + assert_eq!(getenv(n), option::Some(~"VALUE")); } #[test] @@ -1482,7 +1482,7 @@ mod tests { let n = make_rand_name(); setenv(n, ~"VALUE"); unsetenv(n); - assert!(getenv(n) == option::None); + assert_eq!(getenv(n), option::None); } #[test] @@ -1492,9 +1492,9 @@ mod tests { let n = make_rand_name(); setenv(n, ~"1"); setenv(n, ~"2"); - assert!(getenv(n) == option::Some(~"2")); + assert_eq!(getenv(n), option::Some(~"2")); setenv(n, ~""); - assert!(getenv(n) == option::Some(~"")); + assert_eq!(getenv(n), option::Some(~"")); } // Windows GetEnvironmentVariable requires some extra work to make sure @@ -1509,7 +1509,7 @@ mod tests { let n = make_rand_name(); setenv(n, s); debug!(copy s); - assert!(getenv(n) == option::Some(s)); + assert_eq!(getenv(n), option::Some(s)); } #[test] @@ -1567,7 +1567,7 @@ mod tests { let oldhome = getenv(~"HOME"); setenv(~"HOME", ~"/home/MountainView"); - assert!(os::homedir() == Some(Path("/home/MountainView"))); + assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); setenv(~"HOME", ~""); assert!(os::homedir().is_none()); @@ -1588,16 +1588,16 @@ mod tests { assert!(os::homedir().is_none()); setenv(~"HOME", ~"/home/MountainView"); - assert!(os::homedir() == Some(Path("/home/MountainView"))); + assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); setenv(~"HOME", ~""); setenv(~"USERPROFILE", ~"/home/MountainView"); - assert!(os::homedir() == Some(Path("/home/MountainView"))); + assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); setenv(~"HOME", ~"/home/MountainView"); setenv(~"USERPROFILE", ~"/home/PaloAlto"); - assert!(os::homedir() == Some(Path("/home/MountainView"))); + assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); oldhome.each(|s| {setenv(~"HOME", *s);true}); olduserprofile.each(|s| {setenv(~"USERPROFILE", *s);true}); @@ -1668,7 +1668,7 @@ mod tests { (str::len(s) + 1u) as size_t, ostream) == buf.len() as size_t)) } - assert!((libc::fclose(ostream) == (0u as c_int))); + assert_eq!(libc::fclose(ostream), (0u as c_int)); let in_mode = in.get_mode(); let rs = os::copy_file(&in, &out); if (!os::path_exists(&in)) { @@ -1676,8 +1676,8 @@ mod tests { } assert!((rs)); let rslt = run::run_program(~"diff", ~[in.to_str(), out.to_str()]); - assert!((rslt == 0)); - assert!(out.get_mode() == in_mode); + assert_eq!(rslt, 0); + assert_eq!(out.get_mode(), in_mode); assert!((remove_file(&in))); assert!((remove_file(&out))); } diff --git a/src/libcore/path.rs b/src/libcore/path.rs index 8a5d9c0416d07..ed9ef864f8039 100644 --- a/src/libcore/path.rs +++ b/src/libcore/path.rs @@ -952,30 +952,30 @@ mod tests { let path = PosixPath("tmp/"); let path = path.push("/hmm"); let path = path.normalize(); - assert!(~"tmp/hmm" == path.to_str()); + assert_eq!(~"tmp/hmm", path.to_str()); let path = WindowsPath("tmp/"); let path = path.push("/hmm"); let path = path.normalize(); - assert!(~"tmp\\hmm" == path.to_str()); + assert_eq!(~"tmp\\hmm", path.to_str()); } #[test] fn test_filetype_foo_bar() { let wp = PosixPath("foo.bar"); - assert!(wp.filetype() == Some(~".bar")); + assert_eq!(wp.filetype(), Some(~".bar")); let wp = WindowsPath("foo.bar"); - assert!(wp.filetype() == Some(~".bar")); + assert_eq!(wp.filetype(), Some(~".bar")); } #[test] fn test_filetype_foo() { let wp = PosixPath("foo"); - assert!(wp.filetype() == None); + assert_eq!(wp.filetype(), None); let wp = WindowsPath("foo"); - assert!(wp.filetype() == None); + assert_eq!(wp.filetype(), None); } #[test] @@ -986,7 +986,7 @@ mod tests { if (ss != sss) { debug!("got %s", ss); debug!("expected %s", sss); - assert!(ss == sss); + assert_eq!(ss, sss); } } @@ -1044,7 +1044,7 @@ mod tests { if (ss != sss) { debug!("got %s", ss); debug!("expected %s", sss); - assert!(ss == sss); + assert_eq!(ss, sss); } } @@ -1107,7 +1107,7 @@ mod tests { if (ss != sss) { debug!("got %s", ss); debug!("expected %s", sss); - assert!(ss == sss); + assert_eq!(ss, sss); } } @@ -1192,9 +1192,9 @@ mod tests { #[test] fn test_windows_path_restrictions() { - assert!(WindowsPath("hi").is_restricted() == false); - assert!(WindowsPath("C:\\NUL").is_restricted() == true); - assert!(WindowsPath("C:\\COM1.TXT").is_restricted() == true); - assert!(WindowsPath("c:\\prn.exe").is_restricted() == true); + assert_eq!(WindowsPath("hi").is_restricted(), false); + assert_eq!(WindowsPath("C:\\NUL").is_restricted(), true); + assert_eq!(WindowsPath("C:\\COM1.TXT").is_restricted(), true); + assert_eq!(WindowsPath("c:\\prn.exe").is_restricted(), true); } } diff --git a/src/libcore/pipes.rs b/src/libcore/pipes.rs index c0cf4c052c509..1c2b57bb2dffb 100644 --- a/src/libcore/pipes.rs +++ b/src/libcore/pipes.rs @@ -353,7 +353,7 @@ pub fn send(mut p: SendPacketBuffered, let header = p.header(); let p_ = p.unwrap(); let p = unsafe { &mut *p_ }; - assert!(ptr::to_unsafe_ptr(&(p.header)) == header); + assert_eq!(ptr::to_unsafe_ptr(&(p.header)), header); assert!(p.payload.is_none()); p.payload = Some(payload); let old_state = swap_state_rel(&mut p.header.state, Full); @@ -494,7 +494,7 @@ fn try_recv_(p: &mut Packet) -> Option { Terminated => { // This assert detects when we've accidentally unsafely // casted too big of a number to a state. - assert!(old_state == Terminated); + assert_eq!(old_state, Terminated); let old_task = swap_task(&mut p.header.blocked_task, ptr::null()); if !old_task.is_null() { @@ -566,7 +566,7 @@ fn receiver_terminate(p: *mut Packet) { if !old_task.is_null() { unsafe { rustrt::rust_task_deref(old_task); - assert!(old_task == rustrt::rust_get_task()); + assert_eq!(old_task, rustrt::rust_get_task()); } } } diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index e116dc0194310..9d40f1b639cd8 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -343,15 +343,15 @@ pub mod ptr_tests { let mut p = Pair {fst: 10, snd: 20}; let pptr: *mut Pair = &mut p; let iptr: *mut int = cast::transmute(pptr); - assert!((*iptr == 10));; + assert_eq!(*iptr, 10); *iptr = 30; - assert!((*iptr == 30)); - assert!((p.fst == 30));; + assert_eq!(*iptr, 30); + assert_eq!(p.fst, 30); *pptr = Pair {fst: 50, snd: 60}; - assert!((*iptr == 50)); - assert!((p.fst == 50)); - assert!((p.snd == 60)); + assert_eq!(*iptr, 50); + assert_eq!(p.fst, 50); + assert_eq!(p.snd, 60); let v0 = ~[32000u16, 32001u16, 32002u16]; let mut v1 = ~[0u16, 0u16, 0u16]; @@ -396,8 +396,8 @@ pub mod ptr_tests { do str::as_c_str(s2) |p2| { let v = ~[p0, p1, p2, null()]; do vec::as_imm_buf(v) |vp, len| { - assert!(unsafe { buf_len(vp) } == 3u); - assert!(len == 4u); + assert_eq!(unsafe { buf_len(vp) }, 3u); + assert_eq!(len, 4u); } } } @@ -448,11 +448,11 @@ pub mod ptr_tests { debug!( "test_ptr_array_each e: %s, a: %s", expected, actual); - assert!(actual == expected); + assert_eq!(actual, expected); ctr += 1; iteration_count += 1; }); - assert!(iteration_count == 3u); + assert_eq!(iteration_count, 3u); } } #[test] @@ -480,11 +480,11 @@ pub mod ptr_tests { debug!( "test_ptr_array_each e: %s, a: %s", expected, actual); - assert!(actual == expected); + assert_eq!(actual, expected); ctr += 1; iteration_count += 1; }); - assert!(iteration_count == 3); + assert_eq!(iteration_count, 3); } } #[test] diff --git a/src/libcore/rand.rs b/src/libcore/rand.rs index daf0b9d094aca..84dd7d187e4b1 100644 --- a/src/libcore/rand.rs +++ b/src/libcore/rand.rs @@ -880,7 +880,7 @@ mod tests { let seed = seed(); let mut ra = IsaacRng::new_seeded(seed); let mut rb = IsaacRng::new_seeded(seed); - assert!(ra.gen_str(100u) == rb.gen_str(100u)); + assert_eq!(ra.gen_str(100u), rb.gen_str(100u)); } #[test] @@ -889,7 +889,7 @@ mod tests { let seed = [2u8, 32u8, 4u8, 32u8, 51u8]; let mut ra = IsaacRng::new_seeded(seed); let mut rb = IsaacRng::new_seeded(seed); - assert!(ra.gen_str(100u) == rb.gen_str(100u)); + assert_eq!(ra.gen_str(100u), rb.gen_str(100u)); } #[test] @@ -908,8 +908,8 @@ mod tests { let mut r = rng(); let a = r.gen_int_range(-3, 42); assert!(a >= -3 && a < 42); - assert!(r.gen_int_range(0, 1) == 0); - assert!(r.gen_int_range(-12, -11) == -12); + assert_eq!(r.gen_int_range(0, 1), 0); + assert_eq!(r.gen_int_range(-12, -11), -12); } #[test] @@ -925,8 +925,8 @@ mod tests { let mut r = rng(); let a = r.gen_uint_range(3u, 42u); assert!(a >= 3u && a < 42u); - assert!(r.gen_uint_range(0u, 1u) == 0u); - assert!(r.gen_uint_range(12u, 13u) == 12u); + assert_eq!(r.gen_uint_range(0u, 1u), 0u); + assert_eq!(r.gen_uint_range(12u, 13u), 12u); } #[test] @@ -948,8 +948,8 @@ mod tests { #[test] fn test_gen_weighted_bool() { let mut r = rng(); - assert!(r.gen_weighted_bool(0u) == true); - assert!(r.gen_weighted_bool(1u) == true); + assert_eq!(r.gen_weighted_bool(0u), true); + assert_eq!(r.gen_weighted_bool(1u), true); } #[test] @@ -958,23 +958,23 @@ mod tests { debug!(r.gen_str(10u)); debug!(r.gen_str(10u)); debug!(r.gen_str(10u)); - assert!(r.gen_str(0u).len() == 0u); - assert!(r.gen_str(10u).len() == 10u); - assert!(r.gen_str(16u).len() == 16u); + assert_eq!(r.gen_str(0u).len(), 0u); + assert_eq!(r.gen_str(10u).len(), 10u); + assert_eq!(r.gen_str(16u).len(), 16u); } #[test] fn test_gen_bytes() { let mut r = rng(); - assert!(r.gen_bytes(0u).len() == 0u); - assert!(r.gen_bytes(10u).len() == 10u); - assert!(r.gen_bytes(16u).len() == 16u); + assert_eq!(r.gen_bytes(0u).len(), 0u); + assert_eq!(r.gen_bytes(10u).len(), 10u); + assert_eq!(r.gen_bytes(16u).len(), 16u); } #[test] fn test_choose() { let mut r = rng(); - assert!(r.choose([1, 1, 1]) == 1); + assert_eq!(r.choose([1, 1, 1]), 1); } #[test] @@ -982,7 +982,7 @@ mod tests { let mut r = rng(); let x: Option = r.choose_option([]); assert!(x.is_none()); - assert!(r.choose_option([1, 1, 1]) == Some(1)); + assert_eq!(r.choose_option([1, 1, 1]), Some(1)); } #[test] @@ -1015,7 +1015,7 @@ mod tests { fn test_weighted_vec() { let mut r = rng(); let empty: ~[int] = ~[]; - assert!(r.weighted_vec(~[]) == empty); + assert_eq!(r.weighted_vec(~[]), empty); assert!(r.weighted_vec(~[ Weighted { weight: 0u, item: 3u }, Weighted { weight: 1u, item: 2u }, @@ -1027,16 +1027,16 @@ mod tests { fn test_shuffle() { let mut r = rng(); let empty: ~[int] = ~[]; - assert!(r.shuffle(~[]) == empty); - assert!(r.shuffle(~[1, 1, 1]) == ~[1, 1, 1]); + assert_eq!(r.shuffle(~[]), empty); + assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]); } #[test] fn test_task_rng() { let mut r = task_rng(); r.gen::(); - assert!(r.shuffle(~[1, 1, 1]) == ~[1, 1, 1]); - assert!(r.gen_uint_range(0u, 1u) == 0u); + assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]); + assert_eq!(r.gen_uint_range(0u, 1u), 0u); } #[test] diff --git a/src/libcore/repr.rs b/src/libcore/repr.rs index 53f51fe1da2f4..a05009e375cf9 100644 --- a/src/libcore/repr.rs +++ b/src/libcore/repr.rs @@ -220,7 +220,7 @@ pub impl ReprVisitor { } else if mtbl == 1 { // skip, this is ast::m_imm } else { - assert!(mtbl == 2); + assert_eq!(mtbl, 2); self.writer.write_str("const "); } } @@ -592,7 +592,7 @@ fn test_repr() { error!("expected '%s', got '%s'", e, s); } - assert!(s == e); + assert_eq!(s, e); } exact_test(&10, "10"); diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 72704a429ed5a..cda2fe13e3766 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -407,12 +407,12 @@ mod tests { #[test] pub fn chain_success() { - assert!(get(&chain(op1(), op2)) == 667u); + assert_eq!(get(&chain(op1(), op2)), 667u); } #[test] pub fn chain_failure() { - assert!(get_err(&chain(op3(), op2)) == ~"sadface"); + assert_eq!(get_err(&chain(op3(), op2)), ~"sadface"); } #[test] @@ -438,19 +438,19 @@ mod tests { #[test] pub fn test_impl_map() { - assert!(Ok::<~str, ~str>(~"a").map(|_x| ~"b") == Ok(~"b")); - assert!(Err::<~str, ~str>(~"a").map(|_x| ~"b") == Err(~"a")); + assert_eq!(Ok::<~str, ~str>(~"a").map(|_x| ~"b"), Ok(~"b")); + assert_eq!(Err::<~str, ~str>(~"a").map(|_x| ~"b"), Err(~"a")); } #[test] pub fn test_impl_map_err() { - assert!(Ok::<~str, ~str>(~"a").map_err(|_x| ~"b") == Ok(~"a")); - assert!(Err::<~str, ~str>(~"a").map_err(|_x| ~"b") == Err(~"b")); + assert_eq!(Ok::<~str, ~str>(~"a").map_err(|_x| ~"b"), Ok(~"a")); + assert_eq!(Err::<~str, ~str>(~"a").map_err(|_x| ~"b"), Err(~"b")); } #[test] pub fn test_get_ref_method() { let foo: Result = Ok(100); - assert!(*foo.get_ref() == 100); + assert_eq!(*foo.get_ref(), 100); } } diff --git a/src/libcore/rt/io/flate.rs b/src/libcore/rt/io/flate.rs index 24537bef329ab..db2683dc85d83 100644 --- a/src/libcore/rt/io/flate.rs +++ b/src/libcore/rt/io/flate.rs @@ -114,8 +114,8 @@ mod test { let mut inflate_reader = InflateReader::new(mem_reader); let mut out_bytes = [0, .. 100]; let bytes_read = inflate_reader.read(out_bytes).get(); - assert!(bytes_read == in_bytes.len()); + assert_eq!(bytes_read, in_bytes.len()); let out_msg = str::from_bytes(out_bytes); assert!(in_msg == out_msg); } -} \ No newline at end of file +} diff --git a/src/libcore/rt/io/mem.rs b/src/libcore/rt/io/mem.rs index 06e1466831df0..b2701c1fdc392 100644 --- a/src/libcore/rt/io/mem.rs +++ b/src/libcore/rt/io/mem.rs @@ -86,7 +86,7 @@ impl Reader for MemReader { { let input = self.buf.slice(self.pos, self.pos + write_len); let output = vec::mut_slice(buf, 0, write_len); - assert!(input.len() == output.len()); + assert_eq!(input.len(), output.len()); vec::bytes::copy_memory(output, input, write_len); } self.pos += write_len; @@ -189,33 +189,33 @@ mod test { #[test] fn test_mem_writer() { let mut writer = MemWriter::new(); - assert!(writer.tell() == 0); + assert_eq!(writer.tell(), 0); writer.write([0]); - assert!(writer.tell() == 1); + assert_eq!(writer.tell(), 1); writer.write([1, 2, 3]); writer.write([4, 5, 6, 7]); - assert!(writer.tell() == 8); - assert!(writer.inner() == ~[0, 1, 2, 3, 4, 5 , 6, 7]); + assert_eq!(writer.tell(), 8); + assert_eq!(writer.inner(), ~[0, 1, 2, 3, 4, 5 , 6, 7]); } #[test] fn test_mem_reader() { let mut reader = MemReader::new(~[0, 1, 2, 3, 4, 5, 6, 7]); let mut buf = []; - assert!(reader.read(buf) == Some(0)); - assert!(reader.tell() == 0); + assert_eq!(reader.read(buf), Some(0)); + assert_eq!(reader.tell(), 0); let mut buf = [0]; - assert!(reader.read(buf) == Some(1)); - assert!(reader.tell() == 1); - assert!(buf == [0]); + assert_eq!(reader.read(buf), Some(1)); + assert_eq!(reader.tell(), 1); + assert_eq!(buf, [0]); let mut buf = [0, ..4]; - assert!(reader.read(buf) == Some(4)); - assert!(reader.tell() == 5); - assert!(buf == [1, 2, 3, 4]); - assert!(reader.read(buf) == Some(3)); - assert!(buf.slice(0, 3) == [5, 6, 7]); + assert_eq!(reader.read(buf), Some(4)); + assert_eq!(reader.tell(), 5); + assert_eq!(buf, [1, 2, 3, 4]); + assert_eq!(reader.read(buf), Some(3)); + assert_eq!(buf.slice(0, 3), [5, 6, 7]); assert!(reader.eof()); - assert!(reader.read(buf) == None); + assert_eq!(reader.read(buf), None); assert!(reader.eof()); } } diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index a833e92fc1088..a5fd7a395de7f 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -262,7 +262,7 @@ mod test { let mut stream = listener.accept(); let mut buf = [0]; stream.read(buf); - assert!(buf[0] == 99); + assert_eq!(buf[0], 99); } } diff --git a/src/libcore/rt/io/option.rs b/src/libcore/rt/io/option.rs index 6ae747f8b4b4c..d71ef55d3ad97 100644 --- a/src/libcore/rt/io/option.rs +++ b/src/libcore/rt/io/option.rs @@ -87,7 +87,7 @@ mod test { let mut writer: Option = Some(MemWriter::new()); writer.write([0, 1, 2]); writer.flush(); - assert!(writer.unwrap().inner() == ~[0, 1, 2]); + assert_eq!(writer.unwrap().inner(), ~[0, 1, 2]); } } @@ -98,7 +98,7 @@ mod test { let mut called = false; do io_error::cond.trap(|err| { - assert!(err.kind == PreviousIoError); + assert_eq!(err.kind, PreviousIoError); called = true; }).in { writer.write([0, 0, 0]); @@ -107,7 +107,7 @@ mod test { let mut called = false; do io_error::cond.trap(|err| { - assert!(err.kind == PreviousIoError); + assert_eq!(err.kind, PreviousIoError); called = true; }).in { writer.flush(); @@ -122,7 +122,7 @@ mod test { let mut reader: Option = Some(MemReader::new(~[0, 1, 2, 3])); let mut buf = [0, 0]; reader.read(buf); - assert!(buf == [0, 1]); + assert_eq!(buf, [0, 1]); assert!(!reader.eof()); } } @@ -134,7 +134,7 @@ mod test { let mut called = false; do read_error::cond.trap(|err| { - assert!(err.kind == PreviousIoError); + assert_eq!(err.kind, PreviousIoError); called = true; }).in { reader.read(buf); @@ -143,7 +143,7 @@ mod test { let mut called = false; do io_error::cond.trap(|err| { - assert!(err.kind == PreviousIoError); + assert_eq!(err.kind, PreviousIoError); called = true; }).in { assert!(reader.eof()); diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index dab627188d0f5..4dce9da505b5f 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -217,15 +217,15 @@ fn test_context() { use rt::uv::uvio::UvEventLoop; use cell::Cell; - assert!(context() == OldTaskContext); + assert_eq!(context(), OldTaskContext); do run_in_bare_thread { - assert!(context() == GlobalContext); + assert_eq!(context(), GlobalContext); let mut sched = ~UvEventLoop::new_scheduler(); let task = ~do Coroutine::new(&mut sched.stack_pool) { - assert!(context() == TaskContext); + assert_eq!(context(), TaskContext); let sched = local_sched::take(); do sched.deschedule_running_task_and_then() |task| { - assert!(context() == SchedulerContext); + assert_eq!(context(), SchedulerContext); let task = Cell(task); do local_sched::borrow |sched| { sched.enqueue_task(task.take()); diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index c66f20e01b2d7..7fd40fb329f47 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -445,7 +445,7 @@ mod test { sched.enqueue_task(task); } sched.run(); - assert!(task_count == total); + assert_eq!(task_count, total); } } @@ -473,7 +473,7 @@ mod test { }; sched.enqueue_task(task1); sched.run(); - assert!(count == 3); + assert_eq!(count, 3); } } @@ -492,7 +492,7 @@ mod test { sched.enqueue_task(start_task); sched.run(); - assert!(count == MAX); + assert_eq!(count, MAX); fn run_task(count_ptr: *mut int) { do local_sched::borrow |sched| { diff --git a/src/libcore/rt/thread_local_storage.rs b/src/libcore/rt/thread_local_storage.rs index 6a08c0f59b183..7187d2db41cac 100644 --- a/src/libcore/rt/thread_local_storage.rs +++ b/src/libcore/rt/thread_local_storage.rs @@ -21,12 +21,12 @@ pub type Key = pthread_key_t; #[cfg(unix)] pub unsafe fn create(key: &mut Key) { - assert!(0 == pthread_key_create(key, null())); + assert_eq!(0, pthread_key_create(key, null())); } #[cfg(unix)] pub unsafe fn set(key: Key, value: *mut c_void) { - assert!(0 == pthread_setspecific(key, value)); + assert_eq!(0, pthread_setspecific(key, value)); } #[cfg(unix)] @@ -91,10 +91,10 @@ fn tls_smoke_test() { create(&mut key); set(key, transmute(value)); let value: ~int = transmute(get(key)); - assert!(value == ~20); + assert_eq!(value, ~20); let value = ~30; set(key, transmute(value)); let value: ~int = transmute(get(key)); - assert!(value == ~30); + assert_eq!(value, ~30); } } diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index 99a5252c88a66..ad59305830311 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -231,7 +231,7 @@ impl ToStr for UvError { fn error_smoke_test() { let err = uvll::uv_err_t { code: 1, sys_errno_: 1 }; let err: UvError = UvError(err); - assert!(err.to_str() == ~"EOF: end of file"); + assert_eq!(err.to_str(), ~"EOF: end of file"); } pub fn last_uv_error>(watcher: &W) -> UvError { @@ -397,7 +397,7 @@ fn idle_smoke_test() { } loop_.run(); loop_.close(); - assert!(count == 10); + assert_eq!(count, 10); } } diff --git a/src/libcore/rt/uv/net.rs b/src/libcore/rt/uv/net.rs index bdd5588014c01..68b871e6b3118 100644 --- a/src/libcore/rt/uv/net.rs +++ b/src/libcore/rt/uv/net.rs @@ -114,7 +114,7 @@ pub impl StreamWatcher { let self_handle = self.native_handle() as *c_void; let stream_handle = stream.native_handle() as *c_void; unsafe { - assert!(0 == uvll::accept(self_handle, stream_handle)); + assert_eq!(0, uvll::accept(self_handle, stream_handle)); } } @@ -158,7 +158,7 @@ pub impl TcpWatcher { unsafe { let handle = malloc_handle(UV_TCP); assert!(handle.is_not_null()); - assert!(0 == uvll::tcp_init(loop_.native_handle(), handle)); + assert_eq!(0, uvll::tcp_init(loop_.native_handle(), handle)); let mut watcher: TcpWatcher = NativeHandle::from_native_handle(handle); watcher.install_watcher_data(); return watcher; @@ -350,7 +350,7 @@ mod test { do tcp_watcher.connect(addr) |stream_watcher, status| { rtdebug!("tcp_watcher.connect!"); assert!(status.is_some()); - assert!(status.get().name() == ~"ECONNREFUSED"); + assert_eq!(status.get().name(), ~"ECONNREFUSED"); stream_watcher.close(||()); } loop_.run(); @@ -397,7 +397,7 @@ mod test { count += 1; } } else { - assert!(count == MAX); + assert_eq!(count, MAX); do stream_watcher.close { server_stream_watcher.close(||()); } diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index ce4eb6aff8701..8666d43a10048 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -97,7 +97,7 @@ fn test_callback_run_once() { unsafe { *count_ptr += 1 } } event_loop.run(); - assert!(count == 1); + assert_eq!(count, 1); } } @@ -379,10 +379,10 @@ fn test_simple_tcp_server_and_client() { let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; let nread = stream.read(buf).unwrap(); - assert!(nread == 8); + assert_eq!(nread, 8); for uint::range(0, nread) |i| { rtdebug!("%u", buf[i] as uint); - assert!(buf[i] == i as u8); + assert_eq!(buf[i], i as u8); } } } @@ -416,7 +416,7 @@ fn test_read_and_block() { let nread = stream.read(buf).unwrap(); for uint::range(0, nread) |i| { let val = buf[i] as uint; - assert!(val == current % 8); + assert_eq!(val, current % 8); current += 1; } reads += 1; @@ -482,7 +482,7 @@ fn test_read_read_read() { rtdebug!("read %u bytes", nread as uint); total_bytes_read += nread; for uint::range(0, nread) |i| { - assert!(buf[i] == 1); + assert_eq!(buf[i], 1); } } rtdebug!("read %u bytes total", total_bytes_read as uint); diff --git a/src/libcore/rt/uv/uvll.rs b/src/libcore/rt/uv/uvll.rs index 94e1703b263de..ddc9040d73091 100644 --- a/src/libcore/rt/uv/uvll.rs +++ b/src/libcore/rt/uv/uvll.rs @@ -132,14 +132,14 @@ pub unsafe fn free_req(v: *c_void) { #[test] fn handle_sanity_check() { unsafe { - assert!(UV_HANDLE_TYPE_MAX as uint == rust_uv_handle_type_max()); + assert_eq!(UV_HANDLE_TYPE_MAX as uint, rust_uv_handle_type_max()); } } #[test] fn request_sanity_check() { unsafe { - assert!(UV_REQ_TYPE_MAX as uint == rust_uv_req_type_max()); + assert_eq!(UV_REQ_TYPE_MAX as uint, rust_uv_req_type_max()); } } diff --git a/src/libcore/run.rs b/src/libcore/run.rs index c84e920a17202..02757ab489903 100644 --- a/src/libcore/run.rs +++ b/src/libcore/run.rs @@ -835,7 +835,7 @@ mod tests { debug!(copy expected); debug!(copy actual); - assert!((expected == actual)); + assert_eq!(expected, actual); } #[test] @@ -844,7 +844,7 @@ mod tests { &None, &None, 0i32, 0i32, 0i32); let status = run::waitpid(pid); - assert!(status == 1); + assert_eq!(status, 1); } #[test] diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 59f769fd92d42..a3cb180ed2653 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -67,7 +67,7 @@ pub fn from_bytes(vv: &const [u8]) -> ~str { * Fails if not null terminated */ pub fn from_bytes_with_null<'a>(vv: &'a [u8]) -> &'a str { - assert!(vv[vv.len() - 1] == 0); + assert_eq!(vv[vv.len() - 1], 0); assert!(is_utf8(vv)); return unsafe { raw::from_bytes_with_null(vv) }; } @@ -2247,7 +2247,7 @@ pub fn char_range_at(s: &str, i: uint) -> CharRange { let mut i = i + 1u; while i < end { let byte = s[i]; - assert!((byte & 192u8 == tag_cont_u8)); + assert_eq!(byte & 192u8, tag_cont_u8); val <<= 6u; val += (byte & 63u8) as uint; i += 1u; @@ -2733,7 +2733,7 @@ pub mod raw { let a = ~[65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8]; let b = vec::raw::to_ptr(a); let c = from_buf_len(b, 3u); - assert!((c == ~"AAA")); + assert_eq!(c, ~"AAA"); } } @@ -3160,47 +3160,47 @@ mod tests { #[test] fn test_len() { - assert!((len(~"") == 0u)); - assert!((len(~"hello world") == 11u)); - assert!((len(~"\x63") == 1u)); - assert!((len(~"\xa2") == 2u)); - assert!((len(~"\u03c0") == 2u)); - assert!((len(~"\u2620") == 3u)); - assert!((len(~"\U0001d11e") == 4u)); - - assert!((char_len(~"") == 0u)); - assert!((char_len(~"hello world") == 11u)); - assert!((char_len(~"\x63") == 1u)); - assert!((char_len(~"\xa2") == 1u)); - assert!((char_len(~"\u03c0") == 1u)); - assert!((char_len(~"\u2620") == 1u)); - assert!((char_len(~"\U0001d11e") == 1u)); - assert!((char_len(~"ประเทศไทย中华Việt Nam") == 19u)); + assert_eq!(len(~""), 0u); + assert_eq!(len(~"hello world"), 11u); + assert_eq!(len(~"\x63"), 1u); + assert_eq!(len(~"\xa2"), 2u); + assert_eq!(len(~"\u03c0"), 2u); + assert_eq!(len(~"\u2620"), 3u); + assert_eq!(len(~"\U0001d11e"), 4u); + + assert_eq!(char_len(~""), 0u); + assert_eq!(char_len(~"hello world"), 11u); + assert_eq!(char_len(~"\x63"), 1u); + assert_eq!(char_len(~"\xa2"), 1u); + assert_eq!(char_len(~"\u03c0"), 1u); + assert_eq!(char_len(~"\u2620"), 1u); + assert_eq!(char_len(~"\U0001d11e"), 1u); + assert_eq!(char_len(~"ประเทศไทย中华Việt Nam"), 19u); } #[test] fn test_rfind_char() { - assert!(rfind_char(~"hello", 'l') == Some(3u)); - assert!(rfind_char(~"hello", 'o') == Some(4u)); - assert!(rfind_char(~"hello", 'h') == Some(0u)); + assert_eq!(rfind_char(~"hello", 'l'), Some(3u)); + assert_eq!(rfind_char(~"hello", 'o'), Some(4u)); + assert_eq!(rfind_char(~"hello", 'h'), Some(0u)); assert!(rfind_char(~"hello", 'z').is_none()); - assert!(rfind_char(~"ประเทศไทย中华Việt Nam", '华') == Some(30u)); + assert_eq!(rfind_char(~"ประเทศไทย中华Việt Nam", '华'), Some(30u)); } #[test] fn test_pop_char() { let mut data = ~"ประเทศไทย中华"; let cc = pop_char(&mut data); - assert!(~"ประเทศไทย中" == data); - assert!('华' == cc); + assert_eq!(~"ประเทศไทย中", data); + assert_eq!('华', cc); } #[test] fn test_pop_char_2() { let mut data2 = ~"华"; let cc2 = pop_char(&mut data2); - assert!(~"" == data2); - assert!('华' == cc2); + assert_eq!(~"", data2); + assert_eq!('华', cc2); } #[test] @@ -3448,58 +3448,58 @@ mod tests { fn test_find_str() { // byte positions assert!(find_str(~"banana", ~"apple pie").is_none()); - assert!(find_str(~"", ~"") == Some(0u)); + assert_eq!(find_str(~"", ~""), Some(0u)); let data = ~"ประเทศไทย中华Việt Nam"; - assert!(find_str(data, ~"") == Some(0u)); - assert!(find_str(data, ~"ประเ") == Some( 0u)); - assert!(find_str(data, ~"ะเ") == Some( 6u)); - assert!(find_str(data, ~"中华") == Some(27u)); + assert_eq!(find_str(data, ~""), Some(0u)); + assert_eq!(find_str(data, ~"ประเ"), Some( 0u)); + assert_eq!(find_str(data, ~"ะเ"), Some( 6u)); + assert_eq!(find_str(data, ~"中华"), Some(27u)); assert!(find_str(data, ~"ไท华").is_none()); } #[test] fn test_find_str_between() { // byte positions - assert!(find_str_between(~"", ~"", 0u, 0u) == Some(0u)); + assert_eq!(find_str_between(~"", ~"", 0u, 0u), Some(0u)); let data = ~"abcabc"; - assert!(find_str_between(data, ~"ab", 0u, 6u) == Some(0u)); - assert!(find_str_between(data, ~"ab", 2u, 6u) == Some(3u)); + assert_eq!(find_str_between(data, ~"ab", 0u, 6u), Some(0u)); + assert_eq!(find_str_between(data, ~"ab", 2u, 6u), Some(3u)); assert!(find_str_between(data, ~"ab", 2u, 4u).is_none()); let mut data = ~"ประเทศไทย中华Việt Nam"; data = data + data; - assert!(find_str_between(data, ~"", 0u, 43u) == Some(0u)); - assert!(find_str_between(data, ~"", 6u, 43u) == Some(6u)); + assert_eq!(find_str_between(data, ~"", 0u, 43u), Some(0u)); + assert_eq!(find_str_between(data, ~"", 6u, 43u), Some(6u)); - assert!(find_str_between(data, ~"ประ", 0u, 43u) == Some( 0u)); - assert!(find_str_between(data, ~"ทศไ", 0u, 43u) == Some(12u)); - assert!(find_str_between(data, ~"ย中", 0u, 43u) == Some(24u)); - assert!(find_str_between(data, ~"iệt", 0u, 43u) == Some(34u)); - assert!(find_str_between(data, ~"Nam", 0u, 43u) == Some(40u)); + assert_eq!(find_str_between(data, ~"ประ", 0u, 43u), Some( 0u)); + assert_eq!(find_str_between(data, ~"ทศไ", 0u, 43u), Some(12u)); + assert_eq!(find_str_between(data, ~"ย中", 0u, 43u), Some(24u)); + assert_eq!(find_str_between(data, ~"iệt", 0u, 43u), Some(34u)); + assert_eq!(find_str_between(data, ~"Nam", 0u, 43u), Some(40u)); - assert!(find_str_between(data, ~"ประ", 43u, 86u) == Some(43u)); - assert!(find_str_between(data, ~"ทศไ", 43u, 86u) == Some(55u)); - assert!(find_str_between(data, ~"ย中", 43u, 86u) == Some(67u)); - assert!(find_str_between(data, ~"iệt", 43u, 86u) == Some(77u)); - assert!(find_str_between(data, ~"Nam", 43u, 86u) == Some(83u)); + assert_eq!(find_str_between(data, ~"ประ", 43u, 86u), Some(43u)); + assert_eq!(find_str_between(data, ~"ทศไ", 43u, 86u), Some(55u)); + assert_eq!(find_str_between(data, ~"ย中", 43u, 86u), Some(67u)); + assert_eq!(find_str_between(data, ~"iệt", 43u, 86u), Some(77u)); + assert_eq!(find_str_between(data, ~"Nam", 43u, 86u), Some(83u)); } #[test] fn test_substr() { fn t(a: &str, b: &str, start: int) { - assert!(substr(a, start as uint, len(b)) == b); + assert_eq!(substr(a, start as uint, len(b)), b); } t("hello", "llo", 2); t("hello", "el", 1); - assert!("ะเทศไท" == substr("ประเทศไทย中华Việt Nam", 6u, 6u)); + assert_eq!("ะเทศไท", substr("ประเทศไทย中华Việt Nam", 6u, 6u)); } #[test] fn test_concat() { fn t(v: &[~str], s: &str) { - assert!(concat(v) == s.to_str()); + assert_eq!(concat(v), s.to_str()); } t(~[~"you", ~"know", ~"I'm", ~"no", ~"good"], ~"youknowI'mnogood"); let v: ~[~str] = ~[]; @@ -3510,7 +3510,7 @@ mod tests { #[test] fn test_connect() { fn t(v: &[~str], sep: &str, s: &str) { - assert!(connect(v, sep) == s.to_str()); + assert_eq!(connect(v, sep), s.to_str()); } t(~[~"you", ~"know", ~"I'm", ~"no", ~"good"], ~" ", ~"you know I'm no good"); @@ -3522,7 +3522,7 @@ mod tests { #[test] fn test_connect_slices() { fn t(v: &[&str], sep: &str, s: &str) { - assert!(connect_slices(v, sep) == s.to_str()); + assert_eq!(connect_slices(v, sep), s.to_str()); } t(["you", "know", "I'm", "no", "good"], " ", "you know I'm no good"); @@ -3532,18 +3532,18 @@ mod tests { #[test] fn test_repeat() { - assert!(repeat(~"x", 4) == ~"xxxx"); - assert!(repeat(~"hi", 4) == ~"hihihihi"); - assert!(repeat(~"ไท华", 3) == ~"ไท华ไท华ไท华"); - assert!(repeat(~"", 4) == ~""); - assert!(repeat(~"hi", 0) == ~""); + assert_eq!(repeat(~"x", 4), ~"xxxx"); + assert_eq!(repeat(~"hi", 4), ~"hihihihi"); + assert_eq!(repeat(~"ไท华", 3), ~"ไท华ไท华ไท华"); + assert_eq!(repeat(~"", 4), ~""); + assert_eq!(repeat(~"hi", 0), ~""); } #[test] fn test_unsafe_slice() { - assert!("ab" == unsafe {raw::slice_bytes("abc", 0, 2)}); - assert!("bc" == unsafe {raw::slice_bytes("abc", 1, 3)}); - assert!("" == unsafe {raw::slice_bytes("abc", 1, 1)}); + assert_eq!("ab", unsafe {raw::slice_bytes("abc", 0, 2)}); + assert_eq!("bc", unsafe {raw::slice_bytes("abc", 1, 3)}); + assert_eq!("", unsafe {raw::slice_bytes("abc", 1, 1)}); fn a_million_letter_a() -> ~str { let mut i = 0; let mut rs = ~""; @@ -3588,13 +3588,13 @@ mod tests { #[test] fn test_replace() { let a = ~"a"; - assert!(replace(~"", a, ~"b") == ~""); - assert!(replace(~"a", a, ~"b") == ~"b"); - assert!(replace(~"ab", a, ~"b") == ~"bb"); + assert_eq!(replace(~"", a, ~"b"), ~""); + assert_eq!(replace(~"a", a, ~"b"), ~"b"); + assert_eq!(replace(~"ab", a, ~"b"), ~"bb"); let test = ~"test"; assert!(replace(~" test test ", test, ~"toast") == ~" toast toast "); - assert!(replace(~" test test ", test, ~"") == ~" "); + assert_eq!(replace(~" test test ", test, ~""), ~" "); } #[test] @@ -3604,7 +3604,7 @@ mod tests { let a = ~"ประเ"; let A = ~"دولة الكويتทศไทย中华"; - assert!((replace(data, a, repl) == A)); + assert_eq!(replace(data, a, repl), A); } #[test] @@ -3614,7 +3614,7 @@ mod tests { let b = ~"ะเ"; let B = ~"ปรدولة الكويتทศไทย中华"; - assert!((replace(data, b, repl) == B)); + assert_eq!(replace(data, b, repl), B); } #[test] @@ -3624,7 +3624,7 @@ mod tests { let c = ~"中华"; let C = ~"ประเทศไทยدولة الكويت"; - assert!((replace(data, c, repl) == C)); + assert_eq!(replace(data, c, repl), C); } #[test] @@ -3633,21 +3633,21 @@ mod tests { let repl = ~"دولة الكويت"; let d = ~"ไท华"; - assert!((replace(data, d, repl) == data)); + assert_eq!(replace(data, d, repl), data); } #[test] fn test_slice() { - assert!("ab" == slice("abc", 0, 2)); - assert!("bc" == slice("abc", 1, 3)); - assert!("" == slice("abc", 1, 1)); - assert!("\u65e5" == slice("\u65e5\u672c", 0, 3)); + assert_eq!("ab", slice("abc", 0, 2)); + assert_eq!("bc", slice("abc", 1, 3)); + assert_eq!("", slice("abc", 1, 1)); + assert_eq!("\u65e5", slice("\u65e5\u672c", 0, 3)); let data = "ประเทศไทย中华"; - assert!("ป" == slice(data, 0, 3)); - assert!("ร" == slice(data, 3, 6)); - assert!("" == slice(data, 3, 3)); - assert!("华" == slice(data, 30, 33)); + assert_eq!("ป", slice(data, 0, 3)); + assert_eq!("ร", slice(data, 3, 6)); + assert_eq!("", slice(data, 3, 3)); + assert_eq!("华", slice(data, 30, 33)); fn a_million_letter_X() -> ~str { let mut i = 0; @@ -3673,16 +3673,16 @@ mod tests { fn test_slice_2() { let ss = "中华Việt Nam"; - assert!("华" == slice(ss, 3u, 6u)); - assert!("Việt Nam" == slice(ss, 6u, 16u)); + assert_eq!("华", slice(ss, 3u, 6u)); + assert_eq!("Việt Nam", slice(ss, 6u, 16u)); - assert!("ab" == slice("abc", 0u, 2u)); - assert!("bc" == slice("abc", 1u, 3u)); - assert!("" == slice("abc", 1u, 1u)); + assert_eq!("ab", slice("abc", 0u, 2u)); + assert_eq!("bc", slice("abc", 1u, 3u)); + assert_eq!("", slice("abc", 1u, 1u)); - assert!("中" == slice(ss, 0u, 3u)); - assert!("华V" == slice(ss, 3u, 7u)); - assert!("" == slice(ss, 3u, 3u)); + assert_eq!("中", slice(ss, 0u, 3u)); + assert_eq!("华V", slice(ss, 3u, 7u)); + assert_eq!("", slice(ss, 3u, 3u)); /*0: 中 3: 华 6: V @@ -3708,7 +3708,7 @@ mod tests { " *** foo *** "); assert!(trim_left_chars(" *** foo *** ", ~['*', ' ']) == "foo *** "); - assert!(trim_left_chars(" *** *** ", ~['*', ' ']) == ""); + assert_eq!(trim_left_chars(" *** *** ", ~['*', ' ']), ""); assert!(trim_left_chars("foo *** ", ~['*', ' ']) == "foo *** "); } @@ -3719,47 +3719,47 @@ mod tests { " *** foo *** "); assert!(trim_right_chars(" *** foo *** ", ~['*', ' ']) == " *** foo"); - assert!(trim_right_chars(" *** *** ", ~['*', ' ']) == ""); + assert_eq!(trim_right_chars(" *** *** ", ~['*', ' ']), ""); assert!(trim_right_chars(" *** foo", ~['*', ' ']) == " *** foo"); } #[test] fn test_trim_chars() { - assert!(trim_chars(" *** foo *** ", ~[]) == " *** foo *** "); - assert!(trim_chars(" *** foo *** ", ~['*', ' ']) == "foo"); - assert!(trim_chars(" *** *** ", ~['*', ' ']) == ""); - assert!(trim_chars("foo", ~['*', ' ']) == "foo"); + assert_eq!(trim_chars(" *** foo *** ", ~[]), " *** foo *** "); + assert_eq!(trim_chars(" *** foo *** ", ~['*', ' ']), "foo"); + assert_eq!(trim_chars(" *** *** ", ~['*', ' ']), ""); + assert_eq!(trim_chars("foo", ~['*', ' ']), "foo"); } #[test] fn test_trim_left() { - assert!((trim_left("") == "")); - assert!((trim_left("a") == "a")); - assert!((trim_left(" ") == "")); - assert!((trim_left(" blah") == "blah")); - assert!((trim_left(" \u3000 wut") == "wut")); - assert!((trim_left("hey ") == "hey ")); + assert_eq!(trim_left(""), ""); + assert_eq!(trim_left("a"), "a"); + assert_eq!(trim_left(" "), ""); + assert_eq!(trim_left(" blah"), "blah"); + assert_eq!(trim_left(" \u3000 wut"), "wut"); + assert_eq!(trim_left("hey "), "hey "); } #[test] fn test_trim_right() { - assert!((trim_right("") == "")); - assert!((trim_right("a") == "a")); - assert!((trim_right(" ") == "")); - assert!((trim_right("blah ") == "blah")); - assert!((trim_right("wut \u3000 ") == "wut")); - assert!((trim_right(" hey") == " hey")); + assert_eq!(trim_right(""), ""); + assert_eq!(trim_right("a"), "a"); + assert_eq!(trim_right(" "), ""); + assert_eq!(trim_right("blah "), "blah"); + assert_eq!(trim_right("wut \u3000 "), "wut"); + assert_eq!(trim_right(" hey"), " hey"); } #[test] fn test_trim() { - assert!((trim("") == "")); - assert!((trim("a") == "a")); - assert!((trim(" ") == "")); - assert!((trim(" blah ") == "blah")); - assert!((trim("\nwut \u3000 ") == "wut")); - assert!((trim(" hey dude ") == "hey dude")); + assert_eq!(trim(""), ""); + assert_eq!(trim("a"), "a"); + assert_eq!(trim(" "), ""); + assert_eq!(trim(" blah "), "blah"); + assert_eq!(trim("\nwut \u3000 "), "wut"); + assert_eq!(trim(" hey dude "), "hey dude"); } #[test] @@ -3775,23 +3775,23 @@ mod tests { fn test_shift_byte() { let mut s = ~"ABC"; let b = unsafe{raw::shift_byte(&mut s)}; - assert!((s == ~"BC")); - assert!((b == 65u8)); + assert_eq!(s, ~"BC"); + assert_eq!(b, 65u8); } #[test] fn test_pop_byte() { let mut s = ~"ABC"; let b = unsafe{raw::pop_byte(&mut s)}; - assert!((s == ~"AB")); - assert!((b == 67u8)); + assert_eq!(s, ~"AB"); + assert_eq!(b, 67u8); } #[test] fn test_unsafe_from_bytes() { let a = ~[65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8]; let b = unsafe { raw::from_bytes(a) }; - assert!((b == ~"AAAAAAA")); + assert_eq!(b, ~"AAAAAAA"); } #[test] @@ -3808,7 +3808,7 @@ mod tests { 0x20_u8, 0x4e_u8, 0x61_u8, 0x6d_u8]; - assert!(ss == from_bytes(bb)); + assert_eq!(ss, from_bytes(bb)); } #[test] @@ -3895,7 +3895,7 @@ mod tests { let a = ~[65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 65u8, 0u8]; let b = vec::raw::to_ptr(a); let c = raw::from_buf(b); - assert!((c == ~"AAAAAAA")); + assert_eq!(c, ~"AAAAAAA"); } } @@ -3911,20 +3911,20 @@ mod tests { fn test_as_buf() { let a = ~"Abcdefg"; let b = as_buf(a, |buf, _l| { - assert!(unsafe { *buf } == 65u8); + assert_eq!(unsafe { *buf }, 65u8); 100 }); - assert!((b == 100)); + assert_eq!(b, 100); } #[test] fn test_as_buf_small() { let a = ~"A"; let b = as_buf(a, |buf, _l| { - assert!(unsafe { *buf } == 65u8); + assert_eq!(unsafe { *buf }, 65u8); 100 }); - assert!((b == 100)); + assert_eq!(b, 100); } #[test] @@ -3933,7 +3933,7 @@ mod tests { let s = ~"hello"; let sb = as_buf(s, |b, _l| b); let s_cstr = raw::from_buf(sb); - assert!(s_cstr == s); + assert_eq!(s_cstr, s); } } @@ -3942,11 +3942,11 @@ mod tests { let a = ~"hello"; do as_buf(a) |buf, len| { unsafe { - assert!(a[0] == 'h' as u8); - assert!(*buf == 'h' as u8); - assert!(len == 6u); - assert!(*ptr::offset(buf,4u) == 'o' as u8); - assert!(*ptr::offset(buf,5u) == 0u8); + assert_eq!(a[0], 'h' as u8); + assert_eq!(*buf, 'h' as u8); + assert_eq!(len, 6u); + assert_eq!(*ptr::offset(buf,4u), 'o' as u8); + assert_eq!(*ptr::offset(buf,5u), 0u8); } } } @@ -3956,15 +3956,15 @@ mod tests { let a = "kernelsprite"; let b = slice(a, 7, len(a)); let c = slice(a, 0, len(a) - 6); - assert!(subslice_offset(a, b) == 7); - assert!(subslice_offset(a, c) == 0); + assert_eq!(subslice_offset(a, b), 7); + assert_eq!(subslice_offset(a, c), 0); let string = "a\nb\nc"; let mut lines = ~[]; for each_line(string) |line| { lines.push(line) } - assert!(subslice_offset(string, lines[0]) == 0); - assert!(subslice_offset(string, lines[1]) == 2); - assert!(subslice_offset(string, lines[2]) == 4); + assert_eq!(subslice_offset(string, lines[0]), 0); + assert_eq!(subslice_offset(string, lines[1]), 2); + assert_eq!(subslice_offset(string, lines[2]), 4); } #[test] @@ -3984,13 +3984,13 @@ mod tests { let mut i: uint = 0u; let n1: uint = len(s1); let n2: uint = vec::len::(v); - assert!((n1 == n2)); + assert_eq!(n1, n2); while i < n1 { let a: u8 = s1[i]; let b: u8 = s2[i]; debug!(a); debug!(b); - assert!((a == b)); + assert_eq!(a, b); i += 1u; } } @@ -4094,26 +4094,26 @@ mod tests { #[test] fn test_map() { - assert!(~"" == map(~"", |c| unsafe {libc::toupper(c as c_char)} as char)); - assert!(~"YMCA" == map(~"ymca", |c| unsafe {libc::toupper(c as c_char)} as char)); + assert_eq!(~"", map(~"", |c| unsafe {libc::toupper(c as c_char)} as char)); + assert_eq!(~"YMCA", map(~"ymca", |c| unsafe {libc::toupper(c as c_char)} as char)); } #[test] fn test_all() { - assert!(true == all(~"", char::is_uppercase)); - assert!(false == all(~"ymca", char::is_uppercase)); - assert!(true == all(~"YMCA", char::is_uppercase)); - assert!(false == all(~"yMCA", char::is_uppercase)); - assert!(false == all(~"YMCy", char::is_uppercase)); + assert_eq!(true, all(~"", char::is_uppercase)); + assert_eq!(false, all(~"ymca", char::is_uppercase)); + assert_eq!(true, all(~"YMCA", char::is_uppercase)); + assert_eq!(false, all(~"yMCA", char::is_uppercase)); + assert_eq!(false, all(~"YMCy", char::is_uppercase)); } #[test] fn test_any() { - assert!(false == any(~"", char::is_uppercase)); - assert!(false == any(~"ymca", char::is_uppercase)); - assert!(true == any(~"YMCA", char::is_uppercase)); - assert!(true == any(~"yMCA", char::is_uppercase)); - assert!(true == any(~"Ymcy", char::is_uppercase)); + assert_eq!(false, any(~"", char::is_uppercase)); + assert_eq!(false, any(~"ymca", char::is_uppercase)); + assert_eq!(true, any(~"YMCA", char::is_uppercase)); + assert_eq!(true, any(~"yMCA", char::is_uppercase)); + assert_eq!(true, any(~"Ymcy", char::is_uppercase)); } #[test] @@ -4205,7 +4205,7 @@ mod tests { let mut pos = 0; for s.each |b| { - assert!(b == v[pos]); + assert_eq!(b, v[pos]); pos += 1; } } @@ -4213,7 +4213,7 @@ mod tests { #[test] fn test_each_empty() { for "".each |b| { - assert!(b == 0u8); + assert_eq!(b, 0u8); } } @@ -4228,8 +4228,8 @@ mod tests { let mut pos = 0; for s.eachi |i, b| { - assert!(pos == i); - assert!(b == v[pos]); + assert_eq!(pos, i); + assert_eq!(b, v[pos]); pos += 1; } } @@ -4237,8 +4237,8 @@ mod tests { #[test] fn test_eachi_empty() { for "".eachi |i, b| { - assert!(i == 0); - assert!(b == 0); + assert_eq!(i, 0); + assert_eq!(b, 0); } } @@ -4254,14 +4254,14 @@ mod tests { for s.each_reverse |b| { pos -= 1; - assert!(b == v[pos]); + assert_eq!(b, v[pos]); } } #[test] fn test_each_empty_reverse() { for "".each_reverse |b| { - assert!(b == 0u8); + assert_eq!(b, 0u8); } } @@ -4277,16 +4277,16 @@ mod tests { for s.eachi_reverse |i, b| { pos -= 1; - assert!(pos == i); - assert!(b == v[pos]); + assert_eq!(pos, i); + assert_eq!(b, v[pos]); } } #[test] fn test_eachi_reverse_empty() { for "".eachi_reverse |i, b| { - assert!(i == 0); - assert!(b == 0); + assert_eq!(i, 0); + assert_eq!(b, 0); } } @@ -4296,7 +4296,7 @@ mod tests { let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = 0; for s.each_char |ch| { - assert!(ch == v[pos]); + assert_eq!(ch, v[pos]); pos += 1; } } @@ -4307,8 +4307,8 @@ mod tests { let v = ~['ศ','ไ','ท','ย','中','华','V','i','ệ','t',' ','N','a','m']; let mut pos = 0; for s.each_chari |i, ch| { - assert!(pos == i); - assert!(ch == v[pos]); + assert_eq!(pos, i); + assert_eq!(ch, v[pos]); pos += 1; } } @@ -4320,7 +4320,7 @@ mod tests { let mut pos = v.len(); for s.each_char_reverse |ch| { pos -= 1; - assert!(ch == v[pos]); + assert_eq!(ch, v[pos]); } } @@ -4331,43 +4331,43 @@ mod tests { let mut pos = v.len(); for s.each_chari_reverse |i, ch| { pos -= 1; - assert!(pos == i); - assert!(ch == v[pos]); + assert_eq!(pos, i); + assert_eq!(ch, v[pos]); } } #[test] fn test_escape_unicode() { - assert!(escape_unicode(~"abc") == ~"\\x61\\x62\\x63"); - assert!(escape_unicode(~"a c") == ~"\\x61\\x20\\x63"); - assert!(escape_unicode(~"\r\n\t") == ~"\\x0d\\x0a\\x09"); - assert!(escape_unicode(~"'\"\\") == ~"\\x27\\x22\\x5c"); + assert_eq!(escape_unicode(~"abc"), ~"\\x61\\x62\\x63"); + assert_eq!(escape_unicode(~"a c"), ~"\\x61\\x20\\x63"); + assert_eq!(escape_unicode(~"\r\n\t"), ~"\\x0d\\x0a\\x09"); + assert_eq!(escape_unicode(~"'\"\\"), ~"\\x27\\x22\\x5c"); assert!(escape_unicode(~"\x00\x01\xfe\xff") == ~"\\x00\\x01\\xfe\\xff"); - assert!(escape_unicode(~"\u0100\uffff") == ~"\\u0100\\uffff"); + assert_eq!(escape_unicode(~"\u0100\uffff"), ~"\\u0100\\uffff"); assert!(escape_unicode(~"\U00010000\U0010ffff") == ~"\\U00010000\\U0010ffff"); - assert!(escape_unicode(~"ab\ufb00") == ~"\\x61\\x62\\ufb00"); - assert!(escape_unicode(~"\U0001d4ea\r") == ~"\\U0001d4ea\\x0d"); + assert_eq!(escape_unicode(~"ab\ufb00"), ~"\\x61\\x62\\ufb00"); + assert_eq!(escape_unicode(~"\U0001d4ea\r"), ~"\\U0001d4ea\\x0d"); } #[test] fn test_escape_default() { - assert!(escape_default(~"abc") == ~"abc"); - assert!(escape_default(~"a c") == ~"a c"); - assert!(escape_default(~"\r\n\t") == ~"\\r\\n\\t"); - assert!(escape_default(~"'\"\\") == ~"\\'\\\"\\\\"); - assert!(escape_default(~"\u0100\uffff") == ~"\\u0100\\uffff"); + assert_eq!(escape_default(~"abc"), ~"abc"); + assert_eq!(escape_default(~"a c"), ~"a c"); + assert_eq!(escape_default(~"\r\n\t"), ~"\\r\\n\\t"); + assert_eq!(escape_default(~"'\"\\"), ~"\\'\\\"\\\\"); + assert_eq!(escape_default(~"\u0100\uffff"), ~"\\u0100\\uffff"); assert!(escape_default(~"\U00010000\U0010ffff") == ~"\\U00010000\\U0010ffff"); - assert!(escape_default(~"ab\ufb00") == ~"ab\\ufb00"); - assert!(escape_default(~"\U0001d4ea\r") == ~"\\U0001d4ea\\r"); + assert_eq!(escape_default(~"ab\ufb00"), ~"ab\\ufb00"); + assert_eq!(escape_default(~"\U0001d4ea\r"), ~"\\U0001d4ea\\r"); } #[test] fn test_to_managed() { - assert!((~"abc").to_managed() == @"abc"); - assert!(slice("abcdef", 1, 5).to_managed() == @"bcde"); + assert_eq!((~"abc").to_managed(), @"abc"); + assert_eq!(slice("abcdef", 1, 5).to_managed(), @"bcde"); } #[test] @@ -4381,7 +4381,7 @@ mod tests { #[test] fn test_char_range_at_reverse_underflow() { - assert!(char_range_at_reverse("abc", 0).next == 0); + assert_eq!(char_range_at_reverse("abc", 0).next, 0); } #[test] diff --git a/src/libcore/sys.rs b/src/libcore/sys.rs index 50a739ec67df7..fc57cf40d1e01 100644 --- a/src/libcore/sys.rs +++ b/src/libcore/sys.rs @@ -251,10 +251,10 @@ mod tests { #[test] fn size_of_basic() { - assert!(size_of::() == 1u); - assert!(size_of::() == 2u); - assert!(size_of::() == 4u); - assert!(size_of::() == 8u); + assert_eq!(size_of::(), 1u); + assert_eq!(size_of::(), 2u); + assert_eq!(size_of::(), 4u); + assert_eq!(size_of::(), 8u); } #[test] @@ -262,15 +262,15 @@ mod tests { #[cfg(target_arch = "arm")] #[cfg(target_arch = "mips")] fn size_of_32() { - assert!(size_of::() == 4u); - assert!(size_of::<*uint>() == 4u); + assert_eq!(size_of::(), 4u); + assert_eq!(size_of::<*uint>(), 4u); } #[test] #[cfg(target_arch = "x86_64")] fn size_of_64() { - assert!(size_of::() == 8u); - assert!(size_of::<*uint>() == 8u); + assert_eq!(size_of::(), 8u); + assert_eq!(size_of::<*uint>(), 8u); } #[test] @@ -284,9 +284,9 @@ mod tests { #[test] fn nonzero_size_of_basic() { type Z = [i8, ..0]; - assert!(size_of::() == 0u); - assert!(nonzero_size_of::() == 1u); - assert!(nonzero_size_of::() == size_of::()); + assert_eq!(size_of::(), 0u); + assert_eq!(nonzero_size_of::(), 1u); + assert_eq!(nonzero_size_of::(), size_of::()); } #[test] @@ -299,9 +299,9 @@ mod tests { #[test] fn align_of_basic() { - assert!(pref_align_of::() == 1u); - assert!(pref_align_of::() == 2u); - assert!(pref_align_of::() == 4u); + assert_eq!(pref_align_of::(), 1u); + assert_eq!(pref_align_of::(), 2u); + assert_eq!(pref_align_of::(), 4u); } #[test] @@ -309,15 +309,15 @@ mod tests { #[cfg(target_arch = "arm")] #[cfg(target_arch = "mips")] fn align_of_32() { - assert!(pref_align_of::() == 4u); - assert!(pref_align_of::<*uint>() == 4u); + assert_eq!(pref_align_of::(), 4u); + assert_eq!(pref_align_of::<*uint>(), 4u); } #[test] #[cfg(target_arch = "x86_64")] fn align_of_64() { - assert!(pref_align_of::() == 8u); - assert!(pref_align_of::<*uint>() == 8u); + assert_eq!(pref_align_of::(), 8u); + assert_eq!(pref_align_of::<*uint>(), 8u); } #[test] @@ -333,7 +333,7 @@ mod tests { let x = 10; let f: &fn(int) -> int = |y| x + y; - assert!(f(20) == 30); + assert_eq!(f(20), 30); let original_closure: Closure = cast::transmute(f); @@ -346,7 +346,7 @@ mod tests { }; let new_f: &fn(int) -> int = cast::transmute(new_closure); - assert!(new_f(20) == 30); + assert_eq!(new_f(20), 30); } } diff --git a/src/libcore/task/mod.rs b/src/libcore/task/mod.rs index a6edee38e188a..e96da3b08c9ce 100644 --- a/src/libcore/task/mod.rs +++ b/src/libcore/task/mod.rs @@ -805,7 +805,7 @@ fn test_future_result() { let mut builder = task(); builder.future_result(|r| result = Some(r)); do builder.spawn {} - assert!(result.unwrap().recv() == Success); + assert_eq!(result.unwrap().recv(), Success); result = None; let mut builder = task(); @@ -814,7 +814,7 @@ fn test_future_result() { do builder.spawn { fail!(); } - assert!(result.unwrap().recv() == Failure); + assert_eq!(result.unwrap().recv(), Failure); } #[test] #[should_fail] #[ignore(cfg(windows))] @@ -891,7 +891,7 @@ fn test_spawn_sched_childs_on_default_sched() { let ch = ch.take(); let child_sched_id = unsafe { rt::rust_get_sched_id() }; assert!(parent_sched_id != child_sched_id); - assert!(child_sched_id == default_id); + assert_eq!(child_sched_id, default_id); ch.send(()); }; }; @@ -985,7 +985,7 @@ fn avoid_copying_the_body(spawnfn: &fn(v: ~fn())) { } let x_in_child = p.recv(); - assert!(x_in_parent == x_in_child); + assert_eq!(x_in_parent, x_in_child); } #[test] @@ -1143,7 +1143,7 @@ fn test_sched_thread_per_core() { unsafe { let cores = rt::rust_num_threads(); let reported_threads = rt::rust_sched_threads(); - assert!((cores as uint == reported_threads as uint)); + assert_eq!(cores as uint, reported_threads as uint); chan.send(()); } } @@ -1158,9 +1158,9 @@ fn test_spawn_thread_on_demand() { do spawn_sched(ManualThreads(2)) || { unsafe { let max_threads = rt::rust_sched_threads(); - assert!((max_threads as int == 2)); + assert_eq!(max_threads as int, 2); let running_threads = rt::rust_sched_current_nonlazy_threads(); - assert!((running_threads as int == 1)); + assert_eq!(running_threads as int, 1); let (port2, chan2) = comm::stream(); @@ -1169,7 +1169,7 @@ fn test_spawn_thread_on_demand() { } let running_threads2 = rt::rust_sched_current_nonlazy_threads(); - assert!((running_threads2 as int == 2)); + assert_eq!(running_threads2 as int, 2); port2.recv(); chan.send(()); diff --git a/src/libcore/task/spawn.rs b/src/libcore/task/spawn.rs index 5f9642604d0c1..2ac8fc5f073ec 100644 --- a/src/libcore/task/spawn.rs +++ b/src/libcore/task/spawn.rs @@ -774,7 +774,7 @@ fn test_spawn_raw_notify_success() { }; do spawn_raw(opts) { } - assert!(notify_po.recv() == Success); + assert_eq!(notify_po.recv(), Success); } #[test] @@ -791,5 +791,5 @@ fn test_spawn_raw_notify_failure() { do spawn_raw(opts) { fail!(); } - assert!(notify_po.recv() == Failure); + assert_eq!(notify_po.recv(), Failure); } diff --git a/src/libcore/to_str.rs b/src/libcore/to_str.rs index 365cb847740b2..1469471b7cef3 100644 --- a/src/libcore/to_str.rs +++ b/src/libcore/to_str.rs @@ -182,30 +182,30 @@ mod tests { use container::Set; #[test] fn test_simple_types() { - assert!(1i.to_str() == ~"1"); - assert!((-1i).to_str() == ~"-1"); - assert!(200u.to_str() == ~"200"); - assert!(2u8.to_str() == ~"2"); - assert!(true.to_str() == ~"true"); - assert!(false.to_str() == ~"false"); - assert!(().to_str() == ~"()"); - assert!((~"hi").to_str() == ~"hi"); - assert!((@"hi").to_str() == ~"hi"); + assert_eq!(1i.to_str(), ~"1"); + assert_eq!((-1i).to_str(), ~"-1"); + assert_eq!(200u.to_str(), ~"200"); + assert_eq!(2u8.to_str(), ~"2"); + assert_eq!(true.to_str(), ~"true"); + assert_eq!(false.to_str(), ~"false"); + assert_eq!(().to_str(), ~"()"); + assert_eq!((~"hi").to_str(), ~"hi"); + assert_eq!((@"hi").to_str(), ~"hi"); } #[test] fn test_tuple_types() { - assert!((1, 2).to_str() == ~"(1, 2)"); - assert!((~"a", ~"b", false).to_str() == ~"(a, b, false)"); - assert!(((), ((), 100)).to_str() == ~"((), ((), 100))"); + assert_eq!((1, 2).to_str(), ~"(1, 2)"); + assert_eq!((~"a", ~"b", false).to_str(), ~"(a, b, false)"); + assert_eq!(((), ((), 100)).to_str(), ~"((), ((), 100))"); } #[test] fn test_vectors() { let x: ~[int] = ~[]; - assert!(x.to_str() == ~"[]"); - assert!((~[1]).to_str() == ~"[1]"); - assert!((~[1, 2, 3]).to_str() == ~"[1, 2, 3]"); + assert_eq!(x.to_str(), ~"[]"); + assert_eq!((~[1]).to_str(), ~"[1]"); + assert_eq!((~[1, 2, 3]).to_str(), ~"[1, 2, 3]"); assert!((~[~[], ~[1], ~[1, 1]]).to_str() == ~"[[], [1], [1, 1]]"); } @@ -221,7 +221,7 @@ mod tests { let table_str = table.to_str(); assert!(table_str == ~"{1: 2, 3: 4}" || table_str == ~"{3: 4, 1: 2}"); - assert!(empty.to_str() == ~"{}"); + assert_eq!(empty.to_str(), ~"{}"); } #[test] @@ -235,6 +235,6 @@ mod tests { let set_str = set.to_str(); assert!(set_str == ~"{1, 2}" || set_str == ~"{2, 1}"); - assert!(empty_set.to_str() == ~"{}"); + assert_eq!(empty_set.to_str(), ~"{}"); } } diff --git a/src/libcore/trie.rs b/src/libcore/trie.rs index 05ef1cf433faf..c9485654b50e4 100644 --- a/src/libcore/trie.rs +++ b/src/libcore/trie.rs @@ -451,7 +451,7 @@ pub fn check_integrity(trie: &TrieNode) { } } - assert!(sum == trie.count); + assert_eq!(sum, trie.count); } #[cfg(test)] @@ -521,8 +521,8 @@ mod tests { let mut n = 0; for m.each |k, v| { - assert!(*k == n); - assert!(*v == n * 2); + assert_eq!(*k, n); + assert_eq!(*v, n * 2); n += 1; } } @@ -540,8 +540,8 @@ mod tests { if n == uint::max_value - 5000 { break } assert!(n < uint::max_value - 5000); - assert!(*k == n); - assert!(*v == n / 2); + assert_eq!(*k, n); + assert_eq!(*v, n / 2); n += 1; } } @@ -558,8 +558,8 @@ mod tests { let mut n = 4; for m.each_reverse |k, v| { - assert!(*k == n); - assert!(*v == n * 2); + assert_eq!(*k, n); + assert_eq!(*v, n * 2); n -= 1; } } @@ -577,8 +577,8 @@ mod tests { if n == uint::max_value - 5000 { break } assert!(n > uint::max_value - 5000); - assert!(*k == n); - assert!(*v == n / 2); + assert_eq!(*k, n); + assert_eq!(*v, n / 2); n -= 1; } } @@ -593,14 +593,14 @@ mod tests { assert!(trie.insert(x)); assert!(trie.insert(y)); - assert!(trie.len() == 2); + assert_eq!(trie.len(), 2); let expected = [x, y]; let mut i = 0; for trie.each |x| { - assert!(expected[i] == *x); + assert_eq!(expected[i], *x); i += 1; } } @@ -608,16 +608,16 @@ mod tests { #[test] fn test_swap() { let mut m = TrieMap::new(); - assert!(m.swap(1, 2) == None); - assert!(m.swap(1, 3) == Some(2)); - assert!(m.swap(1, 4) == Some(3)); + assert_eq!(m.swap(1, 2), None); + assert_eq!(m.swap(1, 3), Some(2)); + assert_eq!(m.swap(1, 4), Some(3)); } #[test] fn test_pop() { let mut m = TrieMap::new(); m.insert(1, 2); - assert!(m.pop(&1) == Some(2)); - assert!(m.pop(&1) == None); + assert_eq!(m.pop(&1), Some(2)); + assert_eq!(m.pop(&1), None); } } diff --git a/src/libcore/unstable/at_exit.rs b/src/libcore/unstable/at_exit.rs index 39c930d415f1c..d214b509dfbf9 100644 --- a/src/libcore/unstable/at_exit.rs +++ b/src/libcore/unstable/at_exit.rs @@ -83,7 +83,7 @@ fn test_at_exit() { let i = 10; do at_exit { debug!("at_exit1"); - assert!(i == 10); + assert_eq!(i, 10); } } @@ -93,7 +93,7 @@ fn test_at_exit_many() { for uint::range(20, 100) |j| { do at_exit { debug!("at_exit2"); - assert!(i == 10); + assert_eq!(i, 10); assert!(j > i); } } diff --git a/src/libcore/unstable/extfmt.rs b/src/libcore/unstable/extfmt.rs index 11ac8c14fe46d..1a1a89a413fcc 100644 --- a/src/libcore/unstable/extfmt.rs +++ b/src/libcore/unstable/extfmt.rs @@ -355,8 +355,8 @@ pub mod ct { fn test(s: &str, flags: &[Flag], next: uint) { let f = parse_flags(s, 0, s.len()); - assert!(pack(f.val) == pack(flags)); - assert!(f.next == next); + assert_eq!(pack(f.val), pack(flags)); + assert_eq!(f.next, next); } test("", [], 0); @@ -459,10 +459,10 @@ pub mod ct { assert!(peek_num(s2, 0, s2.len()).is_none()); let s3 = "123"; - assert!(peek_num(s3, 0, s3.len()) == Some(Parsed::new(123, 3))); + assert_eq!(peek_num(s3, 0, s3.len()), Some(Parsed::new(123, 3))); let s4 = "123foo"; - assert!(peek_num(s4, 0, s4.len()) == Some(Parsed::new(123, 3))); + assert_eq!(peek_num(s4, 0, s4.len()), Some(Parsed::new(123, 3))); } } diff --git a/src/libcore/unstable/finally.rs b/src/libcore/unstable/finally.rs index 559287b529772..5001fb421cd86 100644 --- a/src/libcore/unstable/finally.rs +++ b/src/libcore/unstable/finally.rs @@ -79,10 +79,10 @@ fn test_success() { i = 10; }).finally { assert!(!failing()); - assert!(i == 10); + assert_eq!(i, 10); i = 20; } - assert!(i == 20); + assert_eq!(i, 20); } #[test] @@ -95,7 +95,7 @@ fn test_fail() { fail!(); }).finally { assert!(failing()); - assert!(i == 10); + assert_eq!(i, 10); } } @@ -103,7 +103,7 @@ fn test_fail() { fn test_retval() { let closure: &fn() -> int = || 10; let i = do closure.finally { }; - assert!(i == 10); + assert_eq!(i, 10); } #[test] @@ -134,6 +134,6 @@ fn test_managed() { *i += 10; r }; - assert!(do managed.finally {} == 10); - assert!(*i == 20); + assert_eq!(do managed.finally {}, 10); + assert_eq!(*i, 20); } \ No newline at end of file diff --git a/src/libcore/unstable/global.rs b/src/libcore/unstable/global.rs index 88433f9cefe51..96549a83a8cf3 100644 --- a/src/libcore/unstable/global.rs +++ b/src/libcore/unstable/global.rs @@ -200,7 +200,7 @@ fn get_global_state() -> Exclusive { let prev_i = unsafe { atomic_cxchg(&mut *global_ptr, state_i, POISON) }; - assert!(prev_i == state_i); + assert_eq!(prev_i, state_i); // Capture the global state object in the at_exit closure // so that it is destroyed at the right time diff --git a/src/libcore/unstable/mod.rs b/src/libcore/unstable/mod.rs index 18a6262f17de9..9681a3f36fcee 100644 --- a/src/libcore/unstable/mod.rs +++ b/src/libcore/unstable/mod.rs @@ -55,7 +55,7 @@ pub fn run_in_bare_thread(f: ~fn()) { fn test_run_in_bare_thread() { let i = 100; do run_in_bare_thread { - assert!(i == 100); + assert_eq!(i, 100); } } diff --git a/src/libcore/unstable/sync.rs b/src/libcore/unstable/sync.rs index 4d5c3bf7a78a4..091031f51fd8a 100644 --- a/src/libcore/unstable/sync.rs +++ b/src/libcore/unstable/sync.rs @@ -275,11 +275,11 @@ mod tests { let x2 = x.clone(); do task::try || { do x2.with |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } }; do x.with |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } } diff --git a/src/libcore/util.rs b/src/libcore/util.rs index e5067fb90bcc0..eaf1e31d403ad 100644 --- a/src/libcore/util.rs +++ b/src/libcore/util.rs @@ -193,8 +193,8 @@ mod tests { let mut x = 31337; let mut y = 42; swap(&mut x, &mut y); - assert!(x == 42); - assert!(y == 31337); + assert_eq!(x, 42); + assert_eq!(y, 31337); } #[test] pub fn test_replace() { diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 4c6e0791ba2ca..f12e70faa8f80 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -1389,7 +1389,7 @@ pub fn zip_slice(v: &const [T], u: &const [U]) let mut zipped = ~[]; let sz = len(v); let mut i = 0u; - assert!(sz == len(u)); + assert_eq!(sz, len(u)); while i < sz { zipped.push((v[i], u[i])); i += 1u; @@ -1405,7 +1405,7 @@ pub fn zip_slice(v: &const [T], u: &const [U]) */ pub fn zip(mut v: ~[T], mut u: ~[U]) -> ~[(T, U)] { let mut i = len(v); - assert!(i == len(u)); + assert_eq!(i, len(u)); let mut w = with_capacity(i); while i > 0 { w.push((v.pop(),u.pop())); @@ -1723,7 +1723,7 @@ pub fn eachi_reverse<'r,T>(v: &'r [T], */ #[inline] pub fn _each2(v1: &[U], v2: &[T], f: &fn(u: &U, t: &T) -> bool) -> bool { - assert!(v1.len() == v2.len()); + assert_eq!(v1.len(), v2.len()); for uint::range(0u, v1.len()) |i| { if !f(&v1[i], &v2[i]) { return false; @@ -1751,7 +1751,7 @@ pub fn each2(v1: &[U], v2: &[T], f: &fn(u: &U, t: &T) -> bool) -> bool { */ #[inline] pub fn _each2_mut(v1: &mut [U], v2: &mut [T], f: &fn(u: &mut U, t: &mut T) -> bool) -> bool { - assert!(v1.len() == v2.len()); + assert_eq!(v1.len(), v2.len()); for uint::range(0u, v1.len()) |i| { if !f(&mut v1[i], &mut v2[i]) { return false; @@ -3139,21 +3139,21 @@ mod tests { let a = ~[1, 2, 3]; let mut ptr = raw::to_ptr(a); let b = from_buf(ptr, 3u); - assert!(b.len() == 3u); - assert!(b[0] == 1); - assert!(b[1] == 2); - assert!(b[2] == 3); + assert_eq!(b.len(), 3u); + assert_eq!(b[0], 1); + assert_eq!(b[1], 2); + assert_eq!(b[2], 3); // Test on-heap copy-from-buf. let c = ~[1, 2, 3, 4, 5]; ptr = raw::to_ptr(c); let d = from_buf(ptr, 5u); - assert!(d.len() == 5u); - assert!(d[0] == 1); - assert!(d[1] == 2); - assert!(d[2] == 3); - assert!(d[3] == 4); - assert!(d[4] == 5); + assert_eq!(d.len(), 5u); + assert_eq!(d[0], 1); + assert_eq!(d[1], 2); + assert_eq!(d[2], 3); + assert_eq!(d[3], 4); + assert_eq!(d[4], 5); } } @@ -3161,37 +3161,37 @@ mod tests { fn test_from_fn() { // Test on-stack from_fn. let mut v = from_fn(3u, square); - assert!(v.len() == 3u); - assert!(v[0] == 0u); - assert!(v[1] == 1u); - assert!(v[2] == 4u); + assert_eq!(v.len(), 3u); + assert_eq!(v[0], 0u); + assert_eq!(v[1], 1u); + assert_eq!(v[2], 4u); // Test on-heap from_fn. v = from_fn(5u, square); - assert!(v.len() == 5u); - assert!(v[0] == 0u); - assert!(v[1] == 1u); - assert!(v[2] == 4u); - assert!(v[3] == 9u); - assert!(v[4] == 16u); + assert_eq!(v.len(), 5u); + assert_eq!(v[0], 0u); + assert_eq!(v[1], 1u); + assert_eq!(v[2], 4u); + assert_eq!(v[3], 9u); + assert_eq!(v[4], 16u); } #[test] fn test_from_elem() { // Test on-stack from_elem. let mut v = from_elem(2u, 10u); - assert!(v.len() == 2u); - assert!(v[0] == 10u); - assert!(v[1] == 10u); + assert_eq!(v.len(), 2u); + assert_eq!(v[0], 10u); + assert_eq!(v[1], 10u); // Test on-heap from_elem. v = from_elem(6u, 20u); - assert!(v[0] == 20u); - assert!(v[1] == 20u); - assert!(v[2] == 20u); - assert!(v[3] == 20u); - assert!(v[4] == 20u); - assert!(v[5] == 20u); + assert_eq!(v[0], 20u); + assert_eq!(v[1], 20u); + assert_eq!(v[2], 20u); + assert_eq!(v[3], 20u); + assert_eq!(v[4], 20u); + assert_eq!(v[5], 20u); } #[test] @@ -3206,18 +3206,18 @@ mod tests { let v0 : &[Z] = &[]; let v1 : &[Z] = &[[]]; let v2 : &[Z] = &[[], []]; - assert!(sys::size_of::() == 0); - assert!(v0.len() == 0); - assert!(v1.len() == 1); - assert!(v2.len() == 2); + assert_eq!(sys::size_of::(), 0); + assert_eq!(v0.len(), 0); + assert_eq!(v1.len(), 1); + assert_eq!(v2.len(), 2); } #[test] fn test_head() { let mut a = ~[11]; - assert!(a.head() == &11); + assert_eq!(a.head(), &11); a = ~[11, 12]; - assert!(a.head() == &11); + assert_eq!(a.head(), &11); } #[test] @@ -3231,19 +3231,19 @@ mod tests { #[test] fn test_head_opt() { let mut a = ~[]; - assert!(a.head_opt() == None); + assert_eq!(a.head_opt(), None); a = ~[11]; - assert!(a.head_opt().unwrap() == &11); + assert_eq!(a.head_opt().unwrap(), &11); a = ~[11, 12]; - assert!(a.head_opt().unwrap() == &11); + assert_eq!(a.head_opt().unwrap(), &11); } #[test] fn test_tail() { let mut a = ~[11]; - assert!(a.tail() == &[]); + assert_eq!(a.tail(), &[]); a = ~[11, 12]; - assert!(a.tail() == &[12]); + assert_eq!(a.tail(), &[12]); } #[test] @@ -3257,9 +3257,9 @@ mod tests { #[test] fn test_tailn() { let mut a = ~[11, 12, 13]; - assert!(a.tailn(0) == &[11, 12, 13]); + assert_eq!(a.tailn(0), &[11, 12, 13]); a = ~[11, 12, 13]; - assert!(a.tailn(2) == &[13]); + assert_eq!(a.tailn(2), &[13]); } #[test] @@ -3273,9 +3273,9 @@ mod tests { #[test] fn test_init() { let mut a = ~[11]; - assert!(a.init() == &[]); + assert_eq!(a.init(), &[]); a = ~[11, 12]; - assert!(a.init() == &[11]); + assert_eq!(a.init(), &[11]); } #[init] @@ -3289,9 +3289,9 @@ mod tests { #[test] fn test_initn() { let mut a = ~[11, 12, 13]; - assert!(a.initn(0) == &[11, 12, 13]); + assert_eq!(a.initn(0), &[11, 12, 13]); a = ~[11, 12, 13]; - assert!(a.initn(2) == &[11]); + assert_eq!(a.initn(2), &[11]); } #[init] @@ -3305,9 +3305,9 @@ mod tests { #[test] fn test_last() { let mut a = ~[11]; - assert!(a.last() == &11); + assert_eq!(a.last(), &11); a = ~[11, 12]; - assert!(a.last() == &12); + assert_eq!(a.last(), &12); } #[test] @@ -3321,11 +3321,11 @@ mod tests { #[test] fn test_last_opt() { let mut a = ~[]; - assert!(a.last_opt() == None); + assert_eq!(a.last_opt(), None); a = ~[11]; - assert!(a.last_opt().unwrap() == &11); + assert_eq!(a.last_opt().unwrap(), &11); a = ~[11, 12]; - assert!(a.last_opt().unwrap() == &12); + assert_eq!(a.last_opt().unwrap(), &12); } #[test] @@ -3333,35 +3333,35 @@ mod tests { // Test fixed length vector. let vec_fixed = [1, 2, 3, 4]; let v_a = slice(vec_fixed, 1u, vec_fixed.len()).to_vec(); - assert!(v_a.len() == 3u); - assert!(v_a[0] == 2); - assert!(v_a[1] == 3); - assert!(v_a[2] == 4); + assert_eq!(v_a.len(), 3u); + assert_eq!(v_a[0], 2); + assert_eq!(v_a[1], 3); + assert_eq!(v_a[2], 4); // Test on stack. let vec_stack = &[1, 2, 3]; let v_b = slice(vec_stack, 1u, 3u).to_vec(); - assert!(v_b.len() == 2u); - assert!(v_b[0] == 2); - assert!(v_b[1] == 3); + assert_eq!(v_b.len(), 2u); + assert_eq!(v_b[0], 2); + assert_eq!(v_b[1], 3); // Test on managed heap. let vec_managed = @[1, 2, 3, 4, 5]; let v_c = slice(vec_managed, 0u, 3u).to_vec(); - assert!(v_c.len() == 3u); - assert!(v_c[0] == 1); - assert!(v_c[1] == 2); - assert!(v_c[2] == 3); + assert_eq!(v_c.len(), 3u); + assert_eq!(v_c[0], 1); + assert_eq!(v_c[1], 2); + assert_eq!(v_c[2], 3); // Test on exchange heap. let vec_unique = ~[1, 2, 3, 4, 5, 6]; let v_d = slice(vec_unique, 1u, 6u).to_vec(); - assert!(v_d.len() == 5u); - assert!(v_d[0] == 2); - assert!(v_d[1] == 3); - assert!(v_d[2] == 4); - assert!(v_d[3] == 5); - assert!(v_d[4] == 6); + assert_eq!(v_d.len(), 5u); + assert_eq!(v_d[0], 2); + assert_eq!(v_d[1], 3); + assert_eq!(v_d[2], 4); + assert_eq!(v_d[3], 5); + assert_eq!(v_d[4], 6); } #[test] @@ -3369,27 +3369,27 @@ mod tests { // Test on-heap pop. let mut v = ~[1, 2, 3, 4, 5]; let e = v.pop(); - assert!(v.len() == 4u); - assert!(v[0] == 1); - assert!(v[1] == 2); - assert!(v[2] == 3); - assert!(v[3] == 4); - assert!(e == 5); + assert_eq!(v.len(), 4u); + assert_eq!(v[0], 1); + assert_eq!(v[1], 2); + assert_eq!(v[2], 3); + assert_eq!(v[3], 4); + assert_eq!(e, 5); } #[test] fn test_swap_remove() { let mut v = ~[1, 2, 3, 4, 5]; let mut e = v.swap_remove(0); - assert!(v.len() == 4); - assert!(e == 1); - assert!(v[0] == 5); + assert_eq!(v.len(), 4); + assert_eq!(e, 1); + assert_eq!(v[0], 5); e = v.swap_remove(3); - assert!(v.len() == 3); - assert!(e == 4); - assert!(v[0] == 5); - assert!(v[1] == 2); - assert!(v[2] == 3); + assert_eq!(v.len(), 3); + assert_eq!(e, 4); + assert_eq!(v[0], 5); + assert_eq!(v[1], 2); + assert_eq!(v[2], 3); } #[test] @@ -3399,11 +3399,11 @@ mod tests { ::unstable::sync::exclusive(()), ::unstable::sync::exclusive(())]; let mut _e = v.swap_remove(0); - assert!(v.len() == 2); + assert_eq!(v.len(), 2); _e = v.swap_remove(1); - assert!(v.len() == 1); + assert_eq!(v.len(), 1); _e = v.swap_remove(0); - assert!(v.len() == 0); + assert_eq!(v.len(), 0); } #[test] @@ -3411,14 +3411,14 @@ mod tests { // Test on-stack push(). let mut v = ~[]; v.push(1); - assert!(v.len() == 1u); - assert!(v[0] == 1); + assert_eq!(v.len(), 1u); + assert_eq!(v[0], 1); // Test on-heap push(). v.push(2); - assert!(v.len() == 2u); - assert!(v[0] == 1); - assert!(v[1] == 2); + assert_eq!(v.len(), 2u); + assert_eq!(v[0], 1); + assert_eq!(v[1], 2); } #[test] @@ -3426,48 +3426,48 @@ mod tests { // Test on-stack grow(). let mut v = ~[]; v.grow(2u, &1); - assert!(v.len() == 2u); - assert!(v[0] == 1); - assert!(v[1] == 1); + assert_eq!(v.len(), 2u); + assert_eq!(v[0], 1); + assert_eq!(v[1], 1); // Test on-heap grow(). v.grow(3u, &2); - assert!(v.len() == 5u); - assert!(v[0] == 1); - assert!(v[1] == 1); - assert!(v[2] == 2); - assert!(v[3] == 2); - assert!(v[4] == 2); + assert_eq!(v.len(), 5u); + assert_eq!(v[0], 1); + assert_eq!(v[1], 1); + assert_eq!(v[2], 2); + assert_eq!(v[3], 2); + assert_eq!(v[4], 2); } #[test] fn test_grow_fn() { let mut v = ~[]; v.grow_fn(3u, square); - assert!(v.len() == 3u); - assert!(v[0] == 0u); - assert!(v[1] == 1u); - assert!(v[2] == 4u); + assert_eq!(v.len(), 3u); + assert_eq!(v[0], 0u); + assert_eq!(v[1], 1u); + assert_eq!(v[2], 4u); } #[test] fn test_grow_set() { let mut v = ~[1, 2, 3]; v.grow_set(4u, &4, 5); - assert!(v.len() == 5u); - assert!(v[0] == 1); - assert!(v[1] == 2); - assert!(v[2] == 3); - assert!(v[3] == 4); - assert!(v[4] == 5); + assert_eq!(v.len(), 5u); + assert_eq!(v[0], 1); + assert_eq!(v[1], 2); + assert_eq!(v[2], 3); + assert_eq!(v[3], 4); + assert_eq!(v[4], 5); } #[test] fn test_truncate() { let mut v = ~[@6,@5,@4]; v.truncate(1); - assert!(v.len() == 1); - assert!(*(v[0]) == 6); + assert_eq!(v.len(), 1); + assert_eq!(*(v[0]), 6); // If the unsafe block didn't drop things properly, we blow up here. } @@ -3475,7 +3475,7 @@ mod tests { fn test_clear() { let mut v = ~[@6,@5,@4]; v.clear(); - assert!(v.len() == 0); + assert_eq!(v.len(), 0); // If the unsafe block didn't drop things properly, we blow up here. } @@ -3484,7 +3484,7 @@ mod tests { fn case(a: ~[uint], b: ~[uint]) { let mut v = a; v.dedup(); - assert!(v == b); + assert_eq!(v, b); } case(~[], ~[]); case(~[1], ~[1]); @@ -3529,20 +3529,20 @@ mod tests { // Test on-stack map. let mut v = ~[1u, 2u, 3u]; let mut w = map(v, square_ref); - assert!(w.len() == 3u); - assert!(w[0] == 1u); - assert!(w[1] == 4u); - assert!(w[2] == 9u); + assert_eq!(w.len(), 3u); + assert_eq!(w[0], 1u); + assert_eq!(w[1], 4u); + assert_eq!(w[2], 9u); // Test on-heap map. v = ~[1u, 2u, 3u, 4u, 5u]; w = map(v, square_ref); - assert!(w.len() == 5u); - assert!(w[0] == 1u); - assert!(w[1] == 4u); - assert!(w[2] == 9u); - assert!(w[3] == 16u); - assert!(w[4] == 25u); + assert_eq!(w.len(), 5u); + assert_eq!(w[0], 1u); + assert_eq!(w[1], 4u); + assert_eq!(w[2], 9u); + assert_eq!(w[3], 16u); + assert_eq!(w[4], 25u); } #[test] @@ -3561,17 +3561,17 @@ mod tests { // Test on-stack filter-map. let mut v = ~[1u, 2u, 3u]; let mut w = filter_mapped(v, square_if_odd_r); - assert!(w.len() == 2u); - assert!(w[0] == 1u); - assert!(w[1] == 9u); + assert_eq!(w.len(), 2u); + assert_eq!(w[0], 1u); + assert_eq!(w[1], 9u); // Test on-heap filter-map. v = ~[1u, 2u, 3u, 4u, 5u]; w = filter_mapped(v, square_if_odd_r); - assert!(w.len() == 3u); - assert!(w[0] == 1u); - assert!(w[1] == 9u); - assert!(w[2] == 25u); + assert_eq!(w.len(), 3u); + assert_eq!(w[0], 1u); + assert_eq!(w[1], 9u); + assert_eq!(w[2], 25u); fn halve(i: &int) -> Option { if *i % 2 == 0 { @@ -3588,9 +3588,9 @@ mod tests { let mix_dest: ~[int] = ~[1, 3, 0, 0]; assert!(filter_mapped(all_even, halve) == map(all_even, halve_for_sure)); - assert!(filter_mapped(all_odd1, halve) == ~[]); - assert!(filter_mapped(all_odd2, halve) == ~[]); - assert!(filter_mapped(mix, halve) == mix_dest); + assert_eq!(filter_mapped(all_odd1, halve), ~[]); + assert_eq!(filter_mapped(all_odd2, halve), ~[]); + assert_eq!(filter_mapped(mix, halve), mix_dest); } #[test] @@ -3598,17 +3598,17 @@ mod tests { // Test on-stack filter-map. let mut v = ~[1u, 2u, 3u]; let mut w = filter_map(v, square_if_odd_v); - assert!(w.len() == 2u); - assert!(w[0] == 1u); - assert!(w[1] == 9u); + assert_eq!(w.len(), 2u); + assert_eq!(w[0], 1u); + assert_eq!(w[1], 9u); // Test on-heap filter-map. v = ~[1u, 2u, 3u, 4u, 5u]; w = filter_map(v, square_if_odd_v); - assert!(w.len() == 3u); - assert!(w[0] == 1u); - assert!(w[1] == 9u); - assert!(w[2] == 25u); + assert_eq!(w.len(), 3u); + assert_eq!(w[0], 1u); + assert_eq!(w[1], 9u); + assert_eq!(w[2], 25u); fn halve(i: int) -> Option { if i % 2 == 0 { @@ -3626,22 +3626,22 @@ mod tests { let mix_dest: ~[int] = ~[1, 3, 0, 0]; assert!(filter_map(all_even, halve) == map(all_even0, halve_for_sure)); - assert!(filter_map(all_odd1, halve) == ~[]); - assert!(filter_map(all_odd2, halve) == ~[]); - assert!(filter_map(mix, halve) == mix_dest); + assert_eq!(filter_map(all_odd1, halve), ~[]); + assert_eq!(filter_map(all_odd2, halve), ~[]); + assert_eq!(filter_map(mix, halve), mix_dest); } #[test] fn test_filter() { - assert!(filter(~[1u, 2u, 3u], is_odd) == ~[1u, 3u]); - assert!(filter(~[1u, 2u, 4u, 8u, 16u], is_three) == ~[]); + assert_eq!(filter(~[1u, 2u, 3u], is_odd), ~[1u, 3u]); + assert_eq!(filter(~[1u, 2u, 4u, 8u, 16u], is_three), ~[]); } #[test] fn test_retain() { let mut v = ~[1, 2, 3, 4, 5]; v.retain(is_odd); - assert!(v == ~[1, 3, 5]); + assert_eq!(v, ~[1, 3, 5]); } #[test] @@ -3649,12 +3649,12 @@ mod tests { // Test on-stack fold. let mut v = ~[1u, 2u, 3u]; let mut sum = foldl(0u, v, add); - assert!(sum == 6u); + assert_eq!(sum, 6u); // Test on-heap fold. v = ~[1u, 2u, 3u, 4u, 5u]; sum = foldl(0u, v, add); - assert!(sum == 15u); + assert_eq!(sum, 15u); } #[test] @@ -3664,7 +3664,7 @@ mod tests { } let v = ~[1, 2, 3, 4]; let sum = foldl(0, v, sub); - assert!(sum == -10); + assert_eq!(sum, -10); } #[test] @@ -3674,7 +3674,7 @@ mod tests { } let v = ~[1, 2, 3, 4]; let sum = foldr(v, 0, sub); - assert!(sum == -2); + assert_eq!(sum, -2); } #[test] @@ -3690,7 +3690,7 @@ mod tests { for each(~[1, 2, 3]) |v| { i += *v; } - assert!(i == 6); + assert_eq!(i, 6); } #[test] @@ -3698,10 +3698,10 @@ mod tests { let mut i = 0; for eachi(~[1, 2, 3]) |j, v| { if i == 0 { assert!(*v == 1); } - assert!(j + 1u == *v as uint); + assert_eq!(j + 1u, *v as uint); i += *v; } - assert!(i == 6); + assert_eq!(i, 6); } #[test] @@ -3719,7 +3719,7 @@ mod tests { if i == 0 { assert!(*v == 3); } i += *v } - assert!(i == 6); + assert_eq!(i, 6); } #[test] @@ -3727,10 +3727,10 @@ mod tests { let mut i = 0; for eachi_reverse(~[0, 1, 2]) |j, v| { if i == 0 { assert!(*v == 2); } - assert!(j == *v as uint); + assert_eq!(j, *v as uint); i += *v; } - assert!(i == 3); + assert_eq!(i, 3); } #[test] @@ -3747,15 +3747,15 @@ mod tests { results = ~[]; for each_permutation(~[]) |v| { results.push(to_owned(v)); } - assert!(results == ~[~[]]); + assert_eq!(results, ~[~[]]); results = ~[]; for each_permutation(~[7]) |v| { results.push(to_owned(v)); } - assert!(results == ~[~[7]]); + assert_eq!(results, ~[~[7]]); results = ~[]; for each_permutation(~[1,1]) |v| { results.push(to_owned(v)); } - assert!(results == ~[~[1,1],~[1,1]]); + assert_eq!(results, ~[~[1,1],~[1,1]]); results = ~[]; for each_permutation(~[5,2,0]) |v| { results.push(to_owned(v)); } @@ -3797,15 +3797,15 @@ mod tests { let z1 = zip(v1, v2); - assert!((1, 4) == z1[0]); - assert!((2, 5) == z1[1]); - assert!((3, 6) == z1[2]); + assert_eq!((1, 4), z1[0]); + assert_eq!((2, 5), z1[1]); + assert_eq!((3, 6), z1[2]); let (left, right) = unzip(z1); - assert!((1, 4) == (left[0], right[0])); - assert!((2, 5) == (left[1], right[1])); - assert!((3, 6) == (left[2], right[2])); + assert_eq!((1, 4), (left[0], right[0])); + assert_eq!((2, 5), (left[1], right[1])); + assert_eq!((3, 6), (left[2], right[2])); } #[test] @@ -3813,9 +3813,9 @@ mod tests { assert!(position_elem(~[], &1).is_none()); let v1 = ~[1, 2, 3, 3, 2, 5]; - assert!(position_elem(v1, &1) == Some(0u)); - assert!(position_elem(v1, &2) == Some(1u)); - assert!(position_elem(v1, &5) == Some(5u)); + assert_eq!(position_elem(v1, &1), Some(0u)); + assert_eq!(position_elem(v1, &2), Some(1u)); + assert_eq!(position_elem(v1, &5), Some(5u)); assert!(position_elem(v1, &4).is_none()); } @@ -3827,7 +3827,7 @@ mod tests { assert!(position(~[], less_than_three).is_none()); let v1 = ~[5, 4, 3, 2, 1]; - assert!(position(v1, less_than_three) == Some(3u)); + assert_eq!(position(v1, less_than_three), Some(3u)); assert!(position(v1, is_eighteen).is_none()); } @@ -3840,21 +3840,21 @@ mod tests { assert!(position_between(v, 0u, 0u, f).is_none()); assert!(position_between(v, 0u, 1u, f).is_none()); - assert!(position_between(v, 0u, 2u, f) == Some(1u)); - assert!(position_between(v, 0u, 3u, f) == Some(1u)); - assert!(position_between(v, 0u, 4u, f) == Some(1u)); + assert_eq!(position_between(v, 0u, 2u, f), Some(1u)); + assert_eq!(position_between(v, 0u, 3u, f), Some(1u)); + assert_eq!(position_between(v, 0u, 4u, f), Some(1u)); assert!(position_between(v, 1u, 1u, f).is_none()); - assert!(position_between(v, 1u, 2u, f) == Some(1u)); - assert!(position_between(v, 1u, 3u, f) == Some(1u)); - assert!(position_between(v, 1u, 4u, f) == Some(1u)); + assert_eq!(position_between(v, 1u, 2u, f), Some(1u)); + assert_eq!(position_between(v, 1u, 3u, f), Some(1u)); + assert_eq!(position_between(v, 1u, 4u, f), Some(1u)); assert!(position_between(v, 2u, 2u, f).is_none()); assert!(position_between(v, 2u, 3u, f).is_none()); - assert!(position_between(v, 2u, 4u, f) == Some(3u)); + assert_eq!(position_between(v, 2u, 4u, f), Some(3u)); assert!(position_between(v, 3u, 3u, f).is_none()); - assert!(position_between(v, 3u, 4u, f) == Some(3u)); + assert_eq!(position_between(v, 3u, 4u, f), Some(3u)); assert!(position_between(v, 4u, 4u, f).is_none()); } @@ -3867,7 +3867,7 @@ mod tests { fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; - assert!(find(v, f) == Some((1, 'b'))); + assert_eq!(find(v, f), Some((1, 'b'))); assert!(find(v, g).is_none()); } @@ -3880,21 +3880,21 @@ mod tests { assert!(find_between(v, 0u, 0u, f).is_none()); assert!(find_between(v, 0u, 1u, f).is_none()); - assert!(find_between(v, 0u, 2u, f) == Some((1, 'b'))); - assert!(find_between(v, 0u, 3u, f) == Some((1, 'b'))); - assert!(find_between(v, 0u, 4u, f) == Some((1, 'b'))); + assert_eq!(find_between(v, 0u, 2u, f), Some((1, 'b'))); + assert_eq!(find_between(v, 0u, 3u, f), Some((1, 'b'))); + assert_eq!(find_between(v, 0u, 4u, f), Some((1, 'b'))); assert!(find_between(v, 1u, 1u, f).is_none()); - assert!(find_between(v, 1u, 2u, f) == Some((1, 'b'))); - assert!(find_between(v, 1u, 3u, f) == Some((1, 'b'))); - assert!(find_between(v, 1u, 4u, f) == Some((1, 'b'))); + assert_eq!(find_between(v, 1u, 2u, f), Some((1, 'b'))); + assert_eq!(find_between(v, 1u, 3u, f), Some((1, 'b'))); + assert_eq!(find_between(v, 1u, 4u, f), Some((1, 'b'))); assert!(find_between(v, 2u, 2u, f).is_none()); assert!(find_between(v, 2u, 3u, f).is_none()); - assert!(find_between(v, 2u, 4u, f) == Some((3, 'b'))); + assert_eq!(find_between(v, 2u, 4u, f), Some((3, 'b'))); assert!(find_between(v, 3u, 3u, f).is_none()); - assert!(find_between(v, 3u, 4u, f) == Some((3, 'b'))); + assert_eq!(find_between(v, 3u, 4u, f), Some((3, 'b'))); assert!(find_between(v, 4u, 4u, f).is_none()); } @@ -3907,7 +3907,7 @@ mod tests { fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; - assert!(position(v, f) == Some(1u)); + assert_eq!(position(v, f), Some(1u)); assert!(position(v, g).is_none()); } @@ -3920,21 +3920,21 @@ mod tests { assert!(rposition_between(v, 0u, 0u, f).is_none()); assert!(rposition_between(v, 0u, 1u, f).is_none()); - assert!(rposition_between(v, 0u, 2u, f) == Some(1u)); - assert!(rposition_between(v, 0u, 3u, f) == Some(1u)); - assert!(rposition_between(v, 0u, 4u, f) == Some(3u)); + assert_eq!(rposition_between(v, 0u, 2u, f), Some(1u)); + assert_eq!(rposition_between(v, 0u, 3u, f), Some(1u)); + assert_eq!(rposition_between(v, 0u, 4u, f), Some(3u)); assert!(rposition_between(v, 1u, 1u, f).is_none()); - assert!(rposition_between(v, 1u, 2u, f) == Some(1u)); - assert!(rposition_between(v, 1u, 3u, f) == Some(1u)); - assert!(rposition_between(v, 1u, 4u, f) == Some(3u)); + assert_eq!(rposition_between(v, 1u, 2u, f), Some(1u)); + assert_eq!(rposition_between(v, 1u, 3u, f), Some(1u)); + assert_eq!(rposition_between(v, 1u, 4u, f), Some(3u)); assert!(rposition_between(v, 2u, 2u, f).is_none()); assert!(rposition_between(v, 2u, 3u, f).is_none()); - assert!(rposition_between(v, 2u, 4u, f) == Some(3u)); + assert_eq!(rposition_between(v, 2u, 4u, f), Some(3u)); assert!(rposition_between(v, 3u, 3u, f).is_none()); - assert!(rposition_between(v, 3u, 4u, f) == Some(3u)); + assert_eq!(rposition_between(v, 3u, 4u, f), Some(3u)); assert!(rposition_between(v, 4u, 4u, f).is_none()); } @@ -3947,7 +3947,7 @@ mod tests { fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; - assert!(rfind(v, f) == Some((3, 'b'))); + assert_eq!(rfind(v, f), Some((3, 'b'))); assert!(rfind(v, g).is_none()); } @@ -3960,87 +3960,87 @@ mod tests { assert!(rfind_between(v, 0u, 0u, f).is_none()); assert!(rfind_between(v, 0u, 1u, f).is_none()); - assert!(rfind_between(v, 0u, 2u, f) == Some((1, 'b'))); - assert!(rfind_between(v, 0u, 3u, f) == Some((1, 'b'))); - assert!(rfind_between(v, 0u, 4u, f) == Some((3, 'b'))); + assert_eq!(rfind_between(v, 0u, 2u, f), Some((1, 'b'))); + assert_eq!(rfind_between(v, 0u, 3u, f), Some((1, 'b'))); + assert_eq!(rfind_between(v, 0u, 4u, f), Some((3, 'b'))); assert!(rfind_between(v, 1u, 1u, f).is_none()); - assert!(rfind_between(v, 1u, 2u, f) == Some((1, 'b'))); - assert!(rfind_between(v, 1u, 3u, f) == Some((1, 'b'))); - assert!(rfind_between(v, 1u, 4u, f) == Some((3, 'b'))); + assert_eq!(rfind_between(v, 1u, 2u, f), Some((1, 'b'))); + assert_eq!(rfind_between(v, 1u, 3u, f), Some((1, 'b'))); + assert_eq!(rfind_between(v, 1u, 4u, f), Some((3, 'b'))); assert!(rfind_between(v, 2u, 2u, f).is_none()); assert!(rfind_between(v, 2u, 3u, f).is_none()); - assert!(rfind_between(v, 2u, 4u, f) == Some((3, 'b'))); + assert_eq!(rfind_between(v, 2u, 4u, f), Some((3, 'b'))); assert!(rfind_between(v, 3u, 3u, f).is_none()); - assert!(rfind_between(v, 3u, 4u, f) == Some((3, 'b'))); + assert_eq!(rfind_between(v, 3u, 4u, f), Some((3, 'b'))); assert!(rfind_between(v, 4u, 4u, f).is_none()); } #[test] fn test_bsearch_elem() { - assert!(bsearch_elem([1,2,3,4,5], &5) == Some(4)); - assert!(bsearch_elem([1,2,3,4,5], &4) == Some(3)); - assert!(bsearch_elem([1,2,3,4,5], &3) == Some(2)); - assert!(bsearch_elem([1,2,3,4,5], &2) == Some(1)); - assert!(bsearch_elem([1,2,3,4,5], &1) == Some(0)); - - assert!(bsearch_elem([2,4,6,8,10], &1) == None); - assert!(bsearch_elem([2,4,6,8,10], &5) == None); - assert!(bsearch_elem([2,4,6,8,10], &4) == Some(1)); - assert!(bsearch_elem([2,4,6,8,10], &10) == Some(4)); - - assert!(bsearch_elem([2,4,6,8], &1) == None); - assert!(bsearch_elem([2,4,6,8], &5) == None); - assert!(bsearch_elem([2,4,6,8], &4) == Some(1)); - assert!(bsearch_elem([2,4,6,8], &8) == Some(3)); - - assert!(bsearch_elem([2,4,6], &1) == None); - assert!(bsearch_elem([2,4,6], &5) == None); - assert!(bsearch_elem([2,4,6], &4) == Some(1)); - assert!(bsearch_elem([2,4,6], &6) == Some(2)); - - assert!(bsearch_elem([2,4], &1) == None); - assert!(bsearch_elem([2,4], &5) == None); - assert!(bsearch_elem([2,4], &2) == Some(0)); - assert!(bsearch_elem([2,4], &4) == Some(1)); - - assert!(bsearch_elem([2], &1) == None); - assert!(bsearch_elem([2], &5) == None); - assert!(bsearch_elem([2], &2) == Some(0)); - - assert!(bsearch_elem([], &1) == None); - assert!(bsearch_elem([], &5) == None); + assert_eq!(bsearch_elem([1,2,3,4,5], &5), Some(4)); + assert_eq!(bsearch_elem([1,2,3,4,5], &4), Some(3)); + assert_eq!(bsearch_elem([1,2,3,4,5], &3), Some(2)); + assert_eq!(bsearch_elem([1,2,3,4,5], &2), Some(1)); + assert_eq!(bsearch_elem([1,2,3,4,5], &1), Some(0)); + + assert_eq!(bsearch_elem([2,4,6,8,10], &1), None); + assert_eq!(bsearch_elem([2,4,6,8,10], &5), None); + assert_eq!(bsearch_elem([2,4,6,8,10], &4), Some(1)); + assert_eq!(bsearch_elem([2,4,6,8,10], &10), Some(4)); + + assert_eq!(bsearch_elem([2,4,6,8], &1), None); + assert_eq!(bsearch_elem([2,4,6,8], &5), None); + assert_eq!(bsearch_elem([2,4,6,8], &4), Some(1)); + assert_eq!(bsearch_elem([2,4,6,8], &8), Some(3)); + + assert_eq!(bsearch_elem([2,4,6], &1), None); + assert_eq!(bsearch_elem([2,4,6], &5), None); + assert_eq!(bsearch_elem([2,4,6], &4), Some(1)); + assert_eq!(bsearch_elem([2,4,6], &6), Some(2)); + + assert_eq!(bsearch_elem([2,4], &1), None); + assert_eq!(bsearch_elem([2,4], &5), None); + assert_eq!(bsearch_elem([2,4], &2), Some(0)); + assert_eq!(bsearch_elem([2,4], &4), Some(1)); + + assert_eq!(bsearch_elem([2], &1), None); + assert_eq!(bsearch_elem([2], &5), None); + assert_eq!(bsearch_elem([2], &2), Some(0)); + + assert_eq!(bsearch_elem([], &1), None); + assert_eq!(bsearch_elem([], &5), None); assert!(bsearch_elem([1,1,1,1,1], &1) != None); assert!(bsearch_elem([1,1,1,1,2], &1) != None); assert!(bsearch_elem([1,1,1,2,2], &1) != None); assert!(bsearch_elem([1,1,2,2,2], &1) != None); - assert!(bsearch_elem([1,2,2,2,2], &1) == Some(0)); + assert_eq!(bsearch_elem([1,2,2,2,2], &1), Some(0)); - assert!(bsearch_elem([1,2,3,4,5], &6) == None); - assert!(bsearch_elem([1,2,3,4,5], &0) == None); + assert_eq!(bsearch_elem([1,2,3,4,5], &6), None); + assert_eq!(bsearch_elem([1,2,3,4,5], &0), None); } #[test] fn reverse_and_reversed() { let mut v: ~[int] = ~[10, 20]; - assert!(v[0] == 10); - assert!(v[1] == 20); + assert_eq!(v[0], 10); + assert_eq!(v[1], 20); reverse(v); - assert!(v[0] == 20); - assert!(v[1] == 10); + assert_eq!(v[0], 20); + assert_eq!(v[1], 10); let v2 = reversed::(~[10, 20]); - assert!(v2[0] == 20); - assert!(v2[1] == 10); + assert_eq!(v2[0], 20); + assert_eq!(v2[1], 10); v[0] = 30; - assert!(v2[0] == 20); + assert_eq!(v2[0], 20); // Make sure they work with 0-length vectors too. let v4 = reversed::(~[]); - assert!(v4 == ~[]); + assert_eq!(v4, ~[]); let mut v3: ~[int] = ~[]; reverse::(v3); } @@ -4048,29 +4048,29 @@ mod tests { #[test] fn reversed_mut() { let v2 = reversed::(~[10, 20]); - assert!(v2[0] == 20); - assert!(v2[1] == 10); + assert_eq!(v2[0], 20); + assert_eq!(v2[1], 10); } #[test] fn test_split() { fn f(x: &int) -> bool { *x == 3 } - assert!(split(~[], f) == ~[]); - assert!(split(~[1, 2], f) == ~[~[1, 2]]); - assert!(split(~[3, 1, 2], f) == ~[~[], ~[1, 2]]); - assert!(split(~[1, 2, 3], f) == ~[~[1, 2], ~[]]); - assert!(split(~[1, 2, 3, 4, 3, 5], f) == ~[~[1, 2], ~[4], ~[5]]); + assert_eq!(split(~[], f), ~[]); + assert_eq!(split(~[1, 2], f), ~[~[1, 2]]); + assert_eq!(split(~[3, 1, 2], f), ~[~[], ~[1, 2]]); + assert_eq!(split(~[1, 2, 3], f), ~[~[1, 2], ~[]]); + assert_eq!(split(~[1, 2, 3, 4, 3, 5], f), ~[~[1, 2], ~[4], ~[5]]); } #[test] fn test_splitn() { fn f(x: &int) -> bool { *x == 3 } - assert!(splitn(~[], 1u, f) == ~[]); - assert!(splitn(~[1, 2], 1u, f) == ~[~[1, 2]]); - assert!(splitn(~[3, 1, 2], 1u, f) == ~[~[], ~[1, 2]]); - assert!(splitn(~[1, 2, 3], 1u, f) == ~[~[1, 2], ~[]]); + assert_eq!(splitn(~[], 1u, f), ~[]); + assert_eq!(splitn(~[1, 2], 1u, f), ~[~[1, 2]]); + assert_eq!(splitn(~[3, 1, 2], 1u, f), ~[~[], ~[1, 2]]); + assert_eq!(splitn(~[1, 2, 3], 1u, f), ~[~[1, 2], ~[]]); assert!(splitn(~[1, 2, 3, 4, 3, 5], 1u, f) == ~[~[1, 2], ~[4, 3, 5]]); } @@ -4079,9 +4079,9 @@ mod tests { fn test_rsplit() { fn f(x: &int) -> bool { *x == 3 } - assert!(rsplit(~[], f) == ~[]); - assert!(rsplit(~[1, 2], f) == ~[~[1, 2]]); - assert!(rsplit(~[1, 2, 3], f) == ~[~[1, 2], ~[]]); + assert_eq!(rsplit(~[], f), ~[]); + assert_eq!(rsplit(~[1, 2], f), ~[~[1, 2]]); + assert_eq!(rsplit(~[1, 2, 3], f), ~[~[1, 2], ~[]]); assert!(rsplit(~[1, 2, 3, 4, 3, 5], f) == ~[~[1, 2], ~[4], ~[5]]); } @@ -4090,9 +4090,9 @@ mod tests { fn test_rsplitn() { fn f(x: &int) -> bool { *x == 3 } - assert!(rsplitn(~[], 1u, f) == ~[]); - assert!(rsplitn(~[1, 2], 1u, f) == ~[~[1, 2]]); - assert!(rsplitn(~[1, 2, 3], 1u, f) == ~[~[1, 2], ~[]]); + assert_eq!(rsplitn(~[], 1u, f), ~[]); + assert_eq!(rsplitn(~[1, 2], 1u, f), ~[~[1, 2]]); + assert_eq!(rsplitn(~[1, 2, 3], 1u, f), ~[~[1, 2], ~[]]); assert!(rsplitn(~[1, 2, 3, 4, 3, 5], 1u, f) == ~[~[1, 2, 3, 4], ~[5]]); } @@ -4100,7 +4100,7 @@ mod tests { #[test] fn test_partition() { // FIXME (#4355 maybe): using v.partition here crashes - assert!(partition(~[], |x: &int| *x < 3) == (~[], ~[])); + assert_eq!(partition(~[], |x: &int| *x < 3), (~[], ~[])); assert!(partition(~[1, 2, 3], |x: &int| *x < 4) == (~[1, 2, 3], ~[])); assert!(partition(~[1, 2, 3], |x: &int| *x < 2) == @@ -4111,7 +4111,7 @@ mod tests { #[test] fn test_partitioned() { - assert!((~[]).partitioned(|x: &int| *x < 3) == (~[], ~[])); + assert_eq!((~[]).partitioned(|x: &int| *x < 3), (~[], ~[])) assert!((~[1, 2, 3]).partitioned(|x: &int| *x < 4) == (~[1, 2, 3], ~[])); assert!((~[1, 2, 3]).partitioned(|x: &int| *x < 2) == @@ -4122,14 +4122,14 @@ mod tests { #[test] fn test_concat() { - assert!(concat(~[~[1], ~[2,3]]) == ~[1, 2, 3]); + assert_eq!(concat(~[~[1], ~[2,3]]), ~[1, 2, 3]); } #[test] fn test_connect() { - assert!(connect(~[], &0) == ~[]); - assert!(connect(~[~[1], ~[2, 3]], &0) == ~[1, 0, 2, 3]); - assert!(connect(~[~[1], ~[2], ~[3]], &0) == ~[1, 0, 2, 0, 3]); + assert_eq!(connect(~[], &0), ~[]); + assert_eq!(connect(~[~[1], ~[2, 3]], &0), ~[1, 0, 2, 3]); + assert_eq!(connect(~[~[1], ~[2], ~[3]], &0), ~[1, 0, 2, 0, 3]); } #[test] @@ -4161,26 +4161,26 @@ mod tests { fn test_unshift() { let mut x = ~[1, 2, 3]; x.unshift(0); - assert!(x == ~[0, 1, 2, 3]); + assert_eq!(x, ~[0, 1, 2, 3]); } #[test] fn test_insert() { let mut a = ~[1, 2, 4]; a.insert(2, 3); - assert!(a == ~[1, 2, 3, 4]); + assert_eq!(a, ~[1, 2, 3, 4]); let mut a = ~[1, 2, 3]; a.insert(0, 0); - assert!(a == ~[0, 1, 2, 3]); + assert_eq!(a, ~[0, 1, 2, 3]); let mut a = ~[1, 2, 3]; a.insert(3, 4); - assert!(a == ~[1, 2, 3, 4]); + assert_eq!(a, ~[1, 2, 3, 4]); let mut a = ~[]; a.insert(0, 1); - assert!(a == ~[1]); + assert_eq!(a, ~[1]); } #[test] @@ -4195,15 +4195,15 @@ mod tests { fn test_remove() { let mut a = ~[1, 2, 3, 4]; a.remove(2); - assert!(a == ~[1, 2, 4]); + assert_eq!(a, ~[1, 2, 4]); let mut a = ~[1, 2, 3]; a.remove(0); - assert!(a == ~[2, 3]); + assert_eq!(a, ~[2, 3]); let mut a = ~[1]; a.remove(0); - assert!(a == ~[]); + assert_eq!(a, ~[]); } #[test] @@ -4218,19 +4218,19 @@ mod tests { fn test_capacity() { let mut v = ~[0u64]; reserve(&mut v, 10u); - assert!(capacity(&v) == 10u); + assert_eq!(capacity(&v), 10u); let mut v = ~[0u32]; reserve(&mut v, 10u); - assert!(capacity(&v) == 10u); + assert_eq!(capacity(&v), 10u); } #[test] fn test_slice_2() { let v = ~[1, 2, 3, 4, 5]; let v = v.slice(1u, 3u); - assert!(v.len() == 2u); - assert!(v[0] == 2); - assert!(v[1] == 3); + assert_eq!(v.len(), 2u); + assert_eq!(v[0], 2); + assert_eq!(v[1], 3); } @@ -4844,6 +4844,6 @@ mod tests { for [1, 2, 3].each_val |v| { i += v; } - assert!(i == 6); + assert_eq!(i, 6); } } diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 37a025cd8205b..4b3ed4c70f596 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -209,7 +209,7 @@ mod test { fn test_rpaths_to_flags() { let flags = rpaths_to_flags(~[Path("path1"), Path("path2")]); - assert!(flags == ~[~"-Wl,-rpath,path1", ~"-Wl,-rpath,path2"]); + assert_eq!(flags, ~[~"-Wl,-rpath,path1", ~"-Wl,-rpath,path2"]); } #[test] @@ -234,7 +234,7 @@ mod test { let res = minimize_rpaths([Path("rpath1"), Path("rpath2"), Path("rpath1")]); - assert!(res == ~[Path("rpath1"), Path("rpath2")]); + assert_eq!(res, ~[Path("rpath1"), Path("rpath2")]); } #[test] @@ -243,7 +243,7 @@ mod test { Path("1a"), Path("4a"),Path("1a"), Path("2"), Path("3"), Path("4a"), Path("3")]); - assert!(res == ~[Path("1a"), Path("2"), Path("4a"), Path("3")]); + assert_eq!(res, ~[Path("1a"), Path("2"), Path("4a"), Path("3")]); } #[test] @@ -251,7 +251,7 @@ mod test { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/lib/mylib"); let res = get_relative_to(&p1, &p2); - assert!(res == Path("../lib")); + assert_eq!(res, Path("../lib")); } #[test] @@ -259,7 +259,7 @@ mod test { let p1 = Path("/usr/bin/rustc"); let p2 = Path("/usr/bin/../lib/mylib"); let res = get_relative_to(&p1, &p2); - assert!(res == Path("../lib")); + assert_eq!(res, Path("../lib")); } #[test] @@ -267,7 +267,7 @@ mod test { let p1 = Path("/usr/bin/whatever/rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); - assert!(res == Path("../../lib/whatever")); + assert_eq!(res, Path("../../lib/whatever")); } #[test] @@ -275,7 +275,7 @@ mod test { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/mylib"); let res = get_relative_to(&p1, &p2); - assert!(res == Path("../lib/whatever")); + assert_eq!(res, Path("../lib/whatever")); } #[test] @@ -283,7 +283,7 @@ mod test { let p1 = Path("/usr/bin/whatever/../rustc"); let p2 = Path("/usr/lib/whatever/../mylib"); let res = get_relative_to(&p1, &p2); - assert!(res == Path("../lib")); + assert_eq!(res, Path("../lib")); } #[test] @@ -291,7 +291,7 @@ mod test { let p1 = Path("/1"); let p2 = Path("/2/3"); let res = get_relative_to(&p1, &p2); - assert!(res == Path("2")); + assert_eq!(res, Path("2")); } #[test] @@ -299,7 +299,7 @@ mod test { let p1 = Path("/1/2"); let p2 = Path("/3"); let res = get_relative_to(&p1, &p2); - assert!(res == Path("..")); + assert_eq!(res, Path("..")); } #[test] @@ -312,7 +312,7 @@ mod test { debug!("test_relative_tu8: %s vs. %s", res.to_str(), Path(".").to_str()); - assert!(res == Path(".")); + assert_eq!(res, Path(".")); } #[test] @@ -322,7 +322,7 @@ mod test { let o = session::os_linux; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); - assert!(res.to_str() == ~"$ORIGIN/../lib"); + assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] @@ -331,7 +331,7 @@ mod test { let o = session::os_freebsd; let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); - assert!(res.to_str() == ~"$ORIGIN/../lib"); + assert_eq!(res.to_str(), ~"$ORIGIN/../lib"); } #[test] @@ -342,7 +342,7 @@ mod test { let res = get_rpath_relative_to_output(o, &Path("bin/rustc"), &Path("lib/libstd.so")); - assert!(res.to_str() == ~"@executable_path/../lib"); + assert_eq!(res.to_str(), ~"@executable_path/../lib"); } #[test] @@ -352,6 +352,6 @@ mod test { res.to_str(), os::make_absolute(&Path("lib")).to_str()); - assert!(res == os::make_absolute(&Path("lib"))); + assert_eq!(res, os::make_absolute(&Path("lib"))); } } diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 99ffa8cc94aa3..572397b7f8af2 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -938,6 +938,6 @@ mod test { let sess = build_session(sessopts, diagnostic::emit); let cfg = build_configuration(sess, @~"whatever", &str_input(~"")); let test_items = attr::find_meta_items_by_name(cfg, ~"test"); - assert!(test_items.len() == 1u); + assert_eq!(test_items.len(), 1u); } } diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 43073728e8351..8779cab87f62f 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -1064,7 +1064,7 @@ fn get_attributes(md: ebml::Doc) -> ~[ast::attribute] { let meta_items = get_meta_items(attr_doc); // Currently it's only possible to have a single meta item on // an attribute - assert!(meta_items.len() == 1u); + assert_eq!(meta_items.len(), 1u); let meta_item = meta_items[0]; attrs.push( codemap::spanned { diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index d27bfd081bc65..8c21998768e95 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -946,7 +946,7 @@ fn encode_info_for_item(ecx: @EncodeContext, // Now output the method info for each method. for ty::trait_method_def_ids(tcx, local_def(item.id)).eachi |i, &method_def_id| { - assert!(method_def_id.crate == ast::local_crate); + assert_eq!(method_def_id.crate, ast::local_crate); let method_ty = ty::method(tcx, method_def_id); @@ -1278,7 +1278,7 @@ fn encode_crate_deps(ecx: @EncodeContext, // Sanity-check the crate numbers let mut expected_cnum = 1; for deps.each |n| { - assert!((n.cnum == expected_cnum)); + assert_eq!(n.cnum, expected_cnum); expected_cnum += 1; } diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index 55a0755f5e3f9..ad5bd2447a6f0 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -156,12 +156,12 @@ fn parse_sigil(st: @mut PState) -> ast::Sigil { } fn parse_vstore(st: @mut PState) -> ty::vstore { - assert!(next(st) == '/'); + assert_eq!(next(st), '/'); let c = peek(st); if '0' <= c && c <= '9' { let n = parse_uint(st); - assert!(next(st) == '|'); + assert_eq!(next(st), '|'); return ty::vstore_fixed(n); } @@ -187,7 +187,7 @@ fn parse_substs(st: @mut PState, conv: conv_did) -> ty::substs { let self_ty = parse_opt(st, || parse_ty(st, conv) ); - assert!(next(st) == '['); + assert_eq!(next(st), '['); let mut params: ~[ty::t] = ~[]; while peek(st) != ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; @@ -204,13 +204,13 @@ fn parse_bound_region(st: @mut PState) -> ty::bound_region { 's' => ty::br_self, 'a' => { let id = parse_uint(st); - assert!(next(st) == '|'); + assert_eq!(next(st), '|'); ty::br_anon(id) } '[' => ty::br_named(st.tcx.sess.ident_of(parse_str(st, ']'))), 'c' => { let id = parse_uint(st) as int; - assert!(next(st) == '|'); + assert_eq!(next(st), '|'); ty::br_cap_avoid(id, @parse_bound_region(st)) }, _ => fail!("parse_bound_region: bad input") @@ -223,17 +223,17 @@ fn parse_region(st: @mut PState) -> ty::Region { ty::re_bound(parse_bound_region(st)) } 'f' => { - assert!(next(st) == '['); + assert_eq!(next(st), '['); let id = parse_uint(st) as int; - assert!(next(st) == '|'); + assert_eq!(next(st), '|'); let br = parse_bound_region(st); - assert!(next(st) == ']'); + assert_eq!(next(st), ']'); ty::re_free(ty::FreeRegion {scope_id: id, bound_region: br}) } 's' => { let id = parse_uint(st) as int; - assert!(next(st) == '|'); + assert_eq!(next(st), '|'); ty::re_scope(id) } 't' => { @@ -294,19 +294,19 @@ fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t { } 'c' => return ty::mk_char(), 't' => { - assert!((next(st) == '[')); + assert_eq!(next(st), '['); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); - assert!(next(st) == ']'); + assert_eq!(next(st), ']'); return ty::mk_enum(st.tcx, def, substs); } 'x' => { - assert!(next(st) == '['); + assert_eq!(next(st), '['); let def = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); let store = parse_trait_store(st); let mt = parse_mutability(st); - assert!(next(st) == ']'); + assert_eq!(next(st), ']'); return ty::mk_trait(st.tcx, def, substs, store, mt); } 'p' => { @@ -337,7 +337,7 @@ fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t { return ty::mk_estr(st.tcx, v); } 'T' => { - assert!((next(st) == '[')); + assert_eq!(next(st), '['); let mut params = ~[]; while peek(st) != ']' { params.push(parse_ty(st, conv)); } st.pos = st.pos + 1u; @@ -356,9 +356,9 @@ fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t { } '#' => { let pos = parse_hex(st); - assert!((next(st) == ':')); + assert_eq!(next(st), ':'); let len = parse_hex(st); - assert!((next(st) == '#')); + assert_eq!(next(st), '#'); let key = ty::creader_cache_key {cnum: st.crate, pos: pos, len: len }; @@ -379,10 +379,10 @@ fn parse_ty(st: @mut PState, conv: conv_did) -> ty::t { } 'B' => ty::mk_opaque_box(st.tcx), 'a' => { - assert!((next(st) == '[')); + assert_eq!(next(st), '['); let did = parse_def(st, NominalType, conv); let substs = parse_substs(st, conv); - assert!((next(st) == ']')); + assert_eq!(next(st), ']'); return ty::mk_struct(st.tcx, did, substs); } c => { error!("unexpected char in type string: %c", c); fail!();} @@ -445,7 +445,7 @@ fn parse_purity(c: char) -> purity { } fn parse_abi_set(st: @mut PState) -> AbiSet { - assert!(next(st) == '['); + assert_eq!(next(st), '['); let mut abis = AbiSet::empty(); while peek(st) != ']' { // FIXME(#5422) str API should not force this copy @@ -453,7 +453,7 @@ fn parse_abi_set(st: @mut PState) -> AbiSet { let abi = abi::lookup(abi_str).expect(abi_str); abis.add(abi); } - assert!(next(st) == ']'); + assert_eq!(next(st), ']'); return abis; } @@ -494,7 +494,7 @@ fn parse_bare_fn_ty(st: @mut PState, conv: conv_did) -> ty::BareFnTy { } fn parse_sig(st: @mut PState, conv: conv_did) -> ty::FnSig { - assert!((next(st) == '[')); + assert_eq!(next(st), '['); let mut inputs = ~[]; while peek(st) != ']' { inputs.push(parse_ty(st, conv)); diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 209a14942e9a7..0235ab47967d7 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -206,7 +206,7 @@ pub impl ExtendedDecodeContext { * refer to the current crate and to the new, inlined node-id. */ - assert!(did.crate == ast::local_crate); + assert_eq!(did.crate, ast::local_crate); ast::def_id { crate: ast::local_crate, node: self.tr_id(did.node) } } fn tr_span(&self, _span: span) -> span { diff --git a/src/librustc/middle/borrowck/gather_loans/mod.rs b/src/librustc/middle/borrowck/gather_loans/mod.rs index 0db7b4880e758..a422d99b6f5cf 100644 --- a/src/librustc/middle/borrowck/gather_loans/mod.rs +++ b/src/librustc/middle/borrowck/gather_loans/mod.rs @@ -218,7 +218,7 @@ pub impl GatherLoanCtxt { fn pop_repeating_id(&mut self, id: ast::node_id) { let popped = self.repeating_ids.pop(); - assert!(id == popped); + assert_eq!(id, popped); } fn guarantee_adjustments(&mut self, diff --git a/src/librustc/middle/entry.rs b/src/librustc/middle/entry.rs index 9ffd0e6f22c3c..f4b9e4b62fc4b 100644 --- a/src/librustc/middle/entry.rs +++ b/src/librustc/middle/entry.rs @@ -144,7 +144,7 @@ fn configure_main(ctxt: @mut EntryContext) { } else { // If we *are* building a library, then we're on android where we still might // optionally want to translate main $4404 - assert!(this.session.targ_cfg.os == session::os_android); + assert_eq!(this.session.targ_cfg.os, session::os_android); } } } diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 27b6273879399..fce078a708f1a 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -365,7 +365,7 @@ pub fn resolve_arm(arm: &ast::arm, cx: Context, visitor: visit::vt) { } pub fn resolve_pat(pat: @ast::pat, cx: Context, visitor: visit::vt) { - assert!(cx.var_parent == cx.parent); + assert_eq!(cx.var_parent, cx.parent); parent_to_expr(cx, pat.id); visit::visit_pat(pat, cx, visitor); } @@ -427,7 +427,7 @@ pub fn resolve_expr(expr: @ast::expr, cx: Context, visitor: visit::vt) pub fn resolve_local(local: @ast::local, cx: Context, visitor: visit::vt) { - assert!(cx.var_parent == cx.parent); + assert_eq!(cx.var_parent, cx.parent); parent_to_expr(cx, local.node.id); visit::visit_local(local, cx, visitor); } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index a7e590e359c4d..1568c3e55352f 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -2321,7 +2321,7 @@ pub impl Resolver { return Indeterminate; } - assert!(containing_module.glob_count == 0); + assert_eq!(containing_module.glob_count, 0); // Add all resolved imports from the containing module. for containing_module.import_resolutions.each @@ -2903,7 +2903,7 @@ pub impl Resolver { // If this is a search of all imports, we should be done with glob // resolution at this point. if name_search_type == SearchItemsAndAllImports { - assert!(module_.glob_count == 0); + assert_eq!(module_.glob_count, 0); } // Check the list of resolved imports. diff --git a/src/librustc/middle/resolve_stage0.rs b/src/librustc/middle/resolve_stage0.rs index 713132b12fc19..aefbcbaa87e96 100644 --- a/src/librustc/middle/resolve_stage0.rs +++ b/src/librustc/middle/resolve_stage0.rs @@ -2368,7 +2368,7 @@ pub impl Resolver { return Indeterminate; } - assert!(containing_module.glob_count == 0); + assert_eq!(containing_module.glob_count, 0); // Add all resolved imports from the containing module. for containing_module.import_resolutions.each @@ -2932,7 +2932,7 @@ pub impl Resolver { // If this is a search of all imports, we should be done with glob // resolution at this point. if name_search_type == SearchItemsAndAllImports { - assert!(module_.glob_count == 0); + assert_eq!(module_.glob_count, 0); } // Check the list of resolved imports. diff --git a/src/librustc/middle/trans/adt.rs b/src/librustc/middle/trans/adt.rs index 21452a736fba8..25e97b0c8a82c 100644 --- a/src/librustc/middle/trans/adt.rs +++ b/src/librustc/middle/trans/adt.rs @@ -169,7 +169,7 @@ fn represent_type_uncached(cx: @CrateContext, t: ty::t) -> Repr { if cases.len() == 1 { // Equivalent to a struct/tuple/newtype. - assert!(cases[0].discr == 0); + assert_eq!(cases[0].discr, 0); return Univariant(mk_struct(cx, cases[0].tys, false), false) } @@ -377,12 +377,12 @@ pub fn trans_start_init(bcx: block, r: &Repr, val: ValueRef, discr: int) { Store(bcx, C_int(bcx.ccx(), discr), GEPi(bcx, val, [0, 0])) } Univariant(ref st, true) => { - assert!(discr == 0); + assert_eq!(discr, 0); Store(bcx, C_bool(true), GEPi(bcx, val, [0, st.fields.len() - 1])) } Univariant(*) => { - assert!(discr == 0); + assert_eq!(discr, 0); } General(*) => { Store(bcx, C_int(bcx.ccx(), discr), GEPi(bcx, val, [0, 0])) @@ -405,7 +405,7 @@ pub fn num_args(r: &Repr, discr: int) -> uint { match *r { CEnum(*) => 0, Univariant(ref st, dtor) => { - assert!(discr == 0); + assert_eq!(discr, 0); st.fields.len() - (if dtor { 1 } else { 0 }) } General(ref cases) => cases[discr as uint].fields.len() - 1, @@ -426,7 +426,7 @@ pub fn trans_field_ptr(bcx: block, r: &Repr, val: ValueRef, discr: int, bcx.ccx().sess.bug(~"element access in C-like enum") } Univariant(ref st, _dtor) => { - assert!(discr == 0); + assert_eq!(discr, 0); struct_field_ptr(bcx, st, val, ix, false) } General(ref cases) => { @@ -439,7 +439,7 @@ pub fn trans_field_ptr(bcx: block, r: &Repr, val: ValueRef, discr: int, // The unit-like case might have a nonzero number of unit-like fields. // (e.g., Result or Either with () as one side.) let llty = type_of::type_of(bcx.ccx(), nullfields[ix]); - assert!(machine::llsize_of_alloc(bcx.ccx(), llty) == 0); + assert_eq!(machine::llsize_of_alloc(bcx.ccx(), llty), 0); // The contents of memory at this pointer can't matter, but use // the value that's "reasonable" in case of pointer comparison. PointerCast(bcx, val, T_ptr(llty)) @@ -498,12 +498,12 @@ pub fn trans_const(ccx: @CrateContext, r: &Repr, discr: int, vals: &[ValueRef]) -> ValueRef { match *r { CEnum(min, max) => { - assert!(vals.len() == 0); + assert_eq!(vals.len(), 0); assert!(min <= discr && discr <= max); C_int(ccx, discr) } Univariant(ref st, _dro) => { - assert!(discr == 0); + assert_eq!(discr, 0); C_struct(build_const_struct(ccx, st, vals)) } General(ref cases) => { @@ -517,7 +517,7 @@ pub fn trans_const(ccx: @CrateContext, r: &Repr, discr: int, if discr == nndiscr { C_struct(build_const_struct(ccx, nonnull, vals)) } else { - assert!(vals.len() == 0); + assert_eq!(vals.len(), 0); let vals = do nonnull.fields.mapi |i, &ty| { let llty = type_of::sizing_type_of(ccx, ty); if i == ptrfield { C_null(llty) } else { C_undef(llty) } @@ -540,7 +540,7 @@ pub fn trans_const(ccx: @CrateContext, r: &Repr, discr: int, */ fn build_const_struct(ccx: @CrateContext, st: &Struct, vals: &[ValueRef]) -> ~[ValueRef] { - assert!(vals.len() == st.fields.len()); + assert_eq!(vals.len(), st.fields.len()); let mut offset = 0; let mut cfields = ~[]; diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index b5cca20d8eccb..66cca74214a41 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -496,7 +496,7 @@ pub fn get_res_dtor(ccx: @CrateContext, } else { did }; - assert!(did.crate == ast::local_crate); + assert_eq!(did.crate, ast::local_crate); let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index 38f8d271f08b3..362bcd483b41f 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -837,7 +837,7 @@ pub fn Phi(cx: block, Ty: TypeRef, vals: &[ValueRef], bbs: &[BasicBlockRef]) -> ValueRef { unsafe { if cx.unreachable { return llvm::LLVMGetUndef(Ty); } - assert!(vals.len() == bbs.len()); + assert_eq!(vals.len(), bbs.len()); let phi = EmptyPhi(cx, Ty); count_insn(cx, "addincoming"); llvm::LLVMAddIncoming(phi, vec::raw::to_ptr(vals), diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index dc81a9805887b..382e80148ec01 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -272,7 +272,7 @@ pub fn trans_fn_ref_with_vtables( // Create a monomorphic verison of generic functions if must_monomorphise { // Should be either intra-crate or inlined. - assert!(def_id.crate == ast::local_crate); + assert_eq!(def_id.crate, ast::local_crate); let mut (val, must_cast) = monomorphize::monomorphic_fn(ccx, def_id, type_params, diff --git a/src/librustc/middle/trans/closure.rs b/src/librustc/middle/trans/closure.rs index c6fa42cb8cbd3..d9cf1a3b4bc54 100644 --- a/src/librustc/middle/trans/closure.rs +++ b/src/librustc/middle/trans/closure.rs @@ -263,7 +263,7 @@ pub fn build_closure(bcx0: block, let datum = expr::trans_local_var(bcx, cap_var.def); match cap_var.mode { moves::CapRef => { - assert!(sigil == ast::BorrowedSigil); + assert_eq!(sigil, ast::BorrowedSigil); env_vals.push(EnvValue {action: EnvRef, datum: datum}); } diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 48c5a96c8e7b2..e08cc536a701f 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -113,7 +113,7 @@ fn const_deref_ptr(cx: @CrateContext, v: ValueRef) -> ValueRef { None => v }; unsafe { - assert!(llvm::LLVMIsGlobalConstant(v) == True); + assert_eq!(llvm::LLVMIsGlobalConstant(v), True); llvm::LLVMGetInitializer(v) } } @@ -209,8 +209,8 @@ pub fn const_expr(cx: @CrateContext, e: @ast::expr) -> ValueRef { assert!(m != ast::m_mutbl); let size = machine::llsize_of(cx, val_ty(llconst)); - assert!(abi::slice_elt_base == 0); - assert!(abi::slice_elt_len == 1); + assert_eq!(abi::slice_elt_base, 0); + assert_eq!(abi::slice_elt_len, 1); llconst = C_struct(~[llptr, size]); } _ => { @@ -486,7 +486,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: @ast::expr) -> ValueRef { } } ast::expr_path(pth) => { - assert!(pth.types.len() == 0); + assert_eq!(pth.types.len(), 0); match cx.tcx.def_map.find(&e.id) { Some(&ast::def_fn(def_id, _purity)) => { if !ast_util::is_local(def_id) { diff --git a/src/librustc/middle/trans/datum.rs b/src/librustc/middle/trans/datum.rs index 13f02b8fcac1d..13b072c6f632b 100644 --- a/src/librustc/middle/trans/datum.rs +++ b/src/librustc/middle/trans/datum.rs @@ -375,7 +375,7 @@ pub impl Datum { * Schedules this datum for cleanup in `bcx`. The datum * must be an rvalue. */ - assert!(self.source == RevokeClean); + assert_eq!(self.source, RevokeClean); match self.mode { ByValue => { add_clean_temp_immediate(bcx, self.val, self.ty); diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 3ed08eade33a4..51f17fcf47c4f 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -287,7 +287,7 @@ pub fn trans_to_datum(bcx: block, expr: @ast::expr) -> DatumBlock { debug!("add_env(closure_ty=%s)", closure_ty.repr(tcx)); let scratch = scratch_datum(bcx, closure_ty, false); let llfn = GEPi(bcx, scratch.val, [0u, abi::fn_field_code]); - assert!(datum.appropriate_mode() == ByValue); + assert_eq!(datum.appropriate_mode(), ByValue); Store(bcx, datum.to_appropriate_llval(bcx), llfn); let llenv = GEPi(bcx, scratch.val, [0u, abi::fn_field_box]); Store(bcx, base::null_env_ptr(bcx), llenv); diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index f8aa3eca28476..f77e2e0d52aa2 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -483,7 +483,7 @@ pub fn trans_struct_drop(bcx: block, // Class dtors have no explicit args, so the params should // just consist of the output pointer and the environment // (self) - assert!((params.len() == 2)); + assert_eq!(params.len(), 2); // Take a reference to the class (because it's using the Drop trait), // do so now. diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index bb18948ce5d54..9ea3259e9699c 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -2194,7 +2194,7 @@ pub fn type_contents(cx: ctxt, ty: t) -> TypeContents { // If this assertion failures, it is likely because of a // failure in the cross-crate inlining code to translate a // def-id. - assert!(p.def_id.crate == ast::local_crate); + assert_eq!(p.def_id.crate, ast::local_crate); type_param_def_to_contents( cx, cx.ty_param_defs.get(&p.def_id.node)) diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index 311aa551601dc..aeb360dc3f2fc 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -863,7 +863,7 @@ pub impl CoherenceChecker { } fn span_of_impl(&self, implementation: @Impl) -> span { - assert!(implementation.did.crate == local_crate); + assert_eq!(implementation.did.crate, local_crate); match self.crate_context.tcx.items.find(&implementation.did.node) { Some(&node_item(item, _)) => { return item.span; diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index a5e8b42dee5ac..1437494e5f86e 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -680,7 +680,7 @@ pub impl RegionVarBindings { match undo_item { Snapshot => {} AddVar(vid) => { - assert!(self.var_spans.len() == vid.to_uint() + 1); + assert_eq!(self.var_spans.len(), vid.to_uint() + 1); self.var_spans.pop(); } AddConstraint(ref constraint) => { @@ -1440,7 +1440,7 @@ pub impl RegionVarBindings { return match a_node.value { NoValue => { - assert!(a_node.classification == Contracting); + assert_eq!(a_node.classification, Contracting); a_node.value = Value(b_region); true // changed } diff --git a/src/librustc/middle/typeck/infer/unify.rs b/src/librustc/middle/typeck/infer/unify.rs index 3bcff92346566..d6e652592d835 100644 --- a/src/librustc/middle/typeck/infer/unify.rs +++ b/src/librustc/middle/typeck/infer/unify.rs @@ -129,7 +129,7 @@ pub impl InferCtxt { } else { // If equal, redirect one to the other and increment the // other's rank. - assert!(node_a.rank == node_b.rank); + assert_eq!(node_a.rank, node_b.rank); self.set(node_b.root, Redirect(node_a.root)); (node_a.root, node_a.rank + 1) } diff --git a/src/librustdoc/astsrv.rs b/src/librustdoc/astsrv.rs index b8a66eb8f64f0..47c99a8d9b773 100644 --- a/src/librustdoc/astsrv.rs +++ b/src/librustdoc/astsrv.rs @@ -162,6 +162,6 @@ fn srv_should_return_request_result() { let source = ~"fn a() { }"; do from_str(source) |srv| { let result = exec(srv, |_ctxt| 1000 ); - assert!(result == 1000); + assert_eq!(result, 1000); } } diff --git a/src/librustdoc/desc_to_brief_pass.rs b/src/librustdoc/desc_to_brief_pass.rs index 278f77135f9f5..c25764ab0601b 100644 --- a/src/librustdoc/desc_to_brief_pass.rs +++ b/src/librustdoc/desc_to_brief_pass.rs @@ -197,7 +197,7 @@ mod test { #[test] fn should_promote_desc() { let doc = mk_doc(~"#[doc = \"desc\"] mod m { }"); - assert!(doc.cratemod().mods()[0].brief() == Some(~"desc")); + assert_eq!(doc.cratemod().mods()[0].brief(), Some(~"desc")); } #[test] @@ -217,20 +217,20 @@ mod test { #[test] fn test_paragraphs_1() { let paras = paragraphs(~"1\n\n2"); - assert!(paras == ~[~"1", ~"2"]); + assert_eq!(paras, ~[~"1", ~"2"]); } #[test] fn test_paragraphs_2() { let paras = paragraphs(~"\n\n1\n1\n\n2\n\n"); - assert!(paras == ~[~"1\n1", ~"2"]); + assert_eq!(paras, ~[~"1\n1", ~"2"]); } #[test] fn should_promote_short_descs() { let desc = Some(~"desc"); let brief = extract(copy desc); - assert!(brief == desc); + assert_eq!(brief, desc); } #[test] @@ -244,7 +244,7 @@ Scotland in the mid 12th century, although it may have been built by King Henry II of England when he took control of England'snorthern counties."); let brief = extract(desc); - assert!(brief == None); + assert_eq!(brief, None); } #[test] diff --git a/src/librustdoc/escape_pass.rs b/src/librustdoc/escape_pass.rs index 949573be05ebb..11e9b71afdfff 100644 --- a/src/librustdoc/escape_pass.rs +++ b/src/librustdoc/escape_pass.rs @@ -27,5 +27,5 @@ fn escape(s: &str) -> ~str { fn should_escape_backslashes() { let s = ~"\\n"; let r = escape(s); - assert!(r == ~"\\\\n"); + assert_eq!(r, ~"\\\\n"); } diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index 7c66b4f4d4e93..4c120aed91161 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -369,7 +369,7 @@ fn default_fold_should_produce_same_doc() { let doc = extract::extract(ast, ~""); let fld = default_seq_fold(()); let folded = (fld.fold_doc)(&fld, copy doc); - assert!(doc == folded); + assert_eq!(doc, folded); } #[test] @@ -379,7 +379,7 @@ fn default_fold_should_produce_same_consts() { let doc = extract::extract(ast, ~""); let fld = default_seq_fold(()); let folded = (fld.fold_doc)(&fld, copy doc); - assert!(doc == folded); + assert_eq!(doc, folded); } #[test] @@ -389,7 +389,7 @@ fn default_fold_should_produce_same_enums() { let doc = extract::extract(ast, ~""); let fld = default_seq_fold(()); let folded = (fld.fold_doc)(&fld, copy doc); - assert!(doc == folded); + assert_eq!(doc, folded); } #[test] @@ -399,5 +399,5 @@ fn default_parallel_fold_should_produce_same_doc() { let doc = extract::extract(ast, ~""); let fld = default_par_fold(()); let folded = (fld.fold_doc)(&fld, copy doc); - assert!(doc == folded); + assert_eq!(doc, folded); } diff --git a/src/librustdoc/markdown_index_pass.rs b/src/librustdoc/markdown_index_pass.rs index 24bfa62305a94..2c34f3543b734 100644 --- a/src/librustdoc/markdown_index_pass.rs +++ b/src/librustdoc/markdown_index_pass.rs @@ -209,7 +209,7 @@ mod test { #[test] fn should_trim_whitespace_after_removing_punctuation() { - assert!(pandoc_header_id("impl foo for ()") == ~"impl-foo-for"); + assert_eq!(pandoc_header_id("impl foo for ()"), ~"impl-foo-for"); } #[test] diff --git a/src/librustdoc/markdown_writer.rs b/src/librustdoc/markdown_writer.rs index 456a5f09a8800..94372127a22ed 100644 --- a/src/librustdoc/markdown_writer.rs +++ b/src/librustdoc/markdown_writer.rs @@ -285,7 +285,7 @@ mod test { let doc = mk_doc(~"test", ~""); let page = doc::CratePage(doc.CrateDoc()); let filename = make_local_filename(config, page); - assert!(filename.to_str() == ~"output/dir/test.md"); + assert_eq!(filename.to_str(), ~"output/dir/test.md"); } #[test] @@ -299,7 +299,7 @@ mod test { let doc = mk_doc(~"", ~""); let page = doc::CratePage(doc.CrateDoc()); let filename = make_local_filename(config, page); - assert!(filename.to_str() == ~"output/dir/index.html"); + assert_eq!(filename.to_str(), ~"output/dir/index.html"); } #[test] @@ -314,6 +314,6 @@ mod test { let modb = copy doc.cratemod().mods()[0].mods()[0]; let page = doc::ItemPage(doc::ModTag(modb)); let filename = make_local_filename(config, page); - assert!(filename == Path("output/dir/a_b.html")); + assert_eq!(filename, Path("output/dir/a_b.html")); } } diff --git a/src/librustdoc/page_pass.rs b/src/librustdoc/page_pass.rs index 89a3acc6cac71..02716ff73b6b3 100644 --- a/src/librustdoc/page_pass.rs +++ b/src/librustdoc/page_pass.rs @@ -176,13 +176,13 @@ mod test { config::DocPerCrate, ~"mod a { } mod b { mod c { } }" ); - assert!(doc.pages.len() == 1u); + assert_eq!(doc.pages.len(), 1u); } #[test] fn should_make_a_page_for_every_mod() { let doc = mk_doc(~"mod a { }"); - assert!(doc.pages.mods()[0].name() == ~"a"); + assert_eq!(doc.pages.mods()[0].name(), ~"a"); } #[test] diff --git a/src/librustdoc/pass.rs b/src/librustdoc/pass.rs index b80f43a7bbd06..6527481d514c7 100644 --- a/src/librustdoc/pass.rs +++ b/src/librustdoc/pass.rs @@ -89,6 +89,6 @@ fn test_run_passes() { ]; let doc = extract::from_srv(srv.clone(), ~"one"); let doc = run_passes(srv, doc, passes); - assert!(doc.cratemod().name() == ~"onetwothree"); + assert_eq!(doc.cratemod().name(), ~"onetwothree"); } } diff --git a/src/librustdoc/path_pass.rs b/src/librustdoc/path_pass.rs index 5560f21af61db..a31a8ac5933de 100644 --- a/src/librustdoc/path_pass.rs +++ b/src/librustdoc/path_pass.rs @@ -109,6 +109,6 @@ fn should_record_fn_paths() { do astsrv::from_str(source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); let doc = run(srv.clone(), doc); - assert!(doc.cratemod().mods()[0].fns()[0].path() == ~[~"a"]); + assert_eq!(doc.cratemod().mods()[0].fns()[0].path(), ~[~"a"]); } } diff --git a/src/librustdoc/prune_private_pass.rs b/src/librustdoc/prune_private_pass.rs index 086b5f476016c..9dfcc7c4ec692 100644 --- a/src/librustdoc/prune_private_pass.rs +++ b/src/librustdoc/prune_private_pass.rs @@ -194,7 +194,7 @@ mod test { pub fn bar() { }\ fn baz() { }\ }"); - assert!(doc.cratemod().impls()[0].methods.len() == 1); + assert_eq!(doc.cratemod().impls()[0].methods.len(), 1); } #[test] @@ -204,7 +204,7 @@ mod test { pub fn bar() { }\ priv fn baz() { }\ }"); - assert!(doc.cratemod().impls()[0].methods.len() == 1); + assert_eq!(doc.cratemod().impls()[0].methods.len(), 1); } #[test] @@ -214,7 +214,7 @@ mod test { fn bar() { }\ priv fn baz() { }\ }"); - assert!(doc.cratemod().impls()[0].methods.len() == 1); + assert_eq!(doc.cratemod().impls()[0].methods.len(), 1); } #[test] @@ -224,7 +224,7 @@ mod test { pub fn bar() { }\ fn baz() { }\ }"); - assert!(doc.cratemod().impls()[0].methods.len() == 1); + assert_eq!(doc.cratemod().impls()[0].methods.len(), 1); } #[test] @@ -234,7 +234,7 @@ mod test { pub fn bar() { }\ priv fn baz() { }\ }"); - assert!(doc.cratemod().impls()[0].methods.len() == 1); + assert_eq!(doc.cratemod().impls()[0].methods.len(), 1); } #[test] diff --git a/src/librustdoc/sectionalize_pass.rs b/src/librustdoc/sectionalize_pass.rs index c69f3b13e26d8..8c3704d55c7d9 100644 --- a/src/librustdoc/sectionalize_pass.rs +++ b/src/librustdoc/sectionalize_pass.rs @@ -236,7 +236,7 @@ mod test { Body\"]\ mod a { }"); - assert!(doc.cratemod().mods()[0].desc() == None); + assert_eq!(doc.cratemod().mods()[0].desc(), None); } #[test] @@ -247,7 +247,7 @@ mod test { # Header\n\ Body\"]\ fn a(); }"); - assert!(doc.cratemod().traits()[0].methods[0].sections.len() == 1u); + assert_eq!(doc.cratemod().traits()[0].methods[0].sections.len(), 1u); } #[test] @@ -258,6 +258,6 @@ mod test { # Header\n\ Body\"]\ fn a() { } }"); - assert!(doc.cratemod().impls()[0].methods[0].sections.len() == 1u); + assert_eq!(doc.cratemod().impls()[0].methods[0].sections.len(), 1u); } } diff --git a/src/librustdoc/sort_item_name_pass.rs b/src/librustdoc/sort_item_name_pass.rs index 86b2cc634fd04..572cb7db926e3 100644 --- a/src/librustdoc/sort_item_name_pass.rs +++ b/src/librustdoc/sort_item_name_pass.rs @@ -31,7 +31,7 @@ fn test() { do astsrv::from_str(source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); let doc = (mk_pass().f)(srv.clone(), doc); - assert!(doc.cratemod().items[0].name() == ~"y"); - assert!(doc.cratemod().items[1].name() == ~"z"); + assert_eq!(doc.cratemod().items[0].name(), ~"y"); + assert_eq!(doc.cratemod().items[1].name(), ~"z"); } } diff --git a/src/librustdoc/sort_item_type_pass.rs b/src/librustdoc/sort_item_type_pass.rs index 158d407fff64f..cdb1a49c36dd7 100644 --- a/src/librustdoc/sort_item_type_pass.rs +++ b/src/librustdoc/sort_item_type_pass.rs @@ -53,13 +53,13 @@ fn test() { do astsrv::from_str(source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); let doc = (mk_pass().f)(srv.clone(), doc); - assert!(doc.cratemod().items[0].name() == ~"iconst"); - assert!(doc.cratemod().items[1].name() == ~"itype"); - assert!(doc.cratemod().items[2].name() == ~"ienum"); - assert!(doc.cratemod().items[3].name() == ~"istruct"); - assert!(doc.cratemod().items[4].name() == ~"itrait"); - assert!(doc.cratemod().items[5].name() == ~"__extensions__"); - assert!(doc.cratemod().items[6].name() == ~"ifn"); - assert!(doc.cratemod().items[7].name() == ~"imod"); + assert_eq!(doc.cratemod().items[0].name(), ~"iconst"); + assert_eq!(doc.cratemod().items[1].name(), ~"itype"); + assert_eq!(doc.cratemod().items[2].name(), ~"ienum"); + assert_eq!(doc.cratemod().items[3].name(), ~"istruct"); + assert_eq!(doc.cratemod().items[4].name(), ~"itrait"); + assert_eq!(doc.cratemod().items[5].name(), ~"__extensions__"); + assert_eq!(doc.cratemod().items[6].name(), ~"ifn"); + assert_eq!(doc.cratemod().items[7].name(), ~"imod"); } } diff --git a/src/librustdoc/sort_pass.rs b/src/librustdoc/sort_pass.rs index dc7bc8b9df21f..72abbd2bdbd05 100644 --- a/src/librustdoc/sort_pass.rs +++ b/src/librustdoc/sort_pass.rs @@ -67,10 +67,10 @@ fn test() { do astsrv::from_str(source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); let doc = (mk_pass(~"", name_lteq).f)(srv.clone(), doc); - assert!(doc.cratemod().mods()[0].name() == ~"w"); - assert!(doc.cratemod().mods()[1].items[0].name() == ~"x"); - assert!(doc.cratemod().mods()[1].items[1].name() == ~"y"); - assert!(doc.cratemod().mods()[1].name() == ~"z"); + assert_eq!(doc.cratemod().mods()[0].name(), ~"w"); + assert_eq!(doc.cratemod().mods()[1].items[0].name(), ~"x"); + assert_eq!(doc.cratemod().mods()[1].items[1].name(), ~"y"); + assert_eq!(doc.cratemod().mods()[1].name(), ~"z"); } } @@ -84,10 +84,10 @@ fn should_be_stable() { do astsrv::from_str(source) |srv| { let doc = extract::from_srv(srv.clone(), ~""); let doc = (mk_pass(~"", always_eq).f)(srv.clone(), doc); - assert!(doc.cratemod().mods()[0].items[0].name() == ~"b"); - assert!(doc.cratemod().mods()[1].items[0].name() == ~"d"); + assert_eq!(doc.cratemod().mods()[0].items[0].name(), ~"b"); + assert_eq!(doc.cratemod().mods()[1].items[0].name(), ~"d"); let doc = (mk_pass(~"", always_eq).f)(srv.clone(), doc); - assert!(doc.cratemod().mods()[0].items[0].name() == ~"b"); - assert!(doc.cratemod().mods()[1].items[0].name() == ~"d"); + assert_eq!(doc.cratemod().mods()[0].items[0].name(), ~"b"); + assert_eq!(doc.cratemod().mods()[1].items[0].name(), ~"d"); } } diff --git a/src/librustdoc/text_pass.rs b/src/librustdoc/text_pass.rs index 61768e37a83ff..3b1a2059622b6 100644 --- a/src/librustdoc/text_pass.rs +++ b/src/librustdoc/text_pass.rs @@ -158,13 +158,13 @@ mod test { #[test] fn should_execute_op_on_enum_brief() { let doc = mk_doc(~"#[doc = \" a \"] enum a { b }"); - assert!(doc.cratemod().enums()[0].brief() == Some(~"a")); + assert_eq!(doc.cratemod().enums()[0].brief(), Some(~"a")); } #[test] fn should_execute_op_on_enum_desc() { let doc = mk_doc(~"#[doc = \" a \"] enum a { b }"); - assert!(doc.cratemod().enums()[0].desc() == Some(~"a")); + assert_eq!(doc.cratemod().enums()[0].desc(), Some(~"a")); } #[test] @@ -177,14 +177,14 @@ mod test { fn should_execute_op_on_trait_brief() { let doc = mk_doc( ~"#[doc = \" a \"] trait i { fn a(); }"); - assert!(doc.cratemod().traits()[0].brief() == Some(~"a")); + assert_eq!(doc.cratemod().traits()[0].brief(), Some(~"a")); } #[test] fn should_execute_op_on_trait_desc() { let doc = mk_doc( ~"#[doc = \" a \"] trait i { fn a(); }"); - assert!(doc.cratemod().traits()[0].desc() == Some(~"a")); + assert_eq!(doc.cratemod().traits()[0].desc(), Some(~"a")); } #[test] @@ -205,14 +205,14 @@ mod test { fn should_execute_op_on_impl_brief() { let doc = mk_doc( ~"#[doc = \" a \"] impl int { fn a() { } }"); - assert!(doc.cratemod().impls()[0].brief() == Some(~"a")); + assert_eq!(doc.cratemod().impls()[0].brief(), Some(~"a")); } #[test] fn should_execute_op_on_impl_desc() { let doc = mk_doc( ~"#[doc = \" a \"] impl int { fn a() { } }"); - assert!(doc.cratemod().impls()[0].desc() == Some(~"a")); + assert_eq!(doc.cratemod().impls()[0].desc(), Some(~"a")); } #[test] @@ -233,14 +233,14 @@ mod test { fn should_execute_op_on_type_brief() { let doc = mk_doc( ~"#[doc = \" a \"] type t = int;"); - assert!(doc.cratemod().types()[0].brief() == Some(~"a")); + assert_eq!(doc.cratemod().types()[0].brief(), Some(~"a")); } #[test] fn should_execute_op_on_type_desc() { let doc = mk_doc( ~"#[doc = \" a \"] type t = int;"); - assert!(doc.cratemod().types()[0].desc() == Some(~"a")); + assert_eq!(doc.cratemod().types()[0].desc(), Some(~"a")); } #[test] diff --git a/src/librustdoc/trim_pass.rs b/src/librustdoc/trim_pass.rs index e56a5f18ac6f7..8bfa12ca0b5c4 100644 --- a/src/librustdoc/trim_pass.rs +++ b/src/librustdoc/trim_pass.rs @@ -45,6 +45,6 @@ mod test { let doc = mk_doc(~"#[doc = \" desc \"] \ mod m { }"); - assert!(doc.cratemod().mods()[0].desc() == Some(~"desc")); + assert_eq!(doc.cratemod().mods()[0].desc(), Some(~"desc")); } } diff --git a/src/librustdoc/unindent_pass.rs b/src/librustdoc/unindent_pass.rs index 082c4dd1989a6..826012a244724 100644 --- a/src/librustdoc/unindent_pass.rs +++ b/src/librustdoc/unindent_pass.rs @@ -92,14 +92,14 @@ fn unindent(s: &str) -> ~str { fn should_unindent() { let s = ~" line1\n line2"; let r = unindent(s); - assert!(r == ~"line1\nline2"); + assert_eq!(r, ~"line1\nline2"); } #[test] fn should_unindent_multiple_paragraphs() { let s = ~" line1\n\n line2"; let r = unindent(s); - assert!(r == ~"line1\n\nline2"); + assert_eq!(r, ~"line1\n\nline2"); } #[test] @@ -108,7 +108,7 @@ fn should_leave_multiple_indent_levels() { // base indentation and should be preserved let s = ~" line1\n\n line2"; let r = unindent(s); - assert!(r == ~"line1\n\n line2"); + assert_eq!(r, ~"line1\n\n line2"); } #[test] @@ -120,12 +120,12 @@ fn should_ignore_first_line_indent() { // and continue here"] let s = ~"line1\n line2"; let r = unindent(s); - assert!(r == ~"line1\nline2"); + assert_eq!(r, ~"line1\nline2"); } #[test] fn should_not_ignore_first_line_indent_in_a_single_line_para() { let s = ~"line1\n\n line2"; let r = unindent(s); - assert!(r == ~"line1\n\n line2"); + assert_eq!(r, ~"line1\n\n line2"); } diff --git a/src/librustpkg/tests.rs b/src/librustpkg/tests.rs index 8eba3f06de387..2574ba4e76228 100644 --- a/src/librustpkg/tests.rs +++ b/src/librustpkg/tests.rs @@ -212,7 +212,7 @@ fn test_package_ids_must_be_relative_path_like() { let whatever = PkgId::new("foo"); - assert!(addversion("foo") == whatever.to_str()); + assert_eq!(addversion("foo"), whatever.to_str()); assert!(addversion("github.com/mozilla/rust") == PkgId::new("github.com/mozilla/rust").to_str()); @@ -222,16 +222,16 @@ fn test_package_ids_must_be_relative_path_like() { copy whatever }).in { let x = PkgId::new(""); - assert!(addversion("foo") == x.to_str()); + assert_eq!(addversion("foo"), x.to_str()); } do cond.trap(|(p, e)| { - assert!(p.to_str() == os::make_absolute(&Path("foo/bar/quux")).to_str()); + assert_eq!(p.to_str(), os::make_absolute(&Path("foo/bar/quux")).to_str()); assert!("absolute pkgid" == e); copy whatever }).in { let z = PkgId::new(os::make_absolute(&Path("foo/bar/quux")).to_str()); - assert!(addversion("foo") == z.to_str()); + assert_eq!(addversion("foo"), z.to_str()); } } diff --git a/src/librustpkg/testsuite/pass/src/install-paths/test.rs b/src/librustpkg/testsuite/pass/src/install-paths/test.rs index acfae9e04fb59..011a1540e1bca 100644 --- a/src/librustpkg/testsuite/pass/src/install-paths/test.rs +++ b/src/librustpkg/testsuite/pass/src/install-paths/test.rs @@ -10,5 +10,5 @@ #[test] fn test_two_plus_two() { - assert!(2 + 2 == 4); + assert_eq!(2 + 2, 4); } diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index 4a9c276948aa0..108a404eb7c02 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -417,7 +417,7 @@ pub fn compile_crate_from_input(input: &driver::input, match crate_opt { Some(c) => { debug!("Calling compile_rest, outputs = %?", outputs); - assert!(what == driver::cu_everything); + assert_eq!(what, driver::cu_everything); driver::compile_rest(sess, cfg, driver::cu_everything, Some(outputs), Some(c)); c } diff --git a/src/libstd/arc.rs b/src/libstd/arc.rs index df49771258e29..f0158acfa79fa 100644 --- a/src/libstd/arc.rs +++ b/src/libstd/arc.rs @@ -501,13 +501,13 @@ mod tests { let arc_v = p.recv(); let v = copy *arc::get::<~[int]>(&arc_v); - assert!(v[3] == 4); + assert_eq!(v[3], 4); }; let c = p.recv(); c.send(arc::clone(&arc_v)); - assert!((*arc::get(&arc_v))[2] == 3); + assert_eq!((*arc::get(&arc_v))[2], 3); info!(arc_v); } @@ -545,7 +545,7 @@ mod tests { do arc2.access_cond |one, cond| { cond.signal(); // Parent should fail when it wakes up. - assert!(*one == 0); + assert_eq!(*one, 0); } } @@ -562,11 +562,11 @@ mod tests { let arc2 = ~arc.clone(); do task::try || { do arc2.access |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } }; do arc.access |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } #[test] #[should_fail] #[ignore(cfg(windows))] @@ -575,11 +575,11 @@ mod tests { let arc2 = (*arc).clone(); do task::try || { do arc2.write |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } }; do arc.read |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } #[test] #[should_fail] #[ignore(cfg(windows))] @@ -588,11 +588,11 @@ mod tests { let arc2 = (*arc).clone(); do task::try || { do arc2.write |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } }; do arc.write |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } #[test] #[should_fail] #[ignore(cfg(windows))] @@ -602,12 +602,12 @@ mod tests { do task::try || { do arc2.write_downgrade |mut write_mode| { do write_mode.write |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } } }; do arc.write |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } #[test] #[ignore(cfg(windows))] @@ -616,11 +616,11 @@ mod tests { let arc2 = (*arc).clone(); do task::try || { do arc2.read |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } }; do arc.read |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } #[test] #[ignore(cfg(windows))] @@ -629,11 +629,11 @@ mod tests { let arc2 = (*arc).clone(); do task::try || { do arc2.read |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } }; do arc.write |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } #[test] #[ignore(cfg(windows))] @@ -644,12 +644,12 @@ mod tests { do arc2.write_downgrade |write_mode| { let read_mode = arc2.downgrade(write_mode); do (&read_mode).read |one| { - assert!(*one == 2); + assert_eq!(*one, 2); } } }; do arc.write |one| { - assert!(*one == 1); + assert_eq!(*one, 1); } } #[test] @@ -691,7 +691,7 @@ mod tests { // Wait for writer to finish p.recv(); do arc.read |num| { - assert!(*num == 10); + assert_eq!(*num, 10); } } #[test] @@ -713,7 +713,7 @@ mod tests { do task::spawn || { rp1.recv(); // wait for downgrader to give go-ahead do arcn.read |state| { - assert!(*state == 31337); + assert_eq!(*state, 31337); rc2.send(()); } } @@ -725,7 +725,7 @@ mod tests { do task::spawn || { wp1.recv(); do arc2.write_cond |state, cond| { - assert!(*state == 0); + assert_eq!(*state, 0); *state = 42; cond.signal(); } @@ -733,7 +733,7 @@ mod tests { do arc2.write |state| { // This shouldn't happen until after the downgrade read // section, and all other readers, finish. - assert!(*state == 31337); + assert_eq!(*state, 31337); *state = 42; } wc2.send(()); @@ -746,7 +746,7 @@ mod tests { while *state == 0 { cond.wait(); } - assert!(*state == 42); + assert_eq!(*state, 42); *state = 31337; // send to other readers for reader_convos.each |x| { @@ -764,7 +764,7 @@ mod tests { } } wc1.send(()); // tell writer to try again - assert!(*state == 31337); + assert_eq!(*state, 31337); } } diff --git a/src/libstd/base64.rs b/src/libstd/base64.rs index 68242f88fae5e..76df10817379f 100644 --- a/src/libstd/base64.rs +++ b/src/libstd/base64.rs @@ -229,23 +229,23 @@ mod tests { #[test] fn test_to_base64() { - assert!((~"").to_base64() == ~""); + assert_eq!((~"").to_base64(), ~""); assert!((~"f").to_base64() == ~"Zg=="); - assert!((~"fo").to_base64() == ~"Zm8="); - assert!((~"foo").to_base64() == ~"Zm9v"); + assert_eq!((~"fo").to_base64(), ~"Zm8="); + assert_eq!((~"foo").to_base64(), ~"Zm9v"); assert!((~"foob").to_base64() == ~"Zm9vYg=="); - assert!((~"fooba").to_base64() == ~"Zm9vYmE="); - assert!((~"foobar").to_base64() == ~"Zm9vYmFy"); + assert_eq!((~"fooba").to_base64(), ~"Zm9vYmE="); + assert_eq!((~"foobar").to_base64(), ~"Zm9vYmFy"); } #[test] fn test_from_base64() { - assert!((~"").from_base64() == str::to_bytes(~"")); + assert_eq!((~"").from_base64(), str::to_bytes(~"")); assert!((~"Zg==").from_base64() == str::to_bytes(~"f")); - assert!((~"Zm8=").from_base64() == str::to_bytes(~"fo")); - assert!((~"Zm9v").from_base64() == str::to_bytes(~"foo")); + assert_eq!((~"Zm8=").from_base64(), str::to_bytes(~"fo")); + assert_eq!((~"Zm9v").from_base64(), str::to_bytes(~"foo")); assert!((~"Zm9vYg==").from_base64() == str::to_bytes(~"foob")); - assert!((~"Zm9vYmE=").from_base64() == str::to_bytes(~"fooba")); - assert!((~"Zm9vYmFy").from_base64() == str::to_bytes(~"foobar")); + assert_eq!((~"Zm9vYmE=").from_base64(), str::to_bytes(~"fooba")) + assert_eq!((~"Zm9vYmFy").from_base64(), str::to_bytes(~"foobar")); } } diff --git a/src/libstd/bitv.rs b/src/libstd/bitv.rs index e31818ecc1c16..f0632e550fa68 100644 --- a/src/libstd/bitv.rs +++ b/src/libstd/bitv.rs @@ -127,7 +127,7 @@ pub impl BigBitv { fn process(&mut self, b: &BigBitv, nbits: uint, op: &fn(uint, uint) -> uint) -> bool { let len = b.storage.len(); - assert!((self.storage.len() == len)); + assert_eq!(self.storage.len(), len); let mut changed = false; for uint::range(0, len) |i| { let mask = big_mask(nbits, i); @@ -508,7 +508,7 @@ pub impl Bitv { * the bitvector and vector must have the same length */ fn eq_vec(&self, v: ~[uint]) -> bool { - assert!(self.nbits == v.len()); + assert_eq!(self.nbits, v.len()); let mut i = 0; while i < self.nbits { let w0 = self.get(i); @@ -909,10 +909,10 @@ mod tests { #[test] fn test_to_str() { let zerolen = Bitv::new(0u, false); - assert!(zerolen.to_str() == ~""); + assert_eq!(zerolen.to_str(), ~""); let eightbits = Bitv::new(8u, false); - assert!(eightbits.to_str() == ~"00000000"); + assert_eq!(eightbits.to_str(), ~"00000000"); } #[test] @@ -938,7 +938,7 @@ mod tests { let mut b = bitv::Bitv::new(2, false); b.set(0, true); b.set(1, false); - assert!(b.to_str() == ~"10"); + assert_eq!(b.to_str(), ~"10"); } #[test] @@ -1248,19 +1248,19 @@ mod tests { fn test_from_bytes() { let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]); let str = ~"10110110" + ~"00000000" + ~"11111111"; - assert!(bitv.to_str() == str); + assert_eq!(bitv.to_str(), str); } #[test] fn test_to_bytes() { let mut bv = Bitv::new(3, true); bv.set(1, false); - assert!(bv.to_bytes() == ~[0b10100000]); + assert_eq!(bv.to_bytes(), ~[0b10100000]); let mut bv = Bitv::new(9, false); bv.set(2, true); bv.set(8, true); - assert!(bv.to_bytes() == ~[0b00100000, 0b10000000]); + assert_eq!(bv.to_bytes(), ~[0b00100000, 0b10000000]); } #[test] @@ -1272,7 +1272,7 @@ mod tests { #[test] fn test_to_bools() { let bools = ~[false, false, true, false, false, true, true, false]; - assert!(from_bytes([0b00100110]).to_bools() == bools); + assert_eq!(from_bytes([0b00100110]).to_bools(), bools); } #[test] @@ -1330,7 +1330,7 @@ mod tests { assert!(b.insert(400)); assert!(!b.insert(400)); assert!(b.contains(&400)); - assert!(b.len() == 2); + assert_eq!(b.len(), 2); } #[test] @@ -1354,10 +1354,10 @@ mod tests { let mut i = 0; let expected = [3, 5, 11, 77]; for a.intersection(&b) |x| { - assert!(*x == expected[i]); + assert_eq!(*x, expected[i]); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1377,10 +1377,10 @@ mod tests { let mut i = 0; let expected = [1, 5, 500]; for a.difference(&b) |x| { - assert!(*x == expected[i]); + assert_eq!(*x, expected[i]); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1402,10 +1402,10 @@ mod tests { let mut i = 0; let expected = [1, 5, 11, 14, 220]; for a.symmetric_difference(&b) |x| { - assert!(*x == expected[i]); + assert_eq!(*x, expected[i]); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1430,10 +1430,10 @@ mod tests { let mut i = 0; let expected = [1, 3, 5, 9, 11, 13, 19, 24, 160]; for a.union(&b) |x| { - assert!(*x == expected[i]); + assert_eq!(*x, expected[i]); i += 1 } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1448,7 +1448,7 @@ mod tests { assert!(a.insert(1000)); assert!(a.remove(&1000)); - assert!(a.capacity() == uint::bits); + assert_eq!(a.capacity(), uint::bits); } fn rng() -> rand::IsaacRng { diff --git a/src/libstd/c_vec.rs b/src/libstd/c_vec.rs index 17b7bae6de5df..e463e5971881c 100644 --- a/src/libstd/c_vec.rs +++ b/src/libstd/c_vec.rs @@ -165,9 +165,9 @@ mod tests { set(cv, 3u, 8u8); set(cv, 4u, 9u8); - assert!(get(cv, 3u) == 8u8); - assert!(get(cv, 4u) == 9u8); - assert!(len(cv) == 16u); + assert_eq!(get(cv, 3u), 8u8); + assert_eq!(get(cv, 4u), 9u8); + assert_eq!(len(cv), 16u); } #[test] @@ -195,7 +195,7 @@ mod tests { set(cv, 0u, 32u8); set(cv, 1u, 33u8); - assert!(unsafe { *p } == 32u8); + assert_eq!(unsafe { *p }, 32u8); set(cv, 2u, 34u8); /* safety */ } diff --git a/src/libstd/comm.rs b/src/libstd/comm.rs index 20ab2d61ecc07..28d3d329b2615 100644 --- a/src/libstd/comm.rs +++ b/src/libstd/comm.rs @@ -104,7 +104,7 @@ mod test { left.send(~"abc"); right.send(123); - assert!(left.recv() == 123); - assert!(right.recv() == ~"abc"); + assert_eq!(left.recv(), 123); + assert_eq!(right.recv(), ~"abc"); } } diff --git a/src/libstd/deque.rs b/src/libstd/deque.rs index c94acaa1f70db..eac765de00636 100644 --- a/src/libstd/deque.rs +++ b/src/libstd/deque.rs @@ -140,7 +140,7 @@ pub impl Deque { /// Grow is only called on full elts, so nelts is also len(elts), unlike /// elsewhere. fn grow(nelts: uint, lo: uint, elts: &mut [Option]) -> ~[Option] { - assert!(nelts == elts.len()); + assert_eq!(nelts, elts.len()); let mut rv = ~[]; do rv.grow_fn(nelts + 1) |i| { @@ -163,46 +163,46 @@ mod tests { #[test] fn test_simple() { let mut d = Deque::new(); - assert!(d.len() == 0u); + assert_eq!(d.len(), 0u); d.add_front(17); d.add_front(42); d.add_back(137); - assert!(d.len() == 3u); + assert_eq!(d.len(), 3u); d.add_back(137); - assert!(d.len() == 4u); + assert_eq!(d.len(), 4u); debug!(d.peek_front()); - assert!(*d.peek_front() == 42); + assert_eq!(*d.peek_front(), 42); debug!(d.peek_back()); - assert!(*d.peek_back() == 137); + assert_eq!(*d.peek_back(), 137); let mut i: int = d.pop_front(); debug!(i); - assert!(i == 42); + assert_eq!(i, 42); i = d.pop_back(); debug!(i); - assert!(i == 137); + assert_eq!(i, 137); i = d.pop_back(); debug!(i); - assert!(i == 137); + assert_eq!(i, 137); i = d.pop_back(); debug!(i); - assert!(i == 17); - assert!(d.len() == 0u); + assert_eq!(i, 17); + assert_eq!(d.len(), 0u); d.add_back(3); - assert!(d.len() == 1u); + assert_eq!(d.len(), 1u); d.add_front(2); - assert!(d.len() == 2u); + assert_eq!(d.len(), 2u); d.add_back(4); - assert!(d.len() == 3u); + assert_eq!(d.len(), 3u); d.add_front(1); - assert!(d.len() == 4u); + assert_eq!(d.len(), 4u); debug!(d.get(0)); debug!(d.get(1)); debug!(d.get(2)); debug!(d.get(3)); - assert!(*d.get(0) == 1); - assert!(*d.get(1) == 2); - assert!(*d.get(2) == 3); - assert!(*d.get(3) == 4); + assert_eq!(*d.get(0), 1); + assert_eq!(*d.get(1), 2); + assert_eq!(*d.get(2), 3); + assert_eq!(*d.get(3), 4); } #[test] @@ -213,63 +213,63 @@ mod tests { let d: @int = @175; let mut deq = Deque::new(); - assert!(deq.len() == 0); + assert_eq!(deq.len(), 0); deq.add_front(a); deq.add_front(b); deq.add_back(c); - assert!(deq.len() == 3); + assert_eq!(deq.len(), 3); deq.add_back(d); - assert!(deq.len() == 4); - assert!(*deq.peek_front() == b); - assert!(*deq.peek_back() == d); - assert!(deq.pop_front() == b); - assert!(deq.pop_back() == d); - assert!(deq.pop_back() == c); - assert!(deq.pop_back() == a); - assert!(deq.len() == 0); + assert_eq!(deq.len(), 4); + assert_eq!(*deq.peek_front(), b); + assert_eq!(*deq.peek_back(), d); + assert_eq!(deq.pop_front(), b); + assert_eq!(deq.pop_back(), d); + assert_eq!(deq.pop_back(), c); + assert_eq!(deq.pop_back(), a); + assert_eq!(deq.len(), 0); deq.add_back(c); - assert!(deq.len() == 1); + assert_eq!(deq.len(), 1); deq.add_front(b); - assert!(deq.len() == 2); + assert_eq!(deq.len(), 2); deq.add_back(d); - assert!(deq.len() == 3); + assert_eq!(deq.len(), 3); deq.add_front(a); - assert!(deq.len() == 4); - assert!(*deq.get(0) == a); - assert!(*deq.get(1) == b); - assert!(*deq.get(2) == c); - assert!(*deq.get(3) == d); + assert_eq!(deq.len(), 4); + assert_eq!(*deq.get(0), a); + assert_eq!(*deq.get(1), b); + assert_eq!(*deq.get(2), c); + assert_eq!(*deq.get(3), d); } #[cfg(test)] fn test_parameterized(a: T, b: T, c: T, d: T) { let mut deq = Deque::new(); - assert!(deq.len() == 0); + assert_eq!(deq.len(), 0); deq.add_front(a); deq.add_front(b); deq.add_back(c); - assert!(deq.len() == 3); + assert_eq!(deq.len(), 3); deq.add_back(d); - assert!(deq.len() == 4); - assert!(*deq.peek_front() == b); - assert!(*deq.peek_back() == d); - assert!(deq.pop_front() == b); - assert!(deq.pop_back() == d); - assert!(deq.pop_back() == c); - assert!(deq.pop_back() == a); - assert!(deq.len() == 0); + assert_eq!(deq.len(), 4); + assert_eq!(*deq.peek_front(), b); + assert_eq!(*deq.peek_back(), d); + assert_eq!(deq.pop_front(), b); + assert_eq!(deq.pop_back(), d); + assert_eq!(deq.pop_back(), c); + assert_eq!(deq.pop_back(), a); + assert_eq!(deq.len(), 0); deq.add_back(c); - assert!(deq.len() == 1); + assert_eq!(deq.len(), 1); deq.add_front(b); - assert!(deq.len() == 2); + assert_eq!(deq.len(), 2); deq.add_back(d); - assert!(deq.len() == 3); + assert_eq!(deq.len(), 3); deq.add_front(a); - assert!(deq.len() == 4); - assert!(*deq.get(0) == a); - assert!(*deq.get(1) == b); - assert!(*deq.get(2) == c); - assert!(*deq.get(3) == d); + assert_eq!(deq.len(), 4); + assert_eq!(*deq.get(0), a); + assert_eq!(*deq.get(1), b); + assert_eq!(*deq.get(2), c); + assert_eq!(*deq.get(3), d); } #[deriving(Eq)] diff --git a/src/libstd/dlist.rs b/src/libstd/dlist.rs index 84bd803afe7e5..e0b4d746d5317 100644 --- a/src/libstd/dlist.rs +++ b/src/libstd/dlist.rs @@ -438,7 +438,7 @@ pub impl DList { link = nobe.next_link(); count += 1; } - assert!(count == self.len()); + assert_eq!(count, self.len()); // iterate backwards - some of this is probably redundant. link = self.peek_tail_n(); rabbit = link; @@ -459,7 +459,7 @@ pub impl DList { link = nobe.prev_link(); count -= 1; } - assert!(count == 0); + assert_eq!(count, 0); } } diff --git a/src/libstd/ebml.rs b/src/libstd/ebml.rs index 64f78d5ab7b2b..8d550081d1e7a 100644 --- a/src/libstd/ebml.rs +++ b/src/libstd/ebml.rs @@ -273,22 +273,22 @@ pub mod reader { pub fn doc_as_str(d: Doc) -> ~str { str::from_bytes(doc_data(d)) } pub fn doc_as_u8(d: Doc) -> u8 { - assert!(d.end == d.start + 1u); + assert_eq!(d.end, d.start + 1u); (*d.data)[d.start] } pub fn doc_as_u16(d: Doc) -> u16 { - assert!(d.end == d.start + 2u); + assert_eq!(d.end, d.start + 2u); io::u64_from_be_bytes(*d.data, d.start, 2u) as u16 } pub fn doc_as_u32(d: Doc) -> u32 { - assert!(d.end == d.start + 4u); + assert_eq!(d.end, d.start + 4u); io::u64_from_be_bytes(*d.data, d.start, 4u) as u32 } pub fn doc_as_u64(d: Doc) -> u64 { - assert!(d.end == d.start + 8u); + assert_eq!(d.end, d.start + 8u); io::u64_from_be_bytes(*d.data, d.start, 8u) } @@ -988,7 +988,7 @@ mod tests { let mut deser = reader::Decoder(ebml_doc); let v1 = serialize::Decodable::decode(&mut deser); debug!("v1 == %?", v1); - assert!(v == v1); + assert_eq!(v, v1); } test_v(Some(22)); diff --git a/src/libstd/flate.rs b/src/libstd/flate.rs index 7485f2645bdf2..b0d219bc945e9 100644 --- a/src/libstd/flate.rs +++ b/src/libstd/flate.rs @@ -102,6 +102,6 @@ fn test_flate_round_trip() { debug!("%u bytes deflated to %u (%.1f%% size)", in.len(), cmp.len(), 100.0 * ((cmp.len() as float) / (in.len() as float))); - assert!((in == out)); + assert_eq!(in, out); } } diff --git a/src/libstd/flatpipes.rs b/src/libstd/flatpipes.rs index f4b581f84fc0d..a634f88dcf577 100644 --- a/src/libstd/flatpipes.rs +++ b/src/libstd/flatpipes.rs @@ -356,7 +356,7 @@ pub mod flatteners { impl Unflattener for PodUnflattener { fn unflatten(&self, buf: ~[u8]) -> T { assert!(size_of::() != 0); - assert!(size_of::() == buf.len()); + assert_eq!(size_of::(), buf.len()); let addr_of_init: &u8 = unsafe { &*vec::raw::to_ptr(buf) }; let addr_of_value: &T = unsafe { cast::transmute(addr_of_init) }; copy *addr_of_value @@ -652,7 +652,7 @@ mod test { let port = serial::reader_port(reader); let res: int = port.recv(); - assert!(res == 10i); + assert_eq!(res, 10i); } #[test] @@ -700,7 +700,7 @@ mod test { let port = pod::reader_port(reader); let res: int = port.recv(); - assert!(res == 10); + assert_eq!(res, 10); } #[test] @@ -843,7 +843,7 @@ mod test { for int::range(0, 10) |i| { let j = port.recv(); debug!("received %?", j); - assert!(i == j); + assert_eq!(i, j); } // The test is over! diff --git a/src/libstd/future.rs b/src/libstd/future.rs index 93b6540a40d28..02828b8eaee9e 100644 --- a/src/libstd/future.rs +++ b/src/libstd/future.rs @@ -154,7 +154,7 @@ mod test { #[test] fn test_from_value() { let mut f = from_value(~"snail"); - assert!(f.get() == ~"snail"); + assert_eq!(f.get(), ~"snail"); } #[test] @@ -162,31 +162,31 @@ mod test { let (po, ch) = oneshot(); send_one(ch, ~"whale"); let mut f = from_port(po); - assert!(f.get() == ~"whale"); + assert_eq!(f.get(), ~"whale"); } #[test] fn test_from_fn() { let mut f = from_fn(|| ~"brail"); - assert!(f.get() == ~"brail"); + assert_eq!(f.get(), ~"brail"); } #[test] fn test_interface_get() { let mut f = from_value(~"fail"); - assert!(f.get() == ~"fail"); + assert_eq!(f.get(), ~"fail"); } #[test] fn test_get_ref_method() { let mut f = from_value(22); - assert!(*f.get_ref() == 22); + assert_eq!(*f.get_ref(), 22); } #[test] fn test_spawn() { let mut f = spawn(|| ~"bale"); - assert!(f.get() == ~"bale"); + assert_eq!(f.get(), ~"bale"); } #[test] @@ -204,7 +204,7 @@ mod test { do task::spawn { let mut f = f.take(); let actual = f.get(); - assert!(actual == expected); + assert_eq!(actual, expected); } } } diff --git a/src/libstd/getopts.rs b/src/libstd/getopts.rs index 1cb6312445696..d0b298deb8984 100644 --- a/src/libstd/getopts.rs +++ b/src/libstd/getopts.rs @@ -684,7 +684,7 @@ mod tests { match rs { Ok(ref m) => { assert!((opt_present(m, ~"test"))); - assert!((opt_str(m, ~"test") == ~"20")); + assert_eq!(opt_str(m, ~"test"), ~"20"); } _ => { fail!("test_reqopt_long failed"); } } @@ -731,7 +731,7 @@ mod tests { match rs { Ok(ref m) => { assert!((opt_present(m, ~"t"))); - assert!((opt_str(m, ~"t") == ~"20")); + assert_eq!(opt_str(m, ~"t"), ~"20"); } _ => fail!() } @@ -780,7 +780,7 @@ mod tests { match rs { Ok(ref m) => { assert!((opt_present(m, ~"test"))); - assert!((opt_str(m, ~"test") == ~"20")); + assert_eq!(opt_str(m, ~"test"), ~"20"); } _ => fail!() } @@ -827,7 +827,7 @@ mod tests { match rs { Ok(ref m) => { assert!((opt_present(m, ~"t"))); - assert!((opt_str(m, ~"t") == ~"20")); + assert_eq!(opt_str(m, ~"t"), ~"20"); } _ => fail!() } @@ -946,7 +946,7 @@ mod tests { Ok(ref m) => { // The next variable after the flag is just a free argument - assert!((m.free[0] == ~"20")); + assert!(m.free[0] == ~"20"); } _ => fail!() } @@ -971,7 +971,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_count(m, ~"v") == 1)); + assert_eq!(opt_count(m, ~"v"), 1); } _ => fail!() } @@ -984,7 +984,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_count(m, ~"v") == 2)); + assert_eq!(opt_count(m, ~"v"), 2); } _ => fail!() } @@ -997,7 +997,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_count(m, ~"v") == 2)); + assert_eq!(opt_count(m, ~"v"), 2); } _ => fail!() } @@ -1010,7 +1010,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_count(m, ~"verbose") == 1)); + assert_eq!(opt_count(m, ~"verbose"), 1); } _ => fail!() } @@ -1023,7 +1023,7 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_count(m, ~"verbose") == 2)); + assert_eq!(opt_count(m, ~"verbose"), 2); } _ => fail!() } @@ -1038,7 +1038,7 @@ mod tests { match rs { Ok(ref m) => { assert!((opt_present(m, ~"test"))); - assert!((opt_str(m, ~"test") == ~"20")); + assert_eq!(opt_str(m, ~"test"), ~"20"); } _ => fail!() } @@ -1073,11 +1073,11 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"test"))); - assert!((opt_str(m, ~"test") == ~"20")); + assert!(opt_present(m, ~"test")); + assert_eq!(opt_str(m, ~"test"), ~"20"); let pair = opt_strs(m, ~"test"); - assert!((pair[0] == ~"20")); - assert!((pair[1] == ~"30")); + assert!(pair[0] == ~"20"); + assert!(pair[1] == ~"30"); } _ => fail!() } @@ -1091,7 +1091,7 @@ mod tests { match rs { Ok(ref m) => { assert!((opt_present(m, ~"t"))); - assert!((opt_str(m, ~"t") == ~"20")); + assert_eq!(opt_str(m, ~"t"), ~"20"); } _ => fail!() } @@ -1127,10 +1127,10 @@ mod tests { match rs { Ok(ref m) => { assert!((opt_present(m, ~"t"))); - assert!((opt_str(m, ~"t") == ~"20")); + assert_eq!(opt_str(m, ~"t"), ~"20"); let pair = opt_strs(m, ~"t"); - assert!((pair[0] == ~"20")); - assert!((pair[1] == ~"30")); + assert!(pair[0] == ~"20"); + assert!(pair[1] == ~"30"); } _ => fail!() } @@ -1171,19 +1171,19 @@ mod tests { let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((m.free[0] == ~"prog")); - assert!((m.free[1] == ~"free1")); - assert!((opt_str(m, ~"s") == ~"20")); - assert!((m.free[2] == ~"free2")); + assert!(m.free[0] == ~"prog"); + assert!(m.free[1] == ~"free1"); + assert_eq!(opt_str(m, ~"s"), ~"20"); + assert!(m.free[2] == ~"free2"); assert!((opt_present(m, ~"flag"))); - assert!((opt_str(m, ~"long") == ~"30")); + assert_eq!(opt_str(m, ~"long"), ~"30"); assert!((opt_present(m, ~"f"))); let pair = opt_strs(m, ~"m"); - assert!((pair[0] == ~"40")); - assert!((pair[1] == ~"50")); + assert!(pair[0] == ~"40"); + assert!(pair[1] == ~"50"); let pair = opt_strs(m, ~"n"); - assert!((pair[0] == ~"-A B")); - assert!((pair[1] == ~"-60 70")); + assert!(pair[0] == ~"-A B"); + assert!(pair[1] == ~"-60 70"); assert!((!opt_present(m, ~"notpresent"))); } _ => fail!() @@ -1206,10 +1206,10 @@ mod tests { assert!(!opts_present(matches, ~[~"thing"])); assert!(!opts_present(matches, ~[])); - assert!(opts_str(matches, ~[~"e"]) == ~"foo"); - assert!(opts_str(matches, ~[~"encrypt"]) == ~"foo"); - assert!(opts_str(matches, ~[~"e", ~"encrypt"]) == ~"foo"); - assert!(opts_str(matches, ~[~"encrypt", ~"e"]) == ~"foo"); + assert_eq!(opts_str(matches, ~[~"e"]), ~"foo"); + assert_eq!(opts_str(matches, ~[~"encrypt"]), ~"foo"); + assert_eq!(opts_str(matches, ~[~"e", ~"encrypt"]), ~"foo"); + assert_eq!(opts_str(matches, ~[~"encrypt", ~"e"]), ~"foo"); } #[test] @@ -1221,9 +1221,9 @@ mod tests { result::Err(_) => fail!() }; assert!(opts_present(matches, ~[~"L"])); - assert!(opts_str(matches, ~[~"L"]) == ~"foo"); + assert_eq!(opts_str(matches, ~[~"L"]), ~"foo"); assert!(opts_present(matches, ~[~"M"])); - assert!(opts_str(matches, ~[~"M"]) == ~"."); + assert_eq!(opts_str(matches, ~[~"M"]), ~"."); } @@ -1290,7 +1290,7 @@ mod tests { let verbose = groups::reqopt(~"b", ~"banana", ~"some bananas", ~"VAL"); - assert!(groups::long_to_short(&verbose) == short); + assert_eq!(groups::long_to_short(&verbose), short); } #[test] @@ -1347,7 +1347,7 @@ Options: debug!("expected: <<%s>>", expected); debug!("generated: <<%s>>", generated_usage); - assert!(generated_usage == expected); + assert_eq!(generated_usage, expected); } #[test] diff --git a/src/libstd/list.rs b/src/libstd/list.rs index aa4abbac9d3d1..ae3251b961c18 100644 --- a/src/libstd/list.rs +++ b/src/libstd/list.rs @@ -228,19 +228,19 @@ mod tests { fn test_from_vec() { let l = from_vec(~[0, 1, 2]); - assert!((head(l) == 0)); + assert_eq!(head(l), 0); let tail_l = tail(l); - assert!((head(tail_l) == 1)); + assert_eq!(head(tail_l), 1); let tail_tail_l = tail(tail_l); - assert!((head(tail_tail_l) == 2)); + assert_eq!(head(tail_tail_l), 2); } #[test] fn test_from_vec_empty() { let empty : @list::List = from_vec(~[]); - assert!((empty == @list::Nil::)); + assert_eq!(empty, @list::Nil::); } #[test] @@ -248,8 +248,8 @@ mod tests { fn add(a: &uint, b: &int) -> uint { return *a + (*b as uint); } let l = from_vec(~[0, 1, 2, 3, 4]); let empty = @list::Nil::; - assert!((list::foldl(0u, l, add) == 10u)); - assert!((list::foldl(0u, empty, add) == 0u)); + assert_eq!(list::foldl(0u, l, add), 10u); + assert_eq!(list::foldl(0u, empty, add), 0u); } #[test] @@ -258,14 +258,14 @@ mod tests { *a - *b } let l = from_vec(~[1, 2, 3, 4]); - assert!((list::foldl(0, l, sub) == -10)); + assert_eq!(list::foldl(0, l, sub), -10); } #[test] fn test_find_success() { fn match_(i: &int) -> bool { return *i == 2; } let l = from_vec(~[0, 1, 2]); - assert!((list::find(l, match_) == option::Some(2))); + assert_eq!(list::find(l, match_), option::Some(2)); } #[test] @@ -273,8 +273,8 @@ mod tests { fn match_(_i: &int) -> bool { return false; } let l = from_vec(~[0, 1, 2]); let empty = @list::Nil::; - assert!((list::find(l, match_) == option::None::)); - assert!((list::find(empty, match_) == option::None::)); + assert_eq!(list::find(l, match_), option::None::); + assert_eq!(list::find(empty, match_), option::None::); } #[test] @@ -291,8 +291,8 @@ mod tests { fn test_len() { let l = from_vec(~[0, 1, 2]); let empty = @list::Nil::; - assert!((list::len(l) == 3u)); - assert!((list::len(empty) == 0u)); + assert_eq!(list::len(l), 3u); + assert_eq!(list::len(empty), 0u); } #[test] diff --git a/src/libstd/md4.rs b/src/libstd/md4.rs index 84561256cd1dd..19cd418915e74 100644 --- a/src/libstd/md4.rs +++ b/src/libstd/md4.rs @@ -125,9 +125,9 @@ pub fn md4_text(msg: &str) -> ~str { md4_str(str::to_bytes(msg)) } #[test] fn test_md4() { - assert!(md4_text(~"") == ~"31d6cfe0d16ae931b73c59d7e0c089c0"); - assert!(md4_text(~"a") == ~"bde52cb31de33e46245e05fbdbd6fb24"); - assert!(md4_text(~"abc") == ~"a448017aaf21d8525fc10ae87aa6729d"); + assert_eq!(md4_text(~""), ~"31d6cfe0d16ae931b73c59d7e0c089c0"); + assert_eq!(md4_text(~"a"), ~"bde52cb31de33e46245e05fbdbd6fb24"); + assert_eq!(md4_text(~"abc"), ~"a448017aaf21d8525fc10ae87aa6729d"); assert!(md4_text(~"message digest") == ~"d9130a8164549fe818874806e1c7014b"); assert!(md4_text(~"abcdefghijklmnopqrstuvwxyz") == diff --git a/src/libstd/net_ip.rs b/src/libstd/net_ip.rs index cc4e7ee02046d..4f67f1c5f1351 100644 --- a/src/libstd/net_ip.rs +++ b/src/libstd/net_ip.rs @@ -383,7 +383,7 @@ mod test { let format_result = format_addr(&v6::parse_addr(localhost_str)); debug!("results: expected: '%s' actual: '%s'", localhost_str, format_result); - assert!(format_result == localhost_str); + assert_eq!(format_result, localhost_str); } #[test] fn test_ip_ipv4_bad_parse() { diff --git a/src/libstd/net_tcp.rs b/src/libstd/net_tcp.rs index 37578e42baff4..db61679890b27 100644 --- a/src/libstd/net_tcp.rs +++ b/src/libstd/net_tcp.rs @@ -1623,7 +1623,7 @@ mod test { // This is what we are actually testing! assert!(net::ip::format_addr(&sock.get_peer_addr()) == ~"127.0.0.1"); - assert!(net::ip::get_port(&sock.get_peer_addr()) == 8887); + assert_eq!(net::ip::get_port(&sock.get_peer_addr()), 8887); // Fulfill the protocol the test server expects let resp_bytes = str::to_bytes(~"ping"); diff --git a/src/libstd/net_url.rs b/src/libstd/net_url.rs index e7cf710cf6797..ef503817b55af 100644 --- a/src/libstd/net_url.rs +++ b/src/libstd/net_url.rs @@ -722,53 +722,53 @@ impl IterBytes for Url { #[test] fn test_split_char_first() { let (u,v) = split_char_first(~"hello, sweet world", ','); - assert!(u == ~"hello"); - assert!(v == ~" sweet world"); + assert_eq!(u, ~"hello"); + assert_eq!(v, ~" sweet world"); let (u,v) = split_char_first(~"hello sweet world", ','); - assert!(u == ~"hello sweet world"); - assert!(v == ~""); + assert_eq!(u, ~"hello sweet world"); + assert_eq!(v, ~""); } #[test] fn test_get_authority() { let (u, h, p, r) = get_authority( "//user:pass@rust-lang.org/something").unwrap(); - assert!(u == Some(UserInfo::new(~"user", Some(~"pass")))); - assert!(h == ~"rust-lang.org"); + assert_eq!(u, Some(UserInfo::new(~"user", Some(~"pass")))); + assert_eq!(h, ~"rust-lang.org"); assert!(p.is_none()); - assert!(r == ~"/something"); + assert_eq!(r, ~"/something"); let (u, h, p, r) = get_authority( "//rust-lang.org:8000?something").unwrap(); assert!(u.is_none()); - assert!(h == ~"rust-lang.org"); - assert!(p == Some(~"8000")); - assert!(r == ~"?something"); + assert_eq!(h, ~"rust-lang.org"); + assert_eq!(p, Some(~"8000")); + assert_eq!(r, ~"?something"); let (u, h, p, r) = get_authority( "//rust-lang.org#blah").unwrap(); assert!(u.is_none()); - assert!(h == ~"rust-lang.org"); + assert_eq!(h, ~"rust-lang.org"); assert!(p.is_none()); - assert!(r == ~"#blah"); + assert_eq!(r, ~"#blah"); // ipv6 tests let (_, h, _, _) = get_authority( "//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").unwrap(); - assert!(h == ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); + assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); let (_, h, p, _) = get_authority( "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").unwrap(); - assert!(h == ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); - assert!(p == Some(~"8000")); + assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); + assert_eq!(p, Some(~"8000")); let (u, h, p, _) = get_authority( "//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah" ).unwrap(); - assert!(u == Some(UserInfo::new(~"us", Some(~"p")))); - assert!(h == ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); - assert!(p == Some(~"8000")); + assert_eq!(u, Some(UserInfo::new(~"us", Some(~"p")))); + assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); + assert_eq!(p, Some(~"8000")); // invalid authorities; assert!(get_authority("//user:pass@rust-lang:something").is_err()); @@ -780,22 +780,22 @@ fn test_get_authority() { // these parse as empty, because they don't start with '//' let (_, h, _, _) = get_authority(~"user:pass@rust-lang").unwrap(); - assert!(h == ~""); + assert_eq!(h, ~""); let (_, h, _, _) = get_authority(~"rust-lang.org").unwrap(); - assert!(h == ~""); + assert_eq!(h, ~""); } #[test] fn test_get_path() { let (p, r) = get_path("/something+%20orother", true).unwrap(); - assert!(p == ~"/something+ orother"); - assert!(r == ~""); + assert_eq!(p, ~"/something+ orother"); + assert_eq!(r, ~""); let (p, r) = get_path("test@email.com#fragment", false).unwrap(); - assert!(p == ~"test@email.com"); - assert!(r == ~"#fragment"); + assert_eq!(p, ~"test@email.com"); + assert_eq!(r, ~"#fragment"); let (p, r) = get_path(~"/gen/:addr=?q=v", false).unwrap(); - assert!(p == ~"/gen/:addr="); - assert!(r == ~"?q=v"); + assert_eq!(p, ~"/gen/:addr="); + assert_eq!(r, ~"?q=v"); //failure cases assert!(get_path(~"something?q", true).is_err()); @@ -860,56 +860,56 @@ mod tests { #[test] fn test_full_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc?s=v#something"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_userless_url_parse_and_format() { let url = ~"http://rust-lang.org/doc?s=v#something"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_queryless_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc#something"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_empty_query_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc?#something"; let should_be = ~"http://user:pass@rust-lang.org/doc#something"; - assert!(from_str(url).unwrap().to_str() == should_be); + assert_eq!(from_str(url).unwrap().to_str(), should_be); } #[test] fn test_fragmentless_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc?q=v"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_minimal_url_parse_and_format() { let url = ~"http://rust-lang.org/doc"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_scheme_host_only_url_parse_and_format() { let url = ~"http://rust-lang.org"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_pathless_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org?q=v#something"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_scheme_host_fragment_only_url_parse_and_format() { let url = ~"http://rust-lang.org#something"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] @@ -923,134 +923,134 @@ mod tests { #[test] fn test_url_without_authority() { let url = ~"mailto:test@email.com"; - assert!(from_str(url).unwrap().to_str() == url); + assert_eq!(from_str(url).unwrap().to_str(), url); } #[test] fn test_encode() { - assert!(encode("") == ~""); - assert!(encode("http://example.com") == ~"http://example.com"); - assert!(encode("foo bar% baz") == ~"foo%20bar%25%20baz"); - assert!(encode(" ") == ~"%20"); - assert!(encode("!") == ~"!"); - assert!(encode("\"") == ~"\""); - assert!(encode("#") == ~"#"); - assert!(encode("$") == ~"$"); - assert!(encode("%") == ~"%25"); - assert!(encode("&") == ~"&"); - assert!(encode("'") == ~"%27"); - assert!(encode("(") == ~"("); - assert!(encode(")") == ~")"); - assert!(encode("*") == ~"*"); - assert!(encode("+") == ~"+"); - assert!(encode(",") == ~","); - assert!(encode("/") == ~"/"); - assert!(encode(":") == ~":"); - assert!(encode(";") == ~";"); - assert!(encode("=") == ~"="); - assert!(encode("?") == ~"?"); - assert!(encode("@") == ~"@"); - assert!(encode("[") == ~"["); - assert!(encode("]") == ~"]"); + assert_eq!(encode(""), ~""); + assert_eq!(encode("http://example.com"), ~"http://example.com"); + assert_eq!(encode("foo bar% baz"), ~"foo%20bar%25%20baz"); + assert_eq!(encode(" "), ~"%20"); + assert_eq!(encode("!"), ~"!"); + assert_eq!(encode("\""), ~"\""); + assert_eq!(encode("#"), ~"#"); + assert_eq!(encode("$"), ~"$"); + assert_eq!(encode("%"), ~"%25"); + assert_eq!(encode("&"), ~"&"); + assert_eq!(encode("'"), ~"%27"); + assert_eq!(encode("("), ~"("); + assert_eq!(encode(")"), ~")"); + assert_eq!(encode("*"), ~"*"); + assert_eq!(encode("+"), ~"+"); + assert_eq!(encode(","), ~","); + assert_eq!(encode("/"), ~"/"); + assert_eq!(encode(":"), ~":"); + assert_eq!(encode(";"), ~";"); + assert_eq!(encode("="), ~"="); + assert_eq!(encode("?"), ~"?"); + assert_eq!(encode("@"), ~"@"); + assert_eq!(encode("["), ~"["); + assert_eq!(encode("]"), ~"]"); } #[test] fn test_encode_component() { - assert!(encode_component("") == ~""); + assert_eq!(encode_component(""), ~""); assert!(encode_component("http://example.com") == ~"http%3A%2F%2Fexample.com"); assert!(encode_component("foo bar% baz") == ~"foo%20bar%25%20baz"); - assert!(encode_component(" ") == ~"%20"); - assert!(encode_component("!") == ~"%21"); - assert!(encode_component("#") == ~"%23"); - assert!(encode_component("$") == ~"%24"); - assert!(encode_component("%") == ~"%25"); - assert!(encode_component("&") == ~"%26"); - assert!(encode_component("'") == ~"%27"); - assert!(encode_component("(") == ~"%28"); - assert!(encode_component(")") == ~"%29"); - assert!(encode_component("*") == ~"%2A"); - assert!(encode_component("+") == ~"%2B"); - assert!(encode_component(",") == ~"%2C"); - assert!(encode_component("/") == ~"%2F"); - assert!(encode_component(":") == ~"%3A"); - assert!(encode_component(";") == ~"%3B"); - assert!(encode_component("=") == ~"%3D"); - assert!(encode_component("?") == ~"%3F"); - assert!(encode_component("@") == ~"%40"); - assert!(encode_component("[") == ~"%5B"); - assert!(encode_component("]") == ~"%5D"); + assert_eq!(encode_component(" "), ~"%20"); + assert_eq!(encode_component("!"), ~"%21"); + assert_eq!(encode_component("#"), ~"%23"); + assert_eq!(encode_component("$"), ~"%24"); + assert_eq!(encode_component("%"), ~"%25"); + assert_eq!(encode_component("&"), ~"%26"); + assert_eq!(encode_component("'"), ~"%27"); + assert_eq!(encode_component("("), ~"%28"); + assert_eq!(encode_component(")"), ~"%29"); + assert_eq!(encode_component("*"), ~"%2A"); + assert_eq!(encode_component("+"), ~"%2B"); + assert_eq!(encode_component(","), ~"%2C"); + assert_eq!(encode_component("/"), ~"%2F"); + assert_eq!(encode_component(":"), ~"%3A"); + assert_eq!(encode_component(";"), ~"%3B"); + assert_eq!(encode_component("="), ~"%3D"); + assert_eq!(encode_component("?"), ~"%3F"); + assert_eq!(encode_component("@"), ~"%40"); + assert_eq!(encode_component("["), ~"%5B"); + assert_eq!(encode_component("]"), ~"%5D"); } #[test] fn test_decode() { - assert!(decode("") == ~""); - assert!(decode("abc/def 123") == ~"abc/def 123"); - assert!(decode("abc%2Fdef%20123") == ~"abc%2Fdef 123"); - assert!(decode("%20") == ~" "); - assert!(decode("%21") == ~"%21"); - assert!(decode("%22") == ~"%22"); - assert!(decode("%23") == ~"%23"); - assert!(decode("%24") == ~"%24"); - assert!(decode("%25") == ~"%"); - assert!(decode("%26") == ~"%26"); - assert!(decode("%27") == ~"'"); - assert!(decode("%28") == ~"%28"); - assert!(decode("%29") == ~"%29"); - assert!(decode("%2A") == ~"%2A"); - assert!(decode("%2B") == ~"%2B"); - assert!(decode("%2C") == ~"%2C"); - assert!(decode("%2F") == ~"%2F"); - assert!(decode("%3A") == ~"%3A"); - assert!(decode("%3B") == ~"%3B"); - assert!(decode("%3D") == ~"%3D"); - assert!(decode("%3F") == ~"%3F"); - assert!(decode("%40") == ~"%40"); - assert!(decode("%5B") == ~"%5B"); - assert!(decode("%5D") == ~"%5D"); + assert_eq!(decode(""), ~""); + assert_eq!(decode("abc/def 123"), ~"abc/def 123"); + assert_eq!(decode("abc%2Fdef%20123"), ~"abc%2Fdef 123"); + assert_eq!(decode("%20"), ~" "); + assert_eq!(decode("%21"), ~"%21"); + assert_eq!(decode("%22"), ~"%22"); + assert_eq!(decode("%23"), ~"%23"); + assert_eq!(decode("%24"), ~"%24"); + assert_eq!(decode("%25"), ~"%"); + assert_eq!(decode("%26"), ~"%26"); + assert_eq!(decode("%27"), ~"'"); + assert_eq!(decode("%28"), ~"%28"); + assert_eq!(decode("%29"), ~"%29"); + assert_eq!(decode("%2A"), ~"%2A"); + assert_eq!(decode("%2B"), ~"%2B"); + assert_eq!(decode("%2C"), ~"%2C"); + assert_eq!(decode("%2F"), ~"%2F"); + assert_eq!(decode("%3A"), ~"%3A"); + assert_eq!(decode("%3B"), ~"%3B"); + assert_eq!(decode("%3D"), ~"%3D"); + assert_eq!(decode("%3F"), ~"%3F"); + assert_eq!(decode("%40"), ~"%40"); + assert_eq!(decode("%5B"), ~"%5B"); + assert_eq!(decode("%5D"), ~"%5D"); } #[test] fn test_decode_component() { - assert!(decode_component("") == ~""); - assert!(decode_component("abc/def 123") == ~"abc/def 123"); - assert!(decode_component("abc%2Fdef%20123") == ~"abc/def 123"); - assert!(decode_component("%20") == ~" "); - assert!(decode_component("%21") == ~"!"); - assert!(decode_component("%22") == ~"\""); - assert!(decode_component("%23") == ~"#"); - assert!(decode_component("%24") == ~"$"); - assert!(decode_component("%25") == ~"%"); - assert!(decode_component("%26") == ~"&"); - assert!(decode_component("%27") == ~"'"); - assert!(decode_component("%28") == ~"("); - assert!(decode_component("%29") == ~")"); - assert!(decode_component("%2A") == ~"*"); - assert!(decode_component("%2B") == ~"+"); - assert!(decode_component("%2C") == ~","); - assert!(decode_component("%2F") == ~"/"); - assert!(decode_component("%3A") == ~":"); - assert!(decode_component("%3B") == ~";"); - assert!(decode_component("%3D") == ~"="); - assert!(decode_component("%3F") == ~"?"); - assert!(decode_component("%40") == ~"@"); - assert!(decode_component("%5B") == ~"["); - assert!(decode_component("%5D") == ~"]"); + assert_eq!(decode_component(""), ~""); + assert_eq!(decode_component("abc/def 123"), ~"abc/def 123"); + assert_eq!(decode_component("abc%2Fdef%20123"), ~"abc/def 123"); + assert_eq!(decode_component("%20"), ~" "); + assert_eq!(decode_component("%21"), ~"!"); + assert_eq!(decode_component("%22"), ~"\""); + assert_eq!(decode_component("%23"), ~"#"); + assert_eq!(decode_component("%24"), ~"$"); + assert_eq!(decode_component("%25"), ~"%"); + assert_eq!(decode_component("%26"), ~"&"); + assert_eq!(decode_component("%27"), ~"'"); + assert_eq!(decode_component("%28"), ~"("); + assert_eq!(decode_component("%29"), ~")"); + assert_eq!(decode_component("%2A"), ~"*"); + assert_eq!(decode_component("%2B"), ~"+"); + assert_eq!(decode_component("%2C"), ~","); + assert_eq!(decode_component("%2F"), ~"/"); + assert_eq!(decode_component("%3A"), ~":"); + assert_eq!(decode_component("%3B"), ~";"); + assert_eq!(decode_component("%3D"), ~"="); + assert_eq!(decode_component("%3F"), ~"?"); + assert_eq!(decode_component("%40"), ~"@"); + assert_eq!(decode_component("%5B"), ~"["); + assert_eq!(decode_component("%5D"), ~"]"); } #[test] fn test_encode_form_urlencoded() { let mut m = HashMap::new(); - assert!(encode_form_urlencoded(&m) == ~""); + assert_eq!(encode_form_urlencoded(&m), ~""); m.insert(~"", ~[]); m.insert(~"foo", ~[]); - assert!(encode_form_urlencoded(&m) == ~""); + assert_eq!(encode_form_urlencoded(&m), ~""); let mut m = HashMap::new(); m.insert(~"foo", ~[~"bar", ~"123"]); - assert!(encode_form_urlencoded(&m) == ~"foo=bar&foo=123"); + assert_eq!(encode_form_urlencoded(&m), ~"foo=bar&foo=123"); let mut m = HashMap::new(); m.insert(~"foo bar", ~[~"abc", ~"12 = 34"]); @@ -1063,13 +1063,13 @@ mod tests { // FIXME #4449: Commented out because this causes an ICE, but only // on FreeBSD /* - assert!(decode_form_urlencoded(~[]).len() == 0); + assert_eq!(decode_form_urlencoded(~[]).len(), 0); let s = str::to_bytes("a=1&foo+bar=abc&foo+bar=12+%3D+34"); let form = decode_form_urlencoded(s); - assert!(form.len() == 2); - assert!(form.get_ref(&~"a") == &~[~"1"]); - assert!(form.get_ref(&~"foo bar") == &~[~"abc", ~"12 = 34"]); + assert_eq!(form.len(), 2); + assert_eq!(form.get_ref(&~"a"), &~[~"1"]); + assert_eq!(form.get_ref(&~"foo bar"), &~[~"abc", ~"12 = 34"]); */ } } diff --git a/src/libstd/num/bigint.rs b/src/libstd/num/bigint.rs index c35415c53317c..21685b03c077d 100644 --- a/src/libstd/num/bigint.rs +++ b/src/libstd/num/bigint.rs @@ -238,7 +238,7 @@ impl Sub for BigUint { lo }; - assert!(borrow == 0); // <=> assert!((self >= other)); + assert_eq!(borrow, 0); // <=> assert!((self >= other)); return BigUint::new(diff); } } @@ -1170,7 +1170,7 @@ mod biguint_tests { if i == j { assert_eq!(ni.cmp(nj), Equal); assert_eq!(nj.cmp(ni), Equal); - assert!(ni == nj); + assert_eq!(ni, nj); assert!(!(ni != nj)); assert!(ni <= nj); assert!(ni >= nj); @@ -1200,7 +1200,7 @@ mod biguint_tests { #[test] fn test_shl() { fn check(v: ~[BigDigit], shift: uint, ans: ~[BigDigit]) { - assert!(BigUint::new(v) << shift == BigUint::new(ans)); + assert_eq!(BigUint::new(v) << shift, BigUint::new(ans)); } check(~[], 3, ~[]); @@ -1245,7 +1245,7 @@ mod biguint_tests { #[ignore(cfg(target_arch = "mips"))] fn test_shr() { fn check(v: ~[BigDigit], shift: uint, ans: ~[BigDigit]) { - assert!(BigUint::new(v) >> shift == BigUint::new(ans)); + assert_eq!(BigUint::new(v) >> shift, BigUint::new(ans)); } check(~[], 3, ~[]); @@ -1298,9 +1298,9 @@ mod biguint_tests { check(~[ 0, 1], ((uint::max_value >> BigDigit::bits) + 1) as int); check(~[-1, -1 >> 1], int::max_value); - assert!(BigUint::new(~[0, -1]).to_int() == int::max_value); - assert!(BigUint::new(~[0, 0, 1]).to_int() == int::max_value); - assert!(BigUint::new(~[0, 0, -1]).to_int() == int::max_value); + assert_eq!(BigUint::new(~[0, -1]).to_int(), int::max_value); + assert_eq!(BigUint::new(~[0, 0, 1]).to_int(), int::max_value); + assert_eq!(BigUint::new(~[0, 0, -1]).to_int(), int::max_value); } #[test] @@ -1318,8 +1318,8 @@ mod biguint_tests { check(~[ 0, -1], uint::max_value << BigDigit::bits); check(~[-1, -1], uint::max_value); - assert!(BigUint::new(~[0, 0, 1]).to_uint() == uint::max_value); - assert!(BigUint::new(~[0, 0, -1]).to_uint() == uint::max_value); + assert_eq!(BigUint::new(~[0, 0, 1]).to_uint(), uint::max_value); + assert_eq!(BigUint::new(~[0, 0, -1]).to_uint(), uint::max_value); } static sum_triples: &'static [(&'static [BigDigit], @@ -1433,10 +1433,10 @@ mod biguint_tests { let c = BigUint::from_slice(cVec); if !a.is_zero() { - assert!(c.div_rem(&a) == (b.clone(), Zero::zero())); + assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero())); } if !b.is_zero() { - assert!(c.div_rem(&b) == (a.clone(), Zero::zero())); + assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero())); } } @@ -1560,7 +1560,7 @@ mod biguint_tests { let &(n, rs) = num_pair; for rs.each |str_pair| { let &(radix, str) = str_pair; - assert!(n.to_str_radix(radix) == str); + assert_eq!(n.to_str_radix(radix), str); } } } @@ -1597,7 +1597,7 @@ mod biguint_tests { let ans = match FromStrRadix::from_str_radix(s, 10) { Some(x) => x, None => fail!() }; - assert!(n == ans); + assert_eq!(n, ans); } check(3, "6"); @@ -1618,7 +1618,7 @@ mod bigint_tests { fn check(inp_s: Sign, inp_n: uint, ans_s: Sign, ans_n: uint) { let inp = BigInt::from_biguint(inp_s, BigUint::from_uint(inp_n)); let ans = BigInt { sign: ans_s, data: BigUint::from_uint(ans_n)}; - assert!(inp == ans); + assert_eq!(inp, ans); } check(Plus, 1, Plus, 1); check(Plus, 0, Zero, 0); @@ -1640,7 +1640,7 @@ mod bigint_tests { if i == j { assert_eq!(ni.cmp(nj), Equal); assert_eq!(nj.cmp(ni), Equal); - assert!(ni == nj); + assert_eq!(ni, nj); assert!(!(ni != nj)); assert!(ni <= nj); assert!(ni >= nj); @@ -1751,7 +1751,7 @@ mod bigint_tests { assert!(c + (-b) == a); assert!(a + (-c) == (-b)); assert!(b + (-c) == (-a)); - assert!((-a) + (-b) == (-c)); + assert!((-a) + (-b) == (-c)) assert!(a + (-a) == Zero::zero()); } } @@ -1766,8 +1766,8 @@ mod bigint_tests { assert!(c - a == b); assert!(c - b == a); - assert!((-b) - a == (-c)); - assert!((-a) - b == (-c)); + assert!((-b) - a == (-c)) + assert!((-a) - b == (-c)) assert!(b - (-a) == c); assert!(a - (-b) == c); assert!((-c) - (-a) == (-b)); @@ -1845,7 +1845,7 @@ mod bigint_tests { fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) { let (d, m) = a.div_mod_floor(b); if !m.is_zero() { - assert!(m.sign == b.sign); + assert_eq!(m.sign, b.sign); } assert!(m.abs() <= b.abs()); assert!(*a == b * d + m); @@ -1896,7 +1896,7 @@ mod bigint_tests { fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) { let (q, r) = a.div_rem(b); if !r.is_zero() { - assert!(r.sign == a.sign); + assert_eq!(r.sign, a.sign); } assert!(r.abs() <= b.abs()); assert!(*a == b * q + r); @@ -1999,7 +1999,7 @@ mod bigint_tests { fn test_from_str_radix() { fn check(s: &str, ans: Option) { let ans = ans.map(|&n| IntConvertible::from_int::(n)); - assert!(FromStrRadix::from_str_radix(s, 10) == ans); + assert_eq!(FromStrRadix::from_str_radix(s, 10), ans); } check("10", Some(10)); check("1", Some(1)); @@ -2016,6 +2016,6 @@ mod bigint_tests { BigInt::new(Minus, ~[1, 1, 1])); assert!(-BigInt::new(Minus, ~[1, 1, 1]) == BigInt::new(Plus, ~[1, 1, 1])); - assert!(-Zero::zero::() == Zero::zero::()); + assert_eq!(-Zero::zero::(), Zero::zero::()); } } diff --git a/src/libstd/par.rs b/src/libstd/par.rs index d1af484cb22bc..e766d2d3bf090 100644 --- a/src/libstd/par.rs +++ b/src/libstd/par.rs @@ -59,7 +59,7 @@ fn map_slices( let slice : &[A] = cast::transmute(slice); info!("slice: %?", (base, slice.len(), end - base)); - assert!(slice.len() == end - base); + assert_eq!(slice.len(), end - base); f(base, slice) } }; @@ -70,7 +70,7 @@ fn map_slices( info!("tasks spawned"); info!("num_tasks: %?", (num_tasks, futures.len())); - assert!((num_tasks == futures.len())); + assert_eq!(num_tasks, futures.len()); let r = do vec::map_consume(futures) |ys| { let mut ys = ys; @@ -106,7 +106,7 @@ pub fn mapi( }); let r = vec::concat(slices); info!("%?", (r.len(), xs.len())); - assert!((r.len() == xs.len())); + assert_eq!(r.len(), xs.len()); r } diff --git a/src/libstd/priority_queue.rs b/src/libstd/priority_queue.rs index 3c96a8e145d80..b54fc81aac11c 100644 --- a/src/libstd/priority_queue.rs +++ b/src/libstd/priority_queue.rs @@ -196,87 +196,87 @@ mod tests { let mut sorted = merge_sort(data, le); let mut heap = from_vec(data); while !heap.is_empty() { - assert!(heap.top() == sorted.last()); - assert!(heap.pop() == sorted.pop()); + assert_eq!(heap.top(), sorted.last()); + assert_eq!(heap.pop(), sorted.pop()); } } #[test] fn test_push() { let mut heap = from_vec(~[2, 4, 9]); - assert!(heap.len() == 3); + assert_eq!(heap.len(), 3); assert!(*heap.top() == 9); heap.push(11); - assert!(heap.len() == 4); + assert_eq!(heap.len(), 4); assert!(*heap.top() == 11); heap.push(5); - assert!(heap.len() == 5); + assert_eq!(heap.len(), 5); assert!(*heap.top() == 11); heap.push(27); - assert!(heap.len() == 6); + assert_eq!(heap.len(), 6); assert!(*heap.top() == 27); heap.push(3); - assert!(heap.len() == 7); + assert_eq!(heap.len(), 7); assert!(*heap.top() == 27); heap.push(103); - assert!(heap.len() == 8); + assert_eq!(heap.len(), 8); assert!(*heap.top() == 103); } #[test] fn test_push_unique() { let mut heap = from_vec(~[~2, ~4, ~9]); - assert!(heap.len() == 3); + assert_eq!(heap.len(), 3); assert!(*heap.top() == ~9); heap.push(~11); - assert!(heap.len() == 4); + assert_eq!(heap.len(), 4); assert!(*heap.top() == ~11); heap.push(~5); - assert!(heap.len() == 5); + assert_eq!(heap.len(), 5); assert!(*heap.top() == ~11); heap.push(~27); - assert!(heap.len() == 6); + assert_eq!(heap.len(), 6); assert!(*heap.top() == ~27); heap.push(~3); - assert!(heap.len() == 7); + assert_eq!(heap.len(), 7); assert!(*heap.top() == ~27); heap.push(~103); - assert!(heap.len() == 8); + assert_eq!(heap.len(), 8); assert!(*heap.top() == ~103); } #[test] fn test_push_pop() { let mut heap = from_vec(~[5, 5, 2, 1, 3]); - assert!(heap.len() == 5); - assert!(heap.push_pop(6) == 6); - assert!(heap.len() == 5); - assert!(heap.push_pop(0) == 5); - assert!(heap.len() == 5); - assert!(heap.push_pop(4) == 5); - assert!(heap.len() == 5); - assert!(heap.push_pop(1) == 4); - assert!(heap.len() == 5); + assert_eq!(heap.len(), 5); + assert_eq!(heap.push_pop(6), 6); + assert_eq!(heap.len(), 5); + assert_eq!(heap.push_pop(0), 5); + assert_eq!(heap.len(), 5); + assert_eq!(heap.push_pop(4), 5); + assert_eq!(heap.len(), 5); + assert_eq!(heap.push_pop(1), 4); + assert_eq!(heap.len(), 5); } #[test] fn test_replace() { let mut heap = from_vec(~[5, 5, 2, 1, 3]); - assert!(heap.len() == 5); - assert!(heap.replace(6) == 5); - assert!(heap.len() == 5); - assert!(heap.replace(0) == 6); - assert!(heap.len() == 5); - assert!(heap.replace(4) == 5); - assert!(heap.len() == 5); - assert!(heap.replace(1) == 4); - assert!(heap.len() == 5); + assert_eq!(heap.len(), 5); + assert_eq!(heap.replace(6), 5); + assert_eq!(heap.len(), 5); + assert_eq!(heap.replace(0), 6); + assert_eq!(heap.len(), 5); + assert_eq!(heap.replace(4), 5); + assert_eq!(heap.len(), 5); + assert_eq!(heap.replace(1), 4); + assert_eq!(heap.len(), 5); } fn check_to_vec(data: ~[int]) { let heap = from_vec(copy data); - assert!(merge_sort((copy heap).to_vec(), le) == merge_sort(data, le)); - assert!(heap.to_sorted_vec() == merge_sort(data, le)); + assert_eq!(merge_sort((copy heap).to_vec(), le), merge_sort(data, le)); + assert_eq!(heap.to_sorted_vec(), merge_sort(data, le)); } #[test] diff --git a/src/libstd/rc.rs b/src/libstd/rc.rs index 46f50eafec160..cc1492ba4489e 100644 --- a/src/libstd/rc.rs +++ b/src/libstd/rc.rs @@ -218,7 +218,7 @@ pub impl RcMut { #[inline] fn with_mut_borrow(&self, f: &fn(&mut T) -> U) -> U { unsafe { - assert!((*self.ptr).borrow == Nothing); + assert_eq!((*self.ptr).borrow, Nothing); (*self.ptr).borrow = Mutable; let res = f(&mut (*self.ptr).value); (*self.ptr).borrow = Nothing; diff --git a/src/libstd/rope.rs b/src/libstd/rope.rs index 9afa7262ce473..925f79b66c9b2 100644 --- a/src/libstd/rope.rs +++ b/src/libstd/rope.rs @@ -1281,8 +1281,8 @@ mod tests { #[test] fn trivial() { - assert!(char_len(empty()) == 0u); - assert!(byte_len(empty()) == 0u); + assert_eq!(char_len(empty()), 0u); + assert_eq!(byte_len(empty()), 0u); } #[test] @@ -1290,7 +1290,7 @@ mod tests { let sample = @~"0123456789ABCDE"; let r = of_str(sample); - assert!(char_len(r) == str::char_len(*sample)); + assert_eq!(char_len(r), str::char_len(*sample)); assert!(rope_to_string(r) == *sample); } @@ -1352,7 +1352,7 @@ mod tests { } } - assert!(len == str::char_len(*sample)); + assert_eq!(len, str::char_len(*sample)); } #[test] @@ -1375,7 +1375,7 @@ mod tests { assert!(eq(r1, r2)); let r3 = bal(r2); - assert!(char_len(r1) == char_len(r3)); + assert_eq!(char_len(r1), char_len(r3)); assert!(eq(r1, r3)); } diff --git a/src/libstd/semver.rs b/src/libstd/semver.rs index f6d1b1ba2ecd4..09855c9334e58 100644 --- a/src/libstd/semver.rs +++ b/src/libstd/semver.rs @@ -239,16 +239,16 @@ pub fn parse(s: &str) -> Option { #[test] fn test_parse() { - assert!(parse("") == None); - assert!(parse(" ") == None); - assert!(parse("1") == None); - assert!(parse("1.2") == None); - assert!(parse("1.2") == None); - assert!(parse("1") == None); - assert!(parse("1.2") == None); - assert!(parse("1.2.3-") == None); - assert!(parse("a.b.c") == None); - assert!(parse("1.2.3 abc") == None); + assert_eq!(parse(""), None); + assert_eq!(parse(" "), None); + assert_eq!(parse("1"), None); + assert_eq!(parse("1.2"), None); + assert_eq!(parse("1.2"), None); + assert_eq!(parse("1"), None); + assert_eq!(parse("1.2"), None); + assert_eq!(parse("1.2.3-"), None); + assert_eq!(parse("a.b.c"), None); + assert_eq!(parse("1.2.3 abc"), None); assert!(parse("1.2.3") == Some(Version { major: 1u, @@ -320,8 +320,8 @@ fn test_parse() { #[test] fn test_eq() { - assert!(parse("1.2.3") == parse("1.2.3")); - assert!(parse("1.2.3-alpha1") == parse("1.2.3-alpha1")); + assert_eq!(parse("1.2.3"), parse("1.2.3")); + assert_eq!(parse("1.2.3-alpha1"), parse("1.2.3-alpha1")); } #[test] diff --git a/src/libstd/serialize.rs b/src/libstd/serialize.rs index a5d2604b6f6db..c270f46751fcd 100644 --- a/src/libstd/serialize.rs +++ b/src/libstd/serialize.rs @@ -500,7 +500,7 @@ impl,T1:Encodable> Encodable for (T0, T1) { impl,T1:Decodable> Decodable for (T0, T1) { fn decode(d: &mut D) -> (T0, T1) { do d.read_seq |d, len| { - assert!(len == 2); + assert_eq!(len, 2); ( d.read_seq_elt(0, |d| Decodable::decode(d)), d.read_seq_elt(1, |d| Decodable::decode(d)) @@ -536,7 +536,7 @@ impl< > Decodable for (T0, T1, T2) { fn decode(d: &mut D) -> (T0, T1, T2) { do d.read_seq |d, len| { - assert!(len == 3); + assert_eq!(len, 3); ( d.read_seq_elt(0, |d| Decodable::decode(d)), d.read_seq_elt(1, |d| Decodable::decode(d)), @@ -576,7 +576,7 @@ impl< > Decodable for (T0, T1, T2, T3) { fn decode(d: &mut D) -> (T0, T1, T2, T3) { do d.read_seq |d, len| { - assert!(len == 4); + assert_eq!(len, 4); ( d.read_seq_elt(0, |d| Decodable::decode(d)), d.read_seq_elt(1, |d| Decodable::decode(d)), @@ -620,7 +620,7 @@ impl< > Decodable for (T0, T1, T2, T3, T4) { fn decode(d: &mut D) -> (T0, T1, T2, T3, T4) { do d.read_seq |d, len| { - assert!(len == 5); + assert_eq!(len, 5); ( d.read_seq_elt(0, |d| Decodable::decode(d)), d.read_seq_elt(1, |d| Decodable::decode(d)), diff --git a/src/libstd/sha1.rs b/src/libstd/sha1.rs index 6d8bf20d837ca..bb3be8a55ea3b 100644 --- a/src/libstd/sha1.rs +++ b/src/libstd/sha1.rs @@ -90,8 +90,8 @@ pub fn sha1() -> @Sha1 { } } fn process_msg_block(st: &mut Sha1State) { - assert!(st.h.len() == digest_buf_len); - assert!(vec::uniq_len(st.work_buf) == work_buf_len); + assert_eq!(st.h.len(), digest_buf_len); + assert_eq!(vec::uniq_len(st.work_buf), work_buf_len); let mut t: int; // Loop counter let w = st.work_buf; @@ -192,7 +192,7 @@ pub fn sha1() -> @Sha1 { * can be assumed that the message digest has been computed. */ fn pad_msg(st: &mut Sha1State) { - assert!((vec::len((*st).msg_block) == msg_block_len)); + assert_eq!(vec::len((*st).msg_block), msg_block_len); /* * Check to see if the current message block is too small to hold @@ -230,7 +230,7 @@ pub fn sha1() -> @Sha1 { impl Sha1 for Sha1State { fn reset(&mut self) { - assert!(self.h.len() == digest_buf_len); + assert_eq!(self.h.len(), digest_buf_len); self.len_low = 0u32; self.len_high = 0u32; self.msg_block_idx = 0u; @@ -365,13 +365,13 @@ mod tests { ]; let tests = fips_180_1_tests + wikipedia_tests; fn check_vec_eq(v0: ~[u8], v1: ~[u8]) { - assert!((vec::len::(v0) == vec::len::(v1))); + assert_eq!(vec::len::(v0), vec::len::(v1)); let len = vec::len::(v0); let mut i = 0u; while i < len { let a = v0[i]; let b = v1[i]; - assert!((a == b)); + assert_eq!(a, b); i += 1u; } } @@ -384,8 +384,8 @@ mod tests { check_vec_eq(copy t.output, out); let out_str = sh.result_str(); - assert!((out_str.len() == 40)); - assert!((out_str == t.output_str)); + assert_eq!(out_str.len(), 40); + assert!(out_str == t.output_str); sh.reset(); } @@ -405,8 +405,8 @@ mod tests { check_vec_eq(copy t.output, out); let out_str = sh.result_str(); - assert!((out_str.len() == 40)); - assert!((out_str == t.output_str)); + assert_eq!(out_str.len(), 40); + assert!(out_str == t.output_str); sh.reset(); } diff --git a/src/libstd/smallintmap.rs b/src/libstd/smallintmap.rs index afc1d0fe65fcb..a336bd54a61aa 100644 --- a/src/libstd/smallintmap.rs +++ b/src/libstd/smallintmap.rs @@ -249,16 +249,16 @@ mod tests { #[test] fn test_len() { let mut map = SmallIntMap::new(); - assert!(map.len() == 0); + assert_eq!(map.len(), 0); assert!(map.is_empty()); assert!(map.insert(5, 20)); - assert!(map.len() == 1); + assert_eq!(map.len(), 1); assert!(!map.is_empty()); assert!(map.insert(11, 12)); - assert!(map.len() == 2); + assert_eq!(map.len(), 2); assert!(!map.is_empty()); assert!(map.insert(14, 22)); - assert!(map.len() == 3); + assert_eq!(map.len(), 3); assert!(!map.is_empty()); } @@ -297,9 +297,9 @@ mod tests { map.update_with_key(3, 2, addMoreToCount); // check the total counts - assert!(map.find(&3).get() == &10); - assert!(map.find(&5).get() == &3); - assert!(map.find(&9).get() == &1); + assert_eq!(map.find(&3).get(), &10); + assert_eq!(map.find(&5).get(), &3); + assert_eq!(map.find(&9).get(), &1); // sadly, no sevens were counted assert!(map.find(&7).is_none()); @@ -308,16 +308,16 @@ mod tests { #[test] fn test_swap() { let mut m = SmallIntMap::new(); - assert!(m.swap(1, 2) == None); - assert!(m.swap(1, 3) == Some(2)); - assert!(m.swap(1, 4) == Some(3)); + assert_eq!(m.swap(1, 2), None); + assert_eq!(m.swap(1, 3), Some(2)); + assert_eq!(m.swap(1, 4), Some(3)); } #[test] fn test_pop() { let mut m = SmallIntMap::new(); m.insert(1, 2); - assert!(m.pop(&1) == Some(2)); - assert!(m.pop(&1) == None); + assert_eq!(m.pop(&1), Some(2)); + assert_eq!(m.pop(&1), None); } } diff --git a/src/libstd/sort.rs b/src/libstd/sort.rs index 0d94a1830a648..ca752a482981a 100644 --- a/src/libstd/sort.rs +++ b/src/libstd/sort.rs @@ -261,7 +261,7 @@ fn binarysort(array: &mut [T], start: uint) { left = mid+1; } } - assert!(left == right); + assert_eq!(left, right); let n = start-left; shift_vec(array, left+1, left, n); @@ -357,7 +357,7 @@ fn gallop_left(key: &T, ofs = m; } } - assert!(last_ofs == ofs); + assert_eq!(last_ofs, ofs); return ofs; } @@ -410,7 +410,7 @@ fn gallop_right(key: &T, ofs = m; } } - assert!(last_ofs == ofs); + assert_eq!(last_ofs, ofs); return ofs; } @@ -449,7 +449,7 @@ impl MergeState { let l2 = self.runs[n+1].len; assert!(l1 > 0 && l2 > 0); - assert!(b1 + l1 == b2); + assert_eq!(b1 + l1, b2); self.runs[n].len = l1 + l2; if n == size-3 { @@ -583,7 +583,7 @@ impl MergeState { } else if len1 == 0 { fail!("Comparison violates its contract!"); } else { - assert!(len2 == 0); + assert_eq!(len2, 0); assert!(len1 > 1); copy_vec(array, dest, tmp.slice(c1, c1+len1)); } @@ -705,7 +705,7 @@ impl MergeState { } else if len2 == 0 { fail!("Comparison violates its contract!"); } else { - assert!(len1 == 0); + assert_eq!(len1, 0); assert!(len2 != 0); copy_vec(array, dest-(len2-1), tmp.slice(0, len2)); } @@ -818,7 +818,7 @@ mod test_qsort { let mut i = 0u; while i < len { // debug!(v2[i]); - assert!((v2[i] == v1[i])); + assert_eq!(v2[i], v1[i]); i += 1; } } @@ -863,7 +863,7 @@ mod test_qsort { for pairs.each |p| { let (a, b) = *p; debug!("%d %d", a, b); - assert!((a == b)); + assert_eq!(a, b); } } } @@ -883,7 +883,7 @@ mod tests { let mut i = 0u; while i < len { debug!(v3[i]); - assert!((v3[i] == v2[i])); + assert_eq!(v3[i], v2[i]); i += 1; } } @@ -910,7 +910,7 @@ mod tests { pub fn le(a: &int, b: &int) -> bool { *a <= *b } let mut v1 = ~[3, 2, 1]; let v2 = merge_sort(v1, le); - assert!(v2 == ~[1, 2, 3]); + assert_eq!(v2, ~[1, 2, 3]); } #[test] @@ -932,7 +932,7 @@ mod tests { let names2 = ~["Alex Andy", "Jack Brown", "joe bob", "Joe Bob", "JOE Bob", "JOE BOB", "Sally Mae"]; let names3 = merge_sort(names1, ile); - assert!(names3 == names2); + assert_eq!(names3, names2); } } @@ -964,7 +964,7 @@ mod test_tim_sort { let mut i = 0u; while i < len { // debug!(v2[i]); - assert!((v2[i] == v1[i])); + assert_eq!(v2[i], v1[i]); i += 1u; } } diff --git a/src/libstd/sort_stage0.rs b/src/libstd/sort_stage0.rs index 270f7196d294b..cdef8e220ceed 100644 --- a/src/libstd/sort_stage0.rs +++ b/src/libstd/sort_stage0.rs @@ -261,7 +261,7 @@ fn binarysort(array: &mut [T], start: uint) { left = mid+1; } } - assert!(left == right); + assert_eq!(left, right); let n = start-left; copy_vec(array, left+1, array, left, n); @@ -357,7 +357,7 @@ fn gallop_left(key: &const T, ofs = m; } } - assert!(last_ofs == ofs); + assert_eq!(last_ofs, ofs); return ofs; } @@ -410,7 +410,7 @@ fn gallop_right(key: &const T, ofs = m; } } - assert!(last_ofs == ofs); + assert_eq!(last_ofs, ofs); return ofs; } @@ -449,7 +449,7 @@ impl MergeState { let l2 = self.runs[n+1].len; assert!(l1 > 0 && l2 > 0); - assert!(b1 + l1 == b2); + assert_eq!(b1 + l1, b2); self.runs[n].len = l1 + l2; if n == size-3 { @@ -579,7 +579,7 @@ impl MergeState { } else if len1 == 0 { fail!("Comparison violates its contract!"); } else { - assert!(len2 == 0); + assert_eq!(len2, 0); assert!(len1 > 1); copy_vec(array, dest, tmp, c1, len1); } @@ -587,7 +587,7 @@ impl MergeState { fn merge_hi(&mut self, array: &mut [T], base1: uint, len1: uint, base2: uint, len2: uint) { - assert!(len1 != 1 && len2 != 0 && base1 + len1 == base2); + assert!(len1 != 1 && len2 != 0 && base1+len1 == base2); let mut tmp = ~[]; for uint::range(base2, base2+len2) |i| { @@ -701,7 +701,7 @@ impl MergeState { } else if len2 == 0 { fail!("Comparison violates its contract!"); } else { - assert!(len1 == 0); + assert_eq!(len1, 0); assert!(len2 != 0); copy_vec(array, dest-(len2-1), tmp, 0, len2); } @@ -766,7 +766,7 @@ mod test_qsort3 { let mut i = 0; while i < len { // debug!(v2[i]); - assert!((v2[i] == v1[i])); + assert_eq!(v2[i], v1[i]); i += 1; } } @@ -811,7 +811,7 @@ mod test_qsort { let mut i = 0u; while i < len { // debug!(v2[i]); - assert!((v2[i] == v1[i])); + assert_eq!(v2[i], v1[i]); i += 1; } } @@ -856,7 +856,7 @@ mod test_qsort { for pairs.each |p| { let (a, b) = *p; debug!("%d %d", a, b); - assert!((a == b)); + assert_eq!(a, b); } } } @@ -876,7 +876,7 @@ mod tests { let mut i = 0u; while i < len { debug!(v3[i]); - assert!((v3[i] == v2[i])); + assert_eq!(v3[i], v2[i]); i += 1; } } @@ -903,7 +903,7 @@ mod tests { pub fn le(a: &int, b: &int) -> bool { *a <= *b } let mut v1 = ~[3, 2, 1]; let v2 = merge_sort(v1, le); - assert!(v2 == ~[1, 2, 3]); + assert_eq!(v2, ~[1, 2, 3]); } #[test] @@ -925,7 +925,7 @@ mod tests { let names2 = ~["Alex Andy", "Jack Brown", "joe bob", "Joe Bob", "JOE Bob", "JOE BOB", "Sally Mae"]; let names3 = merge_sort(names1, ile); - assert!(names3 == names2); + assert_eq!(names3, names2); } } @@ -955,7 +955,7 @@ mod test_tim_sort { let mut i = 0u; while i < len { // debug!(v2[i]); - assert!((v2[i] == v1[i])); + assert_eq!(v2[i], v1[i]); i += 1u; } } diff --git a/src/libstd/sync.rs b/src/libstd/sync.rs index 449edacad32bd..002c6b2eca3ee 100644 --- a/src/libstd/sync.rs +++ b/src/libstd/sync.rs @@ -839,7 +839,7 @@ mod tests { access_shared(sharedstate, m, 10); let _ = p.recv(); - assert!(*sharedstate == 20); + assert_eq!(*sharedstate, 20); } fn access_shared(sharedstate: &mut int, m: &Mutex, n: uint) { @@ -906,7 +906,7 @@ mod tests { for ports.each |port| { let _ = port.recv(); } do m.lock_cond |cond| { let num_woken = cond.broadcast(); - assert!(num_woken == num_waiters); + assert_eq!(num_woken, num_waiters); } // wait until all children wake up for ports.each |port| { let _ = port.recv(); } @@ -1006,7 +1006,7 @@ mod tests { for vec::each(p.recv()) |p| { p.recv(); } // wait on all its siblings do m.lock_cond |cond| { let woken = cond.broadcast(); - assert!(woken == 0); + assert_eq!(woken, 0); } struct SendOnFailure { c: comm::Chan<()>, @@ -1120,7 +1120,7 @@ mod tests { access_shared(sharedstate, x, mode2, 10); let _ = p.recv(); - assert!(*sharedstate == 20); + assert_eq!(*sharedstate, 20); } fn access_shared(sharedstate: &mut int, x: &RWlock, mode: RWlockMode, @@ -1273,7 +1273,7 @@ mod tests { for ports.each |port| { let _ = port.recv(); } do lock_cond(x, dg2) |cond| { let num_woken = cond.broadcast(); - assert!(num_woken == num_waiters); + assert_eq!(num_woken, num_waiters); } // wait until all children wake up for ports.each |port| { let _ = port.recv(); } diff --git a/src/libstd/test.rs b/src/libstd/test.rs index b2f73df316da3..e9fd4e9a2b837 100644 --- a/src/libstd/test.rs +++ b/src/libstd/test.rs @@ -804,7 +804,7 @@ mod tests { let ch = SharedChan::new(ch); run_test(false, desc, ch); let (_, res) = p.recv(); - assert!(res == TrIgnored); + assert_eq!(res, TrIgnored); } #[test] @@ -823,7 +823,7 @@ mod tests { let ch = SharedChan::new(ch); run_test(false, desc, ch); let (_, res) = p.recv(); - assert!(res == TrOk); + assert_eq!(res, TrOk); } #[test] @@ -841,7 +841,7 @@ mod tests { let ch = SharedChan::new(ch); run_test(false, desc, ch); let (_, res) = p.recv(); - assert!(res == TrFailed); + assert_eq!(res, TrFailed); } #[test] @@ -901,9 +901,9 @@ mod tests { ]; let filtered = filter_tests(&opts, tests); - assert!(filtered.len() == 1); - assert!((filtered[0].desc.name.to_str() == ~"1")); - assert!((filtered[0].desc.ignore == false)); + assert_eq!(filtered.len(), 1); + assert_eq!(filtered[0].desc.name.to_str(), ~"1"); + assert!(filtered[0].desc.ignore == false); } #[test] @@ -958,7 +958,7 @@ mod tests { for pairs.each |p| { match *p { (ref a, ref b) => { - assert!((*a == b.desc.name.to_str())); + assert!(*a == b.desc.name.to_str()); } } } diff --git a/src/libstd/time.rs b/src/libstd/time.rs index 202b96f9797aa..9e6a45137a4a5 100644 --- a/src/libstd/time.rs +++ b/src/libstd/time.rs @@ -952,8 +952,8 @@ mod tests { let time = ::time::Timespec::new(1234567890, 54321); let utc = at_utc(time); - assert!(utc.to_timespec() == time); - assert!(utc.to_local().to_timespec() == time); + assert_eq!(utc.to_timespec(), time); + assert_eq!(utc.to_local().to_timespec(), time); } fn test_conversions() { @@ -985,7 +985,7 @@ mod tests { assert!(tm.tm_mon == 0_i32); assert!(tm.tm_year == 0_i32); assert!(tm.tm_wday == 0_i32); - assert!(tm.tm_isdst== 0_i32); + assert!(tm.tm_isdst == 0_i32); assert!(tm.tm_gmtoff == 0_i32); assert!(tm.tm_zone == ~""); assert!(tm.tm_nsec == 0_i32); @@ -994,7 +994,7 @@ mod tests { } let format = ~"%a %b %e %T %Y"; - assert!(strptime(~"", format) == Err(~"Invalid time")); + assert_eq!(strptime(~"", format), Err(~"Invalid time")); assert!(strptime(~"Fri Feb 13 15:31:30", format) == Err(~"Invalid time")); @@ -1140,8 +1140,8 @@ mod tests { error!("test_ctime: %? %?", utc.ctime(), local.ctime()); - assert!(utc.ctime() == ~"Fri Feb 13 23:31:30 2009"); - assert!(local.ctime() == ~"Fri Feb 13 15:31:30 2009"); + assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009"); + assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009"); } fn test_strftime() { @@ -1152,53 +1152,53 @@ mod tests { let utc = at_utc(time); let local = at(time); - assert!(local.strftime(~"") == ~""); - assert!(local.strftime(~"%A") == ~"Friday"); - assert!(local.strftime(~"%a") == ~"Fri"); - assert!(local.strftime(~"%B") == ~"February"); - assert!(local.strftime(~"%b") == ~"Feb"); - assert!(local.strftime(~"%C") == ~"20"); - assert!(local.strftime(~"%c") == ~"Fri Feb 13 15:31:30 2009"); - assert!(local.strftime(~"%D") == ~"02/13/09"); - assert!(local.strftime(~"%d") == ~"13"); - assert!(local.strftime(~"%e") == ~"13"); - assert!(local.strftime(~"%F") == ~"2009-02-13"); + assert_eq!(local.strftime(~""), ~""); + assert_eq!(local.strftime(~"%A"), ~"Friday"); + assert_eq!(local.strftime(~"%a"), ~"Fri"); + assert_eq!(local.strftime(~"%B"), ~"February"); + assert_eq!(local.strftime(~"%b"), ~"Feb"); + assert_eq!(local.strftime(~"%C"), ~"20"); + assert_eq!(local.strftime(~"%c"), ~"Fri Feb 13 15:31:30 2009"); + assert_eq!(local.strftime(~"%D"), ~"02/13/09"); + assert_eq!(local.strftime(~"%d"), ~"13"); + assert_eq!(local.strftime(~"%e"), ~"13"); + assert_eq!(local.strftime(~"%F"), ~"2009-02-13"); // assert!(local.strftime("%G") == "2009"); // assert!(local.strftime("%g") == "09"); - assert!(local.strftime(~"%H") == ~"15"); - assert!(local.strftime(~"%I") == ~"03"); - assert!(local.strftime(~"%j") == ~"044"); - assert!(local.strftime(~"%k") == ~"15"); - assert!(local.strftime(~"%l") == ~" 3"); - assert!(local.strftime(~"%M") == ~"31"); - assert!(local.strftime(~"%m") == ~"02"); - assert!(local.strftime(~"%n") == ~"\n"); - assert!(local.strftime(~"%P") == ~"pm"); - assert!(local.strftime(~"%p") == ~"PM"); - assert!(local.strftime(~"%R") == ~"15:31"); - assert!(local.strftime(~"%r") == ~"03:31:30 PM"); - assert!(local.strftime(~"%S") == ~"30"); - assert!(local.strftime(~"%s") == ~"1234567890"); - assert!(local.strftime(~"%T") == ~"15:31:30"); - assert!(local.strftime(~"%t") == ~"\t"); + assert_eq!(local.strftime(~"%H"), ~"15"); + assert_eq!(local.strftime(~"%I"), ~"03"); + assert_eq!(local.strftime(~"%j"), ~"044"); + assert_eq!(local.strftime(~"%k"), ~"15"); + assert_eq!(local.strftime(~"%l"), ~" 3"); + assert_eq!(local.strftime(~"%M"), ~"31"); + assert_eq!(local.strftime(~"%m"), ~"02"); + assert_eq!(local.strftime(~"%n"), ~"\n"); + assert_eq!(local.strftime(~"%P"), ~"pm"); + assert_eq!(local.strftime(~"%p"), ~"PM"); + assert_eq!(local.strftime(~"%R"), ~"15:31"); + assert_eq!(local.strftime(~"%r"), ~"03:31:30 PM"); + assert_eq!(local.strftime(~"%S"), ~"30"); + assert_eq!(local.strftime(~"%s"), ~"1234567890"); + assert_eq!(local.strftime(~"%T"), ~"15:31:30"); + assert_eq!(local.strftime(~"%t"), ~"\t"); // assert!(local.strftime("%U") == "06"); - assert!(local.strftime(~"%u") == ~"5"); + assert_eq!(local.strftime(~"%u"), ~"5"); // assert!(local.strftime("%V") == "07"); - assert!(local.strftime(~"%v") == ~"13-Feb-2009"); + assert_eq!(local.strftime(~"%v"), ~"13-Feb-2009"); // assert!(local.strftime("%W") == "06"); - assert!(local.strftime(~"%w") == ~"5"); + assert_eq!(local.strftime(~"%w"), ~"5"); // handle "%X" // handle "%x" - assert!(local.strftime(~"%Y") == ~"2009"); - assert!(local.strftime(~"%y") == ~"09"); + assert_eq!(local.strftime(~"%Y"), ~"2009"); + assert_eq!(local.strftime(~"%y"), ~"09"); // FIXME (#2350): We should probably standardize on the timezone // abbreviation. let zone = local.strftime(~"%Z"); assert!(zone == ~"PST" || zone == ~"Pacific Standard Time"); - assert!(local.strftime(~"%z") == ~"-0800"); - assert!(local.strftime(~"%%") == ~"%"); + assert_eq!(local.strftime(~"%z"), ~"-0800"); + assert_eq!(local.strftime(~"%%"), ~"%"); // FIXME (#2350): We should probably standardize on the timezone // abbreviation. @@ -1207,14 +1207,14 @@ mod tests { assert!(rfc822 == prefix + ~"PST" || rfc822 == prefix + ~"Pacific Standard Time"); - assert!(local.ctime() == ~"Fri Feb 13 15:31:30 2009"); - assert!(local.rfc822z() == ~"Fri, 13 Feb 2009 15:31:30 -0800"); - assert!(local.rfc3339() == ~"2009-02-13T15:31:30-08:00"); + assert_eq!(local.ctime(), ~"Fri Feb 13 15:31:30 2009"); + assert_eq!(local.rfc822z(), ~"Fri, 13 Feb 2009 15:31:30 -0800"); + assert_eq!(local.rfc3339(), ~"2009-02-13T15:31:30-08:00"); - assert!(utc.ctime() == ~"Fri Feb 13 23:31:30 2009"); - assert!(utc.rfc822() == ~"Fri, 13 Feb 2009 23:31:30 GMT"); - assert!(utc.rfc822z() == ~"Fri, 13 Feb 2009 23:31:30 -0000"); - assert!(utc.rfc3339() == ~"2009-02-13T23:31:30Z"); + assert_eq!(utc.ctime(), ~"Fri Feb 13 23:31:30 2009"); + assert_eq!(utc.rfc822(), ~"Fri, 13 Feb 2009 23:31:30 GMT"); + assert_eq!(utc.rfc822z(), ~"Fri, 13 Feb 2009 23:31:30 -0000"); + assert_eq!(utc.rfc3339(), ~"2009-02-13T23:31:30Z"); } fn test_timespec_eq_ord() { diff --git a/src/libstd/timer.rs b/src/libstd/timer.rs index e9fd0414244e8..7fea94a39a77e 100644 --- a/src/libstd/timer.rs +++ b/src/libstd/timer.rs @@ -256,7 +256,7 @@ mod test { match recv_timeout(hl_loop, 10u, &test_po) { Some(val) => { - assert!(val == expected); + assert_eq!(val, expected); successes += 1; } _ => failures += 1 diff --git a/src/libstd/treemap.rs b/src/libstd/treemap.rs index e0ee3a1ee01c4..e4026d7306ffe 100644 --- a/src/libstd/treemap.rs +++ b/src/libstd/treemap.rs @@ -920,7 +920,7 @@ mod test_treemap { assert!(m.insert(1, 2)); assert!(m.insert(5, 3)); assert!(m.insert(9, 3)); - assert!(m.find(&2) == None); + assert_eq!(m.find(&2), None); } #[test] @@ -942,7 +942,7 @@ mod test_treemap { assert!(m.insert(5, 2)); assert!(m.insert(2, 9)); assert!(!m.insert(2, 11)); - assert!(m.find(&2).unwrap() == &11); + assert_eq!(m.find(&2).unwrap(), &11); } #[test] @@ -971,13 +971,13 @@ mod test_treemap { m.insert(copy k1, copy v1); m.insert(copy k2, copy v2); - assert!(m.find(&k2) == Some(&v2)); - assert!(m.find(&k1) == Some(&v1)); + assert_eq!(m.find(&k2), Some(&v2)); + assert_eq!(m.find(&k1), Some(&v1)); } fn check_equal(ctrl: &[(K, V)], map: &TreeMap) { - assert!(ctrl.is_empty() == map.is_empty()); + assert_eq!(ctrl.is_empty(), map.is_empty()); for ctrl.each |x| { let &(k, v) = x; assert!(map.find(&k).unwrap() == &v) @@ -1000,7 +1000,7 @@ mod test_treemap { parent: &~TreeNode) { match *node { Some(ref r) => { - assert!(r.key.cmp(&parent.key) == Less); + assert_eq!(r.key.cmp(&parent.key), Less); assert!(r.level == parent.level - 1); // left is black check_left(&r.left, r); check_right(&r.right, r, false); @@ -1014,7 +1014,7 @@ mod test_treemap { parent_red: bool) { match *node { Some(ref r) => { - assert!(r.key.cmp(&parent.key) == Greater); + assert_eq!(r.key.cmp(&parent.key), Greater); let red = r.level == parent.level; if parent_red { assert!(!red) } // no dual horizontal links // Right red or black @@ -1072,19 +1072,19 @@ mod test_treemap { fn test_len() { let mut m = TreeMap::new(); assert!(m.insert(3, 6)); - assert!(m.len() == 1); + assert_eq!(m.len(), 1); assert!(m.insert(0, 0)); - assert!(m.len() == 2); + assert_eq!(m.len(), 2); assert!(m.insert(4, 8)); - assert!(m.len() == 3); + assert_eq!(m.len(), 3); assert!(m.remove(&3)); - assert!(m.len() == 2); + assert_eq!(m.len(), 2); assert!(!m.remove(&5)); - assert!(m.len() == 2); + assert_eq!(m.len(), 2); assert!(m.insert(2, 4)); - assert!(m.len() == 3); + assert_eq!(m.len(), 3); assert!(m.insert(1, 2)); - assert!(m.len() == 4); + assert_eq!(m.len(), 4); } #[test] @@ -1099,8 +1099,8 @@ mod test_treemap { let mut n = 0; for m.each |k, v| { - assert!(*k == n); - assert!(*v == n * 2); + assert_eq!(*k, n); + assert_eq!(*v, n * 2); n += 1; } } @@ -1117,8 +1117,8 @@ mod test_treemap { let mut n = 4; for m.each_reverse |k, v| { - assert!(*k == n); - assert!(*v == n * 2); + assert_eq!(*k, n); + assert_eq!(*v, n * 2); n -= 1; } } @@ -1191,11 +1191,11 @@ mod test_treemap { let m = m; let mut a = m.iter(); - assert!(a.next().unwrap() == (&x1, &y1)); - assert!(a.next().unwrap() == (&x2, &y2)); - assert!(a.next().unwrap() == (&x3, &y3)); - assert!(a.next().unwrap() == (&x4, &y4)); - assert!(a.next().unwrap() == (&x5, &y5)); + assert_eq!(a.next().unwrap(), (&x1, &y1)); + assert_eq!(a.next().unwrap(), (&x2, &y2)); + assert_eq!(a.next().unwrap(), (&x3, &y3)); + assert_eq!(a.next().unwrap(), (&x4, &y4)); + assert_eq!(a.next().unwrap(), (&x5, &y5)); assert!(a.next().is_none()); @@ -1206,7 +1206,7 @@ mod test_treemap { let mut i = 0; for b.advance |x| { - assert!(expected[i] == x); + assert_eq!(expected[i], x); i += 1; if i == 2 { @@ -1215,7 +1215,7 @@ mod test_treemap { } for b.advance |x| { - assert!(expected[i] == x); + assert_eq!(expected[i], x); i += 1; } } @@ -1303,7 +1303,7 @@ mod test_set { let mut n = 0; for m.each |x| { - assert!(*x == n); + assert_eq!(*x, n); n += 1 } } @@ -1320,7 +1320,7 @@ mod test_set { let mut n = 4; for m.each_reverse |x| { - assert!(*x == n); + assert_eq!(*x, n); n -= 1 } } @@ -1335,10 +1335,10 @@ mod test_set { let mut i = 0; for f(&set_a, &set_b) |x| { - assert!(*x == expected[i]); + assert_eq!(*x, expected[i]); i += 1; } - assert!(i == expected.len()); + assert_eq!(i, expected.len()); } #[test] @@ -1421,10 +1421,10 @@ mod test_set { // FIXME: #5801: this needs a type hint to compile... let result: Option<(&uint, & &'static str)> = z.next(); - assert!(result.unwrap() == (&5u, & &"bar")); + assert_eq!(result.unwrap(), (&5u, & &"bar")); let result: Option<(&uint, & &'static str)> = z.next(); - assert!(result.unwrap() == (&11u, & &"foo")); + assert_eq!(result.unwrap(), (&11u, & &"foo")); let result: Option<(&uint, & &'static str)> = z.next(); assert!(result.is_none()); @@ -1433,16 +1433,16 @@ mod test_set { #[test] fn test_swap() { let mut m = TreeMap::new(); - assert!(m.swap(1, 2) == None); - assert!(m.swap(1, 3) == Some(2)); - assert!(m.swap(1, 4) == Some(3)); + assert_eq!(m.swap(1, 2), None); + assert_eq!(m.swap(1, 3), Some(2)); + assert_eq!(m.swap(1, 4), Some(3)); } #[test] fn test_pop() { let mut m = TreeMap::new(); m.insert(1, 2); - assert!(m.pop(&1) == Some(2)); - assert!(m.pop(&1) == None); + assert_eq!(m.pop(&1), Some(2)); + assert_eq!(m.pop(&1), None); } } diff --git a/src/libstd/uv_iotask.rs b/src/libstd/uv_iotask.rs index 2922f403f34a6..d1a95c5b9f764 100644 --- a/src/libstd/uv_iotask.rs +++ b/src/libstd/uv_iotask.rs @@ -183,7 +183,7 @@ extern fn tear_down_walk_cb(handle: *libc::c_void, arg: *libc::c_void) { // pretty much, if we still have an active handle and it is *not* // the async handle that facilities global loop communication, we // want to barf out and fail - assert!(handle == arg); + assert_eq!(handle, arg); } extern fn tear_down_close_cb(handle: *ll::uv_async_t) { diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 44a368738fd16..61921fbf090f2 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -319,7 +319,7 @@ pub impl FileMap { fn next_line(&self, pos: BytePos) { // the new charpos must be > the last one (or it's the first one). let lines = &mut *self.lines; - assert!((lines.len() == 0) || (lines[lines.len() - 1] < pos)); + assert!((lines.len() == 0) || (lines[lines.len() - 1] < pos)) lines.push(pos); } @@ -458,7 +458,7 @@ pub impl CodeMap { pub fn span_to_snippet(&self, sp: span) -> ~str { let begin = self.lookup_byte_offset(sp.lo); let end = self.lookup_byte_offset(sp.hi); - assert!(begin.fm.start_pos == end.fm.start_pos); + assert_eq!(begin.fm.start_pos, end.fm.start_pos); return str::slice(*begin.fm.src, begin.pos.to_uint(), end.pos.to_uint()).to_owned(); } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 9a8a662065234..fa52f3dde3d54 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -381,7 +381,7 @@ mod test { i.intern("c"); i.intern("d"); i.intern("return"); - assert!(i.get(ast::ident{repr:101,ctxt:0}) == @~"b"); + assert_eq!(i.get(ast::ident{repr:101,ctxt:0}), @~"b"); i } diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 38c58612f43a7..52495522613dd 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -111,7 +111,7 @@ pub fn tok_str(t: token) -> ~str { pub fn buf_str(toks: ~[token], szs: ~[int], left: uint, right: uint, lim: uint) -> ~str { let n = toks.len(); - assert!(n == szs.len()); + assert_eq!(n, szs.len()); let mut i = left; let mut L = lim; let mut s = ~"["; @@ -400,7 +400,7 @@ pub impl Printer { match x { BREAK(b) => self.left_total += b.blank_space, STRING(_, len) => { - assert!((len == L)); self.left_total += len; + assert_eq!(len, L); self.left_total += len; } _ => () } @@ -526,7 +526,7 @@ pub impl Printer { } STRING(s, len) => { debug!("print STRING(%s)", *s); - assert!((L == len)); + assert_eq!(L, len); // assert!(L <= space); self.space -= len; self.print_str(*s); diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index ea1682978a463..b2db752af1179 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -2067,7 +2067,7 @@ pub fn maybe_print_comment(s: @ps, pos: BytePos) { pub fn print_comment(s: @ps, cmnt: &comments::cmnt) { match cmnt.style { comments::mixed => { - assert!(cmnt.lines.len() == 1u); + assert_eq!(cmnt.lines.len(), 1u); zerobreak(s.s); word(s.s, cmnt.lines[0]); zerobreak(s.s); diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index cb494ec9d206a..0d951771d7014 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -35,7 +35,7 @@ fn ascending>(map: &mut M, n_keys: uint) { do timed("search") { for uint::range(0, n_keys) |i| { - assert!(map.find(&i).unwrap() == &(i + 1)); + assert_eq!(map.find(&i).unwrap(), &(i + 1)); } } @@ -57,7 +57,7 @@ fn descending>(map: &mut M, n_keys: uint) { do timed("search") { for uint::range_rev(n_keys, 0) |i| { - assert!(map.find(&i).unwrap() == &(i + 1)); + assert_eq!(map.find(&i).unwrap(), &(i + 1)); } } @@ -78,7 +78,7 @@ fn vector>(map: &mut M, n_keys: uint, dist: &[uint]) { do timed("search") { for uint::range(0, n_keys) |i| { - assert!(map.find(&dist[i]).unwrap() == &(i + 1)); + assert_eq!(map.find(&dist[i]).unwrap(), &(i + 1)); } } diff --git a/src/test/bench/graph500-bfs.rs b/src/test/bench/graph500-bfs.rs index ddf6f4bfc55cf..4be2cca0b4855 100644 --- a/src/test/bench/graph500-bfs.rs +++ b/src/test/bench/graph500-bfs.rs @@ -296,7 +296,7 @@ fn pbfs(graph: &arc::ARC, key: node_id) -> bfs_result { }; result }; - assert!((colors.len() == old_len)); + assert_eq!(colors.len(), old_len); } // Convert the results. diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index 95758b3fe6406..d1be03e944ae1 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -93,7 +93,7 @@ fn run(args: &[~str]) { io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed)); let thruput = ((size / workers * workers) as float) / (elapsed as float); io::stdout().write_str(fmt!("Throughput=%f per sec\n", thruput)); - assert!(result == num_bytes * size); + assert_eq!(result, num_bytes * size); } fn main() { diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index e213a44b49ae7..b72a38d4054bd 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -90,7 +90,7 @@ fn run(args: &[~str]) { io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed)); let thruput = ((size / workers * workers) as float) / (elapsed as float); io::stdout().write_str(fmt!("Throughput=%f per sec\n", thruput)); - assert!(result == num_bytes * size); + assert_eq!(result, num_bytes * size); } fn main() { diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index b7ae331c8f376..31945310eb32b 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -70,7 +70,7 @@ fn stress_task(id: int) { let mut i = 0; loop { let n = 15; - assert!((fib(n) == fib(n))); + assert_eq!(fib(n), fib(n)); i += 1; error!("%d: Completed %d iterations", id, i); } diff --git a/src/test/bench/std-smallintmap.rs b/src/test/bench/std-smallintmap.rs index 4b0d34d231511..7b8aca2694e80 100644 --- a/src/test/bench/std-smallintmap.rs +++ b/src/test/bench/std-smallintmap.rs @@ -22,7 +22,7 @@ fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap) { fn check_sequential(min: uint, max: uint, map: &SmallIntMap) { for uint::range(min, max) |i| { - assert!(*map.get(&i) == i + 22u); + assert_eq!(*map.get(&i), i + 22u); } } diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index c18c1eaedd613..4d8614b5eddb6 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -212,30 +212,30 @@ static default_solution: [[u8, ..9], ..9] = [ #[test] fn colors_new_works() { - assert!(*Colors::new(1) == 1022u16); - assert!(*Colors::new(2) == 1020u16); - assert!(*Colors::new(3) == 1016u16); - assert!(*Colors::new(4) == 1008u16); - assert!(*Colors::new(5) == 992u16); - assert!(*Colors::new(6) == 960u16); - assert!(*Colors::new(7) == 896u16); - assert!(*Colors::new(8) == 768u16); - assert!(*Colors::new(9) == 512u16); + assert_eq!(*Colors::new(1), 1022u16); + assert_eq!(*Colors::new(2), 1020u16); + assert_eq!(*Colors::new(3), 1016u16); + assert_eq!(*Colors::new(4), 1008u16); + assert_eq!(*Colors::new(5), 992u16); + assert_eq!(*Colors::new(6), 960u16); + assert_eq!(*Colors::new(7), 896u16); + assert_eq!(*Colors::new(8), 768u16); + assert_eq!(*Colors::new(9), 512u16); } #[test] fn colors_next_works() { - assert!(Colors(0).next() == 0u8); - assert!(Colors(2).next() == 1u8); - assert!(Colors(4).next() == 2u8); - assert!(Colors(8).next() == 3u8); - assert!(Colors(16).next() == 4u8); - assert!(Colors(32).next() == 5u8); - assert!(Colors(64).next() == 6u8); - assert!(Colors(128).next() == 7u8); - assert!(Colors(256).next() == 8u8); - assert!(Colors(512).next() == 9u8); - assert!(Colors(1024).next() == 0u8); + assert_eq!(Colors(0).next(), 0u8); + assert_eq!(Colors(2).next(), 1u8); + assert_eq!(Colors(4).next(), 2u8); + assert_eq!(Colors(8).next(), 3u8); + assert_eq!(Colors(16).next(), 4u8); + assert_eq!(Colors(32).next(), 5u8); + assert_eq!(Colors(64).next(), 6u8); + assert_eq!(Colors(128).next(), 7u8); + assert_eq!(Colors(256).next(), 8u8); + assert_eq!(Colors(512).next(), 9u8); + assert_eq!(Colors(1024).next(), 0u8); } #[test] @@ -247,7 +247,7 @@ fn colors_remove_works() { colors.remove(1); // THEN - assert!(colors.next() == 2u8); + assert_eq!(colors.next(), 2u8); } #[test] diff --git a/src/test/bench/task-perf-linked-failure.rs b/src/test/bench/task-perf-linked-failure.rs index 6015f21be727f..aacdf678bbfe5 100644 --- a/src/test/bench/task-perf-linked-failure.rs +++ b/src/test/bench/task-perf-linked-failure.rs @@ -54,7 +54,7 @@ fn spawn_supervised_blocking(myname: &str, f: ~fn()) { builder.spawn(f); error!("%s group waiting", myname); let x = res.unwrap().recv(); - assert!(x == task::Success); + assert_eq!(x, task::Success); } fn main() { diff --git a/src/test/compile-fail/autoderef-full-lval.rs b/src/test/compile-fail/autoderef-full-lval.rs index ecd31d0dde456..e38c22004ed13 100644 --- a/src/test/compile-fail/autoderef-full-lval.rs +++ b/src/test/compile-fail/autoderef-full-lval.rs @@ -22,10 +22,10 @@ fn main() { let b: clam = clam{x: @10, y: @20}; let z: int = a.x + b.y; //~ ERROR binary operation + cannot be applied to type `@int` debug!(z); - assert!((z == 21)); + assert_eq!(z, 21); let forty: fish = fish{a: @40}; let two: fish = fish{a: @2}; let answer: int = forty.a + two.a; //~ ERROR binary operation + cannot be applied to type `@int` debug!(answer); - assert!((answer == 42)); + assert_eq!(answer, 42); } diff --git a/src/test/compile-fail/block-arg-as-stmt-with-value.rs b/src/test/compile-fail/block-arg-as-stmt-with-value.rs index 42c5ffe3e916b..73a53d6cc988c 100644 --- a/src/test/compile-fail/block-arg-as-stmt-with-value.rs +++ b/src/test/compile-fail/block-arg-as-stmt-with-value.rs @@ -19,5 +19,5 @@ fn compute1() -> float { fn main() { let x = compute1(); debug!(x); - assert!((x == -4f)); + assert_eq!(x, -4f); } diff --git a/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs b/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs index f8415a38573c4..ae8779eafcc70 100644 --- a/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs +++ b/src/test/compile-fail/borrowck-loan-blocks-mut-uniq.rs @@ -16,8 +16,8 @@ fn box_imm() { let mut v = ~3; do borrow(v) |w| { v = ~4; //~ ERROR cannot assign to `v` because it is borrowed - assert!(*v == 3); - assert!(*w == 4); + assert_eq!(*v, 3); + assert_eq!(*w, 4); } } diff --git a/src/test/compile-fail/borrowck-ref-mut-of-imm.rs b/src/test/compile-fail/borrowck-ref-mut-of-imm.rs index 3a37116a1664d..4a34b85c3edfa 100644 --- a/src/test/compile-fail/borrowck-ref-mut-of-imm.rs +++ b/src/test/compile-fail/borrowck-ref-mut-of-imm.rs @@ -16,5 +16,5 @@ fn destructure(x: Option) -> int { } fn main() { - assert!(destructure(Some(22)) == 22); + assert_eq!(destructure(Some(22)), 22); } diff --git a/src/test/compile-fail/issue-1896-1.rs b/src/test/compile-fail/issue-1896-1.rs index 13adcd42da2b8..4750f68d59b34 100644 --- a/src/test/compile-fail/issue-1896-1.rs +++ b/src/test/compile-fail/issue-1896-1.rs @@ -22,5 +22,5 @@ fn main () { let myInt: uint = (aFn.theFn)(); - assert!(myInt == 10); + assert_eq!(myInt, 10); } diff --git a/src/test/compile-fail/issue-2467.rs b/src/test/compile-fail/issue-2467.rs index fd6e5a762b248..3149db8a03f27 100644 --- a/src/test/compile-fail/issue-2467.rs +++ b/src/test/compile-fail/issue-2467.rs @@ -12,5 +12,5 @@ enum test { thing = 3u } //~ ERROR mismatched types //~^ ERROR expected signed integer constant fn main() { error!(thing as int); - assert!((thing as int == 3)); + assert_eq!(thing as int, 3); } diff --git a/src/test/compile-fail/issue-2548.rs b/src/test/compile-fail/issue-2548.rs index 9c2d7baa23c26..fdaf1f562c8df 100644 --- a/src/test/compile-fail/issue-2548.rs +++ b/src/test/compile-fail/issue-2548.rs @@ -38,8 +38,8 @@ fn main() { let mut v = ~[]; v = ~[(res)] + v; //~ instantiating a type parameter with an incompatible type `foo`, which does not fulfill `Copy` - assert!((v.len() == 2)); + assert_eq!(v.len(), 2); } - assert!(*x == 1); + assert_eq!(*x, 1); } diff --git a/src/test/compile-fail/issue-2969.rs b/src/test/compile-fail/issue-2969.rs index 927e81db5c1c4..a9c26fc415ead 100644 --- a/src/test/compile-fail/issue-2969.rs +++ b/src/test/compile-fail/issue-2969.rs @@ -15,5 +15,5 @@ fn main() let mut x = [1, 2, 4]; let v : &int = &x[2]; x[2] = 6; - assert!(*v == 6); + assert_eq!(*v, 6); } diff --git a/src/test/compile-fail/kindck-owned-trait-scoped.rs b/src/test/compile-fail/kindck-owned-trait-scoped.rs index bb0ba87c098cf..dc3717085ca57 100644 --- a/src/test/compile-fail/kindck-owned-trait-scoped.rs +++ b/src/test/compile-fail/kindck-owned-trait-scoped.rs @@ -30,7 +30,7 @@ fn to_foo(t: T) { let v = &3; struct F { f: T } let x = @F {f:t} as @foo; - assert!(x.foo(v) == 3); + assert_eq!(x.foo(v), 3); } fn to_foo_2(t: T) -> @foo { diff --git a/src/test/compile-fail/mod_file_not_exist.rs b/src/test/compile-fail/mod_file_not_exist.rs index 17ca8dca27352..9b16738e951f7 100644 --- a/src/test/compile-fail/mod_file_not_exist.rs +++ b/src/test/compile-fail/mod_file_not_exist.rs @@ -11,5 +11,5 @@ mod not_a_real_file; //~ ERROR not_a_real_file.rs fn main() { - assert!(mod_file_aux::bar() == 10); + assert_eq!(mod_file_aux::bar(), 10); } diff --git a/src/test/compile-fail/mod_file_with_path_attr.rs b/src/test/compile-fail/mod_file_with_path_attr.rs index 827c77bda471d..ff330047c4e96 100644 --- a/src/test/compile-fail/mod_file_with_path_attr.rs +++ b/src/test/compile-fail/mod_file_with_path_attr.rs @@ -12,5 +12,5 @@ mod m; //~ ERROR not_a_real_file.rs fn main() { - assert!(m::foo() == 10); + assert_eq!(m::foo(), 10); } diff --git a/src/test/compile-fail/no-capture-arc.rs b/src/test/compile-fail/no-capture-arc.rs index 2c8c98ad5d6de..4c206a949a238 100644 --- a/src/test/compile-fail/no-capture-arc.rs +++ b/src/test/compile-fail/no-capture-arc.rs @@ -19,10 +19,10 @@ fn main() { do task::spawn() { let v = *arc::get(&arc_v); - assert!(v[3] == 4); + assert_eq!(v[3], 4); }; - assert!((*arc::get(&arc_v))[2] == 3); + assert_eq!((*arc::get(&arc_v))[2], 3); info!(arc_v); } diff --git a/src/test/compile-fail/no-reuse-move-arc.rs b/src/test/compile-fail/no-reuse-move-arc.rs index 75cd706985c64..46eaded4527a3 100644 --- a/src/test/compile-fail/no-reuse-move-arc.rs +++ b/src/test/compile-fail/no-reuse-move-arc.rs @@ -17,7 +17,7 @@ fn main() { do task::spawn() { //~ NOTE `arc_v` moved into closure environment here let v = *arc::get(&arc_v); - assert!(v[3] == 4); + assert_eq!(v[3], 4); }; assert!((*arc::get(&arc_v))[2] == 3); //~ ERROR use of moved value: `arc_v` diff --git a/src/test/compile-fail/regions-glb-free-free.rs b/src/test/compile-fail/regions-glb-free-free.rs index 9a4974849a50d..61300b92afd09 100644 --- a/src/test/compile-fail/regions-glb-free-free.rs +++ b/src/test/compile-fail/regions-glb-free-free.rs @@ -37,5 +37,5 @@ mod argparse { fn main () { let f : argparse::Flag = argparse::flag(~"flag", ~"My flag"); let updated_flag = f.set_desc(~"My new flag"); - assert!(updated_flag.desc == "My new flag"); + assert_eq!(updated_flag.desc, "My new flag"); } diff --git a/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs b/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs index d519397f68c58..5710188ed9fe5 100644 --- a/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs +++ b/src/test/compile-fail/regions-infer-borrow-scope-too-big.rs @@ -19,7 +19,7 @@ fn x_coord<'r>(p: &'r point) -> &'r int { fn foo(p: @point) -> &int { let xc = x_coord(p); //~ ERROR cannot root - assert!(*xc == 3); + assert_eq!(*xc, 3); return xc; } diff --git a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs b/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs index 3b88c634598b1..2ffd0796e30e7 100644 --- a/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs +++ b/src/test/compile-fail/regions-infer-borrow-scope-within-loop.rs @@ -19,7 +19,7 @@ fn foo(cond: &fn() -> bool, box: &fn() -> @int) { // of this borrow is the fn body as a whole. y = borrow(x); //~ ERROR cannot root - assert!(*x == *y); + assert_eq!(*x, *y); if cond() { break; } } assert!(*y != 0); diff --git a/src/test/compile-fail/regions-trait-1.rs b/src/test/compile-fail/regions-trait-1.rs index ff75ba4473de7..ae697ad1181c3 100644 --- a/src/test/compile-fail/regions-trait-1.rs +++ b/src/test/compile-fail/regions-trait-1.rs @@ -34,5 +34,5 @@ fn get_v(gc: @get_ctxt) -> uint { fn main() { let ctxt = ctxt { v: 22u }; let hc = has_ctxt { c: &ctxt }; - assert!(get_v(@hc as @get_ctxt) == 22u); + assert_eq!(get_v(@hc as @get_ctxt), 22u); } diff --git a/src/test/compile-fail/regions-var-type-out-of-scope.rs b/src/test/compile-fail/regions-var-type-out-of-scope.rs index addf20fd70249..8955a26de0b93 100644 --- a/src/test/compile-fail/regions-var-type-out-of-scope.rs +++ b/src/test/compile-fail/regions-var-type-out-of-scope.rs @@ -15,7 +15,7 @@ fn foo(cond: bool) { if cond { x = &3; //~ ERROR borrowed value does not live long enough - assert!((*x == 3)); + assert_eq!(*x, 3); } } diff --git a/src/test/compile-fail/vtable-res-trait-param.rs b/src/test/compile-fail/vtable-res-trait-param.rs index dd0ae87f3118d..5d0991024c4f6 100644 --- a/src/test/compile-fail/vtable-res-trait-param.rs +++ b/src/test/compile-fail/vtable-res-trait-param.rs @@ -29,5 +29,5 @@ fn call_it(b: B) -> int { fn main() { let x = 3i; - assert!(call_it(x) == 22); + assert_eq!(call_it(x), 22); } diff --git a/src/test/pretty/record-trailing-comma.rs b/src/test/pretty/record-trailing-comma.rs index 1ea0e10413271..67059e07c899d 100644 --- a/src/test/pretty/record-trailing-comma.rs +++ b/src/test/pretty/record-trailing-comma.rs @@ -18,5 +18,5 @@ struct Thing { fn main() { let sth = Thing{x: 0, y: 1,}; let sth2 = Thing{y: 9 , ..sth}; - assert!(sth.x + sth2.y == 9); + assert_eq!(sth.x + sth2.y, 9); } diff --git a/src/test/run-fail/str-overrun.rs b/src/test/run-fail/str-overrun.rs index 38b73ea56980e..5ec2c093eebac 100644 --- a/src/test/run-fail/str-overrun.rs +++ b/src/test/run-fail/str-overrun.rs @@ -15,5 +15,5 @@ fn main() { let s: ~str = ~"hello"; // Bounds-check failure. - assert!((s[5] == 0x0 as u8)); + assert_eq!(s[5], 0x0 as u8); } diff --git a/src/test/run-fail/unwind-alt.rs b/src/test/run-fail/unwind-alt.rs index d7e079ad90716..a9761017c73f5 100644 --- a/src/test/run-fail/unwind-alt.rs +++ b/src/test/run-fail/unwind-alt.rs @@ -16,7 +16,7 @@ fn test_box() { fn test_str() { let res = match false { true => { ~"happy" }, _ => fail!("non-exhaustive match failure") }; - assert!(res == ~"happy"); + assert_eq!(res, ~"happy"); } fn main() { test_box(); diff --git a/src/test/run-fail/vec-overrun.rs b/src/test/run-fail/vec-overrun.rs index ab9dcf32781be..411895a2ef037 100644 --- a/src/test/run-fail/vec-overrun.rs +++ b/src/test/run-fail/vec-overrun.rs @@ -14,8 +14,8 @@ fn main() { let v: ~[int] = ~[10]; let x: int = 0; - assert!((v[x] == 10)); + assert_eq!(v[x], 10); // Bounds-check failure. - assert!((v[x + 2] == 20)); + assert_eq!(v[x + 2], 20); } diff --git a/src/test/run-fail/vec-underrun.rs b/src/test/run-fail/vec-underrun.rs index 6f403fd772193..99ce79b3b6c0c 100644 --- a/src/test/run-fail/vec-underrun.rs +++ b/src/test/run-fail/vec-underrun.rs @@ -14,8 +14,8 @@ fn main() { let v: ~[int] = ~[10, 20]; let x: int = 0; - assert!((v[x] == 10)); + assert_eq!(v[x], 10); // Bounds-check failure. - assert!((v[x - 1] == 20)); + assert_eq!(v[x - 1], 20); } diff --git a/src/test/run-pass-fulldeps/qquote.rs b/src/test/run-pass-fulldeps/qquote.rs index 84edb990a7598..53385e16759d1 100644 --- a/src/test/run-pass-fulldeps/qquote.rs +++ b/src/test/run-pass-fulldeps/qquote.rs @@ -82,6 +82,6 @@ fn check_pp(cx: fake_ext_ctxt, stdout().write_line(s); if expect != ~"" { error!("expect: '%s', got: '%s'", expect, s); - assert!(s == expect); + assert_eq!(s, expect); } } diff --git a/src/test/run-pass/alignment-gep-tup-like-1.rs b/src/test/run-pass/alignment-gep-tup-like-1.rs index e3a544af309b2..bf96d6cfab529 100644 --- a/src/test/run-pass/alignment-gep-tup-like-1.rs +++ b/src/test/run-pass/alignment-gep-tup-like-1.rs @@ -20,6 +20,6 @@ fn f(a: A, b: u16) -> @fn() -> (A, u16) { pub fn main() { let (a, b) = f(22_u64, 44u16)(); debug!("a=%? b=%?", a, b); - assert!(a == 22u64); - assert!(b == 44u16); + assert_eq!(a, 22u64); + assert_eq!(b, 44u16); } diff --git a/src/test/run-pass/alignment-gep-tup-like-2.rs b/src/test/run-pass/alignment-gep-tup-like-2.rs index 847e6fce8ee61..6bf4e96bc053d 100644 --- a/src/test/run-pass/alignment-gep-tup-like-2.rs +++ b/src/test/run-pass/alignment-gep-tup-like-2.rs @@ -35,6 +35,6 @@ pub fn main() { make_cycle(z); let (a, b) = z(); debug!("a=%u b=%u", *a as uint, b as uint); - assert!(*a == x); - assert!(b == y); + assert_eq!(*a, x); + assert_eq!(b, y); } diff --git a/src/test/run-pass/alt-ref-binding-mut-option.rs b/src/test/run-pass/alt-ref-binding-mut-option.rs index 9ef414d1170be..8d1e483bcd848 100644 --- a/src/test/run-pass/alt-ref-binding-mut-option.rs +++ b/src/test/run-pass/alt-ref-binding-mut-option.rs @@ -14,5 +14,5 @@ pub fn main() { None => {} Some(ref mut p) => { *p += 1; } } - assert!(v == Some(23)); + assert_eq!(v, Some(23)); } diff --git a/src/test/run-pass/alt-ref-binding-mut.rs b/src/test/run-pass/alt-ref-binding-mut.rs index 2bd55b46784b8..266f7cdde11af 100644 --- a/src/test/run-pass/alt-ref-binding-mut.rs +++ b/src/test/run-pass/alt-ref-binding-mut.rs @@ -21,5 +21,5 @@ fn destructure(x: &mut Rec) { pub fn main() { let mut v = Rec {f: 22}; destructure(&mut v); - assert!(v.f == 23); + assert_eq!(v.f, 23); } diff --git a/src/test/run-pass/alt-ref-binding.rs b/src/test/run-pass/alt-ref-binding.rs index 23b3062a83a8f..0b613df18ee83 100644 --- a/src/test/run-pass/alt-ref-binding.rs +++ b/src/test/run-pass/alt-ref-binding.rs @@ -16,5 +16,5 @@ fn destructure(x: Option) -> int { } pub fn main() { - assert!(destructure(Some(22)) == 22); + assert_eq!(destructure(Some(22)), 22); } diff --git a/src/test/run-pass/alt-str.rs b/src/test/run-pass/alt-str.rs index e41ec8a99e93f..8bbcc507f184f 100644 --- a/src/test/run-pass/alt-str.rs +++ b/src/test/run-pass/alt-str.rs @@ -24,7 +24,7 @@ pub fn main() { } let x = match ~"a" { ~"a" => 1, ~"b" => 2, _ => fail!() }; - assert!((x == 1)); + assert_eq!(x, 1); match ~"a" { ~"a" => { } ~"b" => { }, _ => fail!() } diff --git a/src/test/run-pass/alt-tag.rs b/src/test/run-pass/alt-tag.rs index e2e1bf540c2ce..9eeb12d9c45f2 100644 --- a/src/test/run-pass/alt-tag.rs +++ b/src/test/run-pass/alt-tag.rs @@ -32,7 +32,7 @@ pub fn main() { let gray: color = rgb(127, 127, 127); let clear: color = rgba(50, 150, 250, 0); let red: color = hsl(0, 255, 255); - assert!((process(gray) == 127)); - assert!((process(clear) == 0)); - assert!((process(red) == 255)); + assert_eq!(process(gray), 127); + assert_eq!(process(clear), 0); + assert_eq!(process(red), 255); } diff --git a/src/test/run-pass/alt-unique-bind.rs b/src/test/run-pass/alt-unique-bind.rs index 2fb0a345157ee..997cc1ee9ff9d 100644 --- a/src/test/run-pass/alt-unique-bind.rs +++ b/src/test/run-pass/alt-unique-bind.rs @@ -12,7 +12,7 @@ pub fn main() { match ~100 { ~x => { debug!("%?", x); - assert!(x == 100); + assert_eq!(x, 100); } } } diff --git a/src/test/run-pass/alt-with-ret-arm.rs b/src/test/run-pass/alt-with-ret-arm.rs index d5d2e20cba3d5..f46521f1d5517 100644 --- a/src/test/run-pass/alt-with-ret-arm.rs +++ b/src/test/run-pass/alt-with-ret-arm.rs @@ -16,6 +16,6 @@ pub fn main() { None => return (), Some(num) => num as u32 }; - assert!(f == 1234u32); + assert_eq!(f, 1234u32); error!(f) } diff --git a/src/test/run-pass/argument-passing.rs b/src/test/run-pass/argument-passing.rs index 8c84187ff6f06..7e56edbedf629 100644 --- a/src/test/run-pass/argument-passing.rs +++ b/src/test/run-pass/argument-passing.rs @@ -25,9 +25,9 @@ fn f2(a: int, f: &fn(int)) -> int { f(1); return a; } pub fn main() { let mut a = X {x: 1}, b = 2, c = 3; - assert!((f1(&mut a, &mut b, c) == 6)); - assert!((a.x == 0)); - assert!((b == 10)); - assert!((f2(a.x, |x| a.x = 50) == 0)); - assert!((a.x == 50)); + assert_eq!(f1(&mut a, &mut b, c), 6); + assert_eq!(a.x, 0); + assert_eq!(b, 10); + assert_eq!(f2(a.x, |x| a.x = 50), 0); + assert_eq!(a.x, 50); } diff --git a/src/test/run-pass/arith-0.rs b/src/test/run-pass/arith-0.rs index a0512ffff2a4f..308a5c2721c3d 100644 --- a/src/test/run-pass/arith-0.rs +++ b/src/test/run-pass/arith-0.rs @@ -13,5 +13,5 @@ pub fn main() { let a: int = 10; debug!(a); - assert!((a * (a - 1) == 90)); + assert_eq!(a * (a - 1), 90); } diff --git a/src/test/run-pass/arith-1.rs b/src/test/run-pass/arith-1.rs index c0db96f99c7f4..a6321439db943 100644 --- a/src/test/run-pass/arith-1.rs +++ b/src/test/run-pass/arith-1.rs @@ -12,22 +12,22 @@ pub fn main() { let i32_a: int = 10; - assert!((i32_a == 10)); - assert!((i32_a - 10 == 0)); - assert!((i32_a / 10 == 1)); - assert!((i32_a - 20 == -10)); - assert!((i32_a << 10 == 10240)); - assert!((i32_a << 16 == 655360)); - assert!((i32_a * 16 == 160)); - assert!((i32_a * i32_a * i32_a == 1000)); - assert!((i32_a * i32_a * i32_a * i32_a == 10000)); - assert!((i32_a * i32_a / i32_a * i32_a == 100)); - assert!((i32_a * (i32_a - 1) << 2 + i32_a == 368640)); + assert_eq!(i32_a, 10); + assert_eq!(i32_a - 10, 0); + assert_eq!(i32_a / 10, 1); + assert_eq!(i32_a - 20, -10); + assert_eq!(i32_a << 10, 10240); + assert_eq!(i32_a << 16, 655360); + assert_eq!(i32_a * 16, 160); + assert_eq!(i32_a * i32_a * i32_a, 1000); + assert_eq!(i32_a * i32_a * i32_a * i32_a, 10000); + assert_eq!(i32_a * i32_a / i32_a * i32_a, 100); + assert_eq!(i32_a * (i32_a - 1) << 2 + i32_a, 368640); let i32_b: int = 0x10101010; - assert!((i32_b + 1 - 1 == i32_b)); - assert!((i32_b << 1 == i32_b << 1)); - assert!((i32_b >> 1 == i32_b >> 1)); - assert!((i32_b & i32_b << 1 == 0)); + assert_eq!(i32_b + 1 - 1, i32_b); + assert_eq!(i32_b << 1, i32_b << 1); + assert_eq!(i32_b >> 1, i32_b >> 1); + assert_eq!(i32_b & i32_b << 1, 0); debug!(i32_b | i32_b << 1); - assert!((i32_b | i32_b << 1 == 0x30303030)); + assert_eq!(i32_b | i32_b << 1, 0x30303030); } diff --git a/src/test/run-pass/arith-unsigned.rs b/src/test/run-pass/arith-unsigned.rs index a921d9f7ddc7b..0eb4e7ad92e78 100644 --- a/src/test/run-pass/arith-unsigned.rs +++ b/src/test/run-pass/arith-unsigned.rs @@ -17,20 +17,20 @@ pub fn main() { assert!((0u8 <= 255u8)); assert!((255u8 > 0u8)); assert!((255u8 >= 0u8)); - assert!((250u8 / 10u8 == 25u8)); - assert!((255u8 % 10u8 == 5u8)); + assert_eq!(250u8 / 10u8, 25u8); + assert_eq!(255u8 % 10u8, 5u8); assert!((0u16 < 60000u16)); assert!((0u16 <= 60000u16)); assert!((60000u16 > 0u16)); assert!((60000u16 >= 0u16)); - assert!((60000u16 / 10u16 == 6000u16)); - assert!((60005u16 % 10u16 == 5u16)); + assert_eq!(60000u16 / 10u16, 6000u16); + assert_eq!(60005u16 % 10u16, 5u16); assert!((0u32 < 4000000000u32)); assert!((0u32 <= 4000000000u32)); assert!((4000000000u32 > 0u32)); assert!((4000000000u32 >= 0u32)); - assert!((4000000000u32 / 10u32 == 400000000u32)); - assert!((4000000005u32 % 10u32 == 5u32)); + assert_eq!(4000000000u32 / 10u32, 400000000u32); + assert_eq!(4000000005u32 % 10u32, 5u32); // 64-bit numbers have some flakiness yet. Not tested } diff --git a/src/test/run-pass/assign-assign.rs b/src/test/run-pass/assign-assign.rs index dc0850b24f1f6..5fe2aa6cc7c0e 100644 --- a/src/test/run-pass/assign-assign.rs +++ b/src/test/run-pass/assign-assign.rs @@ -12,21 +12,21 @@ fn test_assign() { let mut x: int; let mut y: () = x = 10; - assert!((x == 10)); + assert_eq!(x, 10); let mut z = x = 11; - assert!((x == 11)); + assert_eq!(x, 11); z = x = 12; - assert!((x == 12)); + assert_eq!(x, 12); } fn test_assign_op() { let mut x: int = 0; let mut y: () = x += 10; - assert!((x == 10)); + assert_eq!(x, 10); let mut z = x += 11; - assert!((x == 21)); + assert_eq!(x, 21); z = x += 12; - assert!((x == 33)); + assert_eq!(x, 33); } pub fn main() { test_assign(); test_assign_op(); } diff --git a/src/test/run-pass/assignability-trait.rs b/src/test/run-pass/assignability-trait.rs index b21213bb221b6..64e1e20e4ba29 100644 --- a/src/test/run-pass/assignability-trait.rs +++ b/src/test/run-pass/assignability-trait.rs @@ -39,15 +39,15 @@ pub fn main() { // Call a method for x.iterate() |y| { assert!(x[*y] == *y); } // Call a parameterized function - assert!(length(x.clone()) == x.len()); + assert_eq!(length(x.clone()), x.len()); // Call a parameterized function, with type arguments that require // a borrow - assert!(length::(x) == x.len()); + assert_eq!(length::(x), x.len()); // Now try it with a type that *needs* to be borrowed let z = [0,1,2,3]; // Call a method for z.iterate() |y| { assert!(z[*y] == *y); } // Call a parameterized function - assert!(length::(z) == z.len()); + assert_eq!(length::(z), z.len()); } diff --git a/src/test/run-pass/auto-loop.rs b/src/test/run-pass/auto-loop.rs index e988028dd1158..dbcbb77efa39e 100644 --- a/src/test/run-pass/auto-loop.rs +++ b/src/test/run-pass/auto-loop.rs @@ -13,5 +13,5 @@ pub fn main() { for vec::each(~[1, 2, 3, 4, 5]) |x| { sum += *x; } - assert!((sum == 15)); + assert_eq!(sum, 15); } diff --git a/src/test/run-pass/auto-ref-newtype.rs b/src/test/run-pass/auto-ref-newtype.rs index a9fca0ccb1589..26ef339daf562 100644 --- a/src/test/run-pass/auto-ref-newtype.rs +++ b/src/test/run-pass/auto-ref-newtype.rs @@ -19,5 +19,5 @@ pub impl Foo { pub fn main() { let m = Foo(3); - assert!(m.len() == 3); + assert_eq!(m.len(), 3); } diff --git a/src/test/run-pass/auto-ref-sliceable.rs b/src/test/run-pass/auto-ref-sliceable.rs index f74d78f99d0b2..8e2b3b56736e2 100644 --- a/src/test/run-pass/auto-ref-sliceable.rs +++ b/src/test/run-pass/auto-ref-sliceable.rs @@ -22,5 +22,5 @@ pub fn main() { let mut v = ~[1]; v.push_val(2); v.push_val(3); - assert!(v == ~[1, 2, 3]); + assert_eq!(v, ~[1, 2, 3]); } diff --git a/src/test/run-pass/autobind.rs b/src/test/run-pass/autobind.rs index afaafd45b7b6f..0788c74d07850 100644 --- a/src/test/run-pass/autobind.rs +++ b/src/test/run-pass/autobind.rs @@ -13,7 +13,7 @@ fn f(x: ~[T]) -> T { return x[0]; } fn g(act: &fn(~[int]) -> int) -> int { return act(~[1, 2, 3]); } pub fn main() { - assert!((g(f) == 1)); + assert_eq!(g(f), 1); let f1: &fn(~[~str]) -> ~str = f; - assert!((f1(~[~"x", ~"y", ~"z"]) == ~"x")); + assert_eq!(f1(~[~"x", ~"y", ~"z"]), ~"x"); } diff --git a/src/test/run-pass/autoderef-method-newtype.rs b/src/test/run-pass/autoderef-method-newtype.rs index 2d6f03c1daf20..e3a19b23e91bf 100644 --- a/src/test/run-pass/autoderef-method-newtype.rs +++ b/src/test/run-pass/autoderef-method-newtype.rs @@ -20,5 +20,5 @@ struct foo(uint); pub fn main() { let x = foo(3u); - assert!(x.double() == 6u); + assert_eq!(x.double(), 6u); } diff --git a/src/test/run-pass/autoderef-method-on-trait.rs b/src/test/run-pass/autoderef-method-on-trait.rs index 32f09369d9817..9bc71517c1fb8 100644 --- a/src/test/run-pass/autoderef-method-on-trait.rs +++ b/src/test/run-pass/autoderef-method-on-trait.rs @@ -18,5 +18,5 @@ impl double for uint { pub fn main() { let x = @(@3u as @double); - assert!(x.double() == 6u); + assert_eq!(x.double(), 6u); } diff --git a/src/test/run-pass/autoderef-method-priority.rs b/src/test/run-pass/autoderef-method-priority.rs index eaef1ae3477a7..9cfdac0a330b0 100644 --- a/src/test/run-pass/autoderef-method-priority.rs +++ b/src/test/run-pass/autoderef-method-priority.rs @@ -25,5 +25,5 @@ impl double for @uint { pub fn main() { let x = @3u; - assert!(x.double() == 6u); + assert_eq!(x.double(), 6u); } diff --git a/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs b/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs index c04efd7e18f54..299760289c2b3 100644 --- a/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs +++ b/src/test/run-pass/autoderef-method-twice-but-not-thrice.rs @@ -18,5 +18,5 @@ impl double for @uint { pub fn main() { let x = @@@@@3u; - assert!(x.double() == 6u); + assert_eq!(x.double(), 6u); } diff --git a/src/test/run-pass/autoderef-method-twice.rs b/src/test/run-pass/autoderef-method-twice.rs index 0a2a93d40d186..f93f0605269a4 100644 --- a/src/test/run-pass/autoderef-method-twice.rs +++ b/src/test/run-pass/autoderef-method-twice.rs @@ -18,5 +18,5 @@ impl double for uint { pub fn main() { let x = @@3u; - assert!(x.double() == 6u); + assert_eq!(x.double(), 6u); } diff --git a/src/test/run-pass/autoderef-method.rs b/src/test/run-pass/autoderef-method.rs index b704011ad9882..eb173e3d5f8ec 100644 --- a/src/test/run-pass/autoderef-method.rs +++ b/src/test/run-pass/autoderef-method.rs @@ -18,5 +18,5 @@ impl double for uint { pub fn main() { let x = @3u; - assert!(x.double() == 6u); + assert_eq!(x.double(), 6u); } diff --git a/src/test/run-pass/autoref-intermediate-types-issue-3585.rs b/src/test/run-pass/autoref-intermediate-types-issue-3585.rs index 5325242b99c33..cae3bff8043ea 100644 --- a/src/test/run-pass/autoref-intermediate-types-issue-3585.rs +++ b/src/test/run-pass/autoref-intermediate-types-issue-3585.rs @@ -26,5 +26,5 @@ impl Foo for uint { pub fn main() { let x = @3u; - assert!(x.foo() == ~"@3"); + assert_eq!(x.foo(), ~"@3"); } diff --git a/src/test/run-pass/big-literals.rs b/src/test/run-pass/big-literals.rs index 41aa204279689..96615b740b72b 100644 --- a/src/test/run-pass/big-literals.rs +++ b/src/test/run-pass/big-literals.rs @@ -11,11 +11,11 @@ // except according to those terms. pub fn main() { - assert!(0xffffffffu32 == (-1 as u32)); - assert!(4294967295u32 == (-1 as u32)); - assert!(0xffffffffffffffffu64 == (-1 as u64)); - assert!(18446744073709551615u64 == (-1 as u64)); + assert_eq!(0xffffffffu32, (-1 as u32)); + assert_eq!(4294967295u32, (-1 as u32)); + assert_eq!(0xffffffffffffffffu64, (-1 as u64)); + assert_eq!(18446744073709551615u64, (-1 as u64)); - assert!(-2147483648i32 - 1i32 == 2147483647i32); - assert!(-9223372036854775808i64 - 1i64 == 9223372036854775807i64); + assert_eq!(-2147483648i32 - 1i32, 2147483647i32); + assert_eq!(-9223372036854775808i64 - 1i64, 9223372036854775807i64); } diff --git a/src/test/run-pass/binary-minus-without-space.rs b/src/test/run-pass/binary-minus-without-space.rs index 93f57c6722f21..78edf3e112e98 100644 --- a/src/test/run-pass/binary-minus-without-space.rs +++ b/src/test/run-pass/binary-minus-without-space.rs @@ -12,5 +12,5 @@ pub fn main() { match -1 { -1 => {}, _ => fail!("wat") } - assert!(1-1 == 0); + assert_eq!(1-1, 0); } diff --git a/src/test/run-pass/binops.rs b/src/test/run-pass/binops.rs index e755a34f0589e..9039730f11963 100644 --- a/src/test/run-pass/binops.rs +++ b/src/test/run-pass/binops.rs @@ -11,7 +11,7 @@ // Binop corner cases fn test_nil() { - assert!((() == ())); + assert_eq!((), ()); assert!((!(() != ()))); assert!((!(() < ()))); assert!((() <= ())); @@ -31,35 +31,35 @@ fn test_bool() { assert!((!(false >= true))); // Bools support bitwise binops - assert!((false & false == false)); - assert!((true & false == false)); - assert!((true & true == true)); - assert!((false | false == false)); - assert!((true | false == true)); - assert!((true | true == true)); - assert!((false ^ false == false)); - assert!((true ^ false == true)); - assert!((true ^ true == false)); + assert_eq!(false & false, false); + assert_eq!(true & false, false); + assert_eq!(true & true, true); + assert_eq!(false | false, false); + assert_eq!(true | false, true); + assert_eq!(true | true, true); + assert_eq!(false ^ false, false); + assert_eq!(true ^ false, true); + assert_eq!(true ^ true, false); } fn test_char() { let ch10 = 10 as char; let ch4 = 4 as char; let ch2 = 2 as char; - assert!((ch10 + ch4 == 14 as char)); - assert!((ch10 - ch4 == 6 as char)); - assert!((ch10 * ch4 == 40 as char)); - assert!((ch10 / ch4 == ch2)); - assert!((ch10 % ch4 == ch2)); - assert!((ch10 >> ch2 == ch2)); - assert!((ch10 << ch4 == 160 as char)); - assert!((ch10 | ch4 == 14 as char)); - assert!((ch10 & ch2 == ch2)); - assert!((ch10 ^ ch2 == 8 as char)); + assert_eq!(ch10 + ch4, 14 as char); + assert_eq!(ch10 - ch4, 6 as char); + assert_eq!(ch10 * ch4, 40 as char); + assert_eq!(ch10 / ch4, ch2); + assert_eq!(ch10 % ch4, ch2); + assert_eq!(ch10 >> ch2, ch2); + assert_eq!(ch10 << ch4, 160 as char); + assert_eq!(ch10 | ch4, 14 as char); + assert_eq!(ch10 & ch2, ch2); + assert_eq!(ch10 ^ ch2, 8 as char); } fn test_box() { - assert!((@10 == @10)); + assert_eq!(@10, @10); } fn test_ptr() { @@ -68,7 +68,7 @@ fn test_ptr() { let p2: *u8 = ::core::cast::transmute(0); let p3: *u8 = ::core::cast::transmute(1); - assert!(p1 == p2); + assert_eq!(p1, p2); assert!(p1 != p3); assert!(p1 < p3); assert!(p1 <= p3); @@ -110,10 +110,10 @@ fn test_class() { (::core::cast::transmute::<*p, uint>(&q)), (::core::cast::transmute::<*p, uint>(&r))); } - assert!((q == r)); + assert_eq!(q, r); r.y = 17; assert!((r.y != q.y)); - assert!((r.y == 17)); + assert_eq!(r.y, 17); assert!((q != r)); } diff --git a/src/test/run-pass/bitwise.rs b/src/test/run-pass/bitwise.rs index ce06f09d32132..d3d1a1d12b269 100644 --- a/src/test/run-pass/bitwise.rs +++ b/src/test/run-pass/bitwise.rs @@ -13,12 +13,12 @@ #[cfg(target_arch = "x86")] #[cfg(target_arch = "arm")] fn target() { - assert!((-1000 as uint >> 3u == 536870787u)); + assert_eq!(-1000 as uint >> 3u, 536870787u); } #[cfg(target_arch = "x86_64")] fn target() { - assert!((-1000 as uint >> 3u == 2305843009213693827u)); + assert_eq!(-1000 as uint >> 3u, 2305843009213693827u); } fn general() { @@ -29,14 +29,14 @@ fn general() { a = a ^ b; debug!(a); debug!(b); - assert!((b == 1)); - assert!((a == 2)); - assert!((!0xf0 & 0xff == 0xf)); - assert!((0xf0 | 0xf == 0xff)); - assert!((0xf << 4 == 0xf0)); - assert!((0xf0 >> 4 == 0xf)); - assert!((-16 >> 2 == -4)); - assert!((0b1010_1010 | 0b0101_0101 == 0xff)); + assert_eq!(b, 1); + assert_eq!(a, 2); + assert_eq!(!0xf0 & 0xff, 0xf); + assert_eq!(0xf0 | 0xf, 0xff); + assert_eq!(0xf << 4, 0xf0); + assert_eq!(0xf0 >> 4, 0xf); + assert_eq!(-16 >> 2, -4); + assert_eq!(0b1010_1010 | 0b0101_0101, 0xff); } pub fn main() { diff --git a/src/test/run-pass/block-arg-call-as.rs b/src/test/run-pass/block-arg-call-as.rs index 22d495e2c1ba2..e27458327696e 100644 --- a/src/test/run-pass/block-arg-call-as.rs +++ b/src/test/run-pass/block-arg-call-as.rs @@ -24,9 +24,9 @@ fn asBlock( f : &fn()->uint ) -> uint { pub fn main() { let x = asSendfn(|| 22u); - assert!((x == 22u)); + assert_eq!(x, 22u); let x = asLambda(|| 22u); - assert!((x == 22u)); + assert_eq!(x, 22u); let x = asBlock(|| 22u); - assert!((x == 22u)); + assert_eq!(x, 22u); } diff --git a/src/test/run-pass/block-arg-can-be-followed-by-binop.rs b/src/test/run-pass/block-arg-can-be-followed-by-binop.rs index 74756d27fe763..d10bcaa216a67 100644 --- a/src/test/run-pass/block-arg-can-be-followed-by-binop.rs +++ b/src/test/run-pass/block-arg-can-be-followed-by-binop.rs @@ -14,5 +14,5 @@ pub fn main() { // Trailing expressions don't require parentheses: let y = do vec::foldl(0f, v) |x, y| { x + *y } + 10f; - assert!(y == 15f); + assert_eq!(y, 15f); } diff --git a/src/test/run-pass/block-arg-can-be-followed-by-block-arg.rs b/src/test/run-pass/block-arg-can-be-followed-by-block-arg.rs index 4cadb883d9962..194fa297361f9 100644 --- a/src/test/run-pass/block-arg-can-be-followed-by-block-arg.rs +++ b/src/test/run-pass/block-arg-can-be-followed-by-block-arg.rs @@ -12,5 +12,5 @@ pub fn main() { fn f(i: &fn() -> uint) -> uint { i() } let v = ~[-1f, 0f, 1f, 2f, 3f]; let z = do do vec::foldl(f, v) |x, _y| { x } { 22u }; - assert!(z == 22u); + assert_eq!(z, 22u); } diff --git a/src/test/run-pass/block-arg-can-be-followed-by-call.rs b/src/test/run-pass/block-arg-can-be-followed-by-call.rs index ac584324cece8..5243eae30ca63 100644 --- a/src/test/run-pass/block-arg-can-be-followed-by-call.rs +++ b/src/test/run-pass/block-arg-can-be-followed-by-call.rs @@ -12,5 +12,5 @@ pub fn main() { fn f(i: uint) -> uint { i } let v = ~[-1f, 0f, 1f, 2f, 3f]; let z = do vec::foldl(f, v) |x, _y| { x } (22u); - assert!(z == 22u); + assert_eq!(z, 22u); } diff --git a/src/test/run-pass/block-arg-in-parentheses.rs b/src/test/run-pass/block-arg-in-parentheses.rs index ad53bd2275451..ea189de562a8b 100644 --- a/src/test/run-pass/block-arg-in-parentheses.rs +++ b/src/test/run-pass/block-arg-in-parentheses.rs @@ -28,8 +28,8 @@ fn w_ret(v: ~[int]) -> int { } pub fn main() { - assert!(w_semi(~[0, 1, 2, 3]) == -10); - assert!(w_paren1(~[0, 1, 2, 3]) == -4); - assert!(w_paren2(~[0, 1, 2, 3]) == -4); - assert!(w_ret(~[0, 1, 2, 3]) == -4); + assert_eq!(w_semi(~[0, 1, 2, 3]), -10); + assert_eq!(w_paren1(~[0, 1, 2, 3]), -4); + assert_eq!(w_paren2(~[0, 1, 2, 3]), -4); + assert_eq!(w_ret(~[0, 1, 2, 3]), -4); } diff --git a/src/test/run-pass/block-arg-used-as-any.rs b/src/test/run-pass/block-arg-used-as-any.rs index d8aeba355d147..7ee9d9e5b5489 100644 --- a/src/test/run-pass/block-arg-used-as-any.rs +++ b/src/test/run-pass/block-arg-used-as-any.rs @@ -14,5 +14,5 @@ fn call_any(f: &fn() -> uint) -> uint { pub fn main() { let x_r = do call_any { 22u }; - assert!(x_r == 22u); + assert_eq!(x_r, 22u); } diff --git a/src/test/run-pass/block-arg-used-as-lambda.rs b/src/test/run-pass/block-arg-used-as-lambda.rs index 2a7bfe4e32876..34fa7e36d973f 100644 --- a/src/test/run-pass/block-arg-used-as-lambda.rs +++ b/src/test/run-pass/block-arg-used-as-lambda.rs @@ -19,6 +19,6 @@ pub fn main() { let x_r = x(22u); let y_r = y(x_r); - assert!(x_r == 44u); - assert!(y_r == 88u); + assert_eq!(x_r, 44u); + assert_eq!(y_r, 88u); } diff --git a/src/test/run-pass/block-arg.rs b/src/test/run-pass/block-arg.rs index 04032900c5160..de29ec99167f9 100644 --- a/src/test/run-pass/block-arg.rs +++ b/src/test/run-pass/block-arg.rs @@ -51,8 +51,8 @@ pub fn main() { let w = do vec::foldl(0f, v) |x, y| { x + *y } + 10f; let y = do vec::foldl(0f, v) |x, y| { x + *y } + 10f; let z = 10f + do vec::foldl(0f, v) |x, y| { x + *y }; - assert!(w == y); - assert!(y == z); + assert_eq!(w, y); + assert_eq!(y, z); // In the tail of a block let w = diff --git a/src/test/run-pass/block-expr-precedence.rs b/src/test/run-pass/block-expr-precedence.rs index d8f6f167f208a..ace372dd2d3d9 100644 --- a/src/test/run-pass/block-expr-precedence.rs +++ b/src/test/run-pass/block-expr-precedence.rs @@ -58,8 +58,8 @@ pub fn main() { let num = 12; - assert!(if (true) { 12 } else { 12 } - num == 0); - assert!(12 - if (true) { 12 } else { 12 } == 0); + assert_eq!(if (true) { 12 } else { 12 } - num, 0); + assert_eq!(12 - if (true) { 12 } else { 12 }, 0); if (true) { 12; } {-num}; if (true) { 12; }; {-num}; if (true) { 12; };;; -num; diff --git a/src/test/run-pass/block-fn-coerce.rs b/src/test/run-pass/block-fn-coerce.rs index 5a4b2f8bfd663..19e1fd4099b74 100644 --- a/src/test/run-pass/block-fn-coerce.rs +++ b/src/test/run-pass/block-fn-coerce.rs @@ -11,7 +11,7 @@ fn force(f: &fn() -> int) -> int { return f(); } pub fn main() { fn f() -> int { return 7; } - assert!((force(f) == 7)); + assert_eq!(force(f), 7); let g = {||force(f)}; - assert!((g() == 7)); + assert_eq!(g(), 7); } diff --git a/src/test/run-pass/block-iter-1.rs b/src/test/run-pass/block-iter-1.rs index 0a3458ed8141a..34b77b4a844a8 100644 --- a/src/test/run-pass/block-iter-1.rs +++ b/src/test/run-pass/block-iter-1.rs @@ -21,5 +21,5 @@ pub fn main() { } }); error!(odds); - assert!((odds == 4)); + assert_eq!(odds, 4); } diff --git a/src/test/run-pass/block-iter-2.rs b/src/test/run-pass/block-iter-2.rs index e5c527db5566b..dc4ff5a054fbb 100644 --- a/src/test/run-pass/block-iter-2.rs +++ b/src/test/run-pass/block-iter-2.rs @@ -21,5 +21,5 @@ pub fn main() { }); }); error!(sum); - assert!((sum == 225)); + assert_eq!(sum, 225); } diff --git a/src/test/run-pass/block-vec-map_zip.rs b/src/test/run-pass/block-vec-map_zip.rs index 5d637ba8cef06..b859dc91fba0c 100644 --- a/src/test/run-pass/block-vec-map_zip.rs +++ b/src/test/run-pass/block-vec-map_zip.rs @@ -16,5 +16,5 @@ pub fn main() { ~[true, false, false, true, true], |i, b| if *b { -(*i) } else { *i } ); error!(v.clone()); - assert!((v == ~[-1, 2, 3, -4, -5])); + assert_eq!(v, ~[-1, 2, 3, -4, -5]); } diff --git a/src/test/run-pass/borrowck-borrow-from-at-vec.rs b/src/test/run-pass/borrowck-borrow-from-at-vec.rs index e5f2a18df63cf..fb91e9a787e36 100644 --- a/src/test/run-pass/borrowck-borrow-from-at-vec.rs +++ b/src/test/run-pass/borrowck-borrow-from-at-vec.rs @@ -16,5 +16,5 @@ fn sum_slice(x: &[int]) -> int { pub fn main() { let x = @[1, 2, 3]; - assert!(sum_slice(x) == 6); + assert_eq!(sum_slice(x), 6); } diff --git a/src/test/run-pass/borrowck-borrow-from-expr-block.rs b/src/test/run-pass/borrowck-borrow-from-expr-block.rs index d65a043bf47e9..5149c87c4908e 100644 --- a/src/test/run-pass/borrowck-borrow-from-expr-block.rs +++ b/src/test/run-pass/borrowck-borrow-from-expr-block.rs @@ -16,7 +16,7 @@ fn test1(x: @~int) { do borrow(&*(*x).clone()) |p| { let x_a = ptr::to_unsafe_ptr(&**x); assert!((x_a as uint) != ptr::to_uint(p)); - assert!(unsafe{*x_a} == *p); + assert_eq!(unsafe{*x_a}, *p); } } diff --git a/src/test/run-pass/borrowck-fixed-length-vecs.rs b/src/test/run-pass/borrowck-fixed-length-vecs.rs index e9d4a24806819..ee561fdb0be52 100644 --- a/src/test/run-pass/borrowck-fixed-length-vecs.rs +++ b/src/test/run-pass/borrowck-fixed-length-vecs.rs @@ -11,5 +11,5 @@ pub fn main() { let x = [22]; let y = &x[0]; - assert!(*y == 22); + assert_eq!(*y, 22); } diff --git a/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs b/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs index 8f66faab01451..4b5d73f597e3f 100644 --- a/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs +++ b/src/test/run-pass/borrowck-mut-vec-as-imm-slice.rs @@ -19,5 +19,5 @@ fn has_mut_vec(v: ~[int]) -> int { } pub fn main() { - assert!(has_mut_vec(~[1, 2, 3]) == 6); + assert_eq!(has_mut_vec(~[1, 2, 3]), 6); } diff --git a/src/test/run-pass/borrowck-preserve-box-in-discr.rs b/src/test/run-pass/borrowck-preserve-box-in-discr.rs index db88646631357..5a94e2f5cd03e 100644 --- a/src/test/run-pass/borrowck-preserve-box-in-discr.rs +++ b/src/test/run-pass/borrowck-preserve-box-in-discr.rs @@ -16,14 +16,14 @@ pub fn main() { let mut x = @F {f: ~3}; match x { @F {f: ref b_x} => { - assert!(**b_x == 3); - assert!(ptr::to_unsafe_ptr(&(*x.f)) == ptr::to_unsafe_ptr(&(**b_x))); + assert_eq!(**b_x, 3); + assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); - assert!(**b_x == 3); + assert_eq!(**b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x))); } } diff --git a/src/test/run-pass/borrowck-preserve-box-in-field.rs b/src/test/run-pass/borrowck-preserve-box-in-field.rs index 3c95054d10c93..f86471fd20904 100644 --- a/src/test/run-pass/borrowck-preserve-box-in-field.rs +++ b/src/test/run-pass/borrowck-preserve-box-in-field.rs @@ -14,7 +14,7 @@ fn borrow(x: &int, f: &fn(x: &int)) { let before = *x; f(x); let after = *x; - assert!(before == after); + assert_eq!(before, after); } struct F { f: ~int } @@ -22,13 +22,13 @@ struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; do borrow(x.f) |b_x| { - assert!(*b_x == 3); - assert!(ptr::to_unsafe_ptr(&(*x.f)) == ptr::to_unsafe_ptr(&(*b_x))); + assert_eq!(*b_x, 3); + assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(*b_x)) as uint); - assert!(*b_x == 3); + assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(*b_x))); } } diff --git a/src/test/run-pass/borrowck-preserve-box-in-pat.rs b/src/test/run-pass/borrowck-preserve-box-in-pat.rs index ad0c5b69ba849..17f9dcb627d69 100644 --- a/src/test/run-pass/borrowck-preserve-box-in-pat.rs +++ b/src/test/run-pass/borrowck-preserve-box-in-pat.rs @@ -16,14 +16,14 @@ pub fn main() { let mut x = @mut @F {f: ~3}; match x { @@F{f: ref b_x} => { - assert!(**b_x == 3); - assert!(ptr::to_unsafe_ptr(&(x.f)) == ptr::to_unsafe_ptr(b_x)); + assert_eq!(**b_x, 3); + assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x)); *x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); - assert!(**b_x == 3); + assert_eq!(**b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x))); } } diff --git a/src/test/run-pass/borrowck-preserve-box-in-uniq.rs b/src/test/run-pass/borrowck-preserve-box-in-uniq.rs index cce08ab235613..25bc5c0c982d9 100644 --- a/src/test/run-pass/borrowck-preserve-box-in-uniq.rs +++ b/src/test/run-pass/borrowck-preserve-box-in-uniq.rs @@ -14,7 +14,7 @@ fn borrow(x: &int, f: &fn(x: &int)) { let before = *x; f(x); let after = *x; - assert!(before == after); + assert_eq!(before, after); } struct F { f: ~int } @@ -22,13 +22,13 @@ struct F { f: ~int } pub fn main() { let mut x = ~@F{f: ~3}; do borrow(x.f) |b_x| { - assert!(*b_x == 3); - assert!(ptr::to_unsafe_ptr(&(*x.f)) == ptr::to_unsafe_ptr(&(*b_x))); + assert_eq!(*b_x, 3); + assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); *x = @F{f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(*b_x)) as uint); - assert!(*b_x == 3); + assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(*b_x))); } } diff --git a/src/test/run-pass/borrowck-preserve-box.rs b/src/test/run-pass/borrowck-preserve-box.rs index 104b0ae6bc551..5f4d907e96289 100644 --- a/src/test/run-pass/borrowck-preserve-box.rs +++ b/src/test/run-pass/borrowck-preserve-box.rs @@ -14,19 +14,19 @@ fn borrow(x: &int, f: &fn(x: &int)) { let before = *x; f(x); let after = *x; - assert!(before == after); + assert_eq!(before, after); } pub fn main() { let mut x = @3; do borrow(x) |b_x| { - assert!(*b_x == 3); - assert!(ptr::to_unsafe_ptr(&(*x)) == ptr::to_unsafe_ptr(&(*b_x))); + assert_eq!(*b_x, 3); + assert_eq!(ptr::to_unsafe_ptr(&(*x)), ptr::to_unsafe_ptr(&(*b_x))); x = @22; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(*b_x)) as uint); - assert!(*b_x == 3); + assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x)) != ptr::to_unsafe_ptr(&(*b_x))); } } diff --git a/src/test/run-pass/borrowck-preserve-cond-box.rs b/src/test/run-pass/borrowck-preserve-cond-box.rs index 18c185cfef1c3..d9adcbb06f17e 100644 --- a/src/test/run-pass/borrowck-preserve-cond-box.rs +++ b/src/test/run-pass/borrowck-preserve-cond-box.rs @@ -25,13 +25,13 @@ fn testfn(cond: bool) { } debug!("*r = %d, exp = %d", *r, exp); - assert!(*r == exp); + assert_eq!(*r, exp); x = @5; y = @6; debug!("*r = %d, exp = %d", *r, exp); - assert!(*r == exp); + assert_eq!(*r, exp); } pub fn main() { diff --git a/src/test/run-pass/borrowck-preserve-expl-deref.rs b/src/test/run-pass/borrowck-preserve-expl-deref.rs index 4c5b9f9bf1f82..ac1463caddf9f 100644 --- a/src/test/run-pass/borrowck-preserve-expl-deref.rs +++ b/src/test/run-pass/borrowck-preserve-expl-deref.rs @@ -14,7 +14,7 @@ fn borrow(x: &int, f: &fn(x: &int)) { let before = *x; f(x); let after = *x; - assert!(before == after); + assert_eq!(before, after); } struct F { f: ~int } @@ -22,13 +22,13 @@ struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; do borrow((*x).f) |b_x| { - assert!(*b_x == 3); - assert!(ptr::to_unsafe_ptr(&(*x.f)) == ptr::to_unsafe_ptr(&(*b_x))); + assert_eq!(*b_x, 3); + assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(*b_x)) as uint); - assert!(*b_x == 3); + assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(*b_x))); } } diff --git a/src/test/run-pass/borrowck-univariant-enum.rs b/src/test/run-pass/borrowck-univariant-enum.rs index 3ec061c2dea61..bb8710aad489b 100644 --- a/src/test/run-pass/borrowck-univariant-enum.rs +++ b/src/test/run-pass/borrowck-univariant-enum.rs @@ -25,5 +25,5 @@ pub fn main() { *x * b } }; - assert!(z == 18); + assert_eq!(z, 18); } diff --git a/src/test/run-pass/borrowed-ptr-pattern-infallible.rs b/src/test/run-pass/borrowed-ptr-pattern-infallible.rs index d49ea86402a5f..4e9ba6d3158e0 100644 --- a/src/test/run-pass/borrowed-ptr-pattern-infallible.rs +++ b/src/test/run-pass/borrowed-ptr-pattern-infallible.rs @@ -10,7 +10,7 @@ pub fn main() { let (&x, &y, &z) = (&3, &'a', &@"No pets!"); - assert!(x == 3); - assert!(y == 'a'); - assert!(z == @"No pets!"); + assert_eq!(x, 3); + assert_eq!(y, 'a'); + assert_eq!(z, @"No pets!"); } diff --git a/src/test/run-pass/borrowed-ptr-pattern-option.rs b/src/test/run-pass/borrowed-ptr-pattern-option.rs index dc620d0733d75..4775e5fe0a80e 100644 --- a/src/test/run-pass/borrowed-ptr-pattern-option.rs +++ b/src/test/run-pass/borrowed-ptr-pattern-option.rs @@ -19,5 +19,5 @@ fn select<'r>(x: &'r Option, y: &'r Option) -> &'r Option { pub fn main() { let x = None; let y = Some(3); - assert!(select(&x, &y).get() == 3); + assert_eq!(select(&x, &y).get(), 3); } diff --git a/src/test/run-pass/borrowed-ptr-pattern.rs b/src/test/run-pass/borrowed-ptr-pattern.rs index 44485b5c8df82..e0af2e80508c3 100644 --- a/src/test/run-pass/borrowed-ptr-pattern.rs +++ b/src/test/run-pass/borrowed-ptr-pattern.rs @@ -15,7 +15,7 @@ fn foo(x: &T) -> T{ } pub fn main() { - assert!(foo(&3) == 3); - assert!(foo(&'a') == 'a'); - assert!(foo(&@"Dogs rule, cats drool") == @"Dogs rule, cats drool"); + assert_eq!(foo(&3), 3); + assert_eq!(foo(&'a'), 'a'); + assert_eq!(foo(&@"Dogs rule, cats drool"), @"Dogs rule, cats drool"); } diff --git a/src/test/run-pass/box-unbox.rs b/src/test/run-pass/box-unbox.rs index 96fc7b84bcd9c..e7dc436567982 100644 --- a/src/test/run-pass/box-unbox.rs +++ b/src/test/run-pass/box-unbox.rs @@ -18,5 +18,5 @@ pub fn main() { let foo: int = 17; let bfoo: Box = Box {c: @foo}; debug!("see what's in our box"); - assert!((unbox::(bfoo) == foo)); + assert_eq!(unbox::(bfoo), foo); } diff --git a/src/test/run-pass/break.rs b/src/test/run-pass/break.rs index a182dcf2ca0b2..da362c8194d7c 100644 --- a/src/test/run-pass/break.rs +++ b/src/test/run-pass/break.rs @@ -11,9 +11,9 @@ pub fn main() { let mut i = 0; while i < 20 { i += 1; if i == 10 { break; } } - assert!((i == 10)); + assert_eq!(i, 10); loop { i += 1; if i == 20 { break; } } - assert!((i == 20)); + assert_eq!(i, 20); for vec::each(~[1, 2, 3, 4, 5, 6]) |x| { if *x == 3 { break; } assert!((*x <= 3)); } diff --git a/src/test/run-pass/c-stack-returning-int64.rs b/src/test/run-pass/c-stack-returning-int64.rs index a87dbaab5c99b..ec204e7a4c23f 100644 --- a/src/test/run-pass/c-stack-returning-int64.rs +++ b/src/test/run-pass/c-stack-returning-int64.rs @@ -29,7 +29,7 @@ fn atoll(s: ~str) -> i64 { pub fn main() { unsafe { - assert!(atol(~"1024") * 10 == atol(~"10240")); + assert_eq!(atol(~"1024") * 10, atol(~"10240")); assert!((atoll(~"11111111111111111") * 10i64) == atoll(~"111111111111111110")); } diff --git a/src/test/run-pass/call-closure-from-overloaded-op.rs b/src/test/run-pass/call-closure-from-overloaded-op.rs index 8832620c4bfc7..cc8d8e9619556 100644 --- a/src/test/run-pass/call-closure-from-overloaded-op.rs +++ b/src/test/run-pass/call-closure-from-overloaded-op.rs @@ -13,5 +13,5 @@ fn foo() -> int { 22 } pub fn main() { let mut x: ~[@fn() -> int] = ~[]; x.push(foo); - assert!((x[0])() == 22); + assert_eq!((x[0])(), 22); } diff --git a/src/test/run-pass/cap-clause-move.rs b/src/test/run-pass/cap-clause-move.rs index 5d20990a5a93b..1993965063355 100644 --- a/src/test/run-pass/cap-clause-move.rs +++ b/src/test/run-pass/cap-clause-move.rs @@ -12,20 +12,20 @@ pub fn main() { let x = ~1; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let lam_move: @fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; - assert!(lam_move() == y); + assert_eq!(lam_move(), y); let x = ~2; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let lam_move: @fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; - assert!(lam_move() == y); + assert_eq!(lam_move(), y); let x = ~3; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let snd_move: ~fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; - assert!(snd_move() == y); + assert_eq!(snd_move(), y); let x = ~4; let y = ptr::to_unsafe_ptr(&(*x)) as uint; let lam_move: ~fn() -> uint = || ptr::to_unsafe_ptr(&(*x)) as uint; - assert!(lam_move() == y); + assert_eq!(lam_move(), y); } diff --git a/src/test/run-pass/cast.rs b/src/test/run-pass/cast.rs index 1df1f3b4c8b4f..10407420a4332 100644 --- a/src/test/run-pass/cast.rs +++ b/src/test/run-pass/cast.rs @@ -14,13 +14,13 @@ // -*- rust -*- pub fn main() { let i: int = 'Q' as int; - assert!((i == 0x51)); + assert_eq!(i, 0x51); let u: u32 = i as u32; - assert!((u == 0x51 as u32)); - assert!((u == 'Q' as u32)); - assert!((i as u8 == 'Q' as u8)); - assert!((i as u8 as i8 == 'Q' as u8 as i8)); - assert!((0x51 as char == 'Q')); - assert!((true == 1 as bool)); - assert!((0 as u32 == false as u32)); + assert_eq!(u, 0x51 as u32); + assert_eq!(u, 'Q' as u32); + assert_eq!(i as u8, 'Q' as u8); + assert_eq!(i as u8 as i8, 'Q' as u8 as i8); + assert_eq!(0x51 as char, 'Q'); + assert_eq!(true, 1 as bool); + assert_eq!(0 as u32, false as u32); } diff --git a/src/test/run-pass/cci_borrow.rs b/src/test/run-pass/cci_borrow.rs index e6ec46acd23e3..460d6136cafe0 100644 --- a/src/test/run-pass/cci_borrow.rs +++ b/src/test/run-pass/cci_borrow.rs @@ -18,5 +18,5 @@ pub fn main() { let p = @22u; let r = foo(p); debug!("r=%u", r); - assert!(r == 22u); + assert_eq!(r, 22u); } diff --git a/src/test/run-pass/cci_nested_exe.rs b/src/test/run-pass/cci_nested_exe.rs index 847d8a4d1f90e..231cd37db5d35 100644 --- a/src/test/run-pass/cci_nested_exe.rs +++ b/src/test/run-pass/cci_nested_exe.rs @@ -18,12 +18,12 @@ pub fn main() { let lst = new_int_alist(); alist_add(&lst, 22, ~"hi"); alist_add(&lst, 44, ~"ho"); - assert!(alist_get(&lst, 22) == ~"hi"); - assert!(alist_get(&lst, 44) == ~"ho"); + assert_eq!(alist_get(&lst, 22), ~"hi"); + assert_eq!(alist_get(&lst, 44), ~"ho"); let lst = new_int_alist_2(); alist_add(&lst, 22, ~"hi"); alist_add(&lst, 44, ~"ho"); - assert!(alist_get(&lst, 22) == ~"hi"); - assert!(alist_get(&lst, 44) == ~"ho"); + assert_eq!(alist_get(&lst, 22), ~"hi"); + assert_eq!(alist_get(&lst, 44), ~"ho"); } diff --git a/src/test/run-pass/cfgs-on-items.rs b/src/test/run-pass/cfgs-on-items.rs index ed025623ac311..237fa3f7ea9c9 100644 --- a/src/test/run-pass/cfgs-on-items.rs +++ b/src/test/run-pass/cfgs-on-items.rs @@ -26,6 +26,6 @@ fn foo2() -> int { 3 } fn main() { - assert!(1 == foo1()); - assert!(3 == foo2()); + assert_eq!(1, foo1()); + assert_eq!(3, foo2()); } diff --git a/src/test/run-pass/char.rs b/src/test/run-pass/char.rs index bcfc6a3ccd9a6..f982d3723b4c2 100644 --- a/src/test/run-pass/char.rs +++ b/src/test/run-pass/char.rs @@ -13,11 +13,11 @@ pub fn main() { let c: char = 'x'; let d: char = 'x'; - assert!((c == 'x')); - assert!(('x' == c)); - assert!((c == c)); - assert!((c == d)); - assert!((d == c)); - assert!((d == 'x')); - assert!(('x' == d)); + assert_eq!(c, 'x'); + assert_eq!('x', c); + assert_eq!(c, c); + assert_eq!(c, d); + assert_eq!(d, c); + assert_eq!(d, 'x'); + assert_eq!('x', d); } diff --git a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs index 76f4e3b68f7c2..8bedfef89d00d 100644 --- a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs +++ b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs @@ -17,7 +17,7 @@ use cci_class_cast::kitty::*; fn print_out(thing: @ToStr, expected: ~str) { let actual = thing.to_str(); debug!("%s", actual); - assert!((actual == expected)); + assert_eq!(actual, expected); } pub fn main() { diff --git a/src/test/run-pass/class-cast-to-trait-cross-crate.rs b/src/test/run-pass/class-cast-to-trait-cross-crate.rs index 10cce8cf56a47..6674147e14769 100644 --- a/src/test/run-pass/class-cast-to-trait-cross-crate.rs +++ b/src/test/run-pass/class-cast-to-trait-cross-crate.rs @@ -51,7 +51,7 @@ class cat : to_str { fn print_out(thing: T, expected: str) { let actual = thing.to_str(); debug!("%s", actual); - assert!((actual == expected)); + assert_eq!(actual, expected); } pub fn main() { diff --git a/src/test/run-pass/class-cast-to-trait-multiple-types.rs b/src/test/run-pass/class-cast-to-trait-multiple-types.rs index be63e3394789e..051c09fac537e 100644 --- a/src/test/run-pass/class-cast-to-trait-multiple-types.rs +++ b/src/test/run-pass/class-cast-to-trait-multiple-types.rs @@ -88,6 +88,6 @@ pub fn main() { let whitefang : dog = dog(); annoy_neighbors(@(copy nyan) as @noisy); annoy_neighbors(@(copy whitefang) as @noisy); - assert!((nyan.meow_count() == 10u)); - assert!((*whitefang.volume == 1)); + assert_eq!(nyan.meow_count(), 10u); + assert_eq!(*whitefang.volume, 1); } diff --git a/src/test/run-pass/class-exports.rs b/src/test/run-pass/class-exports.rs index 6684a729d23bb..eb2c26478b693 100644 --- a/src/test/run-pass/class-exports.rs +++ b/src/test/run-pass/class-exports.rs @@ -34,5 +34,5 @@ mod kitty { } pub fn main() { - assert!((cat(~"Spreckles").get_name() == ~"Spreckles")); + assert_eq!(cat(~"Spreckles").get_name(), ~"Spreckles"); } diff --git a/src/test/run-pass/class-impl-very-parameterized-trait.rs b/src/test/run-pass/class-impl-very-parameterized-trait.rs index f7d526cde911a..ae3d088c539c7 100644 --- a/src/test/run-pass/class-impl-very-parameterized-trait.rs +++ b/src/test/run-pass/class-impl-very-parameterized-trait.rs @@ -136,11 +136,11 @@ priv impl cat { pub fn main() { let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan"); for uint::range(1, 5) |_| { nyan.speak(); } - assert!((*nyan.find(&1).unwrap() == ~"nyan")); - assert!((nyan.find(&10) == None)); + assert!(*nyan.find(&1).unwrap() == ~"nyan"); + assert_eq!(nyan.find(&10), None); let mut spotty: cat = cat::new(2, 57, tuxedo); for uint::range(0, 6) |_| { spotty.speak(); } - assert!((spotty.len() == 8)); + assert_eq!(spotty.len(), 8); assert!((spotty.contains_key(&2))); - assert!((spotty.get(&3) == &tuxedo)); + assert_eq!(spotty.get(&3), &tuxedo); } diff --git a/src/test/run-pass/class-implements-multiple-traits.rs b/src/test/run-pass/class-implements-multiple-traits.rs index 61dfcfed7bdfd..9545f5340df76 100644 --- a/src/test/run-pass/class-implements-multiple-traits.rs +++ b/src/test/run-pass/class-implements-multiple-traits.rs @@ -123,7 +123,7 @@ fn scratched_something(critter: T) -> bool { pub fn main() { let nyan : cat = cat(0u, 2, "nyan"); annoy_neighbors(nyan as noisy); - assert!((nyan.meow_count() == 10u)); + assert_eq!(nyan.meow_count(), 10u); assert!((bite_everything(nyan as bitey))); assert!((scratched_something(nyan as scratchy))); } diff --git a/src/test/run-pass/class-method-cross-crate.rs b/src/test/run-pass/class-method-cross-crate.rs index a6ab91a2c8822..d2c78c7f1add8 100644 --- a/src/test/run-pass/class-method-cross-crate.rs +++ b/src/test/run-pass/class-method-cross-crate.rs @@ -16,7 +16,7 @@ use cci_class_2::kitties::*; pub fn main() { let nyan : cat = cat(52u, 99); let kitty = cat(1000u, 2); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); nyan.speak(); } diff --git a/src/test/run-pass/class-methods-cross-crate.rs b/src/test/run-pass/class-methods-cross-crate.rs index 8e5843c6a85be..c5e37cab2b84a 100644 --- a/src/test/run-pass/class-methods-cross-crate.rs +++ b/src/test/run-pass/class-methods-cross-crate.rs @@ -16,8 +16,8 @@ use cci_class_3::kitties::*; pub fn main() { let mut nyan : cat = cat(52u, 99); let mut kitty = cat(1000u, 2); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); nyan.speak(); - assert!((nyan.meow_count() == 53u)); + assert_eq!(nyan.meow_count(), 53u); } diff --git a/src/test/run-pass/class-methods.rs b/src/test/run-pass/class-methods.rs index 1c4c83999f7df..fa358f4b132aa 100644 --- a/src/test/run-pass/class-methods.rs +++ b/src/test/run-pass/class-methods.rs @@ -29,8 +29,8 @@ fn cat(in_x: uint, in_y: int) -> cat { pub fn main() { let mut nyan: cat = cat(52u, 99); let mut kitty = cat(1000u, 2); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); nyan.speak(); - assert!((nyan.meow_count() == 53u)); + assert_eq!(nyan.meow_count(), 53u); } diff --git a/src/test/run-pass/class-poly-methods-cross-crate.rs b/src/test/run-pass/class-poly-methods-cross-crate.rs index cde171a44e243..62ff54388952f 100644 --- a/src/test/run-pass/class-poly-methods-cross-crate.rs +++ b/src/test/run-pass/class-poly-methods-cross-crate.rs @@ -16,10 +16,10 @@ use cci_class_6::kitties::*; pub fn main() { let mut nyan : cat = cat::(52u, 99, ~['p']); let mut kitty = cat(1000u, 2, ~[~"tabby"]); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); nyan.speak(~[1u,2u,3u]); - assert!((nyan.meow_count() == 55u)); + assert_eq!(nyan.meow_count(), 55u); kitty.speak(~[~"meow", ~"mew", ~"purr", ~"chirp"]); - assert!((kitty.meow_count() == 1004u)); + assert_eq!(kitty.meow_count(), 1004u); } diff --git a/src/test/run-pass/class-poly-methods.rs b/src/test/run-pass/class-poly-methods.rs index 9774d8d14882e..f538eb054a67f 100644 --- a/src/test/run-pass/class-poly-methods.rs +++ b/src/test/run-pass/class-poly-methods.rs @@ -33,10 +33,10 @@ fn cat(in_x : uint, in_y : int, in_info: ~[U]) -> cat { pub fn main() { let mut nyan : cat = cat::(52u, 99, ~[9]); let mut kitty = cat(1000u, 2, ~[~"tabby"]); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); nyan.speak(~[1,2,3]); - assert!((nyan.meow_count() == 55u)); + assert_eq!(nyan.meow_count(), 55u); kitty.speak(~[~"meow", ~"mew", ~"purr", ~"chirp"]); - assert!((kitty.meow_count() == 1004u)); + assert_eq!(kitty.meow_count(), 1004u); } diff --git a/src/test/run-pass/class-separate-impl.rs b/src/test/run-pass/class-separate-impl.rs index e058b3331b386..1952520d018bc 100644 --- a/src/test/run-pass/class-separate-impl.rs +++ b/src/test/run-pass/class-separate-impl.rs @@ -62,7 +62,7 @@ impl ToStr for cat { fn print_out(thing: @ToStr, expected: ~str) { let actual = thing.to_str(); debug!("%s", actual); - assert!((actual == expected)); + assert_eq!(actual, expected); } pub fn main() { diff --git a/src/test/run-pass/class-trait-bounded-param.rs b/src/test/run-pass/class-trait-bounded-param.rs index e1929d33d5b9c..0246946102bdc 100644 --- a/src/test/run-pass/class-trait-bounded-param.rs +++ b/src/test/run-pass/class-trait-bounded-param.rs @@ -31,5 +31,5 @@ pub fn main() { let m = int_hash(); m.insert(1, 2); m.insert(3, 4); - assert!(old_iter::to_vec(keys(m)) == ~[1, 3]); + assert_eq!(old_iter::to_vec(keys(m)), ~[1, 3]); } diff --git a/src/test/run-pass/classes-simple-cross-crate.rs b/src/test/run-pass/classes-simple-cross-crate.rs index 6c35d113e0e39..0df04c40fb7c9 100644 --- a/src/test/run-pass/classes-simple-cross-crate.rs +++ b/src/test/run-pass/classes-simple-cross-crate.rs @@ -16,6 +16,6 @@ use cci_class::kitties::*; pub fn main() { let nyan : cat = cat(52u, 99); let kitty = cat(1000u, 2); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); } diff --git a/src/test/run-pass/classes-simple-method.rs b/src/test/run-pass/classes-simple-method.rs index cd318ab6c6b7e..9de1066ec5701 100644 --- a/src/test/run-pass/classes-simple-method.rs +++ b/src/test/run-pass/classes-simple-method.rs @@ -28,7 +28,7 @@ fn cat(in_x : uint, in_y : int) -> cat { pub fn main() { let mut nyan : cat = cat(52u, 99); let mut kitty = cat(1000u, 2); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); nyan.speak(); } diff --git a/src/test/run-pass/classes-simple.rs b/src/test/run-pass/classes-simple.rs index 0af281bdce40d..3d2b08d7a851d 100644 --- a/src/test/run-pass/classes-simple.rs +++ b/src/test/run-pass/classes-simple.rs @@ -24,6 +24,6 @@ fn cat(in_x : uint, in_y : int) -> cat { pub fn main() { let mut nyan : cat = cat(52u, 99); let mut kitty = cat(1000u, 2); - assert!((nyan.how_hungry == 99)); - assert!((kitty.how_hungry == 2)); + assert_eq!(nyan.how_hungry, 99); + assert_eq!(kitty.how_hungry, 2); } diff --git a/src/test/run-pass/clone-with-exterior.rs b/src/test/run-pass/clone-with-exterior.rs index ae2983b159425..091f955aca01b 100644 --- a/src/test/run-pass/clone-with-exterior.rs +++ b/src/test/run-pass/clone-with-exterior.rs @@ -20,8 +20,8 @@ pub fn main() { let z = ~Pair { a : 10, b : 12}; let f: ~fn() = || { - assert!((z.a == 10)); - assert!((z.b == 12)); + assert_eq!(z.a, 10); + assert_eq!(z.b, 12); }; spawn(f); diff --git a/src/test/run-pass/close-over-big-then-small-data.rs b/src/test/run-pass/close-over-big-then-small-data.rs index 0cff05ed19f27..736c0f9194175 100644 --- a/src/test/run-pass/close-over-big-then-small-data.rs +++ b/src/test/run-pass/close-over-big-then-small-data.rs @@ -24,6 +24,6 @@ fn f(a: A, b: u16) -> @fn() -> (A, u16) { pub fn main() { let (a, b) = f(22_u64, 44u16)(); debug!("a=%? b=%?", a, b); - assert!(a == 22u64); - assert!(b == 44u16); + assert_eq!(a, 22u64); + assert_eq!(b, 44u16); } diff --git a/src/test/run-pass/closure-inference.rs b/src/test/run-pass/closure-inference.rs index 6cdb8f393d526..167fbdf3fc052 100644 --- a/src/test/run-pass/closure-inference.rs +++ b/src/test/run-pass/closure-inference.rs @@ -16,5 +16,5 @@ fn apply(f: &fn(A) -> A, v: A) -> A { f(v) } pub fn main() { let f = {|i| foo(i)}; - assert!(apply(f, 2) == 3); + assert_eq!(apply(f, 2), 3); } diff --git a/src/test/run-pass/closure-inference2.rs b/src/test/run-pass/closure-inference2.rs index 4e2972394453f..fa16ea001452c 100644 --- a/src/test/run-pass/closure-inference2.rs +++ b/src/test/run-pass/closure-inference2.rs @@ -12,6 +12,6 @@ pub fn main() { let f = {|i| i}; - assert!(f(2) == 2); - assert!(f(5) == 5); + assert_eq!(f(2), 2); + assert_eq!(f(5), 5); } diff --git a/src/test/run-pass/coerce-reborrow-imm-ptr-rcvr.rs b/src/test/run-pass/coerce-reborrow-imm-ptr-rcvr.rs index c4bed1e7d7da4..6c78cd250ddd8 100644 --- a/src/test/run-pass/coerce-reborrow-imm-ptr-rcvr.rs +++ b/src/test/run-pass/coerce-reborrow-imm-ptr-rcvr.rs @@ -12,5 +12,5 @@ fn foo(speaker: &const SpeechMaker) -> uint { pub fn main() { let mut lincoln = SpeechMaker {speeches: 22}; - assert!(foo(&const lincoln) == 55); + assert_eq!(foo(&const lincoln), 55); } diff --git a/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs b/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs index 1511eab8241d4..7ab80920849b3 100644 --- a/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs +++ b/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs @@ -14,7 +14,7 @@ fn bip(v: &[uint]) -> ~[uint] { pub fn main() { let mut the_vec = ~[1, 2, 3, 100]; - assert!(the_vec == foo(the_vec)); - assert!(the_vec == bar(the_vec)); - assert!(the_vec == bip(the_vec)); + assert_eq!(the_vec, foo(the_vec)); + assert_eq!(the_vec, bar(the_vec)); + assert_eq!(the_vec, bip(the_vec)); } diff --git a/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs b/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs index bfc1de4d1e7fa..18a28722c7017 100644 --- a/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs +++ b/src/test/run-pass/coerce-reborrow-mut-vec-arg.rs @@ -11,5 +11,5 @@ fn bar(v: &mut [uint]) { pub fn main() { let mut the_vec = ~[1, 2, 3, 100]; bar(the_vec); - assert!(the_vec == ~[100, 3, 2, 1]); + assert_eq!(the_vec, ~[100, 3, 2, 1]); } diff --git a/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs b/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs index b0d06dae10dc0..aa787328c412b 100644 --- a/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs +++ b/src/test/run-pass/coerce-reborrow-mut-vec-rcvr.rs @@ -17,5 +17,5 @@ fn bar(v: &mut [uint]) { pub fn main() { let mut the_vec = ~[1, 2, 3, 100]; bar(the_vec); - assert!(the_vec == ~[100, 3, 2, 1]); + assert_eq!(the_vec, ~[100, 3, 2, 1]); } diff --git a/src/test/run-pass/comm.rs b/src/test/run-pass/comm.rs index a01b06d4d7ce9..510976c56463d 100644 --- a/src/test/run-pass/comm.rs +++ b/src/test/run-pass/comm.rs @@ -17,7 +17,7 @@ pub fn main() { let y = p.recv(); error!("received"); error!(y); - assert!((y == 10)); + assert_eq!(y, 10); } fn child(c: &Chan) { diff --git a/src/test/run-pass/conditional-compile.rs b/src/test/run-pass/conditional-compile.rs index 73fdb219c1941..3fe33eae84d49 100644 --- a/src/test/run-pass/conditional-compile.rs +++ b/src/test/run-pass/conditional-compile.rs @@ -104,7 +104,7 @@ fn test_in_fn_ctxt() { #[cfg(bogus)] static i: int = 0; static i: int = 1; - assert!((i == 1)); + assert_eq!(i, 1); } mod test_foreign_items { diff --git a/src/test/run-pass/const-autoderef-newtype.rs b/src/test/run-pass/const-autoderef-newtype.rs index 021196bf7072a..19dea653a4a27 100644 --- a/src/test/run-pass/const-autoderef-newtype.rs +++ b/src/test/run-pass/const-autoderef-newtype.rs @@ -13,5 +13,5 @@ static C0: S = S([3]); static C1: int = C0[0]; pub fn main() { - assert!(C1 == 3); + assert_eq!(C1, 3); } diff --git a/src/test/run-pass/const-autoderef.rs b/src/test/run-pass/const-autoderef.rs index a7f9b57718c77..e80ed7c984b4a 100644 --- a/src/test/run-pass/const-autoderef.rs +++ b/src/test/run-pass/const-autoderef.rs @@ -14,6 +14,6 @@ static C: &'static &'static &'static &'static [u8, ..1] = & & & &A; static D: u8 = (&C)[0]; pub fn main() { - assert!(B == A[0]); - assert!(D == A[0]); + assert_eq!(B, A[0]); + assert_eq!(D, A[0]); } diff --git a/src/test/run-pass/const-big-enum.rs b/src/test/run-pass/const-big-enum.rs index 3aa7fd475b084..ac2e879ceacc9 100644 --- a/src/test/run-pass/const-big-enum.rs +++ b/src/test/run-pass/const-big-enum.rs @@ -27,8 +27,8 @@ pub fn main() { } match Z { Quux(d,h) => { - assert!((d == 0x123456789abcdef0)); - assert!((h == 0x1234)); + assert_eq!(d, 0x123456789abcdef0); + assert_eq!(h, 0x1234); } _ => fail!() } diff --git a/src/test/run-pass/const-cast-ptr-int.rs b/src/test/run-pass/const-cast-ptr-int.rs index ea5533da14d9d..3dc9493630479 100644 --- a/src/test/run-pass/const-cast-ptr-int.rs +++ b/src/test/run-pass/const-cast-ptr-int.rs @@ -11,5 +11,5 @@ static a: *u8 = 0 as *u8; pub fn main() { - assert!(a == ptr::null()); + assert_eq!(a, ptr::null()); } diff --git a/src/test/run-pass/const-cast.rs b/src/test/run-pass/const-cast.rs index d35ad9d2da3e1..1c8e92b91cd1b 100644 --- a/src/test/run-pass/const-cast.rs +++ b/src/test/run-pass/const-cast.rs @@ -16,6 +16,6 @@ static a: &'static int = &10; static b: *int = a as *int; pub fn main() { - assert!(x as *libc::c_void == y); - assert!(a as *int == b); + assert_eq!(x as *libc::c_void, y); + assert_eq!(a as *int, b); } diff --git a/src/test/run-pass/const-const.rs b/src/test/run-pass/const-const.rs index e68bf8a74c3a3..bdb2b3d211043 100644 --- a/src/test/run-pass/const-const.rs +++ b/src/test/run-pass/const-const.rs @@ -12,5 +12,5 @@ static a: int = 1; static b: int = a + 2; pub fn main() { - assert!(b == 3); + assert_eq!(b, 3); } diff --git a/src/test/run-pass/const-contents.rs b/src/test/run-pass/const-contents.rs index 19ce5b3713df2..5b31c9a44de51 100644 --- a/src/test/run-pass/const-contents.rs +++ b/src/test/run-pass/const-contents.rs @@ -18,10 +18,10 @@ static notb : bool = !true; static neg : int = -(1); pub fn main() { - assert!((lsl == 4)); - assert!((add == 3)); - assert!((addf == 3.0f)); - assert!((not == -1)); - assert!((notb == false)); - assert!((neg == -1)); + assert_eq!(lsl, 4); + assert_eq!(add, 3); + assert_eq!(addf, 3.0f); + assert_eq!(not, -1); + assert_eq!(notb, false); + assert_eq!(neg, -1); } diff --git a/src/test/run-pass/const-cross-crate-const.rs b/src/test/run-pass/const-cross-crate-const.rs index 55975d364c84f..607d0c72b8954 100644 --- a/src/test/run-pass/const-cross-crate-const.rs +++ b/src/test/run-pass/const-cross-crate-const.rs @@ -17,9 +17,9 @@ static a: uint = cci_const::uint_val; static b: uint = cci_const::uint_expr + 5; fn main() { - assert!(a == 12); + assert_eq!(a, 12); let foo2 = a; - assert!(foo2 == cci_const::uint_val); - assert!(b == cci_const::uint_expr + 5); - assert!(foo == cci_const::foopy); + assert_eq!(foo2, cci_const::uint_val); + assert_eq!(b, cci_const::uint_expr + 5); + assert_eq!(foo, cci_const::foopy); } diff --git a/src/test/run-pass/const-cross-crate-extern.rs b/src/test/run-pass/const-cross-crate-extern.rs index bac84d12e4ce1..5281c21762689 100644 --- a/src/test/run-pass/const-cross-crate-extern.rs +++ b/src/test/run-pass/const-cross-crate-extern.rs @@ -16,5 +16,5 @@ use cci_const::bar; static foo: *u8 = bar; pub fn main() { - assert!(foo == cci_const::bar); + assert_eq!(foo, cci_const::bar); } diff --git a/src/test/run-pass/const-deref.rs b/src/test/run-pass/const-deref.rs index ee98e60f4d63f..b1797857d0410 100644 --- a/src/test/run-pass/const-deref.rs +++ b/src/test/run-pass/const-deref.rs @@ -15,6 +15,6 @@ static E: &'static S = &S(C); static F: int = ***E; pub fn main() { - assert!(D == 1000); - assert!(F == 1000); + assert_eq!(D, 1000); + assert_eq!(F, 1000); } diff --git a/src/test/run-pass/const-enum-cast.rs b/src/test/run-pass/const-enum-cast.rs index 89990e9d892cc..616c7567adf47 100644 --- a/src/test/run-pass/const-enum-cast.rs +++ b/src/test/run-pass/const-enum-cast.rs @@ -20,12 +20,12 @@ pub fn main () { let a2 = B2 as int; let a3 = A2 as float; let a4 = B2 as float; - assert!(c1 == 1); - assert!(c2 == 2); - assert!(c3 == 1.0); - assert!(c4 == 2.0); - assert!(a1 == 1); - assert!(a2 == 2); - assert!(a3 == 1.0); - assert!(a4 == 2.0); + assert_eq!(c1, 1); + assert_eq!(c2, 2); + assert_eq!(c3, 1.0); + assert_eq!(c4, 2.0); + assert_eq!(a1, 1); + assert_eq!(a2, 2); + assert_eq!(a3, 1.0); + assert_eq!(a4, 2.0); } diff --git a/src/test/run-pass/const-enum-struct.rs b/src/test/run-pass/const-enum-struct.rs index b6d916a9c38a1..3229293fd7a46 100644 --- a/src/test/run-pass/const-enum-struct.rs +++ b/src/test/run-pass/const-enum-struct.rs @@ -15,5 +15,5 @@ static C: S = S { a: V16(0xDEAD), b: 0x600D, c: 0xBAD }; pub fn main() { let n = C.b; assert!(n != 0xBAD); - assert!(n == 0x600D); + assert_eq!(n, 0x600D); } diff --git a/src/test/run-pass/const-enum-struct2.rs b/src/test/run-pass/const-enum-struct2.rs index 3d9f7fc204404..4530a65002772 100644 --- a/src/test/run-pass/const-enum-struct2.rs +++ b/src/test/run-pass/const-enum-struct2.rs @@ -15,5 +15,5 @@ static C: S = S { a: V0, b: 0x600D, c: 0xBAD }; pub fn main() { let n = C.b; assert!(n != 0xBAD); - assert!(n == 0x600D); + assert_eq!(n, 0x600D); } diff --git a/src/test/run-pass/const-enum-tuple.rs b/src/test/run-pass/const-enum-tuple.rs index ade3dfd6b6358..17d8341457d35 100644 --- a/src/test/run-pass/const-enum-tuple.rs +++ b/src/test/run-pass/const-enum-tuple.rs @@ -14,5 +14,5 @@ static C: (E, u16, u16) = (V16(0xDEAD), 0x600D, 0xBAD); pub fn main() { let (_, n, _) = C; assert!(n != 0xBAD); - assert!(n == 0x600D); + assert_eq!(n, 0x600D); } diff --git a/src/test/run-pass/const-enum-tuple2.rs b/src/test/run-pass/const-enum-tuple2.rs index 14da9438af00a..5d7a161720c18 100644 --- a/src/test/run-pass/const-enum-tuple2.rs +++ b/src/test/run-pass/const-enum-tuple2.rs @@ -14,5 +14,5 @@ static C: (E, u16, u16) = (V0, 0x600D, 0xBAD); pub fn main() { let (_, n, _) = C; assert!(n != 0xBAD); - assert!(n == 0x600D); + assert_eq!(n, 0x600D); } diff --git a/src/test/run-pass/const-enum-tuplestruct.rs b/src/test/run-pass/const-enum-tuplestruct.rs index 885664f7ef03c..40137afa2eee2 100644 --- a/src/test/run-pass/const-enum-tuplestruct.rs +++ b/src/test/run-pass/const-enum-tuplestruct.rs @@ -15,5 +15,5 @@ static C: S = S(V16(0xDEAD), 0x600D, 0xBAD); pub fn main() { let S(_, n, _) = C; assert!(n != 0xBAD); - assert!(n == 0x600D); + assert_eq!(n, 0x600D); } diff --git a/src/test/run-pass/const-enum-tuplestruct2.rs b/src/test/run-pass/const-enum-tuplestruct2.rs index ad4befd92d15e..f6345efcb4348 100644 --- a/src/test/run-pass/const-enum-tuplestruct2.rs +++ b/src/test/run-pass/const-enum-tuplestruct2.rs @@ -15,5 +15,5 @@ static C: S = S(V0, 0x600D, 0xBAD); pub fn main() { let S(_, n, _) = C; assert!(n != 0xBAD); - assert!(n == 0x600D); + assert_eq!(n, 0x600D); } diff --git a/src/test/run-pass/const-extern-function.rs b/src/test/run-pass/const-extern-function.rs index a9d036f121921..9a8104cb14f71 100644 --- a/src/test/run-pass/const-extern-function.rs +++ b/src/test/run-pass/const-extern-function.rs @@ -18,6 +18,6 @@ struct S { } pub fn main() { - assert!(foopy == f); - assert!(f == s.f); + assert_eq!(foopy, f); + assert_eq!(f, s.f); } diff --git a/src/test/run-pass/const-fields-and-indexing.rs b/src/test/run-pass/const-fields-and-indexing.rs index 014ec19d56502..ccc7b486d1ea2 100644 --- a/src/test/run-pass/const-fields-and-indexing.rs +++ b/src/test/run-pass/const-fields-and-indexing.rs @@ -28,7 +28,7 @@ pub fn main() { io::println(fmt!("%?", p)); io::println(fmt!("%?", q)); io::println(fmt!("%?", t)); - assert!(p == 3); - assert!(q == 3); - assert!(t == 20); + assert_eq!(p, 3); + assert_eq!(q, 3); + assert_eq!(t, 20); } diff --git a/src/test/run-pass/const-fn-val.rs b/src/test/run-pass/const-fn-val.rs index 544d671431260..dfcfb30f77ffb 100644 --- a/src/test/run-pass/const-fn-val.rs +++ b/src/test/run-pass/const-fn-val.rs @@ -17,5 +17,5 @@ struct Bar<'self> { f: &'self fn() -> int } static b : Bar<'static> = Bar { f: foo }; pub fn main() { - assert!((b.f)() == 0xca7f000d); + assert_eq!((b.f)(), 0xca7f000d); } diff --git a/src/test/run-pass/const-negative.rs b/src/test/run-pass/const-negative.rs index e4905d5c5324d..4e2be013c11e4 100644 --- a/src/test/run-pass/const-negative.rs +++ b/src/test/run-pass/const-negative.rs @@ -13,5 +13,5 @@ static toplevel_mod: int = -1; pub fn main() { - assert!(toplevel_mod == -1); + assert_eq!(toplevel_mod, -1); } diff --git a/src/test/run-pass/const-nullary-univariant-enum.rs b/src/test/run-pass/const-nullary-univariant-enum.rs index 0d0674aa962fc..30fbe38aed033 100644 --- a/src/test/run-pass/const-nullary-univariant-enum.rs +++ b/src/test/run-pass/const-nullary-univariant-enum.rs @@ -15,8 +15,8 @@ enum Foo { static X: Foo = Bar; pub fn main() { - assert!(((X as uint) == 0xDEADBEE)); - assert!(((Y as uint) == 0xDEADBEE)); + assert_eq!((X as uint), 0xDEADBEE); + assert_eq!((Y as uint), 0xDEADBEE); } static Y: Foo = Bar; diff --git a/src/test/run-pass/const-rec-and-tup.rs b/src/test/run-pass/const-rec-and-tup.rs index 557fa427e4383..acb7fa2f0f475 100644 --- a/src/test/run-pass/const-rec-and-tup.rs +++ b/src/test/run-pass/const-rec-and-tup.rs @@ -20,6 +20,6 @@ static y : AnotherPair = AnotherPair{ x: (0xf0f0f0f0_f0f0f0f0, pub fn main() { let (p, _) = y.x; - assert!(p == - 1085102592571150096); + assert_eq!(p, - 1085102592571150096); io::println(fmt!("0x%x", p as uint)); } diff --git a/src/test/run-pass/const-region-ptrs-noncopy.rs b/src/test/run-pass/const-region-ptrs-noncopy.rs index b8812649fd1c1..14397569ad97f 100644 --- a/src/test/run-pass/const-region-ptrs-noncopy.rs +++ b/src/test/run-pass/const-region-ptrs-noncopy.rs @@ -14,5 +14,5 @@ static x: &'static Big = &([13, 14, 10, 13, 11, 14, 14, 15]); static y: &'static Pair<'static> = &Pair {a: 15, b: x}; pub fn main() { - assert!(ptr::to_unsafe_ptr(x) == ptr::to_unsafe_ptr(y.b)); + assert_eq!(ptr::to_unsafe_ptr(x), ptr::to_unsafe_ptr(y.b)); } diff --git a/src/test/run-pass/const-region-ptrs.rs b/src/test/run-pass/const-region-ptrs.rs index a2bedc85cdd4d..12712844c8a69 100644 --- a/src/test/run-pass/const-region-ptrs.rs +++ b/src/test/run-pass/const-region-ptrs.rs @@ -18,6 +18,6 @@ static y: &'static Pair<'static> = &Pair {a: 15, b: x}; pub fn main() { io::println(fmt!("x = %?", *x)); io::println(fmt!("y = {a: %?, b: %?}", y.a, *(y.b))); - assert!(*x == 10); - assert!(*(y.b) == 10); + assert_eq!(*x, 10); + assert_eq!(*(y.b), 10); } diff --git a/src/test/run-pass/const-str-ptr.rs b/src/test/run-pass/const-str-ptr.rs index 2f98036a5b172..48eb4d6ce59b9 100644 --- a/src/test/run-pass/const-str-ptr.rs +++ b/src/test/run-pass/const-str-ptr.rs @@ -14,9 +14,9 @@ static b: *u8 = c as *u8; pub fn main() { let foo = &a as *u8; - assert!(unsafe { str::raw::from_bytes(a) } == ~"hi\x00"); - assert!(unsafe { str::raw::from_buf(foo) } == ~"hi"); - assert!(unsafe { str::raw::from_buf(b) } == ~"hi"); + assert_eq!(unsafe { str::raw::from_bytes(a) }, ~"hi\x00"); + assert_eq!(unsafe { str::raw::from_buf(foo) }, ~"hi"); + assert_eq!(unsafe { str::raw::from_buf(b) }, ~"hi"); assert!(unsafe { *b == a[0] }); assert!(unsafe { *(&c[0] as *u8) == a[0] }); } diff --git a/src/test/run-pass/const-struct.rs b/src/test/run-pass/const-struct.rs index f75b4321e9025..24542f5492289 100644 --- a/src/test/run-pass/const-struct.rs +++ b/src/test/run-pass/const-struct.rs @@ -25,9 +25,9 @@ static y : foo = foo { b:2, c:3, a: 1 }; static z : &'static foo = &foo { a: 10, b: 22, c: 12 }; pub fn main() { - assert!(x.b == 2); - assert!(x == y); - assert!(z.b == 22); + assert_eq!(x.b, 2); + assert_eq!(x, y); + assert_eq!(z.b, 22); io::println(fmt!("0x%x", x.b as uint)); io::println(fmt!("0x%x", z.c as uint)); } diff --git a/src/test/run-pass/const-tuple-struct.rs b/src/test/run-pass/const-tuple-struct.rs index 828c20912a1cb..54116dd4082ed 100644 --- a/src/test/run-pass/const-tuple-struct.rs +++ b/src/test/run-pass/const-tuple-struct.rs @@ -15,8 +15,8 @@ static X: Bar = Bar(1, 2); pub fn main() { match X { Bar(x, y) => { - assert!(x == 1); - assert!(y == 2); + assert_eq!(x, 1); + assert_eq!(y, 2); } } } diff --git a/src/test/run-pass/const-vecs-and-slices.rs b/src/test/run-pass/const-vecs-and-slices.rs index 517ced302dd8b..134ee58042571 100644 --- a/src/test/run-pass/const-vecs-and-slices.rs +++ b/src/test/run-pass/const-vecs-and-slices.rs @@ -14,7 +14,7 @@ static y : &'static [int] = &[1,2,3,4]; pub fn main() { io::println(fmt!("%?", x[1])); io::println(fmt!("%?", y[1])); - assert!(x[1] == 2); - assert!(x[3] == 4); - assert!(x[3] == y[3]); + assert_eq!(x[1], 2); + assert_eq!(x[3], 4); + assert_eq!(x[3], y[3]); } diff --git a/src/test/run-pass/consts-in-patterns.rs b/src/test/run-pass/consts-in-patterns.rs index c0520cf737ffc..788c30562c182 100644 --- a/src/test/run-pass/consts-in-patterns.rs +++ b/src/test/run-pass/consts-in-patterns.rs @@ -18,5 +18,5 @@ pub fn main() { BAR => 2, _ => 3 }; - assert!(y == 2); + assert_eq!(y, 2); } diff --git a/src/test/run-pass/crateresolve1.rs b/src/test/run-pass/crateresolve1.rs index 1ddb955cee7bc..737a60470ad3e 100644 --- a/src/test/run-pass/crateresolve1.rs +++ b/src/test/run-pass/crateresolve1.rs @@ -16,5 +16,5 @@ extern mod crateresolve1(vers = "0.2"); pub fn main() { - assert!(crateresolve1::f() == 20); + assert_eq!(crateresolve1::f(), 20); } diff --git a/src/test/run-pass/crateresolve6.rs b/src/test/run-pass/crateresolve6.rs index 0263af5510578..883f48656bcf6 100644 --- a/src/test/run-pass/crateresolve6.rs +++ b/src/test/run-pass/crateresolve6.rs @@ -18,6 +18,6 @@ extern mod cr6_1 (name = "crateresolve_calories", vers = "0.1", calories="100"); extern mod cr6_2 (name = "crateresolve_calories", vers = "0.1", calories="200"); pub fn main() { - assert!(cr6_1::f() == 100); - assert!(cr6_2::f() == 200); + assert_eq!(cr6_1::f(), 100); + assert_eq!(cr6_2::f(), 200); } diff --git a/src/test/run-pass/crateresolve7.rs b/src/test/run-pass/crateresolve7.rs index b54b5a0983fbd..86fc72aa489c6 100644 --- a/src/test/run-pass/crateresolve7.rs +++ b/src/test/run-pass/crateresolve7.rs @@ -16,6 +16,6 @@ extern mod crateresolve7x; pub fn main() { - assert!(crateresolve7x::a::f() == 100); - assert!(crateresolve7x::b::f() == 200); + assert_eq!(crateresolve7x::a::f(), 100); + assert_eq!(crateresolve7x::b::f(), 200); } diff --git a/src/test/run-pass/deriving-via-extension-c-enum.rs b/src/test/run-pass/deriving-via-extension-c-enum.rs index 81c4ce013f24c..3c4fb6c8c81b1 100644 --- a/src/test/run-pass/deriving-via-extension-c-enum.rs +++ b/src/test/run-pass/deriving-via-extension-c-enum.rs @@ -18,7 +18,7 @@ enum Foo { pub fn main() { let a = Bar; let b = Bar; - assert!(a == b); + assert_eq!(a, b); assert!(!(a != b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); diff --git a/src/test/run-pass/deriving-via-extension-enum.rs b/src/test/run-pass/deriving-via-extension-enum.rs index fac0d402a3826..4044c58dc5711 100644 --- a/src/test/run-pass/deriving-via-extension-enum.rs +++ b/src/test/run-pass/deriving-via-extension-enum.rs @@ -17,7 +17,7 @@ enum Foo { pub fn main() { let a = Bar(1, 2); let b = Bar(1, 2); - assert!(a == b); + assert_eq!(a, b); assert!(!(a != b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); diff --git a/src/test/run-pass/deriving-via-extension-struct-empty.rs b/src/test/run-pass/deriving-via-extension-struct-empty.rs index 00b0c14369e04..8f6a319798626 100644 --- a/src/test/run-pass/deriving-via-extension-struct-empty.rs +++ b/src/test/run-pass/deriving-via-extension-struct-empty.rs @@ -12,6 +12,6 @@ struct Foo; pub fn main() { - assert!(Foo == Foo); + assert_eq!(Foo, Foo); assert!(!(Foo != Foo)); } \ No newline at end of file diff --git a/src/test/run-pass/deriving-via-extension-struct-like-enum-variant.rs b/src/test/run-pass/deriving-via-extension-struct-like-enum-variant.rs index 4ef8fb6b5d9b7..5189136c4863f 100644 --- a/src/test/run-pass/deriving-via-extension-struct-like-enum-variant.rs +++ b/src/test/run-pass/deriving-via-extension-struct-like-enum-variant.rs @@ -6,6 +6,6 @@ enum S { pub fn main() { let x = X { x: 1, y: 2 }; - assert!(x == x); + assert_eq!(x, x); assert!(!(x != x)); } diff --git a/src/test/run-pass/deriving-via-extension-struct-tuple.rs b/src/test/run-pass/deriving-via-extension-struct-tuple.rs index 906d69dbf5375..cc76751e27f4b 100644 --- a/src/test/run-pass/deriving-via-extension-struct-tuple.rs +++ b/src/test/run-pass/deriving-via-extension-struct-tuple.rs @@ -17,10 +17,10 @@ pub fn main() { let b = Foo(5, 7, ~"def"); assert!(a1 == a1); - assert!(a1 == a2); + assert!(a2 == a1); assert!(!(a1 == b)); assert!(a1 != b); assert!(!(a1 != a1)); - assert!(!(a1 != a2)); + assert!(!(a2 != a1)); } diff --git a/src/test/run-pass/deriving-via-extension-struct.rs b/src/test/run-pass/deriving-via-extension-struct.rs index c0e7ee36b16da..44aca59aa9c07 100644 --- a/src/test/run-pass/deriving-via-extension-struct.rs +++ b/src/test/run-pass/deriving-via-extension-struct.rs @@ -18,7 +18,7 @@ struct Foo { pub fn main() { let a = Foo { x: 1, y: 2, z: 3 }; let b = Foo { x: 1, y: 2, z: 3 }; - assert!(a == b); + assert_eq!(a, b); assert!(!(a != b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); diff --git a/src/test/run-pass/deriving-via-extension-type-params.rs b/src/test/run-pass/deriving-via-extension-type-params.rs index 85a89c629895d..ecc30555162ac 100644 --- a/src/test/run-pass/deriving-via-extension-type-params.rs +++ b/src/test/run-pass/deriving-via-extension-type-params.rs @@ -21,7 +21,7 @@ struct Foo { pub fn main() { let a = Foo { x: 1, y: 2.0, z: 3 }; let b = Foo { x: 1, y: 2.0, z: 3 }; - assert!(a == b); + assert_eq!(a, b); assert!(!(a != b)); assert!(a.eq(&b)); assert!(!a.ne(&b)); diff --git a/src/test/run-pass/div-mod.rs b/src/test/run-pass/div-mod.rs index bf1d6e3c06006..3aeaef01e189b 100644 --- a/src/test/run-pass/div-mod.rs +++ b/src/test/run-pass/div-mod.rs @@ -15,14 +15,14 @@ pub fn main() { let x: int = 15; let y: int = 5; - assert!((x / 5 == 3)); - assert!((x / 4 == 3)); - assert!((x / 3 == 5)); - assert!((x / y == 3)); - assert!((15 / y == 3)); - assert!((x % 5 == 0)); - assert!((x % 4 == 3)); - assert!((x % 3 == 0)); - assert!((x % y == 0)); - assert!((15 % y == 0)); + assert_eq!(x / 5, 3); + assert_eq!(x / 4, 3); + assert_eq!(x / 3, 5); + assert_eq!(x / y, 3); + assert_eq!(15 / y, 3); + assert_eq!(x % 5, 0); + assert_eq!(x % 4, 3); + assert_eq!(x % 3, 0); + assert_eq!(x % y, 0); + assert_eq!(15 % y, 0); } diff --git a/src/test/run-pass/do2.rs b/src/test/run-pass/do2.rs index ee1321e9d0048..684a2c108eb81 100644 --- a/src/test/run-pass/do2.rs +++ b/src/test/run-pass/do2.rs @@ -11,5 +11,5 @@ fn f(f: @fn(int) -> int) -> int { f(10) } pub fn main() { - assert!(do f() |i| { i } == 10); + assert_eq!(do f() |i| { i }, 10); } diff --git a/src/test/run-pass/do3.rs b/src/test/run-pass/do3.rs index 7cbf49a34862d..b0d49fd2bdd92 100644 --- a/src/test/run-pass/do3.rs +++ b/src/test/run-pass/do3.rs @@ -11,5 +11,5 @@ fn f(f: @fn(int) -> int) -> int { f(10) } pub fn main() { - assert!(do f |i| { i } == 10); + assert_eq!(do f |i| { i }, 10); } diff --git a/src/test/run-pass/empty-tag.rs b/src/test/run-pass/empty-tag.rs index f1b89f2bb1d3b..a8822e9a3fcfd 100644 --- a/src/test/run-pass/empty-tag.rs +++ b/src/test/run-pass/empty-tag.rs @@ -18,7 +18,7 @@ impl cmp::Eq for chan { } fn wrapper3(i: chan) { - assert!(i == chan_t); + assert_eq!(i, chan_t); } pub fn main() { diff --git a/src/test/run-pass/estr-slice.rs b/src/test/run-pass/estr-slice.rs index 27a1b9514139e..a851141322f00 100644 --- a/src/test/run-pass/estr-slice.rs +++ b/src/test/run-pass/estr-slice.rs @@ -17,11 +17,11 @@ pub fn main() { debug!(x); debug!(y); - assert!(x[0] == 'h' as u8); - assert!(x[4] == 'o' as u8); + assert_eq!(x[0], 'h' as u8); + assert_eq!(x[4], 'o' as u8); let z : &str = &"thing"; - assert!(v == x); + assert_eq!(v, x); assert!(x != z); let a = &"aaaa"; diff --git a/src/test/run-pass/estr-uniq.rs b/src/test/run-pass/estr-uniq.rs index 5e23fd0f75166..a096a8456739e 100644 --- a/src/test/run-pass/estr-uniq.rs +++ b/src/test/run-pass/estr-uniq.rs @@ -13,6 +13,6 @@ pub fn main() { let _y : ~str = ~"there"; let mut z = ~"thing"; z = x; - assert!(z[0] == ('h' as u8)); - assert!(z[4] == ('o' as u8)); + assert_eq!(z[0], ('h' as u8)); + assert_eq!(z[4], ('o' as u8)); } diff --git a/src/test/run-pass/evec-internal-boxes.rs b/src/test/run-pass/evec-internal-boxes.rs index 7b51b80313680..64c8a4caf80ae 100644 --- a/src/test/run-pass/evec-internal-boxes.rs +++ b/src/test/run-pass/evec-internal-boxes.rs @@ -13,6 +13,6 @@ pub fn main() { let _y : [@int, ..5] = [@1,@2,@3,@4,@5]; let mut z = [@1,@2,@3,@4,@5]; z = x; - assert!(*z[0] == 1); - assert!(*z[4] == 5); + assert_eq!(*z[0], 1); + assert_eq!(*z[4], 5); } diff --git a/src/test/run-pass/evec-internal.rs b/src/test/run-pass/evec-internal.rs index 39a4397f84e73..6c3dfb2cb3de8 100644 --- a/src/test/run-pass/evec-internal.rs +++ b/src/test/run-pass/evec-internal.rs @@ -18,8 +18,8 @@ pub fn main() { let _y : [int, ..5] = [1,2,3,4,5]; let mut z = [1,2,3,4,5]; z = x; - assert!(z[0] == 1); - assert!(z[4] == 5); + assert_eq!(z[0], 1); + assert_eq!(z[4], 5); let a : [int, ..5] = [1,1,1,1,1]; let b : [int, ..5] = [2,2,2,2,2]; diff --git a/src/test/run-pass/evec-slice.rs b/src/test/run-pass/evec-slice.rs index 28bac56b05e76..194560ab127b1 100644 --- a/src/test/run-pass/evec-slice.rs +++ b/src/test/run-pass/evec-slice.rs @@ -12,8 +12,8 @@ pub fn main() { let x : &[int] = &[1,2,3,4,5]; let mut z = &[1,2,3,4,5]; z = x; - assert!(z[0] == 1); - assert!(z[4] == 5); + assert_eq!(z[0], 1); + assert_eq!(z[4], 5); let a : &[int] = &[1,1,1,1,1]; let b : &[int] = &[2,2,2,2,2]; diff --git a/src/test/run-pass/exec-env.rs b/src/test/run-pass/exec-env.rs index 486186e9fe098..2043a170aba75 100644 --- a/src/test/run-pass/exec-env.rs +++ b/src/test/run-pass/exec-env.rs @@ -12,5 +12,5 @@ // exec-env:TEST_EXEC_ENV=22 pub fn main() { - assert!(os::getenv(~"TEST_EXEC_ENV") == Some(~"22")); + assert_eq!(os::getenv(~"TEST_EXEC_ENV"), Some(~"22")); } diff --git a/src/test/run-pass/explicit-self-generic.rs b/src/test/run-pass/explicit-self-generic.rs index ac19592accf8b..ad8af0ce63995 100644 --- a/src/test/run-pass/explicit-self-generic.rs +++ b/src/test/run-pass/explicit-self-generic.rs @@ -38,5 +38,5 @@ pub impl HashMap { pub fn main() { let mut m = ~linear_map::<(),()>(); - assert!(m.len() == 0); + assert_eq!(m.len(), 0); } diff --git a/src/test/run-pass/explicit-self-objects-box.rs b/src/test/run-pass/explicit-self-objects-box.rs index 12a1780e029b1..9010dd34ffedc 100644 --- a/src/test/run-pass/explicit-self-objects-box.rs +++ b/src/test/run-pass/explicit-self-objects-box.rs @@ -18,7 +18,7 @@ struct S { impl Foo for S { fn f(@self) { - assert!(self.x == 3); + assert_eq!(self.x, 3); } } diff --git a/src/test/run-pass/explicit-self-objects-simple.rs b/src/test/run-pass/explicit-self-objects-simple.rs index 814365a835429..6092c386dbb76 100644 --- a/src/test/run-pass/explicit-self-objects-simple.rs +++ b/src/test/run-pass/explicit-self-objects-simple.rs @@ -18,7 +18,7 @@ struct S { impl Foo for S { fn f(&self) { - assert!(self.x == 3); + assert_eq!(self.x, 3); } } diff --git a/src/test/run-pass/explicit-self-objects-uniq.rs b/src/test/run-pass/explicit-self-objects-uniq.rs index dadf53fb9bc6a..69ca98eb018ed 100644 --- a/src/test/run-pass/explicit-self-objects-uniq.rs +++ b/src/test/run-pass/explicit-self-objects-uniq.rs @@ -18,7 +18,7 @@ struct S { impl Foo for S { fn f(~self) { - assert!(self.x == 3); + assert_eq!(self.x, 3); } } diff --git a/src/test/run-pass/explicit-self.rs b/src/test/run-pass/explicit-self.rs index 7e46bf22c4d92..6ae99f64cf069 100644 --- a/src/test/run-pass/explicit-self.rs +++ b/src/test/run-pass/explicit-self.rs @@ -68,13 +68,13 @@ impl Nus for thing { fn f(&self) {} } pub fn main() { let x = @thing(A {a: @10}); - assert!(x.foo() == 10); - assert!(x.quux() == 10); + assert_eq!(x.foo(), 10); + assert_eq!(x.quux(), 10); let y = ~thing(A {a: @10}); - assert!((copy y).bar() == 10); - assert!(y.quux() == 10); + assert_eq!((copy y).bar(), 10); + assert_eq!(y.quux(), 10); let z = thing(A {a: @11}); - assert!(z.spam() == 11); + assert_eq!(z.spam(), 11); } diff --git a/src/test/run-pass/expr-alt-box.rs b/src/test/run-pass/expr-alt-box.rs index 2e65bb8665583..84a78637187fc 100644 --- a/src/test/run-pass/expr-alt-box.rs +++ b/src/test/run-pass/expr-alt-box.rs @@ -16,13 +16,13 @@ // Tests for match as expressions resulting in boxed types fn test_box() { let res = match true { true => { @100 } _ => fail!("wat") }; - assert!((*res == 100)); + assert_eq!(*res, 100); } fn test_str() { let res = match true { true => { ~"happy" }, _ => fail!("not happy at all") }; - assert!((res == ~"happy")); + assert_eq!(res, ~"happy"); } pub fn main() { test_box(); test_str(); } diff --git a/src/test/run-pass/expr-alt-fail.rs b/src/test/run-pass/expr-alt-fail.rs index 4391856230fe9..3e1b96763e196 100644 --- a/src/test/run-pass/expr-alt-fail.rs +++ b/src/test/run-pass/expr-alt-fail.rs @@ -10,12 +10,12 @@ fn test_simple() { let r = match true { true => { true } false => { fail!() } }; - assert!((r == true)); + assert_eq!(r, true); } fn test_box() { let r = match true { true => { ~[10] } false => { fail!() } }; - assert!((r[0] == 10)); + assert_eq!(r[0], 10); } pub fn main() { test_simple(); test_box(); } diff --git a/src/test/run-pass/expr-alt-struct.rs b/src/test/run-pass/expr-alt-struct.rs index a8cacca4fe812..57483d96e8bbd 100644 --- a/src/test/run-pass/expr-alt-struct.rs +++ b/src/test/run-pass/expr-alt-struct.rs @@ -18,7 +18,7 @@ struct R { i: int } fn test_rec() { let rs = match true { true => R {i: 100}, _ => fail!() }; - assert!((rs.i == 100)); + assert_eq!(rs.i, 100); } enum mood { happy, sad, } @@ -32,7 +32,7 @@ impl cmp::Eq for mood { fn test_tag() { let rs = match true { true => { happy } false => { sad } }; - assert!((rs == happy)); + assert_eq!(rs, happy); } pub fn main() { test_rec(); test_tag(); } diff --git a/src/test/run-pass/expr-alt-unique.rs b/src/test/run-pass/expr-alt-unique.rs index dd20840db575e..cdd4e45877ad6 100644 --- a/src/test/run-pass/expr-alt-unique.rs +++ b/src/test/run-pass/expr-alt-unique.rs @@ -16,7 +16,7 @@ // Tests for match as expressions resulting in boxed types fn test_box() { let res = match true { true => { ~100 }, _ => fail!() }; - assert!((*res == 100)); + assert_eq!(*res, 100); } pub fn main() { test_box(); } diff --git a/src/test/run-pass/expr-block-slot.rs b/src/test/run-pass/expr-block-slot.rs index 0a75d9074c6c2..cfb764e85f8d3 100644 --- a/src/test/run-pass/expr-block-slot.rs +++ b/src/test/run-pass/expr-block-slot.rs @@ -15,7 +15,7 @@ struct V { v: int } pub fn main() { let a = { let b = A {a: 3}; b }; - assert!((a.a == 3)); + assert_eq!(a.a, 3); let c = { let d = V {v: 3}; d }; - assert!((c.v == 3)); + assert_eq!(c.v, 3); } diff --git a/src/test/run-pass/expr-block.rs b/src/test/run-pass/expr-block.rs index ee5d41fdd324b..e43377c71fef1 100644 --- a/src/test/run-pass/expr-block.rs +++ b/src/test/run-pass/expr-block.rs @@ -22,7 +22,7 @@ fn test_rec() { let rs = { RS {v1: 10, v2: 20} }; assert!((rs.v2 == 20)); } fn test_filled_with_stuff() { let rs = { let mut a = 0; while a < 10 { a += 1; } a }; - assert!((rs == 10)); + assert_eq!(rs, 10); } pub fn main() { test_basic(); test_rec(); test_filled_with_stuff(); } diff --git a/src/test/run-pass/expr-copy.rs b/src/test/run-pass/expr-copy.rs index 7dc0f8246bf97..96dab798c83ac 100644 --- a/src/test/run-pass/expr-copy.rs +++ b/src/test/run-pass/expr-copy.rs @@ -19,9 +19,9 @@ struct A { a: int } pub fn main() { let mut x = A {a: 10}; f(&mut x); - assert!(x.a == 100); + assert_eq!(x.a, 100); x.a = 20; let mut y = copy x; f(&mut y); - assert!(x.a == 20); + assert_eq!(x.a, 20); } diff --git a/src/test/run-pass/expr-elseif-ref.rs b/src/test/run-pass/expr-elseif-ref.rs index 831ddfde445ad..b13f7ceba4bfe 100644 --- a/src/test/run-pass/expr-elseif-ref.rs +++ b/src/test/run-pass/expr-elseif-ref.rs @@ -13,5 +13,5 @@ pub fn main() { let y: @uint = @10u; let x = if false { y } else if true { y } else { y }; - assert!((*y == 10u)); + assert_eq!(*y, 10u); } diff --git a/src/test/run-pass/expr-fn.rs b/src/test/run-pass/expr-fn.rs index b7ea721464e6e..e4eae9c4c3996 100644 --- a/src/test/run-pass/expr-fn.rs +++ b/src/test/run-pass/expr-fn.rs @@ -10,32 +10,32 @@ fn test_int() { fn f() -> int { 10 } - assert!((f() == 10)); + assert_eq!(f(), 10); } fn test_vec() { fn f() -> ~[int] { ~[10, 11] } - assert!((f()[1] == 11)); + assert_eq!(f()[1], 11); } fn test_generic() { fn f(t: T) -> T { t } - assert!((f(10) == 10)); + assert_eq!(f(10), 10); } fn test_alt() { fn f() -> int { match true { false => { 10 } true => { 20 } } } - assert!((f() == 20)); + assert_eq!(f(), 20); } fn test_if() { fn f() -> int { if true { 10 } else { 20 } } - assert!((f() == 10)); + assert_eq!(f(), 10); } fn test_block() { fn f() -> int { { 10 } } - assert!((f() == 10)); + assert_eq!(f(), 10); } fn test_ret() { @@ -43,14 +43,14 @@ fn test_ret() { return 10 // no semi } - assert!((f() == 10)); + assert_eq!(f(), 10); } // From issue #372 fn test_372() { fn f() -> int { let x = { 3 }; x } - assert!((f() == 3)); + assert_eq!(f(), 3); } fn test_nil() { () } diff --git a/src/test/run-pass/expr-if-box.rs b/src/test/run-pass/expr-if-box.rs index 004137d065c34..e560da224ff80 100644 --- a/src/test/run-pass/expr-if-box.rs +++ b/src/test/run-pass/expr-if-box.rs @@ -16,12 +16,12 @@ // Tests for if as expressions returning boxed types fn test_box() { let rs = if true { @100 } else { @101 }; - assert!((*rs == 100)); + assert_eq!(*rs, 100); } fn test_str() { let rs = if true { ~"happy" } else { ~"sad" }; - assert!((rs == ~"happy")); + assert_eq!(rs, ~"happy"); } pub fn main() { test_box(); test_str(); } diff --git a/src/test/run-pass/expr-if-fail.rs b/src/test/run-pass/expr-if-fail.rs index 7e2e0badb3662..f79b7198b50e7 100644 --- a/src/test/run-pass/expr-if-fail.rs +++ b/src/test/run-pass/expr-if-fail.rs @@ -12,12 +12,12 @@ fn test_if_fail() { let x = if false { fail!() } else { 10 }; assert!((x == 10)) fn test_else_fail() { let x = if true { 10 } else { fail!() }; - assert!((x == 10)); + assert_eq!(x, 10); } fn test_elseif_fail() { let x = if false { 0 } else if false { fail!() } else { 10 }; - assert!((x == 10)); + assert_eq!(x, 10); } pub fn main() { test_if_fail(); test_else_fail(); test_elseif_fail(); } diff --git a/src/test/run-pass/expr-if-struct.rs b/src/test/run-pass/expr-if-struct.rs index b2bbfcaf9a5ca..13479bb80dc7d 100644 --- a/src/test/run-pass/expr-if-struct.rs +++ b/src/test/run-pass/expr-if-struct.rs @@ -19,7 +19,7 @@ struct I { i: int } fn test_rec() { let rs = if true { I {i: 100} } else { I {i: 101} }; - assert!((rs.i == 100)); + assert_eq!(rs.i, 100); } enum mood { happy, sad, } @@ -33,7 +33,7 @@ impl cmp::Eq for mood { fn test_tag() { let rs = if true { happy } else { sad }; - assert!((rs == happy)); + assert_eq!(rs, happy); } pub fn main() { test_rec(); test_tag(); } diff --git a/src/test/run-pass/expr-if-unique.rs b/src/test/run-pass/expr-if-unique.rs index 9f90ff32f8379..2271461927109 100644 --- a/src/test/run-pass/expr-if-unique.rs +++ b/src/test/run-pass/expr-if-unique.rs @@ -16,7 +16,7 @@ // Tests for if as expressions returning boxed types fn test_box() { let rs = if true { ~100 } else { ~101 }; - assert!((*rs == 100)); + assert_eq!(*rs, 100); } pub fn main() { test_box(); } diff --git a/src/test/run-pass/exterior.rs b/src/test/run-pass/exterior.rs index eef0924f487e4..409fec5656c80 100644 --- a/src/test/run-pass/exterior.rs +++ b/src/test/run-pass/exterior.rs @@ -19,8 +19,8 @@ fn f(p: @mut Point) { assert!((p.z == 12)); p.z = 13; assert!((p.z == 13)); } pub fn main() { let a: Point = Point {x: 10, y: 11, z: 12}; let b: @mut Point = @mut copy a; - assert!((b.z == 12)); + assert_eq!(b.z, 12); f(b); - assert!((a.z == 12)); - assert!((b.z == 13)); + assert_eq!(a.z, 12); + assert_eq!(b.z, 13); } diff --git a/src/test/run-pass/extern-call-deep.rs b/src/test/run-pass/extern-call-deep.rs index c29eb2613ad21..b8cdfcb0c4cfe 100644 --- a/src/test/run-pass/extern-call-deep.rs +++ b/src/test/run-pass/extern-call-deep.rs @@ -33,5 +33,5 @@ fn count(n: uint) -> uint { pub fn main() { let result = count(1000u); debug!("result = %?", result); - assert!(result == 1000u); + assert_eq!(result, 1000u); } diff --git a/src/test/run-pass/extern-call-deep2.rs b/src/test/run-pass/extern-call-deep2.rs index 4e807f0f169ec..eb7ab055b07be 100644 --- a/src/test/run-pass/extern-call-deep2.rs +++ b/src/test/run-pass/extern-call-deep2.rs @@ -36,6 +36,6 @@ pub fn main() { do task::spawn { let result = count(1000u); debug!("result = %?", result); - assert!(result == 1000u); + assert_eq!(result, 1000u); }; } diff --git a/src/test/run-pass/extern-call-scrub.rs b/src/test/run-pass/extern-call-scrub.rs index eafdd3c5e9946..4111f9eb00e21 100644 --- a/src/test/run-pass/extern-call-scrub.rs +++ b/src/test/run-pass/extern-call-scrub.rs @@ -40,6 +40,6 @@ pub fn main() { do task::spawn { let result = count(12u); debug!("result = %?", result); - assert!(result == 2048u); + assert_eq!(result, 2048u); }; } diff --git a/src/test/run-pass/extern-call.rs b/src/test/run-pass/extern-call.rs index 37e531eaa8e60..ec335cf8a82b8 100644 --- a/src/test/run-pass/extern-call.rs +++ b/src/test/run-pass/extern-call.rs @@ -33,5 +33,5 @@ fn fact(n: uint) -> uint { pub fn main() { let result = fact(10u); debug!("result = %?", result); - assert!(result == 3628800u); + assert_eq!(result, 3628800u); } diff --git a/src/test/run-pass/extern-crosscrate.rs b/src/test/run-pass/extern-crosscrate.rs index de7dd7e4c8c1d..eb21e19954962 100644 --- a/src/test/run-pass/extern-crosscrate.rs +++ b/src/test/run-pass/extern-crosscrate.rs @@ -23,5 +23,5 @@ fn fact(n: uint) -> uint { pub fn main() { let result = fact(10u); debug!("result = %?", result); - assert!(result == 3628800u); + assert_eq!(result, 3628800u); } diff --git a/src/test/run-pass/extern-pass-TwoU16s.rs b/src/test/run-pass/extern-pass-TwoU16s.rs index ec65cbb5670b9..1ff4cd0053b35 100644 --- a/src/test/run-pass/extern-pass-TwoU16s.rs +++ b/src/test/run-pass/extern-pass-TwoU16s.rs @@ -26,6 +26,6 @@ pub fn main() { unsafe { let x = TwoU16s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU16s(x); - assert!(x == y); + assert_eq!(x, y); } } diff --git a/src/test/run-pass/extern-pass-TwoU32s.rs b/src/test/run-pass/extern-pass-TwoU32s.rs index 6ac5967c54fd5..362fb6b5b2220 100644 --- a/src/test/run-pass/extern-pass-TwoU32s.rs +++ b/src/test/run-pass/extern-pass-TwoU32s.rs @@ -24,6 +24,6 @@ pub fn main() { unsafe { let x = TwoU32s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU32s(x); - assert!(x == y); + assert_eq!(x, y); } } diff --git a/src/test/run-pass/extern-pass-TwoU64s-ref.rs b/src/test/run-pass/extern-pass-TwoU64s-ref.rs index 19b99eaccc956..6479714e0040a 100644 --- a/src/test/run-pass/extern-pass-TwoU64s-ref.rs +++ b/src/test/run-pass/extern-pass-TwoU64s-ref.rs @@ -23,6 +23,6 @@ pub fn main() { unsafe { let x = TwoU64s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU64s(x); - assert!(x == y); + assert_eq!(x, y); } } diff --git a/src/test/run-pass/extern-pass-TwoU64s.rs b/src/test/run-pass/extern-pass-TwoU64s.rs index cd6226b61c984..246012d65322e 100644 --- a/src/test/run-pass/extern-pass-TwoU64s.rs +++ b/src/test/run-pass/extern-pass-TwoU64s.rs @@ -28,6 +28,6 @@ pub fn main() { unsafe { let x = TwoU64s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU64s(x); - assert!(x == y); + assert_eq!(x, y); } } diff --git a/src/test/run-pass/extern-pass-TwoU8s.rs b/src/test/run-pass/extern-pass-TwoU8s.rs index 7d08b436908dc..01052bd0084f0 100644 --- a/src/test/run-pass/extern-pass-TwoU8s.rs +++ b/src/test/run-pass/extern-pass-TwoU8s.rs @@ -26,6 +26,6 @@ pub fn main() { unsafe { let x = TwoU8s {one: 22, two: 23}; let y = rust_dbg_extern_identity_TwoU8s(x); - assert!(x == y); + assert_eq!(x, y); } } diff --git a/src/test/run-pass/extern-pass-char.rs b/src/test/run-pass/extern-pass-char.rs index 645396e5a988d..37e2795904335 100644 --- a/src/test/run-pass/extern-pass-char.rs +++ b/src/test/run-pass/extern-pass-char.rs @@ -16,6 +16,6 @@ pub extern { pub fn main() { unsafe { - assert!(22_u8 == rust_dbg_extern_identity_u8(22_u8)); + assert_eq!(22_u8, rust_dbg_extern_identity_u8(22_u8)); } } diff --git a/src/test/run-pass/extern-pass-double.rs b/src/test/run-pass/extern-pass-double.rs index 3a6dd26a9dc6c..2812068d69d60 100644 --- a/src/test/run-pass/extern-pass-double.rs +++ b/src/test/run-pass/extern-pass-double.rs @@ -14,6 +14,6 @@ pub extern { pub fn main() { unsafe { - assert!(22.0_f64 == rust_dbg_extern_identity_double(22.0_f64)); + assert_eq!(22.0_f64, rust_dbg_extern_identity_double(22.0_f64)); } } diff --git a/src/test/run-pass/extern-pass-u32.rs b/src/test/run-pass/extern-pass-u32.rs index 19c4d6e153998..4f2633f680f06 100644 --- a/src/test/run-pass/extern-pass-u32.rs +++ b/src/test/run-pass/extern-pass-u32.rs @@ -16,6 +16,6 @@ pub extern { pub fn main() { unsafe { - assert!(22_u32 == rust_dbg_extern_identity_u32(22_u32)); + assert_eq!(22_u32, rust_dbg_extern_identity_u32(22_u32)); } } diff --git a/src/test/run-pass/extern-pass-u64.rs b/src/test/run-pass/extern-pass-u64.rs index cce669999222a..2215a3d95fc73 100644 --- a/src/test/run-pass/extern-pass-u64.rs +++ b/src/test/run-pass/extern-pass-u64.rs @@ -16,6 +16,6 @@ pub extern { pub fn main() { unsafe { - assert!(22_u64 == rust_dbg_extern_identity_u64(22_u64)); + assert_eq!(22_u64, rust_dbg_extern_identity_u64(22_u64)); } } diff --git a/src/test/run-pass/extern-return-TwoU16s.rs b/src/test/run-pass/extern-return-TwoU16s.rs index f87b27e1f62d9..3a345099bad0a 100644 --- a/src/test/run-pass/extern-return-TwoU16s.rs +++ b/src/test/run-pass/extern-return-TwoU16s.rs @@ -22,7 +22,7 @@ pub extern { pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU16s(); - assert!(y.one == 10); - assert!(y.two == 20); + assert_eq!(y.one, 10); + assert_eq!(y.two, 20); } } diff --git a/src/test/run-pass/extern-return-TwoU32s.rs b/src/test/run-pass/extern-return-TwoU32s.rs index 9e374687855b0..788754bfb0022 100644 --- a/src/test/run-pass/extern-return-TwoU32s.rs +++ b/src/test/run-pass/extern-return-TwoU32s.rs @@ -19,7 +19,7 @@ pub extern { pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU32s(); - assert!(y.one == 10); - assert!(y.two == 20); + assert_eq!(y.one, 10); + assert_eq!(y.two, 20); } } diff --git a/src/test/run-pass/extern-return-TwoU64s.rs b/src/test/run-pass/extern-return-TwoU64s.rs index 250d3b8f562b0..9243c285901b1 100644 --- a/src/test/run-pass/extern-return-TwoU64s.rs +++ b/src/test/run-pass/extern-return-TwoU64s.rs @@ -19,7 +19,7 @@ pub extern { pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU64s(); - assert!(y.one == 10); - assert!(y.two == 20); + assert_eq!(y.one, 10); + assert_eq!(y.two, 20); } } diff --git a/src/test/run-pass/extern-return-TwoU8s.rs b/src/test/run-pass/extern-return-TwoU8s.rs index 008e153769a64..c1f897e79b00b 100644 --- a/src/test/run-pass/extern-return-TwoU8s.rs +++ b/src/test/run-pass/extern-return-TwoU8s.rs @@ -22,7 +22,7 @@ pub extern { pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU8s(); - assert!(y.one == 10); - assert!(y.two == 20); + assert_eq!(y.one, 10); + assert_eq!(y.two, 20); } } diff --git a/src/test/run-pass/extern-stress.rs b/src/test/run-pass/extern-stress.rs index 0b640c8c62360..1add9d44d9a28 100644 --- a/src/test/run-pass/extern-stress.rs +++ b/src/test/run-pass/extern-stress.rs @@ -36,7 +36,7 @@ fn count(n: uint) -> uint { pub fn main() { for old_iter::repeat(100u) { do task::spawn { - assert!(count(5u) == 16u); + assert_eq!(count(5u), 16u); }; } } diff --git a/src/test/run-pass/extern-take-value.rs b/src/test/run-pass/extern-take-value.rs index c3815cf2a67f6..542686c9099f1 100644 --- a/src/test/run-pass/extern-take-value.rs +++ b/src/test/run-pass/extern-take-value.rs @@ -20,6 +20,6 @@ pub fn main() { let b: *u8 = f; let c: *u8 = g; - assert!(a == b); + assert_eq!(a, b); assert!(a != c); } diff --git a/src/test/run-pass/extern-yield.rs b/src/test/run-pass/extern-yield.rs index bde3f5dd52ff6..ae2d497418cb9 100644 --- a/src/test/run-pass/extern-yield.rs +++ b/src/test/run-pass/extern-yield.rs @@ -35,7 +35,7 @@ pub fn main() { do task::spawn { let result = count(5u); debug!("result = %?", result); - assert!(result == 16u); + assert_eq!(result, 16u); }; } } diff --git a/src/test/run-pass/fact.rs b/src/test/run-pass/fact.rs index ec82db8644c55..cbcf9a6bef4fa 100644 --- a/src/test/run-pass/fact.rs +++ b/src/test/run-pass/fact.rs @@ -32,7 +32,7 @@ fn f(x: int) -> int { } pub fn main() { - assert!((f(5) == 120)); + assert_eq!(f(5), 120); // debug!("all done"); } diff --git a/src/test/run-pass/fixed-point-bind-box.rs b/src/test/run-pass/fixed-point-bind-box.rs index 76b2309085aba..4c28151224c6d 100644 --- a/src/test/run-pass/fixed-point-bind-box.rs +++ b/src/test/run-pass/fixed-point-bind-box.rs @@ -25,6 +25,6 @@ fn fact_(f: @fn(v: int) -> int, n: int) -> int { pub fn main() { let fact = fix(fact_); - assert!((fact(5) == 120)); - assert!((fact(2) == 2)); + assert_eq!(fact(5), 120); + assert_eq!(fact(2), 2); } diff --git a/src/test/run-pass/fixed-point-bind-unique.rs b/src/test/run-pass/fixed-point-bind-unique.rs index 83060baac51a3..53f9c723a4738 100644 --- a/src/test/run-pass/fixed-point-bind-unique.rs +++ b/src/test/run-pass/fixed-point-bind-unique.rs @@ -25,6 +25,6 @@ fn fact_(f: @fn(v: int) -> int, n: int) -> int { pub fn main() { let fact = fix(fact_); - assert!((fact(5) == 120)); - assert!((fact(2) == 2)); + assert_eq!(fact(5), 120); + assert_eq!(fact(2), 2); } diff --git a/src/test/run-pass/fixed_length_copy.rs b/src/test/run-pass/fixed_length_copy.rs index 7ee3f5173b030..ead8e5ea1044c 100644 --- a/src/test/run-pass/fixed_length_copy.rs +++ b/src/test/run-pass/fixed_length_copy.rs @@ -15,6 +15,6 @@ pub fn main() { let arr = [1,2,3]; let arr2 = arr; - assert!((arr[1] == 2)); - assert!((arr2[2] == 3)); + assert_eq!(arr[1], 2); + assert_eq!(arr2[2], 3); } diff --git a/src/test/run-pass/fixed_length_vec_glue.rs b/src/test/run-pass/fixed_length_vec_glue.rs index b3ced135a4faf..eef898a05ed76 100644 --- a/src/test/run-pass/fixed_length_vec_glue.rs +++ b/src/test/run-pass/fixed_length_vec_glue.rs @@ -14,5 +14,5 @@ pub fn main() { let arr = [1,2,3]; let struc = Struc {a: 13u8, b: arr, c: 42}; let s = sys::log_str(&struc); - assert!((s == ~"{a: 13, b: [1, 2, 3], c: 42}")); + assert_eq!(s, ~"{a: 13, b: [1, 2, 3], c: 42}"); } diff --git a/src/test/run-pass/float-nan.rs b/src/test/run-pass/float-nan.rs index 08523de3ccd81..de3ce4d8149be 100644 --- a/src/test/run-pass/float-nan.rs +++ b/src/test/run-pass/float-nan.rs @@ -19,7 +19,7 @@ pub fn main() { assert!((nan).is_NaN()); let inf = infinity::(); - assert!(-inf == neg_infinity::()); + assert_eq!(-inf, neg_infinity::()); assert!( nan != nan); assert!( nan != -nan); @@ -36,17 +36,17 @@ pub fn main() { assert!( inf != nan); assert!(-inf != nan); - assert!(!( nan == nan)); + assert!(!( nan == nan)); assert!(!( nan == -nan)); - assert!(!( nan == 1.)); - assert!(!( nan == 0.)); - assert!(!( nan == inf)); + assert!(!( nan == 1.)); + assert!(!( nan == 0.)); + assert!(!( nan == inf)); assert!(!( nan == -inf)); - assert!(!( 1. == nan)); - assert!(!( 0. == nan)); - assert!(!( inf == nan)); - assert!(!(-inf == nan)); - assert!(!(-nan == nan)); + assert!(!( 1. == nan)); + assert!(!( 0. == nan)); + assert!(!( inf == nan)); + assert!(!(-inf == nan)); + assert!(!(-nan == nan)); assert!(!(-nan == -nan)); assert!(!( nan > nan)); diff --git a/src/test/run-pass/float2.rs b/src/test/run-pass/float2.rs index d84c4930aa209..713d863029c7c 100644 --- a/src/test/run-pass/float2.rs +++ b/src/test/run-pass/float2.rs @@ -22,13 +22,13 @@ pub fn main() { let i = 1.0E7f64; let j = 3.1e+9; let k = 3.2e-10; - assert!((a == b)); + assert_eq!(a, b); assert!((c < b)); - assert!((c == d)); + assert_eq!(c, d); assert!((e < g)); assert!((f < h)); - assert!((g == 1000000.0f32)); - assert!((h == i)); + assert_eq!(g, 1000000.0f32); + assert_eq!(h, i); assert!((j > k)); assert!((k < a)); } diff --git a/src/test/run-pass/fn-assign-managed-to-bare-1.rs b/src/test/run-pass/fn-assign-managed-to-bare-1.rs index 3a6d448667897..dece77595bcd9 100644 --- a/src/test/run-pass/fn-assign-managed-to-bare-1.rs +++ b/src/test/run-pass/fn-assign-managed-to-bare-1.rs @@ -14,7 +14,7 @@ fn add(n: int) -> @fn(int) -> int { } pub fn main() { - assert!(add(3)(4) == 7); + assert_eq!(add(3)(4), 7); let add3 : &fn(int)->int = add(3); - assert!(add3(4) == 7); + assert_eq!(add3(4), 7); } diff --git a/src/test/run-pass/fn-assign-managed-to-bare-2.rs b/src/test/run-pass/fn-assign-managed-to-bare-2.rs index c7b7770d81fef..f8daacfa2337a 100644 --- a/src/test/run-pass/fn-assign-managed-to-bare-2.rs +++ b/src/test/run-pass/fn-assign-managed-to-bare-2.rs @@ -15,14 +15,14 @@ fn add(n: int) -> @fn(int) -> int { pub fn main() { - assert!(add(3)(4) == 7); + assert_eq!(add(3)(4), 7); let add1 : @fn(int)->int = add(1); - assert!(add1(6) == 7); + assert_eq!(add1(6), 7); let add2 : &(@fn(int)->int) = &add(2); - assert!((*add2)(5) == 7); + assert_eq!((*add2)(5), 7); let add3 : &fn(int)->int = add(3); - assert!(add3(4) == 7); + assert_eq!(add3(4), 7); } diff --git a/src/test/run-pass/fn-bare-assign.rs b/src/test/run-pass/fn-bare-assign.rs index 7ad7d24df596a..7c8fbd2989f76 100644 --- a/src/test/run-pass/fn-bare-assign.rs +++ b/src/test/run-pass/fn-bare-assign.rs @@ -9,7 +9,7 @@ // except according to those terms. fn f(i: int, called: &mut bool) { - assert!(i == 10); + assert_eq!(i, 10); *called = true; } @@ -21,5 +21,5 @@ pub fn main() { let mut called = false; let h = f; g(h, &mut called); - assert!(called == true); + assert_eq!(called, true); } diff --git a/src/test/run-pass/fn-bare-spawn.rs b/src/test/run-pass/fn-bare-spawn.rs index b78bd488bc6ea..4f0f451a08c09 100644 --- a/src/test/run-pass/fn-bare-spawn.rs +++ b/src/test/run-pass/fn-bare-spawn.rs @@ -15,7 +15,7 @@ fn spawn(val: T, f: extern fn(T)) { } fn f(i: int) { - assert!(i == 100); + assert_eq!(i, 100); } pub fn main() { diff --git a/src/test/run-pass/fn-pattern-expected-type.rs b/src/test/run-pass/fn-pattern-expected-type.rs index f3949a0f43bf3..450e2a70aab9b 100644 --- a/src/test/run-pass/fn-pattern-expected-type.rs +++ b/src/test/run-pass/fn-pattern-expected-type.rs @@ -10,8 +10,8 @@ pub fn main() { let f: &fn((int,int)) = |(x, y)| { - assert!(x == 1); - assert!(y == 2); + assert_eq!(x, 1); + assert_eq!(y, 2); }; f((1, 2)); } diff --git a/src/test/run-pass/for-destruct.rs b/src/test/run-pass/for-destruct.rs index 4c5084d9f1e21..bbcb7d5892330 100644 --- a/src/test/run-pass/for-destruct.rs +++ b/src/test/run-pass/for-destruct.rs @@ -12,6 +12,6 @@ struct Pair { x: int, y: int } pub fn main() { for vec::each(~[Pair {x: 10, y: 20}, Pair {x: 30, y: 0}]) |elt| { - assert!((elt.x + elt.y == 30)); + assert_eq!(elt.x + elt.y, 30); } } diff --git a/src/test/run-pass/foreach-nested.rs b/src/test/run-pass/foreach-nested.rs index b180e50202345..6987e2cf97d70 100644 --- a/src/test/run-pass/foreach-nested.rs +++ b/src/test/run-pass/foreach-nested.rs @@ -20,8 +20,8 @@ pub fn main() { do two |i| { do two |j| { a[p] = 10 * i + j; p += 1; } } - assert!((a[0] == 0)); - assert!((a[1] == 1)); - assert!((a[2] == 10)); - assert!((a[3] == 11)); + assert_eq!(a[0], 0); + assert_eq!(a[1], 1); + assert_eq!(a[2], 10); + assert_eq!(a[3], 11); } diff --git a/src/test/run-pass/foreach-put-structured.rs b/src/test/run-pass/foreach-put-structured.rs index 421ee7ff2b0f4..d52842b4101ee 100644 --- a/src/test/run-pass/foreach-put-structured.rs +++ b/src/test/run-pass/foreach-put-structured.rs @@ -23,9 +23,9 @@ pub fn main() { let (_0, _1) = p; debug!(_0); debug!(_1); - assert!((_0 + 10 == i)); + assert_eq!(_0 + 10, i); i += 1; j = _1; }; - assert!((j == 45)); + assert_eq!(j, 45); } diff --git a/src/test/run-pass/foreach-simple-outer-slot.rs b/src/test/run-pass/foreach-simple-outer-slot.rs index 99848ddfc7b48..c3120c44c3715 100644 --- a/src/test/run-pass/foreach-simple-outer-slot.rs +++ b/src/test/run-pass/foreach-simple-outer-slot.rs @@ -17,7 +17,7 @@ pub fn main() { do first_ten |i| { debug!("main"); debug!(i); sum = sum + i; } debug!("sum"); debug!(sum); - assert!((sum == 45)); + assert_eq!(sum, 45); } fn first_ten(it: &fn(int)) { diff --git a/src/test/run-pass/foreign-call-no-runtime.rs b/src/test/run-pass/foreign-call-no-runtime.rs index 08cb8db5131ff..3f61fca872616 100644 --- a/src/test/run-pass/foreign-call-no-runtime.rs +++ b/src/test/run-pass/foreign-call-no-runtime.rs @@ -19,6 +19,6 @@ pub fn main() { extern fn callback(data: libc::uintptr_t) { unsafe { let data: *int = cast::transmute(data); - assert!(*data == 100); + assert_eq!(*data, 100); } } diff --git a/src/test/run-pass/foreign-fn-linkname.rs b/src/test/run-pass/foreign-fn-linkname.rs index 429e78b9c2194..3b00b329feb9d 100644 --- a/src/test/run-pass/foreign-fn-linkname.rs +++ b/src/test/run-pass/foreign-fn-linkname.rs @@ -29,5 +29,5 @@ fn strlen(str: ~str) -> uint { pub fn main() { let len = strlen(~"Rust"); - assert!((len == 4u)); + assert_eq!(len, 4u); } diff --git a/src/test/run-pass/foreign-lib-path.rs b/src/test/run-pass/foreign-lib-path.rs index 61fc709d94933..bfa1e79a26fb0 100644 --- a/src/test/run-pass/foreign-lib-path.rs +++ b/src/test/run-pass/foreign-lib-path.rs @@ -22,5 +22,5 @@ mod WHATGOESHERE { } pub fn main() { - assert!(IDONTKNOW() == 0x_BAD_DOOD_u32); + assert_eq!(IDONTKNOW(), 0x_BAD_DOOD_u32); } diff --git a/src/test/run-pass/fun-call-variants.rs b/src/test/run-pass/fun-call-variants.rs index c2baab090db9d..52e6a4649a8dc 100644 --- a/src/test/run-pass/fun-call-variants.rs +++ b/src/test/run-pass/fun-call-variants.rs @@ -17,5 +17,5 @@ pub fn main() { let a: int = direct(3); // direct let b: int = ho(direct); // indirect unbound - assert!((a == b)); + assert_eq!(a, b); } diff --git a/src/test/run-pass/fun-indirect-call.rs b/src/test/run-pass/fun-indirect-call.rs index db39850e74edb..738752924c3c9 100644 --- a/src/test/run-pass/fun-indirect-call.rs +++ b/src/test/run-pass/fun-indirect-call.rs @@ -17,5 +17,5 @@ fn f() -> int { return 42; } pub fn main() { let g: extern fn() -> int = f; let i: int = g(); - assert!((i == 42)); + assert_eq!(i, 42); } diff --git a/src/test/run-pass/generic-alias-box.rs b/src/test/run-pass/generic-alias-box.rs index e5aa54534db1f..bce65161921b6 100644 --- a/src/test/run-pass/generic-alias-box.rs +++ b/src/test/run-pass/generic-alias-box.rs @@ -16,5 +16,5 @@ pub fn main() { let expected = @100; let actual = id::<@int>(expected); debug!(*actual); - assert!((*expected == *actual)); + assert_eq!(*expected, *actual); } diff --git a/src/test/run-pass/generic-alias-unique.rs b/src/test/run-pass/generic-alias-unique.rs index 5eb91b317404b..ad271186639bd 100644 --- a/src/test/run-pass/generic-alias-unique.rs +++ b/src/test/run-pass/generic-alias-unique.rs @@ -16,5 +16,5 @@ pub fn main() { let expected = ~100; let actual = id::<~int>(expected.clone()); debug!(*actual); - assert!((*expected == *actual)); + assert_eq!(*expected, *actual); } diff --git a/src/test/run-pass/generic-box.rs b/src/test/run-pass/generic-box.rs index 0506256459529..7248e5770698f 100644 --- a/src/test/run-pass/generic-box.rs +++ b/src/test/run-pass/generic-box.rs @@ -16,5 +16,5 @@ struct Box {x: T, y: T, z: T} pub fn main() { let x: @Box = box::(Box{x: 1, y: 2, z: 3}); - assert!((x.y == 2)); + assert_eq!(x.y, 2); } diff --git a/src/test/run-pass/generic-derived-type.rs b/src/test/run-pass/generic-derived-type.rs index 747acca903ba2..9e266a3f20804 100644 --- a/src/test/run-pass/generic-derived-type.rs +++ b/src/test/run-pass/generic-derived-type.rs @@ -24,6 +24,6 @@ pub fn main() { let b = f::(10); debug!(b.a); debug!(b.b); - assert!((b.a == 10)); - assert!((b.b == 10)); + assert_eq!(b.a, 10); + assert_eq!(b.b, 10); } diff --git a/src/test/run-pass/generic-exterior-box.rs b/src/test/run-pass/generic-exterior-box.rs index 7708ffad3678a..79ee544d49555 100644 --- a/src/test/run-pass/generic-exterior-box.rs +++ b/src/test/run-pass/generic-exterior-box.rs @@ -17,5 +17,5 @@ fn reclift(t: T) -> Recbox { return Recbox {x: @t}; } pub fn main() { let foo: int = 17; let rbfoo: Recbox = reclift::(foo); - assert!((*rbfoo.x == foo)); + assert_eq!(*rbfoo.x, foo); } diff --git a/src/test/run-pass/generic-exterior-unique.rs b/src/test/run-pass/generic-exterior-unique.rs index 693b83f1102be..cc94fca680408 100644 --- a/src/test/run-pass/generic-exterior-unique.rs +++ b/src/test/run-pass/generic-exterior-unique.rs @@ -15,5 +15,5 @@ fn reclift(t: T) -> Recbox { return Recbox {x: ~t}; } pub fn main() { let foo: int = 17; let rbfoo: Recbox = reclift::(foo); - assert!((*rbfoo.x == foo)); + assert_eq!(*rbfoo.x, foo); } diff --git a/src/test/run-pass/generic-fn.rs b/src/test/run-pass/generic-fn.rs index 8108e15ee148c..bcacccee820be 100644 --- a/src/test/run-pass/generic-fn.rs +++ b/src/test/run-pass/generic-fn.rs @@ -25,13 +25,13 @@ pub fn main() { let mut q: Triple = Triple {x: 68, y: 69, z: 70}; y = id::(x); debug!(y); - assert!((x == y)); + assert_eq!(x, y); b = id::(a); debug!(b); - assert!((a == b)); + assert_eq!(a, b); q = id::(p); x = p.z; y = q.z; debug!(y); - assert!((x == y)); + assert_eq!(x, y); } diff --git a/src/test/run-pass/generic-object.rs b/src/test/run-pass/generic-object.rs index 54ae2c58e42ea..1e532caaf0487 100644 --- a/src/test/run-pass/generic-object.rs +++ b/src/test/run-pass/generic-object.rs @@ -25,5 +25,5 @@ impl Foo for S { pub fn main() { let x = @S { x: 1 }; let y = x as @Foo; - assert!(y.get() == 1); + assert_eq!(y.get(), 1); } diff --git a/src/test/run-pass/generic-tag-values.rs b/src/test/run-pass/generic-tag-values.rs index 42f19e86fe852..eced9a7074298 100644 --- a/src/test/run-pass/generic-tag-values.rs +++ b/src/test/run-pass/generic-tag-values.rs @@ -24,8 +24,8 @@ pub fn main() { some(t) => { debug!(t.x); debug!(t.y); - assert!((t.x == 17)); - assert!((t.y == 42)); + assert_eq!(t.x, 17); + assert_eq!(t.y, 42); } } } diff --git a/src/test/run-pass/generic-tup.rs b/src/test/run-pass/generic-tup.rs index 212e044dd14fc..485b9a78488e4 100644 --- a/src/test/run-pass/generic-tup.rs +++ b/src/test/run-pass/generic-tup.rs @@ -12,6 +12,6 @@ fn get_third(t: (T, T, T)) -> T { let (_, _, x) = t; return x; } pub fn main() { debug!(get_third((1, 2, 3))); - assert!((get_third((1, 2, 3)) == 3)); - assert!((get_third((5u8, 6u8, 7u8)) == 7u8)); + assert_eq!(get_third((1, 2, 3)), 3); + assert_eq!(get_third((5u8, 6u8, 7u8)), 7u8); } diff --git a/src/test/run-pass/generic-type.rs b/src/test/run-pass/generic-type.rs index 8f9208ea91726..0ff7cedc6c5f1 100644 --- a/src/test/run-pass/generic-type.rs +++ b/src/test/run-pass/generic-type.rs @@ -14,6 +14,6 @@ struct Pair {x: T, y: T} pub fn main() { let x: Pair = Pair {x: 10, y: 12}; - assert!((x.x == 10)); - assert!((x.y == 12)); + assert_eq!(x.x, 10); + assert_eq!(x.y, 12); } diff --git a/src/test/run-pass/generic-unique.rs b/src/test/run-pass/generic-unique.rs index 064e2f5462822..8a4fc94135b9a 100644 --- a/src/test/run-pass/generic-unique.rs +++ b/src/test/run-pass/generic-unique.rs @@ -14,5 +14,5 @@ fn box(x: Triple) -> ~Triple { return ~x; } pub fn main() { let x: ~Triple = box::(Triple{x: 1, y: 2, z: 3}); - assert!((x.y == 2)); + assert_eq!(x.y, 2); } diff --git a/src/test/run-pass/guards-not-exhaustive.rs b/src/test/run-pass/guards-not-exhaustive.rs index 8f5b288b755dd..4d30fbe15591a 100644 --- a/src/test/run-pass/guards-not-exhaustive.rs +++ b/src/test/run-pass/guards-not-exhaustive.rs @@ -9,5 +9,5 @@ fn xyzzy(q: Q) -> uint { pub fn main() { - assert!(xyzzy(R(Some(5))) == 0); + assert_eq!(xyzzy(R(Some(5))), 0); } diff --git a/src/test/run-pass/guards.rs b/src/test/run-pass/guards.rs index 8654e4a2a4b27..86bff013eefc6 100644 --- a/src/test/run-pass/guards.rs +++ b/src/test/run-pass/guards.rs @@ -13,7 +13,7 @@ struct Pair { x: int, y: int } pub fn main() { let a = match 10 { x if x < 7 => { 1 } x if x < 11 => { 2 } 10 => { 3 } _ => { 4 } }; - assert!((a == 2)); + assert_eq!(a, 2); let b = match Pair {x: 10, y: 20} { @@ -21,5 +21,5 @@ pub fn main() { Pair {x: x, y: y} if x == 10 && y == 20 => { 2 } Pair {x: x, y: y} => { 3 } }; - assert!((b == 2)); + assert_eq!(b, 2); } diff --git a/src/test/run-pass/i8-incr.rs b/src/test/run-pass/i8-incr.rs index 9708e04058b8c..799910a6a5fca 100644 --- a/src/test/run-pass/i8-incr.rs +++ b/src/test/run-pass/i8-incr.rs @@ -17,5 +17,5 @@ pub fn main() { let y: i8 = -12i8; x = x + 1i8; x = x - 1i8; - assert!((x == y)); + assert_eq!(x, y); } diff --git a/src/test/run-pass/import-glob-crate.rs b/src/test/run-pass/import-glob-crate.rs index a29b1ff0c6984..de25ec42c29f1 100644 --- a/src/test/run-pass/import-glob-crate.rs +++ b/src/test/run-pass/import-glob-crate.rs @@ -17,5 +17,5 @@ use core::vec::*; pub fn main() { let mut v = from_elem(0u, 0); v = vec::append(v, ~[4, 2]); - assert!((reversed(v) == ~[2, 4])); + assert_eq!(reversed(v), ~[2, 4]); } diff --git a/src/test/run-pass/inferred-suffix-in-pattern-range.rs b/src/test/run-pass/inferred-suffix-in-pattern-range.rs index e9287f3562205..447ee2c890c22 100644 --- a/src/test/run-pass/inferred-suffix-in-pattern-range.rs +++ b/src/test/run-pass/inferred-suffix-in-pattern-range.rs @@ -14,19 +14,19 @@ pub fn main() { 0 .. 1 => { ~"not many" } _ => { ~"lots" } }; - assert!(x_message == ~"lots"); + assert_eq!(x_message, ~"lots"); let y = 2i; let y_message = match y { 0 .. 1 => { ~"not many" } _ => { ~"lots" } }; - assert!(y_message == ~"lots"); + assert_eq!(y_message, ~"lots"); let z = 1u64; let z_message = match z { 0 .. 1 => { ~"not many" } _ => { ~"lots" } }; - assert!(z_message == ~"not many"); + assert_eq!(z_message, ~"not many"); } diff --git a/src/test/run-pass/init-res-into-things.rs b/src/test/run-pass/init-res-into-things.rs index 98919e49a1ad3..5e10419da6e72 100644 --- a/src/test/run-pass/init-res-into-things.rs +++ b/src/test/run-pass/init-res-into-things.rs @@ -37,7 +37,7 @@ fn test_box() { { let a = @r(i); } - assert!(*i == 1); + assert_eq!(*i, 1); } fn test_rec() { @@ -45,7 +45,7 @@ fn test_rec() { { let a = Box {x: r(i)}; } - assert!(*i == 1); + assert_eq!(*i, 1); } fn test_tag() { @@ -57,7 +57,7 @@ fn test_tag() { { let a = t0(r(i)); } - assert!(*i == 1); + assert_eq!(*i, 1); } fn test_tup() { @@ -65,7 +65,7 @@ fn test_tup() { { let a = (r(i), 0); } - assert!(*i == 1); + assert_eq!(*i, 1); } fn test_unique() { @@ -73,7 +73,7 @@ fn test_unique() { { let a = ~r(i); } - assert!(*i == 1); + assert_eq!(*i, 1); } fn test_box_rec() { @@ -83,7 +83,7 @@ fn test_box_rec() { x: r(i) }; } - assert!(*i == 1); + assert_eq!(*i, 1); } pub fn main() { diff --git a/src/test/run-pass/int-conversion-coherence.rs b/src/test/run-pass/int-conversion-coherence.rs index ef2a84da219c9..7ef4f6ed22c12 100644 --- a/src/test/run-pass/int-conversion-coherence.rs +++ b/src/test/run-pass/int-conversion-coherence.rs @@ -21,5 +21,5 @@ impl foo of plus for uint { fn plus() -> int { self as int + 20 } } impl foo of plus for int { fn plus() -> int { self + 10 } } pub fn main() { - assert!(10.plus() == 20); + assert_eq!(10.plus(), 20); } diff --git a/src/test/run-pass/integral-indexing.rs b/src/test/run-pass/integral-indexing.rs index 9d30c73860505..b985ed0f6cb6a 100644 --- a/src/test/run-pass/integral-indexing.rs +++ b/src/test/run-pass/integral-indexing.rs @@ -15,16 +15,16 @@ pub fn main() { let v: ~[int] = ~[0, 1, 2, 3, 4, 5]; let s: ~str = ~"abcdef"; - assert!((v[3u] == 3)); - assert!((v[3u8] == 3)); - assert!((v[3i8] == 3)); - assert!((v[3u32] == 3)); - assert!((v[3i32] == 3)); + assert_eq!(v[3u], 3); + assert_eq!(v[3u8], 3); + assert_eq!(v[3i8], 3); + assert_eq!(v[3u32], 3); + assert_eq!(v[3i32], 3); debug!(v[3u8]); - assert!((s[3u] == 'd' as u8)); - assert!((s[3u8] == 'd' as u8)); - assert!((s[3i8] == 'd' as u8)); - assert!((s[3u32] == 'd' as u8)); - assert!((s[3i32] == 'd' as u8)); + assert_eq!(s[3u], 'd' as u8); + assert_eq!(s[3u8], 'd' as u8); + assert_eq!(s[3i8], 'd' as u8); + assert_eq!(s[3u32], 'd' as u8); + assert_eq!(s[3i32], 'd' as u8); debug!(s[3u8]); } diff --git a/src/test/run-pass/intrinsic-alignment.rs b/src/test/run-pass/intrinsic-alignment.rs index cce3d8066ec19..7a54b87404e44 100644 --- a/src/test/run-pass/intrinsic-alignment.rs +++ b/src/test/run-pass/intrinsic-alignment.rs @@ -26,8 +26,8 @@ mod m { #[cfg(target_arch = "x86")] pub fn main() { unsafe { - assert!(::rusti::pref_align_of::() == 8u); - assert!(::rusti::min_align_of::() == 4u); + assert_eq!(::rusti::pref_align_of::(), 8u); + assert_eq!(::rusti::min_align_of::(), 4u); } } @@ -35,8 +35,8 @@ mod m { #[cfg(target_arch = "x86_64")] pub fn main() { unsafe { - assert!(::rusti::pref_align_of::() == 8u); - assert!(::rusti::min_align_of::() == 8u); + assert_eq!(::rusti::pref_align_of::(), 8u); + assert_eq!(::rusti::min_align_of::(), 8u); } } } @@ -47,8 +47,8 @@ mod m { #[cfg(target_arch = "x86")] pub fn main() { unsafe { - assert!(::rusti::pref_align_of::() == 8u); - assert!(::rusti::min_align_of::() == 8u); + assert_eq!(::rusti::pref_align_of::(), 8u); + assert_eq!(::rusti::min_align_of::(), 8u); } } } @@ -59,8 +59,8 @@ mod m { #[cfg(target_arch = "arm")] pub fn main() { unsafe { - assert!(::rusti::pref_align_of::() == 8u); - assert!(::rusti::min_align_of::() == 4u); + assert_eq!(::rusti::pref_align_of::(), 8u); + assert_eq!(::rusti::min_align_of::(), 4u); } } } diff --git a/src/test/run-pass/intrinsic-atomics-cc.rs b/src/test/run-pass/intrinsic-atomics-cc.rs index da0c7e759f580..ad285e9a85fb9 100644 --- a/src/test/run-pass/intrinsic-atomics-cc.rs +++ b/src/test/run-pass/intrinsic-atomics-cc.rs @@ -18,6 +18,6 @@ pub fn main() { unsafe { let mut x = 1; atomic_xchg(&mut x, 5); - assert!(x == 5); + assert_eq!(x, 5); } } diff --git a/src/test/run-pass/intrinsic-atomics.rs b/src/test/run-pass/intrinsic-atomics.rs index 4105e6003b55c..e5ab980cc8d84 100644 --- a/src/test/run-pass/intrinsic-atomics.rs +++ b/src/test/run-pass/intrinsic-atomics.rs @@ -39,41 +39,41 @@ pub fn main() { unsafe { let mut x = ~1; - assert!(rusti::atomic_load(x) == 1); + assert_eq!(rusti::atomic_load(x), 1); *x = 5; - assert!(rusti::atomic_load_acq(x) == 5); + assert_eq!(rusti::atomic_load_acq(x), 5); rusti::atomic_store(x,3); - assert!(*x == 3); + assert_eq!(*x, 3); rusti::atomic_store_rel(x,1); - assert!(*x == 1); + assert_eq!(*x, 1); - assert!(rusti::atomic_cxchg(x, 1, 2) == 1); - assert!(*x == 2); + assert_eq!(rusti::atomic_cxchg(x, 1, 2), 1); + assert_eq!(*x, 2); - assert!(rusti::atomic_cxchg_acq(x, 1, 3) == 2); - assert!(*x == 2); + assert_eq!(rusti::atomic_cxchg_acq(x, 1, 3), 2); + assert_eq!(*x, 2); - assert!(rusti::atomic_cxchg_rel(x, 2, 1) == 2); - assert!(*x == 1); + assert_eq!(rusti::atomic_cxchg_rel(x, 2, 1), 2); + assert_eq!(*x, 1); - assert!(rusti::atomic_xchg(x, 0) == 1); - assert!(*x == 0); + assert_eq!(rusti::atomic_xchg(x, 0), 1); + assert_eq!(*x, 0); - assert!(rusti::atomic_xchg_acq(x, 1) == 0); - assert!(*x == 1); + assert_eq!(rusti::atomic_xchg_acq(x, 1), 0); + assert_eq!(*x, 1); - assert!(rusti::atomic_xchg_rel(x, 0) == 1); - assert!(*x == 0); + assert_eq!(rusti::atomic_xchg_rel(x, 0), 1); + assert_eq!(*x, 0); - assert!(rusti::atomic_xadd(x, 1) == 0); - assert!(rusti::atomic_xadd_acq(x, 1) == 1); - assert!(rusti::atomic_xadd_rel(x, 1) == 2); - assert!(*x == 3); + assert_eq!(rusti::atomic_xadd(x, 1), 0); + assert_eq!(rusti::atomic_xadd_acq(x, 1), 1); + assert_eq!(rusti::atomic_xadd_rel(x, 1), 2); + assert_eq!(*x, 3); - assert!(rusti::atomic_xsub(x, 1) == 3); - assert!(rusti::atomic_xsub_acq(x, 1) == 2); - assert!(rusti::atomic_xsub_rel(x, 1) == 1); - assert!(*x == 0); + assert_eq!(rusti::atomic_xsub(x, 1), 3); + assert_eq!(rusti::atomic_xsub_acq(x, 1), 2); + assert_eq!(rusti::atomic_xsub_rel(x, 1), 1); + assert_eq!(*x, 0); } } diff --git a/src/test/run-pass/intrinsic-move-val.rs b/src/test/run-pass/intrinsic-move-val.rs index 9f683d2089877..1dbb46c271ecb 100644 --- a/src/test/run-pass/intrinsic-move-val.rs +++ b/src/test/run-pass/intrinsic-move-val.rs @@ -21,6 +21,6 @@ pub fn main() { let mut x = @1; let mut y = @2; rusti::move_val(&mut y, x); - assert!(*y == 1); + assert_eq!(*y, 1); } } diff --git a/src/test/run-pass/intrinsics-integer.rs b/src/test/run-pass/intrinsics-integer.rs index 1a0d97a5c5b03..e4d84808673c0 100644 --- a/src/test/run-pass/intrinsics-integer.rs +++ b/src/test/run-pass/intrinsics-integer.rs @@ -40,83 +40,83 @@ pub fn main() { unsafe { use rusti::*; - assert!((ctpop8(0i8) == 0i8)); - assert!((ctpop16(0i16) == 0i16)); - assert!((ctpop32(0i32) == 0i32)); - assert!((ctpop64(0i64) == 0i64)); - - assert!((ctpop8(1i8) == 1i8)); - assert!((ctpop16(1i16) == 1i16)); - assert!((ctpop32(1i32) == 1i32)); - assert!((ctpop64(1i64) == 1i64)); - - assert!((ctpop8(10i8) == 2i8)); - assert!((ctpop16(10i16) == 2i16)); - assert!((ctpop32(10i32) == 2i32)); - assert!((ctpop64(10i64) == 2i64)); - - assert!((ctpop8(100i8) == 3i8)); - assert!((ctpop16(100i16) == 3i16)); - assert!((ctpop32(100i32) == 3i32)); - assert!((ctpop64(100i64) == 3i64)); - - assert!((ctpop8(-1i8) == 8i8)); - assert!((ctpop16(-1i16) == 16i16)); - assert!((ctpop32(-1i32) == 32i32)); - assert!((ctpop64(-1i64) == 64i64)); - - assert!((ctlz8(0i8) == 8i8)); - assert!((ctlz16(0i16) == 16i16)); - assert!((ctlz32(0i32) == 32i32)); - assert!((ctlz64(0i64) == 64i64)); - - assert!((ctlz8(1i8) == 7i8)); - assert!((ctlz16(1i16) == 15i16)); - assert!((ctlz32(1i32) == 31i32)); - assert!((ctlz64(1i64) == 63i64)); - - assert!((ctlz8(10i8) == 4i8)); - assert!((ctlz16(10i16) == 12i16)); - assert!((ctlz32(10i32) == 28i32)); - assert!((ctlz64(10i64) == 60i64)); - - assert!((ctlz8(100i8) == 1i8)); - assert!((ctlz16(100i16) == 9i16)); - assert!((ctlz32(100i32) == 25i32)); - assert!((ctlz64(100i64) == 57i64)); - - assert!((cttz8(-1i8) == 0i8)); - assert!((cttz16(-1i16) == 0i16)); - assert!((cttz32(-1i32) == 0i32)); - assert!((cttz64(-1i64) == 0i64)); - - assert!((cttz8(0i8) == 8i8)); - assert!((cttz16(0i16) == 16i16)); - assert!((cttz32(0i32) == 32i32)); - assert!((cttz64(0i64) == 64i64)); - - assert!((cttz8(1i8) == 0i8)); - assert!((cttz16(1i16) == 0i16)); - assert!((cttz32(1i32) == 0i32)); - assert!((cttz64(1i64) == 0i64)); - - assert!((cttz8(10i8) == 1i8)); - assert!((cttz16(10i16) == 1i16)); - assert!((cttz32(10i32) == 1i32)); - assert!((cttz64(10i64) == 1i64)); - - assert!((cttz8(100i8) == 2i8)); - assert!((cttz16(100i16) == 2i16)); - assert!((cttz32(100i32) == 2i32)); - assert!((cttz64(100i64) == 2i64)); - - assert!((cttz8(-1i8) == 0i8)); - assert!((cttz16(-1i16) == 0i16)); - assert!((cttz32(-1i32) == 0i32)); - assert!((cttz64(-1i64) == 0i64)); - - assert!((bswap16(0x0A0Bi16) == 0x0B0Ai16)); - assert!((bswap32(0x0ABBCC0Di32) == 0x0DCCBB0Ai32)); - assert!((bswap64(0x0122334455667708i64) == 0x0877665544332201i64)); + assert_eq!(ctpop8(0i8), 0i8); + assert_eq!(ctpop16(0i16), 0i16); + assert_eq!(ctpop32(0i32), 0i32); + assert_eq!(ctpop64(0i64), 0i64); + + assert_eq!(ctpop8(1i8), 1i8); + assert_eq!(ctpop16(1i16), 1i16); + assert_eq!(ctpop32(1i32), 1i32); + assert_eq!(ctpop64(1i64), 1i64); + + assert_eq!(ctpop8(10i8), 2i8); + assert_eq!(ctpop16(10i16), 2i16); + assert_eq!(ctpop32(10i32), 2i32); + assert_eq!(ctpop64(10i64), 2i64); + + assert_eq!(ctpop8(100i8), 3i8); + assert_eq!(ctpop16(100i16), 3i16); + assert_eq!(ctpop32(100i32), 3i32); + assert_eq!(ctpop64(100i64), 3i64); + + assert_eq!(ctpop8(-1i8), 8i8); + assert_eq!(ctpop16(-1i16), 16i16); + assert_eq!(ctpop32(-1i32), 32i32); + assert_eq!(ctpop64(-1i64), 64i64); + + assert_eq!(ctlz8(0i8), 8i8); + assert_eq!(ctlz16(0i16), 16i16); + assert_eq!(ctlz32(0i32), 32i32); + assert_eq!(ctlz64(0i64), 64i64); + + assert_eq!(ctlz8(1i8), 7i8); + assert_eq!(ctlz16(1i16), 15i16); + assert_eq!(ctlz32(1i32), 31i32); + assert_eq!(ctlz64(1i64), 63i64); + + assert_eq!(ctlz8(10i8), 4i8); + assert_eq!(ctlz16(10i16), 12i16); + assert_eq!(ctlz32(10i32), 28i32); + assert_eq!(ctlz64(10i64), 60i64); + + assert_eq!(ctlz8(100i8), 1i8); + assert_eq!(ctlz16(100i16), 9i16); + assert_eq!(ctlz32(100i32), 25i32); + assert_eq!(ctlz64(100i64), 57i64); + + assert_eq!(cttz8(-1i8), 0i8); + assert_eq!(cttz16(-1i16), 0i16); + assert_eq!(cttz32(-1i32), 0i32); + assert_eq!(cttz64(-1i64), 0i64); + + assert_eq!(cttz8(0i8), 8i8); + assert_eq!(cttz16(0i16), 16i16); + assert_eq!(cttz32(0i32), 32i32); + assert_eq!(cttz64(0i64), 64i64); + + assert_eq!(cttz8(1i8), 0i8); + assert_eq!(cttz16(1i16), 0i16); + assert_eq!(cttz32(1i32), 0i32); + assert_eq!(cttz64(1i64), 0i64); + + assert_eq!(cttz8(10i8), 1i8); + assert_eq!(cttz16(10i16), 1i16); + assert_eq!(cttz32(10i32), 1i32); + assert_eq!(cttz64(10i64), 1i64); + + assert_eq!(cttz8(100i8), 2i8); + assert_eq!(cttz16(100i16), 2i16); + assert_eq!(cttz32(100i32), 2i32); + assert_eq!(cttz64(100i64), 2i64); + + assert_eq!(cttz8(-1i8), 0i8); + assert_eq!(cttz16(-1i16), 0i16); + assert_eq!(cttz32(-1i32), 0i32); + assert_eq!(cttz64(-1i64), 0i64); + + assert_eq!(bswap16(0x0A0Bi16), 0x0B0Ai16); + assert_eq!(bswap32(0x0ABBCC0Di32), 0x0DCCBB0Ai32); + assert_eq!(bswap64(0x0122334455667708i64), 0x0877665544332201i64); } } diff --git a/src/test/run-pass/issue-1112.rs b/src/test/run-pass/issue-1112.rs index cd15dfa2a0d60..22c88c874f096 100644 --- a/src/test/run-pass/issue-1112.rs +++ b/src/test/run-pass/issue-1112.rs @@ -35,10 +35,10 @@ pub fn main() { } fn bar(x: X) { - assert!(x.b == 9u8); - assert!(x.c == true); - assert!(x.d == 10u8); - assert!(x.e == 11u16); - assert!(x.f == 12u8); - assert!(x.g == 13u8); + assert_eq!(x.b, 9u8); + assert_eq!(x.c, true); + assert_eq!(x.d, 10u8); + assert_eq!(x.e, 11u16); + assert_eq!(x.f, 12u8); + assert_eq!(x.g, 13u8); } diff --git a/src/test/run-pass/issue-1458.rs b/src/test/run-pass/issue-1458.rs index 0677c9dea7402..e22f38287ad5d 100644 --- a/src/test/run-pass/issue-1458.rs +++ b/src/test/run-pass/issue-1458.rs @@ -18,5 +18,5 @@ fn ret_plus_one() -> extern fn(&fn() -> int) -> int { pub fn main() { let z = do (ret_plus_one()) || { 2 }; - assert!(z == 3); + assert_eq!(z, 3); } diff --git a/src/test/run-pass/issue-1701.rs b/src/test/run-pass/issue-1701.rs index c8937a2a628ee..4f3d0dbe13344 100644 --- a/src/test/run-pass/issue-1701.rs +++ b/src/test/run-pass/issue-1701.rs @@ -24,8 +24,8 @@ fn noise(a: animal) -> Option<~str> { } pub fn main() { - assert!(noise(cat(tabby)) == Some(~"meow")); - assert!(noise(dog(pug)) == Some(~"woof")); - assert!(noise(rabbit(~"Hilbert", upright)) == None); - assert!(noise(tiger) == Some(~"roar")); + assert_eq!(noise(cat(tabby)), Some(~"meow")); + assert_eq!(noise(dog(pug)), Some(~"woof")); + assert_eq!(noise(rabbit(~"Hilbert", upright)), None); + assert_eq!(noise(tiger), Some(~"roar")); } diff --git a/src/test/run-pass/issue-2214.rs b/src/test/run-pass/issue-2214.rs index d63e01ec39607..8e4309e08e49c 100644 --- a/src/test/run-pass/issue-2214.rs +++ b/src/test/run-pass/issue-2214.rs @@ -44,5 +44,5 @@ mod m { pub fn main() { let mut y: int = 5; let x: &mut int = &mut y; - assert!((lgamma(1.0 as c_double, x) == 0.0 as c_double)); + assert_eq!(lgamma(1.0 as c_double, x), 0.0 as c_double); } diff --git a/src/test/run-pass/issue-2216.rs b/src/test/run-pass/issue-2216.rs index c3a2a4c0b7e24..0914c81c3ff17 100644 --- a/src/test/run-pass/issue-2216.rs +++ b/src/test/run-pass/issue-2216.rs @@ -28,5 +28,5 @@ pub fn main() { } error!("%?", x); - assert!((x == 42)); + assert_eq!(x, 42); } diff --git a/src/test/run-pass/issue-2428.rs b/src/test/run-pass/issue-2428.rs index 29fa357ba1a28..548f068979665 100644 --- a/src/test/run-pass/issue-2428.rs +++ b/src/test/run-pass/issue-2428.rs @@ -16,5 +16,5 @@ pub fn main() { Bar = quux } - assert!((Bar as int == quux)); + assert_eq!(Bar as int, quux); } diff --git a/src/test/run-pass/issue-2718.rs b/src/test/run-pass/issue-2718.rs index e46d2a923a8c5..55be1056ecaea 100644 --- a/src/test/run-pass/issue-2718.rs +++ b/src/test/run-pass/issue-2718.rs @@ -111,7 +111,7 @@ pub mod pipes { return Some(payload.unwrap()) } terminated => { - assert!(old_state == terminated); + assert_eq!(old_state, terminated); return None; } } diff --git a/src/test/run-pass/issue-2748-b.rs b/src/test/run-pass/issue-2748-b.rs index b9efb441ae78d..3ca8d49eb864d 100644 --- a/src/test/run-pass/issue-2748-b.rs +++ b/src/test/run-pass/issue-2748-b.rs @@ -14,6 +14,6 @@ pub fn main() { let x = &[1,2,3]; let y = x; let z = thing(x); - assert!((z[2] == x[2])); - assert!((z[1] == y[1])); + assert_eq!(z[2], x[2]); + assert_eq!(z[1], y[1]); } diff --git a/src/test/run-pass/issue-2895.rs b/src/test/run-pass/issue-2895.rs index bd075555df193..780ea2dc2c940 100644 --- a/src/test/run-pass/issue-2895.rs +++ b/src/test/run-pass/issue-2895.rs @@ -22,13 +22,13 @@ impl Drop for Kitty { #[cfg(target_arch = "x86_64")] pub fn main() { - assert!((sys::size_of::() == 8 as uint)); - assert!((sys::size_of::() == 16 as uint)); + assert_eq!(sys::size_of::(), 8 as uint); + assert_eq!(sys::size_of::(), 16 as uint); } #[cfg(target_arch = "x86")] #[cfg(target_arch = "arm")] pub fn main() { - assert!((sys::size_of::() == 4 as uint)); - assert!((sys::size_of::() == 8 as uint)); + assert_eq!(sys::size_of::(), 4 as uint); + assert_eq!(sys::size_of::(), 8 as uint); } diff --git a/src/test/run-pass/issue-2936.rs b/src/test/run-pass/issue-2936.rs index b989be0c1826a..183eb6e079f05 100644 --- a/src/test/run-pass/issue-2936.rs +++ b/src/test/run-pass/issue-2936.rs @@ -34,5 +34,5 @@ fn cbar(x: int) -> cbar { pub fn main() { let x: int = foo::(cbar(5)); - assert!(x == 5); + assert_eq!(x, 5); } diff --git a/src/test/run-pass/issue-2989.rs b/src/test/run-pass/issue-2989.rs index fb5df6d50e01f..5aaa3e595e100 100644 --- a/src/test/run-pass/issue-2989.rs +++ b/src/test/run-pass/issue-2989.rs @@ -41,5 +41,5 @@ pub fn main() { io::println(fmt!("%u => %u vs %u", i, bools[i] as uint, bools2[i] as uint)); } - assert!(bools == bools2); + assert_eq!(bools, bools2); } diff --git a/src/test/run-pass/issue-3091.rs b/src/test/run-pass/issue-3091.rs index aa0625aa110d9..c4c2c2b7da878 100644 --- a/src/test/run-pass/issue-3091.rs +++ b/src/test/run-pass/issue-3091.rs @@ -11,5 +11,5 @@ pub fn main() { let x = 1; let y = 1; - assert!(&x == &y); + assert_eq!(&x, &y); } diff --git a/src/test/run-pass/issue-3211.rs b/src/test/run-pass/issue-3211.rs index 02e61fc7ce2ca..360df32591965 100644 --- a/src/test/run-pass/issue-3211.rs +++ b/src/test/run-pass/issue-3211.rs @@ -3,6 +3,6 @@ pub fn main() { for 4096.times { x += 1; } - assert!(x == 4096); + assert_eq!(x, 4096); io::println(fmt!("x = %u", x)); } diff --git a/src/test/run-pass/issue-3683.rs b/src/test/run-pass/issue-3683.rs index bdb191488b985..0072439935b2e 100644 --- a/src/test/run-pass/issue-3683.rs +++ b/src/test/run-pass/issue-3683.rs @@ -24,5 +24,5 @@ impl Foo for int { } pub fn main() { - assert!((3.b() == 5)); + assert_eq!(3.b(), 5); } diff --git a/src/test/run-pass/issue-3979-generics.rs b/src/test/run-pass/issue-3979-generics.rs index 57962911538de..b91ec5711cf21 100644 --- a/src/test/run-pass/issue-3979-generics.rs +++ b/src/test/run-pass/issue-3979-generics.rs @@ -37,5 +37,5 @@ impl Movable for Point; pub fn main() { let p = Point{ x: 1, y: 2}; p.translate(3); - assert!(p.X() == 4); + assert_eq!(p.X(), 4); } diff --git a/src/test/run-pass/issue-3979-xcrate.rs b/src/test/run-pass/issue-3979-xcrate.rs index 5ecf80f481227..4bde414c4acf9 100644 --- a/src/test/run-pass/issue-3979-xcrate.rs +++ b/src/test/run-pass/issue-3979-xcrate.rs @@ -29,5 +29,5 @@ impl Movable for Point; pub fn main() { let mut p = Point{ x: 1, y: 2}; p.translate(3); - assert!(p.X() == 4); + assert_eq!(p.X(), 4); } diff --git a/src/test/run-pass/issue-3979.rs b/src/test/run-pass/issue-3979.rs index 2303c52be58b0..beffea1dbf36c 100644 --- a/src/test/run-pass/issue-3979.rs +++ b/src/test/run-pass/issue-3979.rs @@ -40,5 +40,5 @@ impl Movable for Point; pub fn main() { let mut p = Point{ x: 1, y: 2}; p.translate(3); - assert!(p.X() == 4); + assert_eq!(p.X(), 4); } diff --git a/src/test/run-pass/issue-4241.rs b/src/test/run-pass/issue-4241.rs index e5905e7a5be21..5503441771c45 100644 --- a/src/test/run-pass/issue-4241.rs +++ b/src/test/run-pass/issue-4241.rs @@ -28,13 +28,13 @@ priv fn parse_data(len: uint, io: @io::Reader) -> Result { let res = if (len > 0) { let bytes = io.read_bytes(len as uint); - assert!(bytes.len() == len); + assert_eq!(bytes.len(), len); Data(bytes) } else { Data(~[]) }; - assert!(io.read_char() == '\r'); - assert!(io.read_char() == '\n'); + assert_eq!(io.read_char(), '\r'); + assert_eq!(io.read_char(), '\n'); return res; } diff --git a/src/test/run-pass/issue-4401.rs b/src/test/run-pass/issue-4401.rs index e509cb828f840..73faa9845e771 100644 --- a/src/test/run-pass/issue-4401.rs +++ b/src/test/run-pass/issue-4401.rs @@ -3,6 +3,6 @@ pub fn main() { for 999_999.times() { count += 1; } - assert!(count == 999_999); + assert_eq!(count, 999_999); io::println(fmt!("%u", count)); } diff --git a/src/test/run-pass/issue-4448.rs b/src/test/run-pass/issue-4448.rs index 68abeef15de5f..e1ec65bc10ff0 100644 --- a/src/test/run-pass/issue-4448.rs +++ b/src/test/run-pass/issue-4448.rs @@ -12,7 +12,7 @@ pub fn main() { let (port, chan) = comm::stream::<&'static str>(); do task::spawn { - assert!(port.recv() == "hello, world"); + assert_eq!(port.recv(), "hello, world"); } chan.send("hello, world"); diff --git a/src/test/run-pass/issue-979.rs b/src/test/run-pass/issue-979.rs index 70d7df3f787e7..20bb8ea965ba1 100644 --- a/src/test/run-pass/issue-979.rs +++ b/src/test/run-pass/issue-979.rs @@ -33,5 +33,5 @@ pub fn main() { let p = Some(r(b)); } - assert!(*b == 1); + assert_eq!(*b, 1); } diff --git a/src/test/run-pass/issue2378c.rs b/src/test/run-pass/issue2378c.rs index 98e60c56476d8..ade192618dcf6 100644 --- a/src/test/run-pass/issue2378c.rs +++ b/src/test/run-pass/issue2378c.rs @@ -20,5 +20,5 @@ use issue2378b::{two_maybes}; pub fn main() { let x = two_maybes{a: just(3), b: just(5)}; - assert!(x[0u] == (3, 5)); + assert_eq!(x[0u], (3, 5)); } diff --git a/src/test/run-pass/istr.rs b/src/test/run-pass/istr.rs index 2f641993467c7..a82b263944982 100644 --- a/src/test/run-pass/istr.rs +++ b/src/test/run-pass/istr.rs @@ -12,7 +12,7 @@ fn test_stack_assign() { let s: ~str = ~"a"; debug!(s.clone()); let t: ~str = ~"a"; - assert!((s == t)); + assert!(s == t); let u: ~str = ~"b"; assert!((s != u)); } @@ -22,7 +22,7 @@ fn test_heap_lit() { ~"a big string"; } fn test_heap_assign() { let s: ~str = ~"a big ol' string"; let t: ~str = ~"a big ol' string"; - assert!((s == t)); + assert!(s == t); let u: ~str = ~"a bad ol' string"; assert!((s != u)); } @@ -30,34 +30,34 @@ fn test_heap_assign() { fn test_heap_log() { let s = ~"a big ol' string"; debug!(s); } fn test_stack_add() { - assert!((~"a" + ~"b" == ~"ab")); + assert_eq!(~"a" + ~"b", ~"ab"); let s: ~str = ~"a"; - assert!((s + s == ~"aa")); - assert!((~"" + ~"" == ~"")); + assert_eq!(s + s, ~"aa"); + assert_eq!(~"" + ~"", ~""); } fn test_stack_heap_add() { assert!((~"a" + ~"bracadabra" == ~"abracadabra")); } fn test_heap_add() { - assert!((~"this should" + ~" totally work" == ~"this should totally work")); + assert_eq!(~"this should" + ~" totally work", ~"this should totally work"); } fn test_append() { let mut s = ~""; s += ~"a"; - assert!((s == ~"a")); + assert_eq!(s, ~"a"); let mut s = ~"a"; s += ~"b"; debug!(s.clone()); - assert!((s == ~"ab")); + assert_eq!(s, ~"ab"); let mut s = ~"c"; s += ~"offee"; - assert!((s == ~"coffee")); + assert!(s == ~"coffee"); s += ~"&tea"; - assert!((s == ~"coffee&tea")); + assert!(s == ~"coffee&tea"); } pub fn main() { diff --git a/src/test/run-pass/iter-contains.rs b/src/test/run-pass/iter-contains.rs index fe10ecdcf95e4..5d5db170efe42 100644 --- a/src/test/run-pass/iter-contains.rs +++ b/src/test/run-pass/iter-contains.rs @@ -9,12 +9,12 @@ // except according to those terms. pub fn main() { - assert!([].contains(&22u) == false); - assert!([1u, 3u].contains(&22u) == false); - assert!([22u, 1u, 3u].contains(&22u) == true); - assert!([1u, 22u, 3u].contains(&22u) == true); - assert!([1u, 3u, 22u].contains(&22u) == true); - assert!(old_iter::contains(&None::, &22u) == false); - assert!(old_iter::contains(&Some(1u), &22u) == false); - assert!(old_iter::contains(&Some(22u), &22u) == true); + assert_eq!([].contains(&22u), false); + assert_eq!([1u, 3u].contains(&22u), false); + assert_eq!([22u, 1u, 3u].contains(&22u), true); + assert_eq!([1u, 22u, 3u].contains(&22u), true); + assert_eq!([1u, 3u, 22u].contains(&22u), true); + assert_eq!(old_iter::contains(&None::, &22u), false); + assert_eq!(old_iter::contains(&Some(1u), &22u), false); + assert_eq!(old_iter::contains(&Some(22u), &22u), true); } diff --git a/src/test/run-pass/iter-count.rs b/src/test/run-pass/iter-count.rs index 8e061775c2bfa..3f717195fbc4b 100644 --- a/src/test/run-pass/iter-count.rs +++ b/src/test/run-pass/iter-count.rs @@ -9,11 +9,11 @@ // except according to those terms. pub fn main() { - assert!([].count(&22u) == 0u); - assert!([1u, 3u].count(&22u) == 0u); - assert!([22u, 1u, 3u].count(&22u) == 1u); - assert!([22u, 1u, 22u].count(&22u) == 2u); - assert!(old_iter::count(&None::, &22u) == 0u); - assert!(old_iter::count(&Some(1u), &22u) == 0u); - assert!(old_iter::count(&Some(22u), &22u) == 1u); + assert_eq!([].count(&22u), 0u); + assert_eq!([1u, 3u].count(&22u), 0u); + assert_eq!([22u, 1u, 3u].count(&22u), 1u); + assert_eq!([22u, 1u, 22u].count(&22u), 2u); + assert_eq!(old_iter::count(&None::, &22u), 0u); + assert_eq!(old_iter::count(&Some(1u), &22u), 0u); + assert_eq!(old_iter::count(&Some(22u), &22u), 1u); } diff --git a/src/test/run-pass/iter-eachi.rs b/src/test/run-pass/iter-eachi.rs index 03130a6632c3c..781f02230c01b 100644 --- a/src/test/run-pass/iter-eachi.rs +++ b/src/test/run-pass/iter-eachi.rs @@ -11,17 +11,17 @@ pub fn main() { let mut c = 0u; for [1u, 2u, 3u, 4u, 5u].eachi |i, v| { - assert!((i + 1u) == *v); + assert_eq!((i + 1u), *v); c += 1u; } - assert!(c == 5u); + assert_eq!(c, 5u); for old_iter::eachi(&None::) |i, v| { fail!(); } let mut c = 0u; for old_iter::eachi(&Some(1u)) |i, v| { - assert!((i + 1u) == *v); + assert_eq!((i + 1u), *v); c += 1u; } - assert!(c == 1u); + assert_eq!(c, 1u); } diff --git a/src/test/run-pass/iter-filter-to-vec.rs b/src/test/run-pass/iter-filter-to-vec.rs index a9cdec9a0b7cc..0bb7cd1c4dd36 100644 --- a/src/test/run-pass/iter-filter-to-vec.rs +++ b/src/test/run-pass/iter-filter-to-vec.rs @@ -11,9 +11,9 @@ fn is_even(x: &uint) -> bool { (*x % 2) == 0 } pub fn main() { - assert!([1, 3].filter_to_vec(is_even) == ~[]); - assert!([1, 2, 3].filter_to_vec(is_even) == ~[2]); - assert!(old_iter::filter_to_vec(&None::, is_even) == ~[]); - assert!(old_iter::filter_to_vec(&Some(1u), is_even) == ~[]); - assert!(old_iter::filter_to_vec(&Some(2u), is_even) == ~[2]); + assert_eq!([1, 3].filter_to_vec(is_even), ~[]); + assert_eq!([1, 2, 3].filter_to_vec(is_even), ~[2]); + assert_eq!(old_iter::filter_to_vec(&None::, is_even), ~[]); + assert_eq!(old_iter::filter_to_vec(&Some(1u), is_even), ~[]); + assert_eq!(old_iter::filter_to_vec(&Some(2u), is_even), ~[2]); } diff --git a/src/test/run-pass/iter-flat-map-to-vec.rs b/src/test/run-pass/iter-flat-map-to-vec.rs index d9a7791527e44..af23905fe76ea 100644 --- a/src/test/run-pass/iter-flat-map-to-vec.rs +++ b/src/test/run-pass/iter-flat-map-to-vec.rs @@ -15,15 +15,15 @@ fn incd_if_even(x: &uint) -> Option { } pub fn main() { - assert!((~[1u, 3u]).flat_map_to_vec(repeat) == ~[1u, 1u, 3u, 3u]); - assert!((~[]).flat_map_to_vec(repeat) == ~[]); - assert!(old_iter::flat_map_to_vec(&None::, repeat) == ~[]); - assert!(old_iter::flat_map_to_vec(&Some(1u), repeat) == ~[1u, 1u]); - assert!(old_iter::flat_map_to_vec(&Some(2u), repeat) == ~[2u, 2u]); + assert_eq!((~[1u, 3u]).flat_map_to_vec(repeat), ~[1u, 1u, 3u, 3u]); + assert_eq!((~[]).flat_map_to_vec(repeat), ~[]); + assert_eq!(old_iter::flat_map_to_vec(&None::, repeat), ~[]); + assert_eq!(old_iter::flat_map_to_vec(&Some(1u), repeat), ~[1u, 1u]); + assert_eq!(old_iter::flat_map_to_vec(&Some(2u), repeat), ~[2u, 2u]); - assert!((~[1u, 2u, 5u]).flat_map_to_vec(incd_if_even) == ~[3u]); - assert!((~[]).flat_map_to_vec(incd_if_even) == ~[]); - assert!(old_iter::flat_map_to_vec(&None::, incd_if_even) == ~[]); - assert!(old_iter::flat_map_to_vec(&Some(1u), incd_if_even) == ~[]); - assert!(old_iter::flat_map_to_vec(&Some(2u), incd_if_even) == ~[3u]); + assert_eq!((~[1u, 2u, 5u]).flat_map_to_vec(incd_if_even), ~[3u]); + assert_eq!((~[]).flat_map_to_vec(incd_if_even), ~[]); + assert_eq!(old_iter::flat_map_to_vec(&None::, incd_if_even), ~[]); + assert_eq!(old_iter::flat_map_to_vec(&Some(1u), incd_if_even), ~[]); + assert_eq!(old_iter::flat_map_to_vec(&Some(2u), incd_if_even), ~[3u]); } diff --git a/src/test/run-pass/iter-foldl.rs b/src/test/run-pass/iter-foldl.rs index b299cf8322505..f40abe0c56c1b 100644 --- a/src/test/run-pass/iter-foldl.rs +++ b/src/test/run-pass/iter-foldl.rs @@ -11,9 +11,9 @@ fn add(x: &float, y: &uint) -> float { *x + ((*y) as float) } pub fn main() { - assert!([1u, 3u].foldl(20f, add) == 24f); - assert!([].foldl(20f, add) == 20f); - assert!(old_iter::foldl(&None::, 20f, add) == 20f); - assert!(old_iter::foldl(&Some(1u), 20f, add) == 21f); - assert!(old_iter::foldl(&Some(2u), 20f, add) == 22f); + assert_eq!([1u, 3u].foldl(20f, add), 24f); + assert_eq!([].foldl(20f, add), 20f); + assert_eq!(old_iter::foldl(&None::, 20f, add), 20f); + assert_eq!(old_iter::foldl(&Some(1u), 20f, add), 21f); + assert_eq!(old_iter::foldl(&Some(2u), 20f, add), 22f); } diff --git a/src/test/run-pass/iter-map-to-vec.rs b/src/test/run-pass/iter-map-to-vec.rs index 4e9976e4eb9d3..e9fd68d10f1b9 100644 --- a/src/test/run-pass/iter-map-to-vec.rs +++ b/src/test/run-pass/iter-map-to-vec.rs @@ -11,9 +11,9 @@ fn inc(x: &uint) -> uint { *x + 1 } pub fn main() { - assert!([1, 3].map_to_vec(inc) == ~[2, 4]); - assert!([1, 2, 3].map_to_vec(inc) == ~[2, 3, 4]); - assert!(old_iter::map_to_vec(&None::, inc) == ~[]); - assert!(old_iter::map_to_vec(&Some(1u), inc) == ~[2]); - assert!(old_iter::map_to_vec(&Some(2u), inc) == ~[3]); + assert_eq!([1, 3].map_to_vec(inc), ~[2, 4]); + assert_eq!([1, 2, 3].map_to_vec(inc), ~[2, 3, 4]); + assert_eq!(old_iter::map_to_vec(&None::, inc), ~[]); + assert_eq!(old_iter::map_to_vec(&Some(1u), inc), ~[2]); + assert_eq!(old_iter::map_to_vec(&Some(2u), inc), ~[3]); } diff --git a/src/test/run-pass/iter-min-max.rs b/src/test/run-pass/iter-min-max.rs index 5f427861e7917..6ce24aedf13e1 100644 --- a/src/test/run-pass/iter-min-max.rs +++ b/src/test/run-pass/iter-min-max.rs @@ -11,11 +11,11 @@ fn is_even(x: uint) -> bool { (x % 2u) == 0u } pub fn main() { - assert!([1u, 3u].min() == 1u); - assert!([3u, 1u].min() == 1u); - assert!(old_iter::min(&Some(1u)) == 1u); + assert_eq!([1u, 3u].min(), 1u); + assert_eq!([3u, 1u].min(), 1u); + assert_eq!(old_iter::min(&Some(1u)), 1u); - assert!([1u, 3u].max() == 3u); - assert!([3u, 1u].max() == 3u); - assert!(old_iter::max(&Some(3u)) == 3u); + assert_eq!([1u, 3u].max(), 3u); + assert_eq!([3u, 1u].max(), 3u); + assert_eq!(old_iter::max(&Some(3u)), 3u); } diff --git a/src/test/run-pass/iter-to-vec.rs b/src/test/run-pass/iter-to-vec.rs index d7fdcdbe4e0a0..b7f2ac77074a2 100644 --- a/src/test/run-pass/iter-to-vec.rs +++ b/src/test/run-pass/iter-to-vec.rs @@ -9,10 +9,10 @@ // except according to those terms. pub fn main() { - assert!([1u, 3u].to_vec() == ~[1u, 3u]); + assert_eq!([1u, 3u].to_vec(), ~[1u, 3u]); let e: ~[uint] = ~[]; - assert!(e.to_vec() == ~[]); - assert!(old_iter::to_vec(&None::) == ~[]); - assert!(old_iter::to_vec(&Some(1u)) == ~[1u]); - assert!(old_iter::to_vec(&Some(2u)) == ~[2u]); + assert_eq!(e.to_vec(), ~[]); + assert_eq!(old_iter::to_vec(&None::), ~[]); + assert_eq!(old_iter::to_vec(&Some(1u)), ~[1u]); + assert_eq!(old_iter::to_vec(&Some(2u)), ~[2u]); } diff --git a/src/test/run-pass/ivec-add.rs b/src/test/run-pass/ivec-add.rs index bd58ae6565143..80168daf62d08 100644 --- a/src/test/run-pass/ivec-add.rs +++ b/src/test/run-pass/ivec-add.rs @@ -14,10 +14,10 @@ fn double_int(a: int) -> ~[int] { return ~[a] + ~[a]; } pub fn main() { let mut d = double(1); - assert!((d[0] == 1)); - assert!((d[1] == 1)); + assert_eq!(d[0], 1); + assert_eq!(d[1], 1); d = double_int(1); - assert!((d[0] == 1)); - assert!((d[1] == 1)); + assert_eq!(d[0], 1); + assert_eq!(d[1], 1); } diff --git a/src/test/run-pass/kindck-owned-trait-contains-1.rs b/src/test/run-pass/kindck-owned-trait-contains-1.rs index 3fb554dc4509a..35b5e077e7af7 100644 --- a/src/test/run-pass/kindck-owned-trait-contains-1.rs +++ b/src/test/run-pass/kindck-owned-trait-contains-1.rs @@ -22,5 +22,5 @@ fn repeater(v: @A) -> @repeat { pub fn main() { let x = &3; let y = repeater(@x); - assert!(*x == *(y.get())); + assert_eq!(*x, *(y.get())); } diff --git a/src/test/run-pass/last-use-in-cap-clause.rs b/src/test/run-pass/last-use-in-cap-clause.rs index 442e79bde77ce..75c3008af8eb3 100644 --- a/src/test/run-pass/last-use-in-cap-clause.rs +++ b/src/test/run-pass/last-use-in-cap-clause.rs @@ -20,5 +20,5 @@ fn foo() -> @fn() -> int { } pub fn main() { - assert!(foo()() == 22); + assert_eq!(foo()(), 22); } diff --git a/src/test/run-pass/lazy-and-or.rs b/src/test/run-pass/lazy-and-or.rs index 1a1e4816a361a..74febe6ff7dcd 100644 --- a/src/test/run-pass/lazy-and-or.rs +++ b/src/test/run-pass/lazy-and-or.rs @@ -17,6 +17,6 @@ pub fn main() { assert!((x)); let mut y: int = 10; debug!(x || incr(&mut y)); - assert!((y == 10)); + assert_eq!(y, 10); if true && x { assert!((true)); } else { assert!((false)); } } diff --git a/src/test/run-pass/let-destruct-fresh-mem.rs b/src/test/run-pass/let-destruct-fresh-mem.rs index ae6118d063e9e..500502320df0f 100644 --- a/src/test/run-pass/let-destruct-fresh-mem.rs +++ b/src/test/run-pass/let-destruct-fresh-mem.rs @@ -16,8 +16,8 @@ pub fn main() { let mut X {x: x, y: @A {a: a}} = u; x = 100; a = 100; - assert!((x == 100)); - assert!((a == 100)); - assert!((u.x == 10)); - assert!((u.y.a == 20)); + assert_eq!(x, 100); + assert_eq!(a, 100); + assert_eq!(u.x, 10); + assert_eq!(u.y.a, 20); } diff --git a/src/test/run-pass/let-destruct.rs b/src/test/run-pass/let-destruct.rs index 6e2ce508928a7..aab19b31397b6 100644 --- a/src/test/run-pass/let-destruct.rs +++ b/src/test/run-pass/let-destruct.rs @@ -14,5 +14,5 @@ struct X { x: xx, y: int } pub fn main() { let @X {x: xx(x), y: y} = @X{x: xx(10), y: 20}; - assert!((x + y == 30)); + assert_eq!(x + y, 30); } diff --git a/src/test/run-pass/linear-for-loop.rs b/src/test/run-pass/linear-for-loop.rs index f2fb63cfc9e79..c9f768d7606ee 100644 --- a/src/test/run-pass/linear-for-loop.rs +++ b/src/test/run-pass/linear-for-loop.rs @@ -15,7 +15,7 @@ pub fn main() { let mut y = 0; for x.each |i| { debug!(*i); y += *i; } debug!(y); - assert!((y == 6)); + assert_eq!(y, 6); let s = ~"hello there"; let mut i: int = 0; for str::each(s) |c| { @@ -30,5 +30,5 @@ pub fn main() { debug!(i); debug!(c); } - assert!((i == 11)); + assert_eq!(i, 11); } 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 44e1292d9b1c1..2cddc51042277 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 @@ -19,7 +19,7 @@ enum foo { } fn check_log(exp: ~str, v: T) { - assert!(exp == fmt!("%?", v)); + assert_eq!(exp, fmt!("%?", v)); } pub fn main() { 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 641d6155e23a9..7a0d763f7e0f4 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 @@ -19,8 +19,8 @@ enum bar { } pub fn main() { - assert!(~"a(22)" == fmt!("%?", a(22u))); - assert!(~"b(~\"hi\")" == fmt!("%?", b(~"hi"))); - assert!(~"c" == fmt!("%?", c)); - assert!(~"d" == fmt!("%?", d)); + assert_eq!(~"a(22)", fmt!("%?", a(22u))); + assert_eq!(~"b(~\"hi\")", fmt!("%?", b(~"hi"))); + assert_eq!(~"c", fmt!("%?", c)); + assert_eq!(~"d", fmt!("%?", d)); } diff --git a/src/test/run-pass/log-str.rs b/src/test/run-pass/log-str.rs index e321789a2b1a1..d45602d9ed1ff 100644 --- a/src/test/run-pass/log-str.rs +++ b/src/test/run-pass/log-str.rs @@ -10,8 +10,8 @@ pub fn main() { let act = sys::log_str(&~[1, 2, 3]); - assert!(~"~[1, 2, 3]" == act); + assert_eq!(~"~[1, 2, 3]", act); let act = fmt!("%?/%6?", ~[1, 2, 3], ~"hi"); - assert!(act == ~"~[1, 2, 3]/ ~\"hi\""); + assert_eq!(act, ~"~[1, 2, 3]/ ~\"hi\""); } diff --git a/src/test/run-pass/loop-break-cont.rs b/src/test/run-pass/loop-break-cont.rs index 4a4da79367fb4..64d2b3d0b215b 100644 --- a/src/test/run-pass/loop-break-cont.rs +++ b/src/test/run-pass/loop-break-cont.rs @@ -17,7 +17,7 @@ pub fn main() { break; } } - assert!((i == 10u)); + assert_eq!(i, 10u); let mut is_even = false; loop { if i == 21u { diff --git a/src/test/run-pass/loop-scope.rs b/src/test/run-pass/loop-scope.rs index a3caf1e4800d2..07be3bd6c81f5 100644 --- a/src/test/run-pass/loop-scope.rs +++ b/src/test/run-pass/loop-scope.rs @@ -12,5 +12,5 @@ pub fn main() { let x = ~[10, 20, 30]; let mut sum = 0; for x.each |x| { sum += *x; } - assert!((sum == 60)); + assert_eq!(sum, 60); } diff --git a/src/test/run-pass/macro-path.rs b/src/test/run-pass/macro-path.rs index a3bd03c80bc46..4aa1587943413 100644 --- a/src/test/run-pass/macro-path.rs +++ b/src/test/run-pass/macro-path.rs @@ -20,5 +20,5 @@ macro_rules! foo { } pub fn main() { - assert!(foo!(m::t) == 10); + assert_eq!(foo!(m::t), 10); } diff --git a/src/test/run-pass/macro-stmt.rs b/src/test/run-pass/macro-stmt.rs index d9417ee0a1953..66f16bc9f2e03 100644 --- a/src/test/run-pass/macro-stmt.rs +++ b/src/test/run-pass/macro-stmt.rs @@ -27,16 +27,16 @@ pub fn main() { ); mylet!(y, 8*2); - assert!((y == 16)); + assert_eq!(y, 16); myfn!(mult, (a,b), { a*b } ); - assert!((mult(2, add(4,4)) == 16)); + assert_eq!(mult(2, add(4,4)), 16); macro_rules! actually_an_expr_macro ( () => ( 16 ) ) - assert!({ actually_an_expr_macro!() } == 16); + assert_eq!({ actually_an_expr_macro!() }, 16); } diff --git a/src/test/run-pass/mod-inside-fn.rs b/src/test/run-pass/mod-inside-fn.rs index e4bc850644e4b..388d2e4905fab 100644 --- a/src/test/run-pass/mod-inside-fn.rs +++ b/src/test/run-pass/mod-inside-fn.rs @@ -17,5 +17,5 @@ fn f() -> int { } pub fn main() { - assert!(f() == 720); + assert_eq!(f(), 720); } diff --git a/src/test/run-pass/mod-merge-hack.rs b/src/test/run-pass/mod-merge-hack.rs index 10f661b4f8d58..fdef8c5b54102 100644 --- a/src/test/run-pass/mod-merge-hack.rs +++ b/src/test/run-pass/mod-merge-hack.rs @@ -14,6 +14,6 @@ mod myint32; pub fn main() { - assert!(myint32::bits == 32); - assert!(myint32::min(10, 20) == 10); + assert_eq!(myint32::bits, 32); + assert_eq!(myint32::min(10, 20), 10); } diff --git a/src/test/run-pass/mod_dir_path.rs b/src/test/run-pass/mod_dir_path.rs index f0cc4aa52d665..a356a0ab07e91 100644 --- a/src/test/run-pass/mod_dir_path.rs +++ b/src/test/run-pass/mod_dir_path.rs @@ -17,5 +17,5 @@ mod mod_dir_simple { } pub fn main() { - assert!(mod_dir_simple::syrup::foo() == 10); + assert_eq!(mod_dir_simple::syrup::foo(), 10); } diff --git a/src/test/run-pass/mod_dir_path2.rs b/src/test/run-pass/mod_dir_path2.rs index 2635084a07273..6119e9631e8d2 100644 --- a/src/test/run-pass/mod_dir_path2.rs +++ b/src/test/run-pass/mod_dir_path2.rs @@ -18,5 +18,5 @@ mod pancakes { } pub fn main() { - assert!(pancakes::syrup::foo() == 10); + assert_eq!(pancakes::syrup::foo(), 10); } diff --git a/src/test/run-pass/mod_dir_path3.rs b/src/test/run-pass/mod_dir_path3.rs index 0971120eb6f7d..00282658508b8 100644 --- a/src/test/run-pass/mod_dir_path3.rs +++ b/src/test/run-pass/mod_dir_path3.rs @@ -17,5 +17,5 @@ mod pancakes { } pub fn main() { - assert!(pancakes::test::foo() == 10); + assert_eq!(pancakes::test::foo(), 10); } diff --git a/src/test/run-pass/mod_dir_path_multi.rs b/src/test/run-pass/mod_dir_path_multi.rs index c6ab45d1b3a4d..4766d330a4e43 100644 --- a/src/test/run-pass/mod_dir_path_multi.rs +++ b/src/test/run-pass/mod_dir_path_multi.rs @@ -22,6 +22,6 @@ mod gravy { } pub fn main() { - assert!(biscuits::test::foo() == 10); - assert!(gravy::test::foo() == 10); + assert_eq!(biscuits::test::foo(), 10); + assert_eq!(gravy::test::foo(), 10); } diff --git a/src/test/run-pass/mod_dir_recursive.rs b/src/test/run-pass/mod_dir_recursive.rs index 5392671651d1a..a39d41414ff9c 100644 --- a/src/test/run-pass/mod_dir_recursive.rs +++ b/src/test/run-pass/mod_dir_recursive.rs @@ -20,5 +20,5 @@ mod mod_dir_simple { } pub fn main() { - assert!(mod_dir_simple::load_another_mod::test::foo() == 10); + assert_eq!(mod_dir_simple::load_another_mod::test::foo(), 10); } diff --git a/src/test/run-pass/mod_dir_simple.rs b/src/test/run-pass/mod_dir_simple.rs index 382911d49793f..fbc522f07b283 100644 --- a/src/test/run-pass/mod_dir_simple.rs +++ b/src/test/run-pass/mod_dir_simple.rs @@ -16,5 +16,5 @@ mod mod_dir_simple { } pub fn main() { - assert!(mod_dir_simple::test::foo() == 10); + assert_eq!(mod_dir_simple::test::foo(), 10); } diff --git a/src/test/run-pass/mod_file.rs b/src/test/run-pass/mod_file.rs index a03dc04401141..b2dd931161572 100644 --- a/src/test/run-pass/mod_file.rs +++ b/src/test/run-pass/mod_file.rs @@ -15,5 +15,5 @@ mod mod_file_aux; pub fn main() { - assert!(mod_file_aux::foo() == 10); + assert_eq!(mod_file_aux::foo(), 10); } diff --git a/src/test/run-pass/mod_file_with_path_attr.rs b/src/test/run-pass/mod_file_with_path_attr.rs index ecd4fd73a062f..8455b662efaa1 100644 --- a/src/test/run-pass/mod_file_with_path_attr.rs +++ b/src/test/run-pass/mod_file_with_path_attr.rs @@ -16,5 +16,5 @@ mod m; pub fn main() { - assert!(m::foo() == 10); + assert_eq!(m::foo(), 10); } diff --git a/src/test/run-pass/monad.rs b/src/test/run-pass/monad.rs index 303d5bc1b4170..6803eb1c6d78a 100644 --- a/src/test/run-pass/monad.rs +++ b/src/test/run-pass/monad.rs @@ -40,8 +40,8 @@ fn transform(x: Option) -> Option<~str> { } pub fn main() { - assert!(transform(Some(10)) == Some(~"11")); - assert!(transform(None) == None); + assert_eq!(transform(Some(10)), Some(~"11")); + assert_eq!(transform(None), None); assert!((~[~"hi"]) .bind(|x| ~[x.clone(), *x + ~"!"] ) .bind(|x| ~[x.clone(), *x + ~"?"] ) == diff --git a/src/test/run-pass/monomorphize-trait-in-fn-at.rs b/src/test/run-pass/monomorphize-trait-in-fn-at.rs index 61d9456296e96..8e36b1138bd43 100644 --- a/src/test/run-pass/monomorphize-trait-in-fn-at.rs +++ b/src/test/run-pass/monomorphize-trait-in-fn-at.rs @@ -26,5 +26,5 @@ impl ty_ops for () { pub fn main() { let fn_env: @fn() -> uint = || mk_nil(()); - assert!(fn_env() == 22u); + assert_eq!(fn_env(), 22u); } diff --git a/src/test/run-pass/morestack3.rs b/src/test/run-pass/morestack3.rs index 07edf0d2e1cf4..a21b13743fe9d 100644 --- a/src/test/run-pass/morestack3.rs +++ b/src/test/run-pass/morestack3.rs @@ -21,15 +21,15 @@ fn getbig(a0: int, a8: int, a9: int) -> int { - assert!(a0 + 1 == a1); - assert!(a1 + 1 == a2); - assert!(a2 + 1 == a3); - assert!(a3 + 1 == a4); - assert!(a4 + 1 == a5); - assert!(a5 + 1 == a6); - assert!(a6 + 1 == a7); - assert!(a7 + 1 == a8); - assert!(a8 + 1 == a9); + assert_eq!(a0 + 1, a1); + assert_eq!(a1 + 1, a2); + assert_eq!(a2 + 1, a3); + assert_eq!(a3 + 1, a4); + assert_eq!(a4 + 1, a5); + assert_eq!(a5 + 1, a6); + assert_eq!(a6 + 1, a7); + assert_eq!(a7 + 1, a8); + assert_eq!(a8 + 1, a9); if a0 != 0 { let j = getbig(a0 - 1, a1 - 1, @@ -41,7 +41,7 @@ fn getbig(a0: int, a7 - 1, a8 - 1, a9 - 1); - assert!(j == a0 - 1); + assert_eq!(j, a0 - 1); } return a0; } diff --git a/src/test/run-pass/move-1-unique.rs b/src/test/run-pass/move-1-unique.rs index 47902363db7bc..9194fc830e069 100644 --- a/src/test/run-pass/move-1-unique.rs +++ b/src/test/run-pass/move-1-unique.rs @@ -19,8 +19,8 @@ fn test(x: bool, foo: ~Triple) -> int { pub fn main() { let x = ~Triple{x: 1, y: 2, z: 3}; - assert!((test(true, copy x) == 2)); - assert!((test(true, copy x) == 2)); - assert!((test(true, copy x) == 2)); - assert!((test(false, x) == 5)); + assert_eq!(test(true, copy x), 2); + assert_eq!(test(true, copy x), 2); + assert_eq!(test(true, copy x), 2); + assert_eq!(test(false, x), 5); } diff --git a/src/test/run-pass/move-1.rs b/src/test/run-pass/move-1.rs index 04354d74159a4..5d3b25ebd7ef0 100644 --- a/src/test/run-pass/move-1.rs +++ b/src/test/run-pass/move-1.rs @@ -19,8 +19,8 @@ fn test(x: bool, foo: @Triple) -> int { pub fn main() { let x = @Triple {x: 1, y: 2, z: 3}; - assert!((test(true, x) == 2)); - assert!((test(true, x) == 2)); - assert!((test(true, x) == 2)); - assert!((test(false, x) == 5)); + assert_eq!(test(true, x), 2); + assert_eq!(test(true, x), 2); + assert_eq!(test(true, x), 2); + assert_eq!(test(false, x), 5); } diff --git a/src/test/run-pass/move-3-unique.rs b/src/test/run-pass/move-3-unique.rs index 36c9c787b754d..dcd4cc9a7ea06 100644 --- a/src/test/run-pass/move-3-unique.rs +++ b/src/test/run-pass/move-3-unique.rs @@ -22,7 +22,7 @@ fn test(x: bool, foo: ~Triple) -> int { pub fn main() { let x = ~Triple{x: 1, y: 2, z: 3}; for uint::range(0u, 10000u) |_i| { - assert!((test(true, copy x) == 2)); + assert_eq!(test(true, copy x), 2); } - assert!((test(false, x) == 5)); + assert_eq!(test(false, x), 5); } diff --git a/src/test/run-pass/move-3.rs b/src/test/run-pass/move-3.rs index f2b6b2f998080..42955b9472127 100644 --- a/src/test/run-pass/move-3.rs +++ b/src/test/run-pass/move-3.rs @@ -22,7 +22,7 @@ fn test(x: bool, foo: @Triple) -> int { pub fn main() { let x = @Triple{x: 1, y: 2, z: 3}; for uint::range(0u, 10000u) |i| { - assert!((test(true, x) == 2)); + assert_eq!(test(true, x), 2); } - assert!((test(false, x) == 5)); + assert_eq!(test(false, x), 5); } diff --git a/src/test/run-pass/move-4.rs b/src/test/run-pass/move-4.rs index fe544e54742bd..cd88b67936155 100644 --- a/src/test/run-pass/move-4.rs +++ b/src/test/run-pass/move-4.rs @@ -24,5 +24,5 @@ fn test(foo: @Triple) -> @Triple { pub fn main() { let x = @Triple{a: 1, b: 2, c: 3}; let y = test(x); - assert!((y.c == 3)); + assert_eq!(y.c, 3); } diff --git a/src/test/run-pass/move-scalar.rs b/src/test/run-pass/move-scalar.rs index 6a8091d7b770f..845cb8ab6011e 100644 --- a/src/test/run-pass/move-scalar.rs +++ b/src/test/run-pass/move-scalar.rs @@ -13,5 +13,5 @@ pub fn main() { let y: int = 42; let mut x: int; x = y; - assert!((x == 42)); + assert_eq!(x, 42); } diff --git a/src/test/run-pass/mut-function-arguments.rs b/src/test/run-pass/mut-function-arguments.rs index 20813bb4a0335..0fa89ba0f049d 100644 --- a/src/test/run-pass/mut-function-arguments.rs +++ b/src/test/run-pass/mut-function-arguments.rs @@ -10,7 +10,7 @@ fn f(mut y: ~int) { *y = 5; - assert!(*y == 5); + assert_eq!(*y, 5); } fn g() { diff --git a/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs b/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs index c4caf716df239..aef857f36ee06 100644 --- a/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs +++ b/src/test/run-pass/mutability-inherits-through-fixed-length-vec.rs @@ -11,7 +11,7 @@ fn test1() { let mut ints = [0, ..32]; ints[0] += 1; - assert!(ints[0] == 1); + assert_eq!(ints[0], 1); } fn test2() { diff --git a/src/test/run-pass/mutable-alias-vec.rs b/src/test/run-pass/mutable-alias-vec.rs index c6bf07536b1a9..42c623ec41c58 100644 --- a/src/test/run-pass/mutable-alias-vec.rs +++ b/src/test/run-pass/mutable-alias-vec.rs @@ -22,5 +22,5 @@ pub fn main() { grow(&mut v); let len = vec::len::(v); debug!(len); - assert!((len == 3 as uint)); + assert_eq!(len, 3 as uint); } diff --git a/src/test/run-pass/nested-class.rs b/src/test/run-pass/nested-class.rs index 83820f87d5030..3bf4b53c18407 100644 --- a/src/test/run-pass/nested-class.rs +++ b/src/test/run-pass/nested-class.rs @@ -26,6 +26,6 @@ pub fn main() { // fn b(x:int) -> int { fail!(); } let z = b(42); - assert!((z.i == 42)); - assert!((z.do_stuff() == 37)); + assert_eq!(z.i, 42); + assert_eq!(z.do_stuff(), 37); } diff --git a/src/test/run-pass/nested-patterns.rs b/src/test/run-pass/nested-patterns.rs index 6c56e39d2d308..bd9e4bdfd8724 100644 --- a/src/test/run-pass/nested-patterns.rs +++ b/src/test/run-pass/nested-patterns.rs @@ -20,8 +20,8 @@ pub fn main() { } let mut x@B {b, _} = B {a: 10, b: C {c: 20}}; x.b.c = 30; - assert!(b.c == 20); + assert_eq!(b.c, 20); let mut y@D {d, _} = D {a: 10, d: C {c: 20}}; y.d.c = 30; - assert!(d.c == 20); + assert_eq!(d.c, 20); } diff --git a/src/test/run-pass/newlambdas.rs b/src/test/run-pass/newlambdas.rs index 1fb98d54adc7a..c6536c68a8336 100644 --- a/src/test/run-pass/newlambdas.rs +++ b/src/test/run-pass/newlambdas.rs @@ -19,11 +19,11 @@ fn ff() -> @fn(int) -> int { } pub fn main() { - assert!(f(10, |a| a) == 10); + assert_eq!(f(10, |a| a), 10); g(||()); - assert!(do f(10) |a| { a } == 10); + assert_eq!(do f(10) |a| { a }, 10); do g() { } let _x: @fn() -> int = || 10; let _y: @fn(int) -> int = |a| a; - assert!(ff()(10) == 11); + assert_eq!(ff()(10), 11); } diff --git a/src/test/run-pass/newtype-polymorphic.rs b/src/test/run-pass/newtype-polymorphic.rs index 6b1b97cfd5f82..f88c71bdf39fc 100644 --- a/src/test/run-pass/newtype-polymorphic.rs +++ b/src/test/run-pass/newtype-polymorphic.rs @@ -16,7 +16,7 @@ fn myvec_elt(mv: myvec) -> X { return mv[0]; } pub fn main() { let mv = myvec(~[1, 2, 3]); - assert!((myvec_deref(copy mv)[1] == 2)); - assert!((myvec_elt(copy mv) == 1)); - assert!((mv[2] == 3)); + assert_eq!(myvec_deref(copy mv)[1], 2); + assert_eq!(myvec_elt(copy mv), 1); + assert_eq!(mv[2], 3); } diff --git a/src/test/run-pass/newtype.rs b/src/test/run-pass/newtype.rs index ad2c502f20e93..6d36357ccfa13 100644 --- a/src/test/run-pass/newtype.rs +++ b/src/test/run-pass/newtype.rs @@ -17,5 +17,5 @@ fn compute(i: mytype) -> int { return i.val + 20; } pub fn main() { let myval = mytype(Mytype{compute: compute, val: 30}); io::println(fmt!("%d", compute(myval))); - assert!(((myval.compute)(myval) == 50)); + assert_eq!((myval.compute)(myval), 50); } diff --git a/src/test/run-pass/non-boolean-pure-fns.rs b/src/test/run-pass/non-boolean-pure-fns.rs index 6a76f9d1646d4..58ac4fc576d9b 100644 --- a/src/test/run-pass/non-boolean-pure-fns.rs +++ b/src/test/run-pass/non-boolean-pure-fns.rs @@ -30,5 +30,5 @@ fn safe_head(ls: @List) -> T { pub fn main() { let mylist = @Cons(@1u, @Nil); assert!((nonempty_list(mylist))); - assert!((*safe_head(mylist) == 1u)); + assert_eq!(*safe_head(mylist), 1u); } diff --git a/src/test/run-pass/non-legacy-modes.rs b/src/test/run-pass/non-legacy-modes.rs index 69feae49157cb..642686e06e5dd 100644 --- a/src/test/run-pass/non-legacy-modes.rs +++ b/src/test/run-pass/non-legacy-modes.rs @@ -17,7 +17,7 @@ fn apply(x: T, f: &fn(T)) { } fn check_int(x: int) { - assert!(x == 22); + assert_eq!(x, 22); } fn check_struct(x: X) { diff --git a/src/test/run-pass/nullable-pointer-size.rs b/src/test/run-pass/nullable-pointer-size.rs index 246fc4e304df3..1e8ddc2905e54 100644 --- a/src/test/run-pass/nullable-pointer-size.rs +++ b/src/test/run-pass/nullable-pointer-size.rs @@ -15,13 +15,13 @@ struct S(int, T); macro_rules! check_option { ($T:ty) => { - assert!(sys::size_of::>() == sys::size_of::<$T>()); + assert_eq!(sys::size_of::>(), sys::size_of::<$T>()); } } macro_rules! check_fancy { ($T:ty) => { - assert!(sys::size_of::>() == sys::size_of::>()); + assert_eq!(sys::size_of::>(), sys::size_of::>()); } } diff --git a/src/test/run-pass/nullary-or-pattern.rs b/src/test/run-pass/nullary-or-pattern.rs index 6a92c1c993c23..8e932c4b14b80 100644 --- a/src/test/run-pass/nullary-or-pattern.rs +++ b/src/test/run-pass/nullary-or-pattern.rs @@ -15,6 +15,6 @@ fn or_alt(q: blah) -> int { } pub fn main() { - assert!((or_alt(a) == 42)); - assert!((or_alt(b) == 42)); + assert_eq!(or_alt(a), 42); + assert_eq!(or_alt(b), 42); } diff --git a/src/test/run-pass/numeric-method-autoexport.rs b/src/test/run-pass/numeric-method-autoexport.rs index 719f1015684a1..7092f8190154a 100644 --- a/src/test/run-pass/numeric-method-autoexport.rs +++ b/src/test/run-pass/numeric-method-autoexport.rs @@ -17,26 +17,26 @@ pub fn main() { // ints // num - assert!(15i.add(&6) == 21); - assert!(15i8.add(&6i8) == 21i8); - assert!(15i16.add(&6i16) == 21i16); - assert!(15i32.add(&6i32) == 21i32); - assert!(15i64.add(&6i64) == 21i64); + assert_eq!(15i.add(&6), 21); + assert_eq!(15i8.add(&6i8), 21i8); + assert_eq!(15i16.add(&6i16), 21i16); + assert_eq!(15i32.add(&6i32), 21i32); + assert_eq!(15i64.add(&6i64), 21i64); // uints // num - assert!(15u.add(&6u) == 21u); - assert!(15u8.add(&6u8) == 21u8); - assert!(15u16.add(&6u16) == 21u16); - assert!(15u32.add(&6u32) == 21u32); - assert!(15u64.add(&6u64) == 21u64); + assert_eq!(15u.add(&6u), 21u); + assert_eq!(15u8.add(&6u8), 21u8); + assert_eq!(15u16.add(&6u16), 21u16); + assert_eq!(15u32.add(&6u32), 21u32); + assert_eq!(15u64.add(&6u64), 21u64); // times 15u.times(|| false); // floats // num - assert!(10f.to_int() == 10); - assert!(10f32.to_int() == 10); - assert!(10f64.to_int() == 10); + assert_eq!(10f.to_int(), 10); + assert_eq!(10f32.to_int(), 10); + assert_eq!(10f64.to_int(), 10); } diff --git a/src/test/run-pass/one-tuple.rs b/src/test/run-pass/one-tuple.rs index eb32e7cda1ad8..8377a45a1d8a0 100644 --- a/src/test/run-pass/one-tuple.rs +++ b/src/test/run-pass/one-tuple.rs @@ -13,11 +13,11 @@ pub fn main() { match ('c',) { (x,) => { - assert!(x == 'c'); + assert_eq!(x, 'c'); } } // test the 1-tuple type too let x: (char,) = ('d',); let (y,) = x; - assert!(y == 'd'); + assert_eq!(y, 'd'); } diff --git a/src/test/run-pass/opeq.rs b/src/test/run-pass/opeq.rs index 004aa864f99da..652ac24d35d5b 100644 --- a/src/test/run-pass/opeq.rs +++ b/src/test/run-pass/opeq.rs @@ -16,14 +16,14 @@ pub fn main() { let mut x: int = 1; x *= 2; debug!(x); - assert!((x == 2)); + assert_eq!(x, 2); x += 3; debug!(x); - assert!((x == 5)); + assert_eq!(x, 5); x *= x; debug!(x); - assert!((x == 25)); + assert_eq!(x, 25); x /= 5; debug!(x); - assert!((x == 5)); + assert_eq!(x, 5); } diff --git a/src/test/run-pass/operator-overloading.rs b/src/test/run-pass/operator-overloading.rs index 8c26dfa1fac56..b54e3188dae4c 100644 --- a/src/test/run-pass/operator-overloading.rs +++ b/src/test/run-pass/operator-overloading.rs @@ -56,14 +56,14 @@ pub fn main() { let mut p = Point {x: 10, y: 20}; p += Point {x: 101, y: 102}; p = p - Point {x: 100, y: 100}; - assert!(p + Point {x: 5, y: 5} == Point {x: 16, y: 27}); - assert!(-p == Point {x: -11, y: -22}); - assert!(p[true] == 11); - assert!(p[false] == 22); + assert_eq!(p + Point {x: 5, y: 5}, Point {x: 16, y: 27}); + assert_eq!(-p, Point {x: -11, y: -22}); + assert_eq!(p[true], 11); + assert_eq!(p[false], 22); let q = !p; - assert!(q.x == !(p.x)); - assert!(q.y == !(p.y)); + assert_eq!(q.x, !(p.x)); + assert_eq!(q.y, !(p.y)); // Issue #1733 let result: ~fn(int) = |_|(); diff --git a/src/test/run-pass/option-unwrap.rs b/src/test/run-pass/option-unwrap.rs index 8698d1f39a88f..ea8a6f236cd14 100644 --- a/src/test/run-pass/option-unwrap.rs +++ b/src/test/run-pass/option-unwrap.rs @@ -38,5 +38,5 @@ pub fn main() { let c = unwrap(b); } - assert!(*x == 0); + assert_eq!(*x, 0); } diff --git a/src/test/run-pass/option_addition.rs b/src/test/run-pass/option_addition.rs index 10b8c92e7d60a..07996cb439dae 100644 --- a/src/test/run-pass/option_addition.rs +++ b/src/test/run-pass/option_addition.rs @@ -22,9 +22,9 @@ pub fn main() { None => (), Some(foo) => fail!("expected None, but found %?", foo) } - assert!(foo == somefoo.get()); - assert!(bar == somebar.get()); - assert!(foobar == somefoobar.get()); + assert_eq!(foo, somefoo.get()); + assert_eq!(bar, somebar.get()); + assert_eq!(foobar, somefoobar.get()); } fn optint(in: int) -> Option { diff --git a/src/test/run-pass/or-pattern.rs b/src/test/run-pass/or-pattern.rs index 93d51ab7e8b8b..a014257fb1c9d 100644 --- a/src/test/run-pass/or-pattern.rs +++ b/src/test/run-pass/or-pattern.rs @@ -15,7 +15,7 @@ fn or_alt(q: blah) -> int { } pub fn main() { - assert!((or_alt(c) == 0)); - assert!((or_alt(a(10, 100, 0u)) == 110)); - assert!((or_alt(b(20, 200)) == 220)); + assert_eq!(or_alt(c), 0); + assert_eq!(or_alt(a(10, 100, 0u)), 110); + assert_eq!(or_alt(b(20, 200)), 220); } diff --git a/src/test/run-pass/pattern-bound-var-in-for-each.rs b/src/test/run-pass/pattern-bound-var-in-for-each.rs index 63d9ec17ccb5e..a2630c398032f 100644 --- a/src/test/run-pass/pattern-bound-var-in-for-each.rs +++ b/src/test/run-pass/pattern-bound-var-in-for-each.rs @@ -18,7 +18,7 @@ fn foo(src: uint) { Some(src_id) => { for uint::range(0u, 10u) |i| { let yyy = src_id; - assert!((yyy == 0u)); + assert_eq!(yyy, 0u); } } _ => { } diff --git a/src/test/run-pass/pipe-select.rs b/src/test/run-pass/pipe-select.rs index 8782f6f6ebd15..7e0a59f57fc5a 100644 --- a/src/test/run-pass/pipe-select.rs +++ b/src/test/run-pass/pipe-select.rs @@ -66,7 +66,7 @@ pub fn main() { error!("selecting"); let (i, _, _) = select(~[left, right]); error!("selected"); - assert!(i == 0); + assert_eq!(i, 0); error!("waiting for pipes"); let stream::send(x, _) = recv(p); @@ -78,7 +78,7 @@ pub fn main() { let (i, m, _) = select(~[left, right]); error!("selected %?", i); if m.is_some() { - assert!(i == 1); + assert_eq!(i, 1); } }); diff --git a/src/test/run-pass/placement-new-arena.rs b/src/test/run-pass/placement-new-arena.rs index 166435cbc3d50..ac5bc4f62d9ea 100644 --- a/src/test/run-pass/placement-new-arena.rs +++ b/src/test/run-pass/placement-new-arena.rs @@ -18,5 +18,5 @@ pub fn main() { let p = &mut arena; let x = p.alloc(|| 4u); io::print(fmt!("%u", *x)); - assert!(*x == 4u); + assert_eq!(*x, 4u); } diff --git a/src/test/run-pass/private-class-field.rs b/src/test/run-pass/private-class-field.rs index 75f933ac769b0..44a56333a780b 100644 --- a/src/test/run-pass/private-class-field.rs +++ b/src/test/run-pass/private-class-field.rs @@ -27,5 +27,5 @@ fn cat(in_x : uint, in_y : int) -> cat { pub fn main() { let mut nyan : cat = cat(52u, 99); - assert!((nyan.meow_count() == 52u)); + assert_eq!(nyan.meow_count(), 52u); } diff --git a/src/test/run-pass/propagate-expected-type-through-block.rs b/src/test/run-pass/propagate-expected-type-through-block.rs index aeeae0da9e34a..f8f824cd59603 100644 --- a/src/test/run-pass/propagate-expected-type-through-block.rs +++ b/src/test/run-pass/propagate-expected-type-through-block.rs @@ -8,5 +8,5 @@ pub fn main() { let y = y.clone(); |x| *x + *y }; - assert!(foo(@22) == 25); + assert_eq!(foo(@22), 25); } diff --git a/src/test/run-pass/rcvr-borrowed-to-region.rs b/src/test/run-pass/rcvr-borrowed-to-region.rs index 04f86fdad01fd..fbd7d851fa378 100644 --- a/src/test/run-pass/rcvr-borrowed-to-region.rs +++ b/src/test/run-pass/rcvr-borrowed-to-region.rs @@ -26,26 +26,26 @@ pub fn main() { /* let x = @mut 6; let y = x.get(); - assert!(y == 6); + assert_eq!(y, 6); */ let x = @6; let y = x.get(); debug!("y=%d", y); - assert!(y == 6); + assert_eq!(y, 6); let mut x = ~6; let y = x.get(); debug!("y=%d", y); - assert!(y == 6); + assert_eq!(y, 6); let x = ~6; let y = x.get(); debug!("y=%d", y); - assert!(y == 6); + assert_eq!(y, 6); let x = &6; let y = x.get(); debug!("y=%d", y); - assert!(y == 6); + assert_eq!(y, 6); } diff --git a/src/test/run-pass/rcvr-borrowed-to-slice.rs b/src/test/run-pass/rcvr-borrowed-to-slice.rs index 483a2ee25e5d5..188dca2f03937 100644 --- a/src/test/run-pass/rcvr-borrowed-to-slice.rs +++ b/src/test/run-pass/rcvr-borrowed-to-slice.rs @@ -27,15 +27,15 @@ pub fn main() { let x = ~[1, 2, 3]; let y = call_sum(x); debug!("y==%d", y); - assert!(y == 6); + assert_eq!(y, 6); let mut x = ~[1, 2, 3]; let y = x.sum(); debug!("y==%d", y); - assert!(y == 6); + assert_eq!(y, 6); let x = ~[1, 2, 3]; let y = x.sum(); debug!("y==%d", y); - assert!(y == 6); + assert_eq!(y, 6); } diff --git a/src/test/run-pass/rec-align-u32.rs b/src/test/run-pass/rec-align-u32.rs index ff72eab7df16c..202f6a4ac6426 100644 --- a/src/test/run-pass/rec-align-u32.rs +++ b/src/test/run-pass/rec-align-u32.rs @@ -56,12 +56,12 @@ pub fn main() { debug!("y = %s", y); // per clang/gcc the alignment of `inner` is 4 on x86. - assert!(rusti::min_align_of::() == m::align()); + assert_eq!(rusti::min_align_of::(), m::align()); // per clang/gcc the size of `outer` should be 12 // because `inner`s alignment was 4. - assert!(sys::size_of::() == m::size()); + assert_eq!(sys::size_of::(), m::size()); - assert!(y == ~"{c8: 22, t: {c64: 44}}"); + assert_eq!(y, ~"{c8: 22, t: {c64: 44}}"); } } diff --git a/src/test/run-pass/rec-align-u64.rs b/src/test/run-pass/rec-align-u64.rs index 0fad3e1f511f8..49092c26c9534 100644 --- a/src/test/run-pass/rec-align-u64.rs +++ b/src/test/run-pass/rec-align-u64.rs @@ -78,12 +78,12 @@ pub fn main() { debug!("y = %s", y); // per clang/gcc the alignment of `Inner` is 4 on x86. - assert!(rusti::min_align_of::() == m::m::align()); + assert_eq!(rusti::min_align_of::(), m::m::align()); // per clang/gcc the size of `Outer` should be 12 // because `Inner`s alignment was 4. - assert!(sys::size_of::() == m::m::size()); + assert_eq!(sys::size_of::(), m::m::size()); - assert!(y == ~"{c8: 22, t: {c64: 44}}"); + assert_eq!(y, ~"{c8: 22, t: {c64: 44}}"); } } diff --git a/src/test/run-pass/rec-extend.rs b/src/test/run-pass/rec-extend.rs index c352c06247b03..4e029be8f76a7 100644 --- a/src/test/run-pass/rec-extend.rs +++ b/src/test/run-pass/rec-extend.rs @@ -18,10 +18,10 @@ pub fn main() { let origin: Point = Point {x: 0, y: 0}; let right: Point = Point {x: origin.x + 10,.. origin}; let up: Point = Point {y: origin.y + 10,.. origin}; - assert!((origin.x == 0)); - assert!((origin.y == 0)); - assert!((right.x == 10)); - assert!((right.y == 0)); - assert!((up.x == 0)); - assert!((up.y == 10)); + assert_eq!(origin.x, 0); + assert_eq!(origin.y, 0); + assert_eq!(right.x, 10); + assert_eq!(right.y, 0); + assert_eq!(up.x, 0); + assert_eq!(up.y, 10); } diff --git a/src/test/run-pass/rec-tup.rs b/src/test/run-pass/rec-tup.rs index 46fb619fd8015..fb5c5f3ce01e8 100644 --- a/src/test/run-pass/rec-tup.rs +++ b/src/test/run-pass/rec-tup.rs @@ -17,21 +17,21 @@ fn fst(r: rect) -> Point { let (fst, _) = r; return fst; } fn snd(r: rect) -> Point { let (_, snd) = r; return snd; } fn f(r: rect, x1: int, y1: int, x2: int, y2: int) { - assert!((fst(r).x == x1)); - assert!((fst(r).y == y1)); - assert!((snd(r).x == x2)); - assert!((snd(r).y == y2)); + assert_eq!(fst(r).x, x1); + assert_eq!(fst(r).y, y1); + assert_eq!(snd(r).x, x2); + assert_eq!(snd(r).y, y2); } pub fn main() { let r: rect = (Point {x: 10, y: 20}, Point {x: 11, y: 22}); - assert!((fst(r).x == 10)); - assert!((fst(r).y == 20)); - assert!((snd(r).x == 11)); - assert!((snd(r).y == 22)); + assert_eq!(fst(r).x, 10); + assert_eq!(fst(r).y, 20); + assert_eq!(snd(r).x, 11); + assert_eq!(snd(r).y, 22); let r2 = r; let x: int = fst(r2).x; - assert!((x == 10)); + assert_eq!(x, 10); f(r, 10, 20, 11, 22); f(r2, 10, 20, 11, 22); } diff --git a/src/test/run-pass/rec.rs b/src/test/run-pass/rec.rs index 9d9322f7f3dd7..fa3fa01dd4df9 100644 --- a/src/test/run-pass/rec.rs +++ b/src/test/run-pass/rec.rs @@ -15,21 +15,21 @@ struct Rect {x: int, y: int, w: int, h: int} fn f(r: Rect, x: int, y: int, w: int, h: int) { - assert!((r.x == x)); - assert!((r.y == y)); - assert!((r.w == w)); - assert!((r.h == h)); + assert_eq!(r.x, x); + assert_eq!(r.y, y); + assert_eq!(r.w, w); + assert_eq!(r.h, h); } pub fn main() { let r: Rect = Rect {x: 10, y: 20, w: 100, h: 200}; - assert!((r.x == 10)); - assert!((r.y == 20)); - assert!((r.w == 100)); - assert!((r.h == 200)); + assert_eq!(r.x, 10); + assert_eq!(r.y, 20); + assert_eq!(r.w, 100); + assert_eq!(r.h, 200); let r2: Rect = r; let x: int = r2.x; - assert!((x == 10)); + assert_eq!(x, 10); f(r, 10, 20, 100, 200); f(r2, 10, 20, 100, 200); } diff --git a/src/test/run-pass/record-pat.rs b/src/test/run-pass/record-pat.rs index 0019f1dc23b3f..b13a955404cb4 100644 --- a/src/test/run-pass/record-pat.rs +++ b/src/test/run-pass/record-pat.rs @@ -20,6 +20,6 @@ fn m(in: t3) -> int { } pub fn main() { - assert!((m(c(T2 {x: a(10), y: 5}, 4u)) == 10)); - assert!((m(c(T2 {x: b(10u), y: 5}, 4u)) == 19)); + assert_eq!(m(c(T2 {x: a(10), y: 5}, 4u)), 10); + assert_eq!(m(c(T2 {x: b(10u), y: 5}, 4u)), 19); } diff --git a/src/test/run-pass/region-dependent-addr-of.rs b/src/test/run-pass/region-dependent-addr-of.rs index dd33f7f1e309b..ac2fc2eda23cf 100644 --- a/src/test/run-pass/region-dependent-addr-of.rs +++ b/src/test/run-pass/region-dependent-addr-of.rs @@ -90,29 +90,29 @@ pub fn main() { v6: Some(C { f: 31 })}}; let p = get_v1(&a); - assert!(*p == a.value.v1); + assert_eq!(*p, a.value.v1); let p = get_v2(&a, 1); - assert!(*p == a.value.v2[1]); + assert_eq!(*p, a.value.v2[1]); let p = get_v3(&a, 1); - assert!(*p == a.value.v3[1]); + assert_eq!(*p, a.value.v3[1]); let p = get_v4(&a, 1); - assert!(*p == a.value.v4.f); + assert_eq!(*p, a.value.v4.f); let p = get_v5(&a, 1); - assert!(*p == a.value.v5.f); + assert_eq!(*p, a.value.v5.f); let p = get_v6_a(&a, 1); - assert!(*p == a.value.v6.get().f); + assert_eq!(*p, a.value.v6.get().f); let p = get_v6_b(&a, 1); - assert!(*p == a.value.v6.get().f); + assert_eq!(*p, a.value.v6.get().f); let p = get_v6_c(&a, 1); - assert!(*p == a.value.v6.get().f); + assert_eq!(*p, a.value.v6.get().f); let p = get_v5_ref(&a, 1); - assert!(*p == a.value.v5.f); + assert_eq!(*p, a.value.v5.f); } diff --git a/src/test/run-pass/region-return-interior-of-option.rs b/src/test/run-pass/region-return-interior-of-option.rs index 8bb069990ee48..aa4630717db6c 100644 --- a/src/test/run-pass/region-return-interior-of-option.rs +++ b/src/test/run-pass/region-return-interior-of-option.rs @@ -20,13 +20,13 @@ pub fn main() { { let y = get(&x); - assert!(*y == 23); + assert_eq!(*y, 23); } x = Some(24); { let y = get(&x); - assert!(*y == 24); + assert_eq!(*y, 24); } } diff --git a/src/test/run-pass/regions-appearance-constraint.rs b/src/test/run-pass/regions-appearance-constraint.rs index cfe721612e1e2..e587fa15f5ccd 100644 --- a/src/test/run-pass/regions-appearance-constraint.rs +++ b/src/test/run-pass/regions-appearance-constraint.rs @@ -25,7 +25,7 @@ fn testfn(cond: bool) { x = @5; y = @6; - assert!(*a == exp); + assert_eq!(*a, exp); } pub fn main() { diff --git a/src/test/run-pass/regions-borrow-at.rs b/src/test/run-pass/regions-borrow-at.rs index f12c80c2e8841..a8637fc8ab782 100644 --- a/src/test/run-pass/regions-borrow-at.rs +++ b/src/test/run-pass/regions-borrow-at.rs @@ -16,5 +16,5 @@ pub fn main() { let p = @22u; let r = foo(p); debug!("r=%u", r); - assert!(r == 22u); + assert_eq!(r, 22u); } diff --git a/src/test/run-pass/regions-borrow-estr-uniq.rs b/src/test/run-pass/regions-borrow-estr-uniq.rs index 18082e857514f..b7d9b9f8fa9d5 100644 --- a/src/test/run-pass/regions-borrow-estr-uniq.rs +++ b/src/test/run-pass/regions-borrow-estr-uniq.rs @@ -15,9 +15,9 @@ fn foo(x: &str) -> u8 { pub fn main() { let p = ~"hello"; let r = foo(p); - assert!(r == 'h' as u8); + assert_eq!(r, 'h' as u8); let p = ~"hello"; let r = foo(p); - assert!(r == 'h' as u8); + assert_eq!(r, 'h' as u8); } diff --git a/src/test/run-pass/regions-borrow-evec-at.rs b/src/test/run-pass/regions-borrow-evec-at.rs index 3247f9df30d87..a018dad64b366 100644 --- a/src/test/run-pass/regions-borrow-evec-at.rs +++ b/src/test/run-pass/regions-borrow-evec-at.rs @@ -17,5 +17,5 @@ fn foo(x: &[uint]) -> uint { pub fn main() { let p = @[22u]; let r = foo(p); - assert!(r == 22u); + assert_eq!(r, 22u); } diff --git a/src/test/run-pass/regions-borrow-evec-fixed.rs b/src/test/run-pass/regions-borrow-evec-fixed.rs index 557b66735c016..129a299bcd415 100644 --- a/src/test/run-pass/regions-borrow-evec-fixed.rs +++ b/src/test/run-pass/regions-borrow-evec-fixed.rs @@ -16,5 +16,5 @@ fn foo(x: &[int]) -> int { pub fn main() { let p = [1,2,3,4,5]; - assert!(foo(p) == 1); + assert_eq!(foo(p), 1); } diff --git a/src/test/run-pass/regions-borrow-evec-uniq.rs b/src/test/run-pass/regions-borrow-evec-uniq.rs index 80ea1bb452daa..914c51eaa7012 100644 --- a/src/test/run-pass/regions-borrow-evec-uniq.rs +++ b/src/test/run-pass/regions-borrow-evec-uniq.rs @@ -15,9 +15,9 @@ fn foo(x: &[int]) -> int { pub fn main() { let p = ~[1,2,3,4,5]; let r = foo(p); - assert!(r == 1); + assert_eq!(r, 1); let p = ~[5,4,3,2,1]; let r = foo(p); - assert!(r == 5); + assert_eq!(r, 5); } diff --git a/src/test/run-pass/regions-borrow-uniq.rs b/src/test/run-pass/regions-borrow-uniq.rs index e59352667c2a1..10037d9dfe43b 100644 --- a/src/test/run-pass/regions-borrow-uniq.rs +++ b/src/test/run-pass/regions-borrow-uniq.rs @@ -15,5 +15,5 @@ fn foo(x: &uint) -> uint { pub fn main() { let p = ~3u; let r = foo(p); - assert!(r == 3u); + assert_eq!(r, 3u); } diff --git a/src/test/run-pass/regions-copy-closure.rs b/src/test/run-pass/regions-copy-closure.rs index 2e9ff88f96e90..0b962731ecf3c 100644 --- a/src/test/run-pass/regions-copy-closure.rs +++ b/src/test/run-pass/regions-copy-closure.rs @@ -19,7 +19,7 @@ fn box_it<'r>(x: &'r fn()) -> closure_box<'r> { pub fn main() { let mut i = 3; let cl_box = box_it(|| i += 1); - assert!(i == 3); + assert_eq!(i, 3); (cl_box.cl)(); - assert!(i == 4); + assert_eq!(i, 4); } diff --git a/src/test/run-pass/regions-escape-into-other-fn.rs b/src/test/run-pass/regions-escape-into-other-fn.rs index 22b98726fb1a9..986071ec53599 100644 --- a/src/test/run-pass/regions-escape-into-other-fn.rs +++ b/src/test/run-pass/regions-escape-into-other-fn.rs @@ -13,5 +13,5 @@ fn bar(x: &uint) -> uint { *x } pub fn main() { let p = @3u; - assert!(bar(foo(p)) == 3); + assert_eq!(bar(foo(p)), 3); } diff --git a/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs b/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs index 73535f52043eb..db4a51bbf2221 100644 --- a/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs +++ b/src/test/run-pass/regions-infer-borrow-scope-within-loop-ok.rs @@ -14,7 +14,7 @@ pub fn main() { let x = @3; loop { let y = borrow(x); - assert!(*x == *y); + assert_eq!(*x, *y); break; } } diff --git a/src/test/run-pass/regions-infer-borrow-scope.rs b/src/test/run-pass/regions-infer-borrow-scope.rs index 61b9000aea318..6bd3fa5a73bcb 100644 --- a/src/test/run-pass/regions-infer-borrow-scope.rs +++ b/src/test/run-pass/regions-infer-borrow-scope.rs @@ -17,5 +17,5 @@ fn x_coord<'r>(p: &'r Point) -> &'r int { pub fn main() { let p = @Point {x: 3, y: 4}; let xc = x_coord(p); - assert!(*xc == 3); + assert_eq!(*xc, 3); } diff --git a/src/test/run-pass/regions-infer-call-2.rs b/src/test/run-pass/regions-infer-call-2.rs index 2772660ff83ce..42be3b5b97553 100644 --- a/src/test/run-pass/regions-infer-call-2.rs +++ b/src/test/run-pass/regions-infer-call-2.rs @@ -19,5 +19,5 @@ fn has_one<'a>(x: &'a int) -> int { } pub fn main() { - assert!(has_one(&2) == 22); + assert_eq!(has_one(&2), 22); } diff --git a/src/test/run-pass/regions-infer-call.rs b/src/test/run-pass/regions-infer-call.rs index 39dec6c81334f..fdb7485efc35b 100644 --- a/src/test/run-pass/regions-infer-call.rs +++ b/src/test/run-pass/regions-infer-call.rs @@ -15,5 +15,5 @@ fn has_two<'a,'b>(x: &'a int, y: &'b int) -> int { } pub fn main() { - assert!(has_two(&20, &2) == 22); + assert_eq!(has_two(&20, &2), 22); } diff --git a/src/test/run-pass/regions-infer-contravariance-due-to-ret.rs b/src/test/run-pass/regions-infer-contravariance-due-to-ret.rs index 46581e4f3d075..f07105cebed0b 100644 --- a/src/test/run-pass/regions-infer-contravariance-due-to-ret.rs +++ b/src/test/run-pass/regions-infer-contravariance-due-to-ret.rs @@ -24,5 +24,5 @@ fn with(bi: &boxed_int) -> int { pub fn main() { let g = 21; let foo = boxed_int { f: &g }; - assert!(with(&foo) == 22); + assert_eq!(with(&foo), 22); } diff --git a/src/test/run-pass/regions-params.rs b/src/test/run-pass/regions-params.rs index 8a8147e42d959..ea32cf866a0cd 100644 --- a/src/test/run-pass/regions-params.rs +++ b/src/test/run-pass/regions-params.rs @@ -23,5 +23,5 @@ fn parameterized(x: &uint) -> uint { pub fn main() { let x = 3u; - assert!(parameterized(&x) == 3u); + assert_eq!(parameterized(&x), 3u); } diff --git a/src/test/run-pass/regions-trait.rs b/src/test/run-pass/regions-trait.rs index a2ed9da67f264..b5b13efa634fa 100644 --- a/src/test/run-pass/regions-trait.rs +++ b/src/test/run-pass/regions-trait.rs @@ -30,5 +30,5 @@ pub fn main() { let ctxt = Ctxt { v: 22 }; let hc = HasCtxt { c: &ctxt }; - assert!(get_v(@hc as @get_ctxt) == 22); + assert_eq!(get_v(@hc as @get_ctxt), 22); } diff --git a/src/test/run-pass/resource-assign-is-not-copy.rs b/src/test/run-pass/resource-assign-is-not-copy.rs index 68ec3fc4d42e0..edd692196ecd5 100644 --- a/src/test/run-pass/resource-assign-is-not-copy.rs +++ b/src/test/run-pass/resource-assign-is-not-copy.rs @@ -36,5 +36,5 @@ pub fn main() { let (c, _d) = b; debug!(c); } - assert!(*i == 1); + assert_eq!(*i, 1); } diff --git a/src/test/run-pass/resource-destruct.rs b/src/test/run-pass/resource-destruct.rs index 1fcf677a0b3dd..b69248e327710 100644 --- a/src/test/run-pass/resource-destruct.rs +++ b/src/test/run-pass/resource-destruct.rs @@ -35,5 +35,5 @@ pub fn main() { let my_total = @@mut 10; { let pt = shrinky_pointer(my_total); assert!((pt.look_at() == 10)); } error!("my_total = %d", **my_total); - assert!((**my_total == 9)); + assert_eq!(**my_total, 9); } diff --git a/src/test/run-pass/resource-generic.rs b/src/test/run-pass/resource-generic.rs index 8a1835d6585fa..41eafb0293af9 100644 --- a/src/test/run-pass/resource-generic.rs +++ b/src/test/run-pass/resource-generic.rs @@ -36,5 +36,5 @@ pub fn main() { fn dec_box(i: @mut int) { *i -= 1; } { let _i = finish(Arg{val: box, fin: dec_box}); } - assert!((*box == 9)); + assert_eq!(*box, 9); } diff --git a/src/test/run-pass/ret-break-cont-in-block.rs b/src/test/run-pass/ret-break-cont-in-block.rs index 1792a89d64f1e..f1b1267faa78a 100644 --- a/src/test/run-pass/ret-break-cont-in-block.rs +++ b/src/test/run-pass/ret-break-cont-in-block.rs @@ -56,17 +56,17 @@ pub fn main() { last = *e; if *e == 5 { break; } if *e % 2 == 1 { loop; } - assert!(*e % 2 == 0); + assert_eq!(*e % 2, 0); }; - assert!(last == 5); + assert_eq!(last, 5); - assert!(find_pos(1, ~[0, 1, 2, 3]) == Some(1u)); - assert!(find_pos(1, ~[0, 4, 2, 3]) == None); - assert!(find_pos(~"hi", ~[~"foo", ~"bar", ~"baz", ~"hi"]) == Some(3u)); + assert_eq!(find_pos(1, ~[0, 1, 2, 3]), Some(1u)); + assert_eq!(find_pos(1, ~[0, 4, 2, 3]), None); + assert_eq!(find_pos(~"hi", ~[~"foo", ~"bar", ~"baz", ~"hi"]), Some(3u)); bail_deep(~[~[false, false], ~[true, true], ~[false, true]]); bail_deep(~[~[true]]); bail_deep(~[~[false, false, false]]); - assert!(ret_deep() == ~"hi"); + assert_eq!(ret_deep(), ~"hi"); } diff --git a/src/test/run-pass/rt-sched-1.rs b/src/test/run-pass/rt-sched-1.rs index e7dd240eb184c..17c5994634fe3 100644 --- a/src/test/run-pass/rt-sched-1.rs +++ b/src/test/run-pass/rt-sched-1.rs @@ -44,7 +44,7 @@ pub fn main() { let child_sched_id = rustrt::rust_get_sched_id(); error!("child_sched_id %?", child_sched_id); assert!(child_sched_id != parent_sched_id); - assert!(child_sched_id == new_sched_id); + assert_eq!(child_sched_id, new_sched_id); ch.send(()); } }; diff --git a/src/test/run-pass/sendfn-is-a-block.rs b/src/test/run-pass/sendfn-is-a-block.rs index 8ccc6bb5efb08..f7808f7f8ac8b 100644 --- a/src/test/run-pass/sendfn-is-a-block.rs +++ b/src/test/run-pass/sendfn-is-a-block.rs @@ -16,5 +16,5 @@ fn test(f: &fn(uint) -> uint) -> uint { pub fn main() { let y = test(|x| 4u * x); - assert!(y == 88u); + assert_eq!(y, 88u); } diff --git a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs index 2a69b2ca01779..9816849d80826 100644 --- a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs +++ b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs @@ -20,7 +20,7 @@ fn test05() { let three = ~3; let fn_to_send: ~fn(int) = |n| { error!(*three + n); // will copy x into the closure - assert!((*three == 3)); + assert_eq!(*three, 3); }; let fn_to_send = Cell(fn_to_send); task::spawn(|| { diff --git a/src/test/run-pass/seq-compare.rs b/src/test/run-pass/seq-compare.rs index 5fb5297360081..86907bdf2a38f 100644 --- a/src/test/run-pass/seq-compare.rs +++ b/src/test/run-pass/seq-compare.rs @@ -21,6 +21,6 @@ pub fn main() { assert!((~[1, 2, 3] <= ~[1, 2, 3])); assert!((~[1, 2, 3] <= ~[1, 2, 3, 3])); assert!((~[1, 2, 3, 4] > ~[1, 2, 3])); - assert!((~[1, 2, 3] == ~[1, 2, 3])); + assert_eq!(~[1, 2, 3], ~[1, 2, 3]); assert!((~[1, 2, 3] != ~[1, 1, 3])); } diff --git a/src/test/run-pass/shift.rs b/src/test/run-pass/shift.rs index d839825a773c2..7b676f05c9084 100644 --- a/src/test/run-pass/shift.rs +++ b/src/test/run-pass/shift.rs @@ -18,64 +18,64 @@ pub fn main() { } fn test_misc() { - assert!(1 << 1i8 << 1u8 << 1i16 << 1 as char << 1u64 == 32); + assert_eq!(1 << 1i8 << 1u8 << 1i16 << 1 as char << 1u64, 32); } fn test_expr() { let v10 = 10 as uint; let v4 = 4 as u8; let v2 = 2 as u8; - assert!((v10 >> v2 == v2 as uint)); - assert!((v10 << v4 == 160 as uint)); + assert_eq!(v10 >> v2, v2 as uint); + assert_eq!(v10 << v4, 160 as uint); let v10 = 10 as u8; let v4 = 4 as uint; let v2 = 2 as uint; - assert!((v10 >> v2 == v2 as u8)); - assert!((v10 << v4 == 160 as u8)); + assert_eq!(v10 >> v2, v2 as u8); + assert_eq!(v10 << v4, 160 as u8); let v10 = 10 as int; let v4 = 4 as i8; let v2 = 2 as i8; - assert!((v10 >> v2 == v2 as int)); - assert!((v10 << v4 == 160 as int)); + assert_eq!(v10 >> v2, v2 as int); + assert_eq!(v10 << v4, 160 as int); let v10 = 10 as i8; let v4 = 4 as int; let v2 = 2 as int; - assert!((v10 >> v2 == v2 as i8)); - assert!((v10 << v4 == 160 as i8)); + assert_eq!(v10 >> v2, v2 as i8); + assert_eq!(v10 << v4, 160 as i8); let v10 = 10 as uint; let v4 = 4 as int; let v2 = 2 as int; - assert!((v10 >> v2 == v2 as uint)); - assert!((v10 << v4 == 160 as uint)); + assert_eq!(v10 >> v2, v2 as uint); + assert_eq!(v10 << v4, 160 as uint); } fn test_const() { static r1_1: uint = 10u >> 2u8; static r2_1: uint = 10u << 4u8; - assert!(r1_1 == 2 as uint); - assert!(r2_1 == 160 as uint); + assert_eq!(r1_1, 2 as uint); + assert_eq!(r2_1, 160 as uint); static r1_2: u8 = 10u8 >> 2u; static r2_2: u8 = 10u8 << 4u; - assert!(r1_2 == 2 as u8); - assert!(r2_2 == 160 as u8); + assert_eq!(r1_2, 2 as u8); + assert_eq!(r2_2, 160 as u8); static r1_3: int = 10 >> 2i8; static r2_3: int = 10 << 4i8; - assert!(r1_3 == 2 as int); - assert!(r2_3 == 160 as int); + assert_eq!(r1_3, 2 as int); + assert_eq!(r2_3, 160 as int); static r1_4: i8 = 10i8 >> 2; static r2_4: i8 = 10i8 << 4; - assert!(r1_4 == 2 as i8); - assert!(r2_4 == 160 as i8); + assert_eq!(r1_4, 2 as i8); + assert_eq!(r2_4, 160 as i8); static r1_5: uint = 10u >> 2i8; static r2_5: uint = 10u << 4i8; - assert!(r1_5 == 2 as uint); - assert!(r2_5 == 160 as uint); + assert_eq!(r1_5, 2 as uint); + assert_eq!(r2_5, 160 as uint); } diff --git a/src/test/run-pass/signed-shift-const-eval.rs b/src/test/run-pass/signed-shift-const-eval.rs index 0d3ecae01fb92..92c83c22085b0 100644 --- a/src/test/run-pass/signed-shift-const-eval.rs +++ b/src/test/run-pass/signed-shift-const-eval.rs @@ -10,5 +10,5 @@ enum test { thing = -5 >> 1u } pub fn main() { - assert!((thing as int == -3)); + assert_eq!(thing as int, -3); } diff --git a/src/test/run-pass/spawn-types.rs b/src/test/run-pass/spawn-types.rs index 7bc55d647df5a..eb1c082f2f2e6 100644 --- a/src/test/run-pass/spawn-types.rs +++ b/src/test/run-pass/spawn-types.rs @@ -19,7 +19,7 @@ use core::comm::*; type ctx = Chan; fn iotask(cx: &ctx, ip: ~str) { - assert!((ip == ~"localhost")); + assert_eq!(ip, ~"localhost"); } pub fn main() { diff --git a/src/test/run-pass/spawn2.rs b/src/test/run-pass/spawn2.rs index 642babb5a1e5c..cb35f0828f241 100644 --- a/src/test/run-pass/spawn2.rs +++ b/src/test/run-pass/spawn2.rs @@ -22,13 +22,13 @@ fn child(args: (int, int, int, int, int, int, int, int, int)) { error!(i7); error!(i8); error!(i9); - assert!((i1 == 10)); - assert!((i2 == 20)); - assert!((i3 == 30)); - assert!((i4 == 40)); - assert!((i5 == 50)); - assert!((i6 == 60)); - assert!((i7 == 70)); - assert!((i8 == 80)); - assert!((i9 == 90)); + assert_eq!(i1, 10); + assert_eq!(i2, 20); + assert_eq!(i3, 30); + assert_eq!(i4, 40); + assert_eq!(i5, 50); + assert_eq!(i6, 60); + assert_eq!(i7, 70); + assert_eq!(i8, 80); + assert_eq!(i9, 90); } diff --git a/src/test/run-pass/stable-addr-of.rs b/src/test/run-pass/stable-addr-of.rs index 3731f41f8f81c..9008e9452dbc5 100644 --- a/src/test/run-pass/stable-addr-of.rs +++ b/src/test/run-pass/stable-addr-of.rs @@ -12,5 +12,5 @@ pub fn main() { let foo = 1; - assert!(ptr::to_unsafe_ptr(&foo) == ptr::to_unsafe_ptr(&foo)); + assert_eq!(ptr::to_unsafe_ptr(&foo), ptr::to_unsafe_ptr(&foo)); } diff --git a/src/test/run-pass/stat.rs b/src/test/run-pass/stat.rs index 0967eaf061509..2e081f364e768 100644 --- a/src/test/run-pass/stat.rs +++ b/src/test/run-pass/stat.rs @@ -30,7 +30,7 @@ pub fn main() { } assert!(path.exists()); - assert!(path.get_size() == Some(1000)); + assert_eq!(path.get_size(), Some(1000)); os::remove_dir(&dir); } diff --git a/src/test/run-pass/static-impl.rs b/src/test/run-pass/static-impl.rs index 3f4a956b3a424..e96ab30f037d0 100644 --- a/src/test/run-pass/static-impl.rs +++ b/src/test/run-pass/static-impl.rs @@ -54,13 +54,13 @@ impl vec_utils for ~[T] { } pub fn main() { - assert!(10u.plus() == 30); - assert!((~"hi").plus() == 200); + assert_eq!(10u.plus(), 30); + assert_eq!((~"hi").plus(), 200); - assert!((~[1]).length_().str() == ~"1"); - assert!((~[3, 4]).map_(|a| *a + 4 )[0] == 7); - assert!((~[3, 4]).map_::(|a| *a as uint + 4u )[0] == 7u); + assert_eq!((~[1]).length_().str(), ~"1"); + assert_eq!((~[3, 4]).map_(|a| *a + 4 )[0], 7); + assert_eq!((~[3, 4]).map_::(|a| *a as uint + 4u )[0], 7u); let mut x = 0u; 10u.multi(|_n| x += 2u ); - assert!(x == 20u); + assert_eq!(x, 20u); } diff --git a/src/test/run-pass/static-method-in-trait-with-tps-intracrate.rs b/src/test/run-pass/static-method-in-trait-with-tps-intracrate.rs index e8bb9c485ead2..d1fcc4659b937 100644 --- a/src/test/run-pass/static-method-in-trait-with-tps-intracrate.rs +++ b/src/test/run-pass/static-method-in-trait-with-tps-intracrate.rs @@ -31,5 +31,5 @@ impl Deserializer for FromThinAir { pub fn main() { let d = FromThinAir { dummy: () }; let i: int = Deserializable::deserialize(&d); - assert!(i == 22); + assert_eq!(i, 22); } diff --git a/src/test/run-pass/static-method-test.rs b/src/test/run-pass/static-method-test.rs index e06d09c564c00..3ae8768e41e32 100644 --- a/src/test/run-pass/static-method-test.rs +++ b/src/test/run-pass/static-method-test.rs @@ -76,15 +76,15 @@ fn seq_range>(lo: uint, hi: uint) -> BT { pub fn main() { let v: @[int] = seq_range(0, 10); - assert!(v == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + assert_eq!(v, @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); let v: @[int] = map(&[1,2,3], |&x| 1+x); - assert!(v == @[2, 3, 4]); + assert_eq!(v, @[2, 3, 4]); let v: ~[int] = map(&[1,2,3], |&x| 1+x); - assert!(v == ~[2, 3, 4]); + assert_eq!(v, ~[2, 3, 4]); - assert!(bool_like::select(true, 9, 14) == 9); + assert_eq!(bool_like::select(true, 9, 14), 9); assert!(!andand(true, false)); - assert!(andand(7, 12) == 12); - assert!(andand(0, 12) == 0); + assert_eq!(andand(7, 12), 12); + assert_eq!(andand(0, 12), 0); } diff --git a/src/test/run-pass/static-method-xcrate.rs b/src/test/run-pass/static-method-xcrate.rs index aa4f65669ad90..c5d3b58276e5b 100644 --- a/src/test/run-pass/static-method-xcrate.rs +++ b/src/test/run-pass/static-method-xcrate.rs @@ -17,7 +17,7 @@ use readMaybeRenamed = static_methods_crate::read::readMaybe; pub fn main() { let result: int = read(~"5"); - assert!(result == 5); - assert!(readMaybeRenamed(~"false") == Some(false)); - assert!(readMaybeRenamed(~"foo") == None::); + assert_eq!(result, 5); + assert_eq!(readMaybeRenamed(~"false"), Some(false)); + assert_eq!(readMaybeRenamed(~"foo"), None::); } diff --git a/src/test/run-pass/static-methods-in-traits.rs b/src/test/run-pass/static-methods-in-traits.rs index 42d0f02d6425c..8cd7b78312bf2 100644 --- a/src/test/run-pass/static-methods-in-traits.rs +++ b/src/test/run-pass/static-methods-in-traits.rs @@ -29,6 +29,6 @@ mod a { pub fn main() { let x: int = a::Foo::foo(); let y: uint = a::Foo::foo(); - assert!(x == 3); - assert!(y == 5); + assert_eq!(x, 3); + assert_eq!(y, 5); } diff --git a/src/test/run-pass/str-append.rs b/src/test/run-pass/str-append.rs index 4332a184edade..d8cc8716e11c9 100644 --- a/src/test/run-pass/str-append.rs +++ b/src/test/run-pass/str-append.rs @@ -17,7 +17,7 @@ fn test1() { let mut s: ~str = ~"hello"; s += ~"world"; debug!(s.clone()); - assert!((s[9] == 'd' as u8)); + assert_eq!(s[9], 'd' as u8); } fn test2() { @@ -28,8 +28,8 @@ fn test2() { let b: ~str = ~"ABC" + ff + ~"ABC"; debug!(a.clone()); debug!(b.clone()); - assert!((a == ~"abcABCabc")); - assert!((b == ~"ABCabcABC")); + assert_eq!(a, ~"abcABCabc"); + assert_eq!(b, ~"ABCabcABC"); } pub fn main() { test1(); test2(); } diff --git a/src/test/run-pass/str-concat.rs b/src/test/run-pass/str-concat.rs index 0d43329baae47..402d2fbbe3ffb 100644 --- a/src/test/run-pass/str-concat.rs +++ b/src/test/run-pass/str-concat.rs @@ -17,5 +17,5 @@ pub fn main() { let b: ~str = ~"world"; let s: ~str = a + b; debug!(s.clone()); - assert!((s[9] == 'd' as u8)); + assert_eq!(s[9], 'd' as u8); } diff --git a/src/test/run-pass/str-growth.rs b/src/test/run-pass/str-growth.rs index fe9721a92e033..6938b52eee83e 100644 --- a/src/test/run-pass/str-growth.rs +++ b/src/test/run-pass/str-growth.rs @@ -13,12 +13,12 @@ pub fn main() { let mut s = ~"a"; s += ~"b"; - assert!((s[0] == 'a' as u8)); - assert!((s[1] == 'b' as u8)); + assert_eq!(s[0], 'a' as u8); + assert_eq!(s[1], 'b' as u8); s += ~"c"; s += ~"d"; - assert!((s[0] == 'a' as u8)); - assert!((s[1] == 'b' as u8)); - assert!((s[2] == 'c' as u8)); - assert!((s[3] == 'd' as u8)); + assert_eq!(s[0], 'a' as u8); + assert_eq!(s[1], 'b' as u8); + assert_eq!(s[2], 'c' as u8); + assert_eq!(s[3], 'd' as u8); } diff --git a/src/test/run-pass/str-idx.rs b/src/test/run-pass/str-idx.rs index 24d2438e86857..84f63c0137e1a 100644 --- a/src/test/run-pass/str-idx.rs +++ b/src/test/run-pass/str-idx.rs @@ -14,5 +14,5 @@ pub fn main() { let s = ~"hello"; let c: u8 = s[4]; debug!(c); - assert!((c == 0x6f as u8)); + assert_eq!(c, 0x6f as u8); } diff --git a/src/test/run-pass/str-multiline.rs b/src/test/run-pass/str-multiline.rs index ae400acdb8feb..90a7583dec951 100644 --- a/src/test/run-pass/str-multiline.rs +++ b/src/test/run-pass/str-multiline.rs @@ -21,6 +21,6 @@ is a test"; is \ another \ test"; - assert!((a == ~"this is a test")); - assert!((b == ~"this is another test")); + assert_eq!(a, ~"this is a test"); + assert_eq!(b, ~"this is another test"); } diff --git a/src/test/run-pass/string-self-append.rs b/src/test/run-pass/string-self-append.rs index c19a2afbd417f..8c15a8c689279 100644 --- a/src/test/run-pass/string-self-append.rs +++ b/src/test/run-pass/string-self-append.rs @@ -17,7 +17,7 @@ pub fn main() { let mut expected_len = 1u; while i > 0 { error!(str::len(a)); - assert!((str::len(a) == expected_len)); + assert_eq!(str::len(a), expected_len); a = a + a; // FIXME(#3387)---can't write a += a i -= 1; expected_len *= 2u; diff --git a/src/test/run-pass/struct-deref.rs b/src/test/run-pass/struct-deref.rs index a52a2851689bb..b1de9880d4b4f 100644 --- a/src/test/run-pass/struct-deref.rs +++ b/src/test/run-pass/struct-deref.rs @@ -12,5 +12,5 @@ struct Foo(int); pub fn main() { let x: Foo = Foo(2); - assert!(*x == 2); + assert_eq!(*x, 2); } diff --git a/src/test/run-pass/struct-destructuring-cross-crate.rs b/src/test/run-pass/struct-destructuring-cross-crate.rs index 55d25845971aa..23c508791beee 100644 --- a/src/test/run-pass/struct-destructuring-cross-crate.rs +++ b/src/test/run-pass/struct-destructuring-cross-crate.rs @@ -16,6 +16,6 @@ extern mod struct_destructuring_cross_crate; pub fn main() { let x = struct_destructuring_cross_crate::S { x: 1, y: 2 }; let struct_destructuring_cross_crate::S { x: a, y: b } = x; - assert!(a == 1); - assert!(b == 2); + assert_eq!(a, 1); + assert_eq!(b, 2); } diff --git a/src/test/run-pass/struct-field-assignability.rs b/src/test/run-pass/struct-field-assignability.rs index 0aca1a3d05fdf..335e13caa14cb 100644 --- a/src/test/run-pass/struct-field-assignability.rs +++ b/src/test/run-pass/struct-field-assignability.rs @@ -4,5 +4,5 @@ struct Foo<'self> { pub fn main() { let f = Foo { x: @3 }; - assert!(*f.x == 3); + assert_eq!(*f.x, 3); } diff --git a/src/test/run-pass/struct-like-variant-match.rs b/src/test/run-pass/struct-like-variant-match.rs index 64a75ddab22b7..ef558de433fe8 100644 --- a/src/test/run-pass/struct-like-variant-match.rs +++ b/src/test/run-pass/struct-like-variant-match.rs @@ -22,12 +22,12 @@ enum Foo { fn f(x: &Foo) { match *x { Baz { x: x, y: y } => { - assert!(x == 1.0); - assert!(y == 2.0); + assert_eq!(x, 1.0); + assert_eq!(y, 2.0); } Bar { y: y, x: x } => { - assert!(x == 1); - assert!(y == 2); + assert_eq!(x, 1); + assert_eq!(y, 2); } } } diff --git a/src/test/run-pass/struct-return.rs b/src/test/run-pass/struct-return.rs index 7ac74fd52175f..552683992b659 100644 --- a/src/test/run-pass/struct-return.rs +++ b/src/test/run-pass/struct-return.rs @@ -32,10 +32,10 @@ fn test1() { error!("b: %x", qq.b as uint); error!("c: %x", qq.c as uint); error!("d: %x", qq.d as uint); - assert!(qq.a == q.c + 1u64); - assert!(qq.b == q.d - 1u64); - assert!(qq.c == q.a + 1u64); - assert!(qq.d == q.b - 1u64); + assert_eq!(qq.a, q.c + 1u64); + assert_eq!(qq.b, q.d - 1u64); + assert_eq!(qq.c, q.a + 1u64); + assert_eq!(qq.d, q.b - 1u64); } } @@ -49,9 +49,9 @@ fn test2() { error!("a: %f", ff.a as float); error!("b: %u", ff.b as uint); error!("c: %f", ff.c as float); - assert!(ff.a == f.c + 1.0f64); - assert!(ff.b == 0xff_u8); - assert!(ff.c == f.a - 1.0f64); + assert_eq!(ff.a, f.c + 1.0f64); + assert_eq!(ff.b, 0xff_u8); + assert_eq!(ff.c, f.a - 1.0f64); } } diff --git a/src/test/run-pass/structured-compare.rs b/src/test/run-pass/structured-compare.rs index 4a8d155c73926..d03bc594bb42d 100644 --- a/src/test/run-pass/structured-compare.rs +++ b/src/test/run-pass/structured-compare.rs @@ -22,7 +22,7 @@ impl cmp::Eq for foo { pub fn main() { let a = (1, 2, 3); let b = (1, 2, 3); - assert!((a == b)); + assert_eq!(a, b); assert!((a != (1, 2, 4))); assert!((a < (1, 2, 4))); assert!((a <= (1, 2, 4))); @@ -31,6 +31,6 @@ pub fn main() { let x = large; let y = small; assert!((x != y)); - assert!((x == large)); + assert_eq!(x, large); assert!((x != small)); } diff --git a/src/test/run-pass/swap-2.rs b/src/test/run-pass/swap-2.rs index 63b377b26d83e..738460def923a 100644 --- a/src/test/run-pass/swap-2.rs +++ b/src/test/run-pass/swap-2.rs @@ -13,10 +13,10 @@ use core::util; pub fn main() { let mut a: ~[int] = ~[0, 1, 2, 3, 4, 5, 6]; vec::swap(a, 2, 4); - assert!((a[2] == 4)); - assert!((a[4] == 2)); + assert_eq!(a[2], 4); + assert_eq!(a[4], 2); let mut n = 42; util::swap(&mut n, &mut a[0]); - assert!((a[0] == 42)); - assert!((n == 0)); + assert_eq!(a[0], 42); + assert_eq!(n, 0); } diff --git a/src/test/run-pass/syntax-extension-fmt.rs b/src/test/run-pass/syntax-extension-fmt.rs index a61feadfc9464..936c71dc0f3c3 100644 --- a/src/test/run-pass/syntax-extension-fmt.rs +++ b/src/test/run-pass/syntax-extension-fmt.rs @@ -13,7 +13,7 @@ extern mod std; fn test(actual: ~str, expected: ~str) { debug!(actual.clone()); debug!(expected.clone()); - assert!((actual == expected)); + assert_eq!(actual, expected); } pub fn main() { @@ -250,13 +250,13 @@ fn part6() { fn percent() { let s = fmt!("ab%%cd"); - assert!((s == ~"ab%cd")); + assert_eq!(s, ~"ab%cd"); } fn more_floats() { - assert!(~"3.1416" == fmt!("%.4f", 3.14159)); - assert!(~"3" == fmt!("%.0f", 3.14159)); - assert!(~"99" == fmt!("%.0f", 98.5)); - assert!(~"7.0000" == fmt!("%.4f", 6.999999999)); - assert!(~"3.141590000" == fmt!("%.9f", 3.14159)); + assert_eq!(~"3.1416", fmt!("%.4f", 3.14159)); + assert_eq!(~"3", fmt!("%.0f", 3.14159)); + assert_eq!(~"99", fmt!("%.0f", 98.5)); + assert_eq!(~"7.0000", fmt!("%.4f", 6.999999999)); + assert_eq!(~"3.141590000", fmt!("%.9f", 3.14159)); } diff --git a/src/test/run-pass/syntax-extension-minor.rs b/src/test/run-pass/syntax-extension-minor.rs index ac0b63e98ca61..497a55b7c78e2 100644 --- a/src/test/run-pass/syntax-extension-minor.rs +++ b/src/test/run-pass/syntax-extension-minor.rs @@ -11,7 +11,7 @@ pub fn main() { let asdf_fdsa = ~"<.<"; - assert!((concat_idents!(asd, f_f, dsa) == ~"<.<")); + assert_eq!(concat_idents!(asd, f_f, dsa), ~"<.<"); assert!(stringify!(use_mention_distinction) == ~"use_mention_distinction"); diff --git a/src/test/run-pass/syntax-extension-source-utils.rs b/src/test/run-pass/syntax-extension-source-utils.rs index 7b52f52137ec0..eceba6cf7b18e 100644 --- a/src/test/run-pass/syntax-extension-source-utils.rs +++ b/src/test/run-pass/syntax-extension-source-utils.rs @@ -20,11 +20,11 @@ pub mod m1 { macro_rules! indirect_line( () => ( line!() ) ) pub fn main() { - assert!((line!() == 23)); + assert_eq!(line!(), 23); //assert!((col!() == 11)); - assert!((indirect_line!() == 25)); + assert_eq!(indirect_line!(), 25); assert!((file!().to_owned().ends_with(~"syntax-extension-source-utils.rs"))); - assert!((stringify!((2*3) + 5).to_owned() == ~"( 2 * 3 ) + 5")); + assert_eq!(stringify!((2*3) + 5).to_owned(), ~"( 2 * 3 ) + 5"); assert!(include!("syntax-extension-source-utils-files/includeme.fragment").to_owned() == ~"victory robot 6"); diff --git a/src/test/run-pass/tag-disr-val-shape.rs b/src/test/run-pass/tag-disr-val-shape.rs index dd78dff0d6ea7..a562b79e4fd06 100644 --- a/src/test/run-pass/tag-disr-val-shape.rs +++ b/src/test/run-pass/tag-disr-val-shape.rs @@ -19,7 +19,7 @@ enum color { pub fn main() { let act = fmt!("%?", red); io::println(act); - assert!(~"red" == act); - assert!(~"green" == fmt!("%?", green)); - assert!(~"white" == fmt!("%?", white)); + assert_eq!(~"red", act); + assert_eq!(~"green", fmt!("%?", green)); + assert_eq!(~"white", fmt!("%?", white)); } diff --git a/src/test/run-pass/tag-variant-disr-val.rs b/src/test/run-pass/tag-variant-disr-val.rs index d4eadd366de06..d1e26a9c50c4a 100644 --- a/src/test/run-pass/tag-variant-disr-val.rs +++ b/src/test/run-pass/tag-variant-disr-val.rs @@ -39,8 +39,8 @@ pub fn main() { fn test_color(color: color, val: int, name: ~str) { //assert!(unsafe::transmute(color) == val); - assert!(color as int == val); - assert!(color as float == val as float); + assert_eq!(color as int, val); + assert_eq!(color as float, val as float); assert!(get_color_alt(color) == name); assert!(get_color_if(color) == name); } diff --git a/src/test/run-pass/task-comm-0.rs b/src/test/run-pass/task-comm-0.rs index 6fc29fa32db32..bd5575f61549d 100644 --- a/src/test/run-pass/task-comm-0.rs +++ b/src/test/run-pass/task-comm-0.rs @@ -35,5 +35,5 @@ fn test05() { error!(value); value = po.recv(); error!(value); - assert!((value == 30)); + assert_eq!(value, 30); } diff --git a/src/test/run-pass/task-comm-16.rs b/src/test/run-pass/task-comm-16.rs index 237c721129fe5..c9e8ae3ab7981 100644 --- a/src/test/run-pass/task-comm-16.rs +++ b/src/test/run-pass/task-comm-16.rs @@ -19,9 +19,9 @@ fn test_rec() { ch.send(r0); let mut r1: R; r1 = po.recv(); - assert!((r1.val0 == 0)); - assert!((r1.val1 == 1u8)); - assert!((r1.val2 == '2')); + assert_eq!(r1.val0, 0); + assert_eq!(r1.val1, 1u8); + assert_eq!(r1.val2, '2'); } fn test_vec() { @@ -29,9 +29,9 @@ fn test_vec() { let v0: ~[int] = ~[0, 1, 2]; ch.send(v0); let v1 = po.recv(); - assert!((v1[0] == 0)); - assert!((v1[1] == 1)); - assert!((v1[2] == 2)); + assert_eq!(v1[0], 0); + assert_eq!(v1[1], 1); + assert_eq!(v1[2], 2); } fn test_str() { @@ -39,10 +39,10 @@ fn test_str() { let s0 = ~"test"; ch.send(s0); let s1 = po.recv(); - assert!((s1[0] == 't' as u8)); - assert!((s1[1] == 'e' as u8)); - assert!((s1[2] == 's' as u8)); - assert!((s1[3] == 't' as u8)); + assert_eq!(s1[0], 't' as u8); + assert_eq!(s1[1], 'e' as u8); + assert_eq!(s1[2], 's' as u8); + assert_eq!(s1[3], 't' as u8); } enum t { @@ -85,11 +85,11 @@ fn test_tag() { ch.send(tag3(10, 11u8, 'A')); let mut t1: t; t1 = po.recv(); - assert!((t1 == tag1)); + assert_eq!(t1, tag1); t1 = po.recv(); - assert!((t1 == tag2(10))); + assert_eq!(t1, tag2(10)); t1 = po.recv(); - assert!((t1 == tag3(10, 11u8, 'A'))); + assert_eq!(t1, tag3(10, 11u8, 'A')); } fn test_chan() { @@ -102,7 +102,7 @@ fn test_chan() { ch1.send(10); let mut i: int; i = po0.recv(); - assert!((i == 10)); + assert_eq!(i, 10); } pub fn main() { diff --git a/src/test/run-pass/task-comm-3.rs b/src/test/run-pass/task-comm-3.rs index fd700475988cf..1a3dc678d4211 100644 --- a/src/test/run-pass/task-comm-3.rs +++ b/src/test/run-pass/task-comm-3.rs @@ -67,5 +67,5 @@ fn test00() { error!(sum); // assert (sum == (((number_of_tasks * (number_of_tasks - 1)) / 2) * // number_of_messages)); - assert!((sum == 480)); + assert_eq!(sum, 480); } diff --git a/src/test/run-pass/task-comm-4.rs b/src/test/run-pass/task-comm-4.rs index 3b606642571c8..a1afefed2ee0f 100644 --- a/src/test/run-pass/task-comm-4.rs +++ b/src/test/run-pass/task-comm-4.rs @@ -46,5 +46,5 @@ fn test00() { r = p.recv(); sum += r; debug!(r); - assert!((sum == 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8)); + assert_eq!(sum, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8); } diff --git a/src/test/run-pass/task-comm-5.rs b/src/test/run-pass/task-comm-5.rs index 7522a092872ad..b6a517a6f8141 100644 --- a/src/test/run-pass/task-comm-5.rs +++ b/src/test/run-pass/task-comm-5.rs @@ -21,5 +21,5 @@ fn test00() { while i < number_of_messages { c.send(i + 0); i += 1; } i = 0; while i < number_of_messages { sum += p.recv(); i += 1; } - assert!((sum == number_of_messages * (number_of_messages - 1) / 2)); + assert_eq!(sum, number_of_messages * (number_of_messages - 1) / 2); } diff --git a/src/test/run-pass/task-comm-6.rs b/src/test/run-pass/task-comm-6.rs index 67ef5fb190526..38fdc2dc33e9a 100644 --- a/src/test/run-pass/task-comm-6.rs +++ b/src/test/run-pass/task-comm-6.rs @@ -41,7 +41,7 @@ fn test00() { sum += r; i += 1; } - assert!((sum == 1998000)); + assert_eq!(sum, 1998000); // assert (sum == 4 * ((number_of_messages * // (number_of_messages - 1)) / 2)); diff --git a/src/test/run-pass/task-comm-7.rs b/src/test/run-pass/task-comm-7.rs index 12f9a113dfc3e..227f8aadecdf4 100644 --- a/src/test/run-pass/task-comm-7.rs +++ b/src/test/run-pass/task-comm-7.rs @@ -55,5 +55,5 @@ fn test00() { i += 1; } - assert!((sum == number_of_messages * 4 * (number_of_messages * 4 - 1) / 2)); + assert_eq!(sum, number_of_messages * 4 * (number_of_messages * 4 - 1) / 2); } diff --git a/src/test/run-pass/task-comm-9.rs b/src/test/run-pass/task-comm-9.rs index 798e9d37b5534..f13377369651f 100644 --- a/src/test/run-pass/task-comm-9.rs +++ b/src/test/run-pass/task-comm-9.rs @@ -42,5 +42,5 @@ fn test00() { result.unwrap().recv(); - assert!((sum == number_of_messages * (number_of_messages - 1) / 2)); + assert_eq!(sum, number_of_messages * (number_of_messages - 1) / 2); } diff --git a/src/test/run-pass/task-comm-chan-nil.rs b/src/test/run-pass/task-comm-chan-nil.rs index bae3cbbf58729..ec534a6650042 100644 --- a/src/test/run-pass/task-comm-chan-nil.rs +++ b/src/test/run-pass/task-comm-chan-nil.rs @@ -19,5 +19,5 @@ pub fn main() { let (po, ch) = comm::stream(); ch.send(()); let n: () = po.recv(); - assert!((n == ())); + assert_eq!(n, ()); } diff --git a/src/test/run-pass/task-spawn-move-and-copy.rs b/src/test/run-pass/task-spawn-move-and-copy.rs index ba10bfb670452..f67cc0d51af04 100644 --- a/src/test/run-pass/task-spawn-move-and-copy.rs +++ b/src/test/run-pass/task-spawn-move-and-copy.rs @@ -22,5 +22,5 @@ pub fn main() { }); let x_in_child = p.recv(); - assert!(x_in_parent == x_in_child); + assert_eq!(x_in_parent, x_in_child); } diff --git a/src/test/run-pass/trait-bounds.rs b/src/test/run-pass/trait-bounds.rs index 3bdd9aa508803..7ec6ffbd46458 100644 --- a/src/test/run-pass/trait-bounds.rs +++ b/src/test/run-pass/trait-bounds.rs @@ -31,5 +31,5 @@ pub fn main() { let factory = (); let connection = factory.create(); let result = connection.read(); - assert!(result == 43); + assert_eq!(result, 43); } diff --git a/src/test/run-pass/trait-cast.rs b/src/test/run-pass/trait-cast.rs index 303eaa13af852..f21ea06697d8f 100644 --- a/src/test/run-pass/trait-cast.rs +++ b/src/test/run-pass/trait-cast.rs @@ -55,7 +55,7 @@ pub fn main() { right: Some(t1), val: 2 as to_str }); let expected = ~"[2, some([1, none, none]), some([1, none, none])]"; - assert!(t2.to_str() == expected); - assert!(foo(t2 as to_str) == expected); + assert_eq!(t2.to_str(), expected); + assert_eq!(foo(t2 as to_str), expected); t1.left = Some(t2); // create cycle } diff --git a/src/test/run-pass/trait-default-method-bound-subst.rs b/src/test/run-pass/trait-default-method-bound-subst.rs index a489f2b405ffc..dc0af7f7d5412 100644 --- a/src/test/run-pass/trait-default-method-bound-subst.rs +++ b/src/test/run-pass/trait-default-method-bound-subst.rs @@ -21,5 +21,5 @@ fn f>(i: V, j: T, k: U) -> (T, U) { } pub fn main () { - assert!(f(0, 1, 2) == (1, 2)); + assert_eq!(f(0, 1, 2), (1, 2)); } diff --git a/src/test/run-pass/trait-default-method-bound-subst2.rs b/src/test/run-pass/trait-default-method-bound-subst2.rs index 4203f73236e13..93cc752527b80 100644 --- a/src/test/run-pass/trait-default-method-bound-subst2.rs +++ b/src/test/run-pass/trait-default-method-bound-subst2.rs @@ -21,5 +21,5 @@ fn f>(i: V, j: T) -> T { } pub fn main () { - assert!(f(0, 2) == 2); + assert_eq!(f(0, 2), 2); } diff --git a/src/test/run-pass/trait-default-method-bound-subst3.rs b/src/test/run-pass/trait-default-method-bound-subst3.rs index 11830e7e7d248..cb86736b79dab 100644 --- a/src/test/run-pass/trait-default-method-bound-subst3.rs +++ b/src/test/run-pass/trait-default-method-bound-subst3.rs @@ -21,6 +21,6 @@ fn f(i: V, j: T, k: T) -> (T, T) { } pub fn main () { - assert!(f(0, 1, 2) == (1, 2)); - assert!(f(0, 1u8, 2u8) == (1u8, 2u8)); + assert_eq!(f(0, 1, 2), (1, 2)); + assert_eq!(f(0, 1u8, 2u8), (1u8, 2u8)); } diff --git a/src/test/run-pass/trait-default-method-bound-subst4.rs b/src/test/run-pass/trait-default-method-bound-subst4.rs index 285d31152e2ab..d386fd44b6b13 100644 --- a/src/test/run-pass/trait-default-method-bound-subst4.rs +++ b/src/test/run-pass/trait-default-method-bound-subst4.rs @@ -21,6 +21,6 @@ fn f>(i: V, j: uint) -> uint { } pub fn main () { - assert!(f::(0, 2u) == 2u); - assert!(f::(0, 2u) == 2u); + assert_eq!(f::(0, 2u), 2u); + assert_eq!(f::(0, 2u), 2u); } diff --git a/src/test/run-pass/trait-default-method-bound.rs b/src/test/run-pass/trait-default-method-bound.rs index 756af0d63fdef..ce2df508f70e1 100644 --- a/src/test/run-pass/trait-default-method-bound.rs +++ b/src/test/run-pass/trait-default-method-bound.rs @@ -17,7 +17,7 @@ trait A { impl A for int { } fn f(i: T) { - assert!(i.g() == 10); + assert_eq!(i.g(), 10); } pub fn main () { diff --git a/src/test/run-pass/trait-generic.rs b/src/test/run-pass/trait-generic.rs index eacd51266adc2..fedf6e25ec399 100644 --- a/src/test/run-pass/trait-generic.rs +++ b/src/test/run-pass/trait-generic.rs @@ -42,8 +42,8 @@ fn bar>(x: T) -> ~[~str] { } pub fn main() { - assert!(foo(~[1]) == ~[~"hi"]); - assert!(bar::(~[4, 5]) == ~[~"4", ~"5"]); - assert!(bar::<~str, ~[~str]>(~[~"x", ~"y"]) == ~[~"x", ~"y"]); - assert!(bar::<(), ~[()]>(~[()]) == ~[~"()"]); + assert_eq!(foo(~[1]), ~[~"hi"]); + assert_eq!(bar::(~[4, 5]), ~[~"4", ~"5"]); + assert_eq!(bar::<~str, ~[~str]>(~[~"x", ~"y"]), ~[~"x", ~"y"]); + assert_eq!(bar::<(), ~[()]>(~[()]), ~[~"()"]); } diff --git a/src/test/run-pass/trait-inheritance-auto-xc-2.rs b/src/test/run-pass/trait-inheritance-auto-xc-2.rs index 996f55d4019a8..3f8d536888469 100644 --- a/src/test/run-pass/trait-inheritance-auto-xc-2.rs +++ b/src/test/run-pass/trait-inheritance-auto-xc-2.rs @@ -21,9 +21,9 @@ pub trait Quux: Foo + Bar + Baz { } impl Quux for T { } fn f(a: &T) { - assert!(a.f() == 10); - assert!(a.g() == 20); - assert!(a.h() == 30); + assert_eq!(a.f(), 10); + assert_eq!(a.g(), 20); + assert_eq!(a.h(), 30); } pub fn main() { diff --git a/src/test/run-pass/trait-inheritance-auto-xc.rs b/src/test/run-pass/trait-inheritance-auto-xc.rs index 3af8d606bf4ae..2e8883f026788 100644 --- a/src/test/run-pass/trait-inheritance-auto-xc.rs +++ b/src/test/run-pass/trait-inheritance-auto-xc.rs @@ -22,9 +22,9 @@ impl Bar for A { fn g(&self) -> int { 20 } } impl Baz for A { fn h(&self) -> int { 30 } } fn f(a: &T) { - assert!(a.f() == 10); - assert!(a.g() == 20); - assert!(a.h() == 30); + assert_eq!(a.f(), 10); + assert_eq!(a.g(), 20); + assert_eq!(a.h(), 30); } pub fn main() { diff --git a/src/test/run-pass/trait-inheritance-auto.rs b/src/test/run-pass/trait-inheritance-auto.rs index fb97dd5e7741a..c5a7720e3c341 100644 --- a/src/test/run-pass/trait-inheritance-auto.rs +++ b/src/test/run-pass/trait-inheritance-auto.rs @@ -25,9 +25,9 @@ impl Bar for A { fn g(&self) -> int { 20 } } impl Baz for A { fn h(&self) -> int { 30 } } fn f(a: &T) { - assert!(a.f() == 10); - assert!(a.g() == 20); - assert!(a.h() == 30); + assert_eq!(a.f(), 10); + assert_eq!(a.g(), 20); + assert_eq!(a.h(), 30); } pub fn main() { diff --git a/src/test/run-pass/trait-inheritance-call-bound-inherited.rs b/src/test/run-pass/trait-inheritance-call-bound-inherited.rs index 805c9655d81d4..46258902f9cae 100644 --- a/src/test/run-pass/trait-inheritance-call-bound-inherited.rs +++ b/src/test/run-pass/trait-inheritance-call-bound-inherited.rs @@ -23,5 +23,5 @@ fn gg(a: &T) -> int { pub fn main() { let a = &A { x: 3 }; - assert!(gg(a) == 10); + assert_eq!(gg(a), 10); } diff --git a/src/test/run-pass/trait-inheritance-call-bound-inherited2.rs b/src/test/run-pass/trait-inheritance-call-bound-inherited2.rs index 0b35fd90bbd19..7b79ad42ed2b3 100644 --- a/src/test/run-pass/trait-inheritance-call-bound-inherited2.rs +++ b/src/test/run-pass/trait-inheritance-call-bound-inherited2.rs @@ -26,5 +26,5 @@ fn gg(a: &T) -> int { pub fn main() { let a = &A { x: 3 }; - assert!(gg(a) == 10); + assert_eq!(gg(a), 10); } diff --git a/src/test/run-pass/trait-inheritance-cast-without-call-to-supertrait.rs b/src/test/run-pass/trait-inheritance-cast-without-call-to-supertrait.rs index df9cc4fb8b6d4..68a31ba9dbe64 100644 --- a/src/test/run-pass/trait-inheritance-cast-without-call-to-supertrait.rs +++ b/src/test/run-pass/trait-inheritance-cast-without-call-to-supertrait.rs @@ -35,6 +35,6 @@ pub fn main() { let a = &A { x: 3 }; let afoo = a as &Foo; let abar = a as &Bar; - assert!(afoo.f() == 10); - assert!(abar.g() == 20); + assert_eq!(afoo.f(), 10); + assert_eq!(abar.g(), 20); } diff --git a/src/test/run-pass/trait-inheritance-cast.rs b/src/test/run-pass/trait-inheritance-cast.rs index 75c121e10b014..1f69ba29b09a7 100644 --- a/src/test/run-pass/trait-inheritance-cast.rs +++ b/src/test/run-pass/trait-inheritance-cast.rs @@ -36,7 +36,7 @@ pub fn main() { let a = &A { x: 3 }; let afoo = a as &Foo; let abar = a as &Bar; - assert!(afoo.f() == 10); - assert!(abar.g() == 20); - assert!(abar.f() == 10); + assert_eq!(afoo.f(), 10); + assert_eq!(abar.g(), 20); + assert_eq!(abar.f(), 10); } diff --git a/src/test/run-pass/trait-inheritance-cross-trait-call-xc.rs b/src/test/run-pass/trait-inheritance-cross-trait-call-xc.rs index 976c9a0243927..eddec87472c5a 100644 --- a/src/test/run-pass/trait-inheritance-cross-trait-call-xc.rs +++ b/src/test/run-pass/trait-inheritance-cross-trait-call-xc.rs @@ -25,5 +25,5 @@ impl Bar for aux::A { pub fn main() { let a = &aux::A { x: 3 }; - assert!(a.g() == 10); + assert_eq!(a.g(), 10); } diff --git a/src/test/run-pass/trait-inheritance-cross-trait-call.rs b/src/test/run-pass/trait-inheritance-cross-trait-call.rs index 20dac16b4927d..7b047b5cc800a 100644 --- a/src/test/run-pass/trait-inheritance-cross-trait-call.rs +++ b/src/test/run-pass/trait-inheritance-cross-trait-call.rs @@ -22,5 +22,5 @@ impl Bar for A { pub fn main() { let a = &A { x: 3 }; - assert!(a.g() == 10); + assert_eq!(a.g(), 10); } diff --git a/src/test/run-pass/trait-inheritance-diamond.rs b/src/test/run-pass/trait-inheritance-diamond.rs index abfbec6d35863..253c10ac6f1b0 100644 --- a/src/test/run-pass/trait-inheritance-diamond.rs +++ b/src/test/run-pass/trait-inheritance-diamond.rs @@ -23,10 +23,10 @@ impl C for S { fn c(&self) -> int { 30 } } impl D for S { fn d(&self) -> int { 40 } } fn f(x: &T) { - assert!(x.a() == 10); - assert!(x.b() == 20); - assert!(x.c() == 30); - assert!(x.d() == 40); + assert_eq!(x.a(), 10); + assert_eq!(x.b(), 20); + assert_eq!(x.c(), 30); + assert_eq!(x.d(), 40); } pub fn main() { diff --git a/src/test/run-pass/trait-inheritance-multiple-inheritors.rs b/src/test/run-pass/trait-inheritance-multiple-inheritors.rs index 5bd8f7f25ea09..6cd3d62473692 100644 --- a/src/test/run-pass/trait-inheritance-multiple-inheritors.rs +++ b/src/test/run-pass/trait-inheritance-multiple-inheritors.rs @@ -20,9 +20,9 @@ impl C for S { fn c(&self) -> int { 30 } } // Both B and C inherit from A fn f(x: &T) { - assert!(x.a() == 10); - assert!(x.b() == 20); - assert!(x.c() == 30); + assert_eq!(x.a(), 10); + assert_eq!(x.b(), 20); + assert_eq!(x.c(), 30); } pub fn main() { diff --git a/src/test/run-pass/trait-inheritance-multiple-params.rs b/src/test/run-pass/trait-inheritance-multiple-params.rs index e01860ba50336..b5524c6dda6cd 100644 --- a/src/test/run-pass/trait-inheritance-multiple-params.rs +++ b/src/test/run-pass/trait-inheritance-multiple-params.rs @@ -20,11 +20,11 @@ impl C for S { fn c(&self) -> int { 30 } } // Multiple type params, multiple levels of inheritance fn f(x: &X, y: &Y, z: &Z) { - assert!(x.a() == 10); - assert!(y.a() == 10); - assert!(y.b() == 20); - assert!(z.a() == 10); - assert!(z.c() == 30); + assert_eq!(x.a(), 10); + assert_eq!(y.a(), 10); + assert_eq!(y.b(), 20); + assert_eq!(z.a(), 10); + assert_eq!(z.c(), 30); } pub fn main() { diff --git a/src/test/run-pass/trait-inheritance-overloading-simple.rs b/src/test/run-pass/trait-inheritance-overloading-simple.rs index 3a1c3716df442..2e9b60303c6c3 100644 --- a/src/test/run-pass/trait-inheritance-overloading-simple.rs +++ b/src/test/run-pass/trait-inheritance-overloading-simple.rs @@ -30,5 +30,5 @@ fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y, z) = (mi(3), mi(5), mi(3)); assert!(x != y); - assert!(x == z); + assert_eq!(x, z); } diff --git a/src/test/run-pass/trait-inheritance-overloading-xc-exe.rs b/src/test/run-pass/trait-inheritance-overloading-xc-exe.rs index d89852e2b05f9..21f840ca8d346 100644 --- a/src/test/run-pass/trait-inheritance-overloading-xc-exe.rs +++ b/src/test/run-pass/trait-inheritance-overloading-xc-exe.rs @@ -23,7 +23,7 @@ fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y) = (mi(3), mi(5)); let (a, b, c) = f(x, y); - assert!(a == mi(8)); - assert!(b == mi(-2)); - assert!(c == mi(15)); + assert_eq!(a, mi(8)); + assert_eq!(b, mi(-2)); + assert_eq!(c, mi(15)); } diff --git a/src/test/run-pass/trait-inheritance-overloading.rs b/src/test/run-pass/trait-inheritance-overloading.rs index e58ec24f1b7d4..82c9091147dc4 100644 --- a/src/test/run-pass/trait-inheritance-overloading.rs +++ b/src/test/run-pass/trait-inheritance-overloading.rs @@ -42,7 +42,7 @@ fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y) = (mi(3), mi(5)); let (a, b, c) = f(x, y); - assert!(a == mi(8)); - assert!(b == mi(-2)); - assert!(c == mi(15)); + assert_eq!(a, mi(8)); + assert_eq!(b, mi(-2)); + assert_eq!(c, mi(15)); } diff --git a/src/test/run-pass/trait-inheritance-simple.rs b/src/test/run-pass/trait-inheritance-simple.rs index 2da1f02779e0a..113efa663afaf 100644 --- a/src/test/run-pass/trait-inheritance-simple.rs +++ b/src/test/run-pass/trait-inheritance-simple.rs @@ -26,6 +26,6 @@ fn gg(a: &T) -> int { pub fn main() { let a = &A { x: 3 }; - assert!(ff(a) == 10); - assert!(gg(a) == 20); + assert_eq!(ff(a), 10); + assert_eq!(gg(a), 20); } diff --git a/src/test/run-pass/trait-inheritance-static.rs b/src/test/run-pass/trait-inheritance-static.rs index 3b87387d4d6f1..08543b236f3dc 100644 --- a/src/test/run-pass/trait-inheritance-static.rs +++ b/src/test/run-pass/trait-inheritance-static.rs @@ -30,5 +30,5 @@ fn greater_than_one() -> T { MyNum::from_int(1) } pub fn main() { let v: S = greater_than_one(); - assert!(v.v == 1); + assert_eq!(v.v, 1); } diff --git a/src/test/run-pass/trait-inheritance-static2.rs b/src/test/run-pass/trait-inheritance-static2.rs index 2718949db070a..95131176ce752 100644 --- a/src/test/run-pass/trait-inheritance-static2.rs +++ b/src/test/run-pass/trait-inheritance-static2.rs @@ -34,5 +34,5 @@ fn greater_than_one() -> T { MyNum::from_int(1) } pub fn main() { let v: S = greater_than_one(); - assert!(v.v == 1); + assert_eq!(v.v, 1); } diff --git a/src/test/run-pass/trait-inheritance-subst2.rs b/src/test/run-pass/trait-inheritance-subst2.rs index 5d1741a45f327..214505172a51a 100644 --- a/src/test/run-pass/trait-inheritance-subst2.rs +++ b/src/test/run-pass/trait-inheritance-subst2.rs @@ -41,5 +41,5 @@ fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y) = (mi(3), mi(5)); let z = f(x, y); - assert!(z.val == 13); + assert_eq!(z.val, 13); } diff --git a/src/test/run-pass/trait-inheritance-visibility.rs b/src/test/run-pass/trait-inheritance-visibility.rs index 81f119612d994..3cdedd884a42c 100644 --- a/src/test/run-pass/trait-inheritance-visibility.rs +++ b/src/test/run-pass/trait-inheritance-visibility.rs @@ -20,7 +20,7 @@ impl Quux for T { } // Foo is not in scope but because Quux is we can still access // Foo's methods on a Quux bound typaram fn f(x: &T) { - assert!(x.f() == 10); + assert_eq!(x.f(), 10); } pub fn main() { diff --git a/src/test/run-pass/trait-inheritance2.rs b/src/test/run-pass/trait-inheritance2.rs index adb7ab018d6c4..6046da412174f 100644 --- a/src/test/run-pass/trait-inheritance2.rs +++ b/src/test/run-pass/trait-inheritance2.rs @@ -22,9 +22,9 @@ impl Baz for A { fn h(&self) -> int { 30 } } impl Quux for A; fn f(a: &T) { - assert!(a.f() == 10); - assert!(a.g() == 20); - assert!(a.h() == 30); + assert_eq!(a.f(), 10); + assert_eq!(a.g(), 20); + assert_eq!(a.h(), 30); } pub fn main() { diff --git a/src/test/run-pass/trait-region-pointer-simple.rs b/src/test/run-pass/trait-region-pointer-simple.rs index a2742828a1bc0..7162420dbc3fc 100644 --- a/src/test/run-pass/trait-region-pointer-simple.rs +++ b/src/test/run-pass/trait-region-pointer-simple.rs @@ -26,5 +26,5 @@ impl Foo for A { pub fn main() { let a = A { x: 3 }; let b = (&a) as &Foo; - assert!(b.f() == 3); + assert_eq!(b.f(), 3); } diff --git a/src/test/run-pass/trait_with_static_methods_cross_crate.rs b/src/test/run-pass/trait_with_static_methods_cross_crate.rs index 1af8629468024..20dcbf3267b70 100644 --- a/src/test/run-pass/trait_with_static_methods_cross_crate.rs +++ b/src/test/run-pass/trait_with_static_methods_cross_crate.rs @@ -15,5 +15,5 @@ extern mod mod_trait_with_static_methods_lib; use mod_trait_with_static_methods_lib::Foo; pub fn main() { - assert!(42 == Foo::foo()); + assert_eq!(42, Foo::foo()); } diff --git a/src/test/run-pass/traits-default-method-macro.rs b/src/test/run-pass/traits-default-method-macro.rs index 7f106f71f8ed0..b25f345b9dec2 100644 --- a/src/test/run-pass/traits-default-method-macro.rs +++ b/src/test/run-pass/traits-default-method-macro.rs @@ -25,5 +25,5 @@ impl Foo for Baz { pub fn main() { let q = Quux; - assert!(q.bar() == ~"test"); + assert_eq!(q.bar(), ~"test"); } diff --git a/src/test/run-pass/tup.rs b/src/test/run-pass/tup.rs index c1a34a326a6e5..795ed1d0f8a01 100644 --- a/src/test/run-pass/tup.rs +++ b/src/test/run-pass/tup.rs @@ -13,15 +13,15 @@ type point = (int, int); fn f(p: point, x: int, y: int) { let (a, b) = p; - assert!((a == x)); - assert!((b == y)); + assert_eq!(a, x); + assert_eq!(b, y); } pub fn main() { let p: point = (10, 20); let (a, b) = p; - assert!((a == 10)); - assert!((b == 20)); + assert_eq!(a, 10); + assert_eq!(b, 20); let p2: point = p; f(p, 10, 20); f(p2, 10, 20); diff --git a/src/test/run-pass/tuple-struct-destructuring.rs b/src/test/run-pass/tuple-struct-destructuring.rs index 1cb944da0403e..c7dc132f3b74b 100644 --- a/src/test/run-pass/tuple-struct-destructuring.rs +++ b/src/test/run-pass/tuple-struct-destructuring.rs @@ -14,6 +14,6 @@ pub fn main() { let x = Foo(1, 2); let Foo(y, z) = x; io::println(fmt!("%d %d", y, z)); - assert!(y == 1); - assert!(z == 2); + assert_eq!(y, 1); + assert_eq!(z, 2); } diff --git a/src/test/run-pass/tuple-struct-matching.rs b/src/test/run-pass/tuple-struct-matching.rs index e3cbd1201c127..037f847629cbe 100644 --- a/src/test/run-pass/tuple-struct-matching.rs +++ b/src/test/run-pass/tuple-struct-matching.rs @@ -14,8 +14,8 @@ pub fn main() { let x = Foo(1, 2); match x { Foo(a, b) => { - assert!(a == 1); - assert!(b == 2); + assert_eq!(a, 1); + assert_eq!(b, 2); io::println(fmt!("%d %d", a, b)); } } diff --git a/src/test/run-pass/type-sizes.rs b/src/test/run-pass/type-sizes.rs index 134f1e4098f07..adb3ae9557be1 100644 --- a/src/test/run-pass/type-sizes.rs +++ b/src/test/run-pass/type-sizes.rs @@ -20,19 +20,19 @@ struct x {a: int, b: (), c: ()} struct y {x: int} pub fn main() { - assert!((size_of::() == 1 as uint)); - assert!((size_of::() == 4 as uint)); - assert!((size_of::() == 4 as uint)); - assert!((size_of::() == 1 as uint)); - assert!((size_of::() == 4 as uint)); - assert!((size_of::() == 2 as uint)); - assert!((size_of::() == 3 as uint)); + assert_eq!(size_of::(), 1 as uint); + assert_eq!(size_of::(), 4 as uint); + assert_eq!(size_of::(), 4 as uint); + assert_eq!(size_of::(), 1 as uint); + assert_eq!(size_of::(), 4 as uint); + assert_eq!(size_of::(), 2 as uint); + assert_eq!(size_of::(), 3 as uint); // Alignment causes padding before the char and the u32. assert!(size_of::() == 16 as uint); - assert!((size_of::() == size_of::())); - assert!((size_of::() == size_of::())); - assert!((size_of::() == size_of::())); - assert!((size_of::() == size_of::())); + assert_eq!(size_of::(), size_of::()); + assert_eq!(size_of::(), size_of::()); + assert_eq!(size_of::(), size_of::()); + assert_eq!(size_of::(), size_of::()); } diff --git a/src/test/run-pass/u32-decr.rs b/src/test/run-pass/u32-decr.rs index 2b68e89ed26dd..f40d06f6c92dc 100644 --- a/src/test/run-pass/u32-decr.rs +++ b/src/test/run-pass/u32-decr.rs @@ -15,5 +15,5 @@ pub fn main() { let mut word: u32 = 200000u32; word = word - 1u32; - assert!((word == 199999u32)); + assert_eq!(word, 199999u32); } diff --git a/src/test/run-pass/u8-incr-decr.rs b/src/test/run-pass/u8-incr-decr.rs index e864cd0ad4ab4..18543599fd0bb 100644 --- a/src/test/run-pass/u8-incr-decr.rs +++ b/src/test/run-pass/u8-incr-decr.rs @@ -24,5 +24,5 @@ pub fn main() { y = y - 9u8; // 0x9 - assert!((x == y)); + assert_eq!(x, y); } diff --git a/src/test/run-pass/u8-incr.rs b/src/test/run-pass/u8-incr.rs index c9d31fb72b7c5..1a4013645e8ef 100644 --- a/src/test/run-pass/u8-incr.rs +++ b/src/test/run-pass/u8-incr.rs @@ -17,7 +17,7 @@ pub fn main() { let y: u8 = 12u8; x = x + 1u8; x = x - 1u8; - assert!((x == y)); + assert_eq!(x, y); // x = 14u8; // x = x + 1u8; diff --git a/src/test/run-pass/unique-assign-copy.rs b/src/test/run-pass/unique-assign-copy.rs index d05cb76e11335..e59fe469dec6f 100644 --- a/src/test/run-pass/unique-assign-copy.rs +++ b/src/test/run-pass/unique-assign-copy.rs @@ -15,6 +15,6 @@ pub fn main() { j = i.clone(); *i = 2; *j = 3; - assert!(*i == 2); - assert!(*j == 3); + assert_eq!(*i, 2); + assert_eq!(*j, 3); } diff --git a/src/test/run-pass/unique-assign-drop.rs b/src/test/run-pass/unique-assign-drop.rs index 0faa6b1b555f6..2205eaeb97cc9 100644 --- a/src/test/run-pass/unique-assign-drop.rs +++ b/src/test/run-pass/unique-assign-drop.rs @@ -13,5 +13,5 @@ pub fn main() { let mut j = ~2; // Should drop the previous value of j j = i; - assert!(*j == 1); + assert_eq!(*j, 1); } diff --git a/src/test/run-pass/unique-assign-generic.rs b/src/test/run-pass/unique-assign-generic.rs index 75753b31ed7e2..67ffc797ee4bf 100644 --- a/src/test/run-pass/unique-assign-generic.rs +++ b/src/test/run-pass/unique-assign-generic.rs @@ -15,7 +15,7 @@ fn f(t: T) -> T { pub fn main() { let t = f(~100); - assert!(t == ~100); + assert_eq!(t, ~100); let t = f(~@~[100]); - assert!(t == ~@~[100]); + assert_eq!(t, ~@~[100]); } diff --git a/src/test/run-pass/unique-assign.rs b/src/test/run-pass/unique-assign.rs index 6fc16cae76f1d..43df53c78a8dd 100644 --- a/src/test/run-pass/unique-assign.rs +++ b/src/test/run-pass/unique-assign.rs @@ -11,5 +11,5 @@ pub fn main() { let mut i; i = ~1; - assert!(*i == 1); + assert_eq!(*i, 1); } diff --git a/src/test/run-pass/unique-autoderef-field.rs b/src/test/run-pass/unique-autoderef-field.rs index 07105a53caf27..6836ba4e79b00 100644 --- a/src/test/run-pass/unique-autoderef-field.rs +++ b/src/test/run-pass/unique-autoderef-field.rs @@ -14,5 +14,5 @@ pub fn main() { let i = ~J { j: 100 }; - assert!(i.j == 100); + assert_eq!(i.j, 100); } diff --git a/src/test/run-pass/unique-autoderef-index.rs b/src/test/run-pass/unique-autoderef-index.rs index 324efe5abe5c8..46f9ca794a9fe 100644 --- a/src/test/run-pass/unique-autoderef-index.rs +++ b/src/test/run-pass/unique-autoderef-index.rs @@ -10,5 +10,5 @@ pub fn main() { let i = ~~[100]; - assert!(i[0] == 100); + assert_eq!(i[0], 100); } diff --git a/src/test/run-pass/unique-containing-tag.rs b/src/test/run-pass/unique-containing-tag.rs index c8ed7b10a1ffa..ba5627fee5229 100644 --- a/src/test/run-pass/unique-containing-tag.rs +++ b/src/test/run-pass/unique-containing-tag.rs @@ -15,14 +15,14 @@ pub fn main() { /*alt *x { t1(a) { - assert!(a == 10); + assert_eq!(a, 10); } _ { fail!(); } }*/ /*alt x { ~t1(a) { - assert!(a == 10); + assert_eq!(a, 10); } _ { fail!(); } }*/ diff --git a/src/test/run-pass/unique-copy-box.rs b/src/test/run-pass/unique-copy-box.rs index b483881f1a63c..38a608c191bc5 100644 --- a/src/test/run-pass/unique-copy-box.rs +++ b/src/test/run-pass/unique-copy-box.rs @@ -16,6 +16,6 @@ pub fn main() { let j = copy i; let rc2 = sys::refcount(*i); error!("rc1: %u rc2: %u", rc1, rc2); - assert!(rc1 + 1u == rc2); + assert_eq!(rc1 + 1u, rc2); } } diff --git a/src/test/run-pass/unique-decl-init-copy.rs b/src/test/run-pass/unique-decl-init-copy.rs index 670bc35d85748..13594d86f6764 100644 --- a/src/test/run-pass/unique-decl-init-copy.rs +++ b/src/test/run-pass/unique-decl-init-copy.rs @@ -14,6 +14,6 @@ pub fn main() { let mut j = i.clone(); *i = 2; *j = 3; - assert!(*i == 2); - assert!(*j == 3); + assert_eq!(*i, 2); + assert_eq!(*j, 3); } diff --git a/src/test/run-pass/unique-decl-init.rs b/src/test/run-pass/unique-decl-init.rs index f5f1829cae047..c507d19fac16b 100644 --- a/src/test/run-pass/unique-decl-init.rs +++ b/src/test/run-pass/unique-decl-init.rs @@ -11,5 +11,5 @@ pub fn main() { let i = ~1; let j = i; - assert!(*j == 1); + assert_eq!(*j, 1); } diff --git a/src/test/run-pass/unique-decl-move-temp.rs b/src/test/run-pass/unique-decl-move-temp.rs index b9f122acbcd7f..6cf781d735cfa 100644 --- a/src/test/run-pass/unique-decl-move-temp.rs +++ b/src/test/run-pass/unique-decl-move-temp.rs @@ -10,5 +10,5 @@ pub fn main() { let i = ~100; - assert!(*i == 100); + assert_eq!(*i, 100); } diff --git a/src/test/run-pass/unique-decl-move.rs b/src/test/run-pass/unique-decl-move.rs index 81c59bae35708..335275ff7c102 100644 --- a/src/test/run-pass/unique-decl-move.rs +++ b/src/test/run-pass/unique-decl-move.rs @@ -11,5 +11,5 @@ pub fn main() { let i = ~100; let j = i; - assert!(*j == 100); + assert_eq!(*j, 100); } diff --git a/src/test/run-pass/unique-deref.rs b/src/test/run-pass/unique-deref.rs index b9f122acbcd7f..6cf781d735cfa 100644 --- a/src/test/run-pass/unique-deref.rs +++ b/src/test/run-pass/unique-deref.rs @@ -10,5 +10,5 @@ pub fn main() { let i = ~100; - assert!(*i == 100); + assert_eq!(*i, 100); } diff --git a/src/test/run-pass/unique-destructure.rs b/src/test/run-pass/unique-destructure.rs index 64e01f8647465..6c35cb4dba77b 100644 --- a/src/test/run-pass/unique-destructure.rs +++ b/src/test/run-pass/unique-destructure.rs @@ -12,5 +12,5 @@ struct Foo { a: int, b: int } pub fn main() { let ~Foo{a, b} = ~Foo{a: 100, b: 200}; - assert!(a + b == 300); + assert_eq!(a + b, 300); } diff --git a/src/test/run-pass/unique-fn-arg-move.rs b/src/test/run-pass/unique-fn-arg-move.rs index 4a6386244f177..503bbae8c55a9 100644 --- a/src/test/run-pass/unique-fn-arg-move.rs +++ b/src/test/run-pass/unique-fn-arg-move.rs @@ -9,7 +9,7 @@ // except according to those terms. fn f(i: ~int) { - assert!(*i == 100); + assert_eq!(*i, 100); } pub fn main() { diff --git a/src/test/run-pass/unique-fn-arg-mut.rs b/src/test/run-pass/unique-fn-arg-mut.rs index 56ec9663ec626..c2d78c3303902 100644 --- a/src/test/run-pass/unique-fn-arg-mut.rs +++ b/src/test/run-pass/unique-fn-arg-mut.rs @@ -15,5 +15,5 @@ fn f(i: &mut ~int) { pub fn main() { let mut i = ~100; f(&mut i); - assert!(*i == 200); + assert_eq!(*i, 200); } diff --git a/src/test/run-pass/unique-fn-arg.rs b/src/test/run-pass/unique-fn-arg.rs index 931c5acbe1d76..230131bae62bc 100644 --- a/src/test/run-pass/unique-fn-arg.rs +++ b/src/test/run-pass/unique-fn-arg.rs @@ -9,7 +9,7 @@ // except according to those terms. fn f(i: ~int) { - assert!(*i == 100); + assert_eq!(*i, 100); } pub fn main() { diff --git a/src/test/run-pass/unique-fn-ret.rs b/src/test/run-pass/unique-fn-ret.rs index 0ef9d12f75b0d..dd39e136fc9bb 100644 --- a/src/test/run-pass/unique-fn-ret.rs +++ b/src/test/run-pass/unique-fn-ret.rs @@ -13,5 +13,5 @@ fn f() -> ~int { } pub fn main() { - assert!(f() == ~100); + assert_eq!(f(), ~100); } diff --git a/src/test/run-pass/unique-in-vec-copy.rs b/src/test/run-pass/unique-in-vec-copy.rs index e72262795796c..3a27d7844bcad 100644 --- a/src/test/run-pass/unique-in-vec-copy.rs +++ b/src/test/run-pass/unique-in-vec-copy.rs @@ -12,12 +12,12 @@ pub fn main() { let mut a = ~[~10]; let b = a.clone(); - assert!(*a[0] == 10); - assert!(*b[0] == 10); + assert_eq!(*a[0], 10); + assert_eq!(*b[0], 10); // This should only modify the value in a, not b *a[0] = 20; - assert!(*a[0] == 20); - assert!(*b[0] == 10); + assert_eq!(*a[0], 20); + assert_eq!(*b[0], 10); } diff --git a/src/test/run-pass/unique-kinds.rs b/src/test/run-pass/unique-kinds.rs index da48f2ff51ba8..dbbd238cbac22 100644 --- a/src/test/run-pass/unique-kinds.rs +++ b/src/test/run-pass/unique-kinds.rs @@ -13,7 +13,7 @@ use core::cmp::Eq; fn sendable() { fn f(i: T, j: T) { - assert!(i == j); + assert_eq!(i, j); } fn g(i: T, j: T) { @@ -31,7 +31,7 @@ fn sendable() { fn copyable() { fn f(i: T, j: T) { - assert!(i == j); + assert_eq!(i, j); } fn g(i: T, j: T) { @@ -49,7 +49,7 @@ fn copyable() { fn noncopyable() { fn f(i: T, j: T) { - assert!(i == j); + assert_eq!(i, j); } fn g(i: T, j: T) { diff --git a/src/test/run-pass/unique-move-drop.rs b/src/test/run-pass/unique-move-drop.rs index 5ddc85ea5faa6..29267956a59f4 100644 --- a/src/test/run-pass/unique-move-drop.rs +++ b/src/test/run-pass/unique-move-drop.rs @@ -12,5 +12,5 @@ pub fn main() { let i = ~100; let j = ~200; let j = i; - assert!(*j == 100); + assert_eq!(*j, 100); } diff --git a/src/test/run-pass/unique-move-temp.rs b/src/test/run-pass/unique-move-temp.rs index 343b0d431428b..7c7ca1379ea29 100644 --- a/src/test/run-pass/unique-move-temp.rs +++ b/src/test/run-pass/unique-move-temp.rs @@ -11,5 +11,5 @@ pub fn main() { let mut i; i = ~100; - assert!(*i == 100); + assert_eq!(*i, 100); } diff --git a/src/test/run-pass/unique-move.rs b/src/test/run-pass/unique-move.rs index 3331350facdcb..dbdfc5cb5bb5f 100644 --- a/src/test/run-pass/unique-move.rs +++ b/src/test/run-pass/unique-move.rs @@ -12,5 +12,5 @@ pub fn main() { let i = ~100; let mut j; j = i; - assert!(*j == 100); + assert_eq!(*j, 100); } diff --git a/src/test/run-pass/unique-mutable.rs b/src/test/run-pass/unique-mutable.rs index e4a1b4a548b4b..4f353c566717c 100644 --- a/src/test/run-pass/unique-mutable.rs +++ b/src/test/run-pass/unique-mutable.rs @@ -11,5 +11,5 @@ pub fn main() { let mut i = ~0; *i = 1; - assert!(*i == 1); + assert_eq!(*i, 1); } diff --git a/src/test/run-pass/unique-object.rs b/src/test/run-pass/unique-object.rs index 5e0954969ef8d..e645f13cd4c51 100644 --- a/src/test/run-pass/unique-object.rs +++ b/src/test/run-pass/unique-object.rs @@ -25,5 +25,5 @@ impl Foo for Bar { pub fn main() { let x = ~Bar { x: 10 }; let y = x as ~Foo; - assert!(y.f() == 10); + assert_eq!(y.f(), 10); } diff --git a/src/test/run-pass/unique-pinned-nocopy-2.rs b/src/test/run-pass/unique-pinned-nocopy-2.rs index d3cdc9a878875..197f26f897d86 100644 --- a/src/test/run-pass/unique-pinned-nocopy-2.rs +++ b/src/test/run-pass/unique-pinned-nocopy-2.rs @@ -32,5 +32,5 @@ pub fn main() { { let j = ~r(i); } - assert!(*i == 1); + assert_eq!(*i, 1); } diff --git a/src/test/run-pass/unique-rec.rs b/src/test/run-pass/unique-rec.rs index 0564c2ebddd12..f740dd2a22cdb 100644 --- a/src/test/run-pass/unique-rec.rs +++ b/src/test/run-pass/unique-rec.rs @@ -13,5 +13,5 @@ struct X { x: int } pub fn main() { let x = ~X {x: 1}; let bar = x; - assert!(bar.x == 1); + assert_eq!(bar.x, 1); } diff --git a/src/test/run-pass/unique-send-2.rs b/src/test/run-pass/unique-send-2.rs index df1c8708acd11..9b522490f988a 100644 --- a/src/test/run-pass/unique-send-2.rs +++ b/src/test/run-pass/unique-send-2.rs @@ -31,5 +31,5 @@ pub fn main() { actual += *j; } - assert!(expected == actual); + assert_eq!(expected, actual); } diff --git a/src/test/run-pass/unique-send.rs b/src/test/run-pass/unique-send.rs index c9d3a9519209d..a611992d7eee5 100644 --- a/src/test/run-pass/unique-send.rs +++ b/src/test/run-pass/unique-send.rs @@ -14,5 +14,5 @@ pub fn main() { let (p, c) = stream(); c.send(~100); let v = p.recv(); - assert!(v == ~100); + assert_eq!(v, ~100); } diff --git a/src/test/run-pass/unique-swap.rs b/src/test/run-pass/unique-swap.rs index bf58e2c7cb53b..fa3aeb5d4218d 100644 --- a/src/test/run-pass/unique-swap.rs +++ b/src/test/run-pass/unique-swap.rs @@ -14,6 +14,6 @@ pub fn main() { let mut i = ~100; let mut j = ~200; util::swap(&mut i, &mut j); - assert!(i == ~200); - assert!(j == ~100); + assert_eq!(i, ~200); + assert_eq!(j, ~100); } diff --git a/src/test/run-pass/unsafe-pointer-assignability.rs b/src/test/run-pass/unsafe-pointer-assignability.rs index f19558fbb1d01..3385c6f6fef53 100644 --- a/src/test/run-pass/unsafe-pointer-assignability.rs +++ b/src/test/run-pass/unsafe-pointer-assignability.rs @@ -10,7 +10,7 @@ fn f(x: *int) { unsafe { - assert!(*x == 3); + assert_eq!(*x, 3); } } diff --git a/src/test/run-pass/utf8.rs b/src/test/run-pass/utf8.rs index 51fc42491e059..aab51207a9f97 100644 --- a/src/test/run-pass/utf8.rs +++ b/src/test/run-pass/utf8.rs @@ -15,14 +15,14 @@ pub fn main() { let y_diaeresis: char = 'ÿ'; // 0xff let pi: char = 'Π'; // 0x3a0 - assert!((yen as int == 0xa5)); - assert!((c_cedilla as int == 0xe7)); - assert!((thorn as int == 0xfe)); - assert!((y_diaeresis as int == 0xff)); - assert!((pi as int == 0x3a0)); + assert_eq!(yen as int, 0xa5); + assert_eq!(c_cedilla as int, 0xe7); + assert_eq!(thorn as int, 0xfe); + assert_eq!(y_diaeresis as int, 0xff); + assert_eq!(pi as int, 0x3a0); - assert!((pi as int == '\u03a0' as int)); - assert!(('\x0a' as int == '\n' as int)); + assert_eq!(pi as int, '\u03a0' as int); + assert_eq!('\x0a' as int, '\n' as int); let bhutan: ~str = ~"འབྲུག་ཡུལ།"; let japan: ~str = ~"日本"; @@ -37,7 +37,7 @@ pub fn main() { let austria_e: ~str = ~"\u00d6sterreich"; let oo: char = 'Ö'; - assert!((oo as int == 0xd6)); + assert_eq!(oo as int, 0xd6); fn check_str_eq(a: ~str, b: ~str) { let mut i: int = 0; @@ -46,7 +46,7 @@ pub fn main() { debug!(ab); let bb: u8 = b[i]; debug!(bb); - assert!((ab == bb)); + assert_eq!(ab, bb); i += 1; } } diff --git a/src/test/run-pass/utf8_chars.rs b/src/test/run-pass/utf8_chars.rs index 714fd6e3ac5ab..fd98723c2f6ca 100644 --- a/src/test/run-pass/utf8_chars.rs +++ b/src/test/run-pass/utf8_chars.rs @@ -15,12 +15,12 @@ pub fn main() { let chs: ~[char] = ~['e', 'é', '€', 0x10000 as char]; let s: ~str = str::from_chars(chs); - assert!((str::len(s) == 10u)); - assert!((str::char_len(s) == 4u)); - assert!((vec::len(str::to_chars(s)) == 4u)); - assert!((str::from_chars(str::to_chars(s)) == s)); - assert!((str::char_at(s, 0u) == 'e')); - assert!((str::char_at(s, 1u) == 'é')); + assert!(str::len(s) == 10u); + assert!(str::char_len(s) == 4u); + assert!(vec::len(str::to_chars(s)) == 4u); + assert!(str::from_chars(str::to_chars(s)) == s); + assert!(str::char_at(s, 0u) == 'e'); + assert!(str::char_at(s, 1u) == 'é'); assert!((str::is_utf8(str::to_bytes(s)))); assert!((!str::is_utf8(~[0x80_u8]))); @@ -28,12 +28,12 @@ pub fn main() { assert!((!str::is_utf8(~[0xc0_u8, 0x10_u8]))); let mut stack = ~"a×c€"; - assert!((str::pop_char(&mut stack) == '€')); - assert!((str::pop_char(&mut stack) == 'c')); + assert_eq!(str::pop_char(&mut stack), '€'); + assert_eq!(str::pop_char(&mut stack), 'c'); str::push_char(&mut stack, 'u'); - assert!((stack == ~"a×u")); - assert!((str::shift_char(&mut stack) == 'a')); - assert!((str::shift_char(&mut stack) == '×')); + assert!(stack == ~"a×u"); + assert_eq!(str::shift_char(&mut stack), 'a'); + assert_eq!(str::shift_char(&mut stack), '×'); str::unshift_char(&mut stack, 'ß'); - assert!((stack == ~"ßu")); + assert!(stack == ~"ßu"); } diff --git a/src/test/run-pass/utf8_idents.rs b/src/test/run-pass/utf8_idents.rs index 25d2d91d565df..4e86b6cc948cf 100644 --- a/src/test/run-pass/utf8_idents.rs +++ b/src/test/run-pass/utf8_idents.rs @@ -13,7 +13,7 @@ pub fn main() { let Π = 3.14; let लंच = Π * Π + 1.54; assert!(float::abs((लंच - 1.54) - (Π * Π)) < ε); - assert!(საჭმელად_გემრიელი_სადილი() == 0); + assert_eq!(საჭმელად_გემრიელი_სადილი(), 0); } fn საჭმელად_გემრიელი_სადილი() -> int { @@ -37,9 +37,9 @@ fn საჭმელად_გემრიელი_სადილი() -> int // Lunchy arithmetic, mm. - assert!(hádegismatur * ручек * обед == 1000); - assert!(10 == ארוחת_צהריי); - assert!(ランチ + 午餐 + μεσημεριανό == 30); - assert!(ăn_trưa + อาหารกลางวัน == 20); + assert_eq!(hádegismatur * ручек * обед, 1000); + assert_eq!(10, ארוחת_צהריי); + assert_eq!(ランチ + 午餐 + μεσημεριανό, 30); + assert_eq!(ăn_trưa + อาหารกลางวัน, 20); return (абед + լանչ) >> غداء; } diff --git a/src/test/run-pass/vec-concat.rs b/src/test/run-pass/vec-concat.rs index 0045b356d652e..b6fa7c107dbc7 100644 --- a/src/test/run-pass/vec-concat.rs +++ b/src/test/run-pass/vec-concat.rs @@ -14,7 +14,7 @@ pub fn main() { let b: ~[int] = ~[6, 7, 8, 9, 0]; let v: ~[int] = a + b; debug!(v[9]); - assert!((v[0] == 1)); - assert!((v[7] == 8)); - assert!((v[9] == 0)); + assert_eq!(v[0], 1); + assert_eq!(v[7], 8); + assert_eq!(v[9], 0); } diff --git a/src/test/run-pass/vec-each2_mut.rs b/src/test/run-pass/vec-each2_mut.rs index 3c6b7da9f1478..05314f94c6712 100644 --- a/src/test/run-pass/vec-each2_mut.rs +++ b/src/test/run-pass/vec-each2_mut.rs @@ -17,8 +17,8 @@ fn main(){ t2.push('b'); for vec::each2_mut(t1, t2) | i1, i2 | { - assert!(*i1 == 'a'); - assert!(*i2 == 'b'); + assert_eq!(*i1, 'a'); + assert_eq!(*i2, 'b'); } for vec::each2(t1, t2) | i1, i2 | { @@ -28,8 +28,8 @@ fn main(){ for vec::each2_mut(t1, t2) | i1, i2 | { *i1 = 'b'; *i2 = 'a'; - assert!(*i1 == 'b'); - assert!(*i2 == 'a'); + assert_eq!(*i1, 'b'); + assert_eq!(*i2, 'a'); } for vec::each2(t1, t2) | i1, i2 | { diff --git a/src/test/run-pass/vec-growth.rs b/src/test/run-pass/vec-growth.rs index e1e268e63deb5..816228b62c674 100644 --- a/src/test/run-pass/vec-growth.rs +++ b/src/test/run-pass/vec-growth.rs @@ -16,9 +16,9 @@ pub fn main() { v += ~[3]; v += ~[4]; v += ~[5]; - assert!((v[0] == 1)); - assert!((v[1] == 2)); - assert!((v[2] == 3)); - assert!((v[3] == 4)); - assert!((v[4] == 5)); + assert_eq!(v[0], 1); + assert_eq!(v[1], 2); + assert_eq!(v[2], 3); + assert_eq!(v[3], 4); + assert_eq!(v[4], 5); } diff --git a/src/test/run-pass/vec-matching-autoslice.rs b/src/test/run-pass/vec-matching-autoslice.rs index 012b8b83637aa..6757ef46951e9 100644 --- a/src/test/run-pass/vec-matching-autoslice.rs +++ b/src/test/run-pass/vec-matching-autoslice.rs @@ -3,7 +3,7 @@ pub fn main() { match x { [2, .._] => ::core::util::unreachable(), [1, ..tail] => { - assert!(tail == [2, 3]); + assert_eq!(tail, [2, 3]); } [_] => ::core::util::unreachable(), [] => ::core::util::unreachable() @@ -13,8 +13,8 @@ pub fn main() { match y { ([_, _, _], 0.5) => ::core::util::unreachable(), ([(1, a), (b, false), ..tail], _) => { - assert!(a == true); - assert!(b == 2); + assert_eq!(a, true); + assert_eq!(b, 2); assert!(tail.is_empty()); } ([..tail], _) => ::core::util::unreachable() diff --git a/src/test/run-pass/vec-matching-fold.rs b/src/test/run-pass/vec-matching-fold.rs index e6b7bffc1583d..7dcea2d30b7df 100644 --- a/src/test/run-pass/vec-matching-fold.rs +++ b/src/test/run-pass/vec-matching-fold.rs @@ -26,8 +26,8 @@ pub fn main() { let x = [1, 2, 3, 4, 5]; let product = foldl(x, 1, |a, b| a * *b); - assert!(product == 120); + assert_eq!(product, 120); let sum = foldr(x, 0, |a, b| *a + b); - assert!(sum == 15); + assert_eq!(sum, 15); } diff --git a/src/test/run-pass/vec-matching.rs b/src/test/run-pass/vec-matching.rs index e9cf400334cbe..e4ca51368b29b 100644 --- a/src/test/run-pass/vec-matching.rs +++ b/src/test/run-pass/vec-matching.rs @@ -6,7 +6,7 @@ fn a() { [_, .._, _, _] => ::core::util::unreachable(), [_, _] => ::core::util::unreachable(), [a] => { - assert!(a == 1); + assert_eq!(a, 1); } [] => ::core::util::unreachable() } @@ -16,33 +16,33 @@ fn b() { let x = [1, 2, 3]; match x { [a, b, ..c] => { - assert!(a == 1); - assert!(b == 2); - assert!(c == &[3]); + assert_eq!(a, 1); + assert_eq!(b, 2); + assert_eq!(c, &[3]); } _ => fail!() } match x { [..a, b, c] => { - assert!(a == &[1]); - assert!(b == 2); - assert!(c == 3); + assert_eq!(a, &[1]); + assert_eq!(b, 2); + assert_eq!(c, 3); } _ => fail!() } match x { [a, ..b, c] => { - assert!(a == 1); - assert!(b == &[2]); - assert!(c == 3); + assert_eq!(a, 1); + assert_eq!(b, &[2]); + assert_eq!(c, 3); } _ => fail!() } match x { [a, b, c] => { - assert!(a == 1); - assert!(b == 2); - assert!(c == 3); + assert_eq!(a, 1); + assert_eq!(b, 2); + assert_eq!(c, 3); } _ => fail!() } diff --git a/src/test/run-pass/vec-self-append.rs b/src/test/run-pass/vec-self-append.rs index 7507a78378e8f..30f6befe69c5d 100644 --- a/src/test/run-pass/vec-self-append.rs +++ b/src/test/run-pass/vec-self-append.rs @@ -14,17 +14,17 @@ fn test_heap_to_heap() { // a spills onto the heap let mut a = ~[0, 1, 2, 3, 4]; a = a + a; // FIXME(#3387)---can't write a += a - assert!(a.len() == 10u); - assert!((a[0] == 0)); - assert!((a[1] == 1)); - assert!((a[2] == 2)); - assert!((a[3] == 3)); - assert!((a[4] == 4)); - assert!((a[5] == 0)); - assert!((a[6] == 1)); - assert!((a[7] == 2)); - assert!((a[8] == 3)); - assert!((a[9] == 4)); + assert_eq!(a.len(), 10u); + assert_eq!(a[0], 0); + assert_eq!(a[1], 1); + assert_eq!(a[2], 2); + assert_eq!(a[3], 3); + assert_eq!(a[4], 4); + assert_eq!(a[5], 0); + assert_eq!(a[6], 1); + assert_eq!(a[7], 2); + assert_eq!(a[8], 3); + assert_eq!(a[9], 4); } fn test_stack_to_heap() { @@ -32,13 +32,13 @@ fn test_stack_to_heap() { let mut a = ~[0, 1, 2]; // a spills to the heap a = a + a; // FIXME(#3387)---can't write a += a - assert!(a.len() == 6u); - assert!((a[0] == 0)); - assert!((a[1] == 1)); - assert!((a[2] == 2)); - assert!((a[3] == 0)); - assert!((a[4] == 1)); - assert!((a[5] == 2)); + assert_eq!(a.len(), 6u); + assert_eq!(a[0], 0); + assert_eq!(a[1], 1); + assert_eq!(a[2], 2); + assert_eq!(a[3], 0); + assert_eq!(a[4], 1); + assert_eq!(a[5], 2); } fn test_loop() { @@ -48,7 +48,7 @@ fn test_loop() { let mut expected_len = 1u; while i > 0 { error!(a.len()); - assert!(a.len() == expected_len); + assert_eq!(a.len(), expected_len); a = a + a; // FIXME(#3387)---can't write a += a i -= 1; expected_len *= 2u; diff --git a/src/test/run-pass/vec-slice-drop.rs b/src/test/run-pass/vec-slice-drop.rs index cc0649790fd87..695441daf2858 100644 --- a/src/test/run-pass/vec-slice-drop.rs +++ b/src/test/run-pass/vec-slice-drop.rs @@ -32,7 +32,7 @@ pub fn main() { let x = @mut 0; { let l = &[foo(x)]; - assert!(*l[0].x == 0); + assert_eq!(*l[0].x, 0); } - assert!(*x == 1); + assert_eq!(*x, 1); } diff --git a/src/test/run-pass/vec-slice.rs b/src/test/run-pass/vec-slice.rs index 8e653d21ec664..25ae7340bc1b8 100644 --- a/src/test/run-pass/vec-slice.rs +++ b/src/test/run-pass/vec-slice.rs @@ -11,6 +11,6 @@ pub fn main() { let v = ~[1,2,3,4,5]; let v2 = vec::slice(v, 1, 3); - assert!((v2[0] == 2)); - assert!((v2[1] == 3)); + assert_eq!(v2[0], 2); + assert_eq!(v2[1], 3); } diff --git a/src/test/run-pass/vec-tail-matching.rs b/src/test/run-pass/vec-tail-matching.rs index fd65f150e4c91..6a98ed678b264 100644 --- a/src/test/run-pass/vec-tail-matching.rs +++ b/src/test/run-pass/vec-tail-matching.rs @@ -11,7 +11,7 @@ pub fn main() { match x { [first, ..tail] => { assert!(first.string == ~"foo"); - assert!(tail.len() == 2); + assert_eq!(tail.len(), 2); assert!(tail[0].string == ~"bar"); assert!(tail[1].string == ~"baz"); @@ -20,8 +20,8 @@ pub fn main() { ::core::util::unreachable(); } [Foo { string: a }, Foo { string: b }] => { - assert!(a == ~"bar"); - assert!(b == ~"baz"); + assert_eq!(a, ~"bar"); + assert_eq!(b, ~"baz"); } _ => { ::core::util::unreachable(); diff --git a/src/test/run-pass/vec-to_str.rs b/src/test/run-pass/vec-to_str.rs index 1767dd3ee5b39..a24ef38b28341 100644 --- a/src/test/run-pass/vec-to_str.rs +++ b/src/test/run-pass/vec-to_str.rs @@ -9,16 +9,16 @@ // except according to those terms. pub fn main() { - assert!((~[0, 1]).to_str() == ~"[0, 1]"); - assert!((&[1, 2]).to_str() == ~"[1, 2]"); - assert!((@[2, 3]).to_str() == ~"[2, 3]"); + assert_eq!((~[0, 1]).to_str(), ~"[0, 1]"); + assert_eq!((&[1, 2]).to_str(), ~"[1, 2]"); + assert_eq!((@[2, 3]).to_str(), ~"[2, 3]"); let foo = ~[3, 4]; let bar = &[4, 5]; let baz = @[5, 6]; - assert!(foo.to_str() == ~"[3, 4]"); - assert!(bar.to_str() == ~"[4, 5]"); - assert!(baz.to_str() == ~"[5, 6]"); + assert_eq!(foo.to_str(), ~"[3, 4]"); + assert_eq!(bar.to_str(), ~"[4, 5]"); + assert_eq!(baz.to_str(), ~"[5, 6]"); } diff --git a/src/test/run-pass/vec-trailing-comma.rs b/src/test/run-pass/vec-trailing-comma.rs index 686fc655bdb76..426416f63d307 100644 --- a/src/test/run-pass/vec-trailing-comma.rs +++ b/src/test/run-pass/vec-trailing-comma.rs @@ -13,8 +13,8 @@ pub fn main() { let v1: ~[int] = ~[10, 20, 30,]; let v2: ~[int] = ~[10, 20, 30]; - assert!((v1[2] == v2[2])); + assert_eq!(v1[2], v2[2]); let v3: ~[int] = ~[10,]; let v4: ~[int] = ~[10]; - assert!((v3[0] == v4[0])); + assert_eq!(v3[0], v4[0]); } diff --git a/src/test/run-pass/vec.rs b/src/test/run-pass/vec.rs index d021588814780..34fcca9e35bfc 100644 --- a/src/test/run-pass/vec.rs +++ b/src/test/run-pass/vec.rs @@ -14,12 +14,12 @@ // -*- rust -*- pub fn main() { let v: ~[int] = ~[10, 20]; - assert!((v[0] == 10)); - assert!((v[1] == 20)); + assert_eq!(v[0], 10); + assert_eq!(v[1], 20); let mut x: int = 0; - assert!((v[x] == 10)); - assert!((v[x + 1] == 20)); + assert_eq!(v[x], 10); + assert_eq!(v[x + 1], 20); x = x + 1; - assert!((v[x] == 20)); - assert!((v[x - 1] == 10)); + assert_eq!(v[x], 20); + assert_eq!(v[x - 1], 10); } diff --git a/src/test/run-pass/while-with-break.rs b/src/test/run-pass/while-with-break.rs index 417c0cdd9157f..465cb7d562b37 100644 --- a/src/test/run-pass/while-with-break.rs +++ b/src/test/run-pass/while-with-break.rs @@ -15,5 +15,5 @@ pub fn main() { break; } } - assert!((i == 95)); + assert_eq!(i, 95); } diff --git a/src/test/run-pass/writealias.rs b/src/test/run-pass/writealias.rs index f22f90380c6c4..7e2229e78ea28 100644 --- a/src/test/run-pass/writealias.rs +++ b/src/test/run-pass/writealias.rs @@ -19,5 +19,5 @@ fn f(p: &mut Point) { p.z = 13; } pub fn main() { let mut x: Point = Point {x: 10, y: 11, z: 12}; f(&mut x); - assert!((x.z == 13)); + assert_eq!(x.z, 13); } diff --git a/src/test/run-pass/x86stdcall.rs b/src/test/run-pass/x86stdcall.rs index c7c47753b8a82..f584237d0dec8 100644 --- a/src/test/run-pass/x86stdcall.rs +++ b/src/test/run-pass/x86stdcall.rs @@ -25,7 +25,7 @@ pub fn main() { kernel32::SetLastError(expected); let actual = kernel32::GetLastError(); log(error, actual); - assert!((expected == actual)); + assert_eq!(expected, actual); } } diff --git a/src/test/run-pass/zip-same-length.rs b/src/test/run-pass/zip-same-length.rs index 50c3e78006111..bf45b2fc039d6 100644 --- a/src/test/run-pass/zip-same-length.rs +++ b/src/test/run-pass/zip-same-length.rs @@ -34,6 +34,6 @@ pub fn main() { let ps = vec::zip(chars, ints); - assert!((ps.head() == &('a', 1u))); - assert!((ps.last() == &(j as char, 10u))); + assert_eq!(ps.head(), &('a', 1u)); + assert_eq!(ps.last(), &(j as char, 10u)); } From e0b1bdca5b56a104d8c221cb3bbb7eb16b5fcec4 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 12:06:39 -0700 Subject: [PATCH 097/248] Add additional documentation in core::io. Added docs for stdout, stderr, print, and println. --- src/libcore/io.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 77b486ca44619..820d810a36f8c 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -1561,13 +1561,55 @@ pub fn buffered_file_writer(path: &Path) -> Result<@Writer, ~str> { // FIXME (#2004) it would be great if this could be a const // FIXME (#2004) why are these different from the way stdin() is // implemented? + + +/** +* Gives a `Writer` which allows you to write to the standard output. +* +* # Examples +* ~~~ +* let stdout = core::io::stdout(); +* stdout.write_str("hello\n"); +* ~~~ +*/ pub fn stdout() -> @Writer { fd_writer(libc::STDOUT_FILENO as c_int, false) } + +/** +* Gives a `Writer` which allows you to write to standard error. +* +* # Examples +* ~~~ +* let stderr = core::io::stderr(); +* stderr.write_str("hello\n"); +* ~~~ +*/ pub fn stderr() -> @Writer { fd_writer(libc::STDERR_FILENO as c_int, false) } +/** +* Prints a string to standard output. +* +* This string will not have an implicit newline at the end. If you want +* an implicit newline, please see `println`. +* +* # Examples +* ~~~ +* core::io::print("hello"); +* ~~~ +*/ pub fn print(s: &str) { stdout().write_str(s); } +/** +* Prints a string to standard output, followed by a newline. +* +* If you do not want an implicit newline, please see `print`. +* +* # Examples +* ~~~ +* core::io::println("hello"); +* ~~~ +*/ pub fn println(s: &str) { stdout().write_line(s); } From a389d86fa46d4a01b7839560a8851d84b7b2153d Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 12:33:01 -0700 Subject: [PATCH 098/248] Add docs for stdin in core::io. --- src/libcore/io.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 77b486ca44619..677903433e01c 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -1010,6 +1010,16 @@ pub fn FILE_reader(f: *libc::FILE, cleanup: bool) -> @Reader { // top-level functions that take a reader, or a set of default methods on // reader (which can then be called reader) +/** +* Gives a `Reader` that allows you to read values from standard input. +* +* # Examples +* ~~~ +* let stdin = core::io::stdin(); +* let line = stdin.read_line(); +* core::io::print(line); +* ~~~ +*/ pub fn stdin() -> @Reader { unsafe { @rustrt::rust_get_stdin() as @Reader From 929050de73c1edb22211fa05e891068fe9a1a0d2 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 12:42:00 -0700 Subject: [PATCH 099/248] Added note about prelude inclusion. --- src/libcore/io.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 820d810a36f8c..feceb9f4b17d7 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -1593,7 +1593,8 @@ pub fn stderr() -> @Writer { fd_writer(libc::STDERR_FILENO as c_int, false) } * * # Examples * ~~~ -* core::io::print("hello"); +* // print is imported into the prelude, and so is always available. +* print("hello"); * ~~~ */ pub fn print(s: &str) { @@ -1607,7 +1608,8 @@ pub fn print(s: &str) { * * # Examples * ~~~ -* core::io::println("hello"); +* // println is imported into the prelude, and so is always available. +* println("hello"); * ~~~ */ pub fn println(s: &str) { From 1065a92bf3bbe1f4bb11b7b7268a91529bbf8f89 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 12:57:00 -0700 Subject: [PATCH 100/248] Elaborate a bit in the Reader docs regarding stream position. Had a conversation with @cmr in IRC about some places that these docs were confusing. The functions that advance the stream now say so. In addition, I think that calling out the similarities to familliar C functions should help people coming from other languages. --- src/libcore/io.rs | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 77b486ca44619..8be02947ddb21 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -84,14 +84,16 @@ pub trait Reader { // FIXME (#2982): This should probably return an error. /** - * Reads bytes and puts them into `bytes`. Returns the number of - * bytes read. + * Reads bytes and puts them into `bytes`, advancing the cursor. Returns the + * number of bytes read. * * The number of bytes to be read is `len` or the end of the file, * whichever comes first. * * The buffer must be at least `len` bytes long. * + * `read` is conceptually similar to C's `fread`. + * * # Examples * * None right now. @@ -99,10 +101,12 @@ pub trait Reader { fn read(&self, bytes: &mut [u8], len: uint) -> uint; /** - * Reads a single byte. + * Reads a single byte, advancing the cursor. * * In the case of an EOF or an error, returns a negative value. * + * `read_byte` is conceptually similar to C's `getc` function. + * * # Examples * * None right now. @@ -112,6 +116,8 @@ pub trait Reader { /** * Returns a boolean value: are we currently at EOF? * + * `eof` is conceptually similar to C's `feof` function. + * * # Examples * * None right now. @@ -124,6 +130,8 @@ pub trait Reader { * Takes an optional SeekStyle, which affects how we seek from the * position. See `SeekStyle` docs for more details. * + * `seek` is conceptually similar to C's `fseek`. + * * # Examples * * None right now. @@ -133,6 +141,8 @@ pub trait Reader { /** * Returns the current position within the stream. * + * `tell` is conceptually similar to C's `ftell` function. + * * # Examples * * None right now. From 58777272857526eb301bfedd909e6826e5edf716 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 15:31:19 -0700 Subject: [PATCH 101/248] Fix trailing whitespace --- src/libcore/io.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index feceb9f4b17d7..2060964173d37 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -1587,7 +1587,7 @@ pub fn stderr() -> @Writer { fd_writer(libc::STDERR_FILENO as c_int, false) } /** * Prints a string to standard output. -* +* * This string will not have an implicit newline at the end. If you want * an implicit newline, please see `println`. * @@ -1603,7 +1603,7 @@ pub fn print(s: &str) { /** * Prints a string to standard output, followed by a newline. -* +* * If you do not want an implicit newline, please see `print`. * * # Examples From e02716e6d3a65bde24f49207274a74a22790a201 Mon Sep 17 00:00:00 2001 From: Tom Lee Date: Sat, 11 May 2013 21:46:30 -0700 Subject: [PATCH 102/248] Reexport static trait methods on traits in the same module. --- src/librustc/metadata/encoder.rs | 6 ++++-- .../auxiliary/mod_trait_with_static_methods_lib.rs | 10 ++++++++++ .../run-pass/trait_with_static_methods_cross_crate.rs | 2 ++ 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 8c21998768e95..78adee4b4f2f1 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -386,8 +386,10 @@ fn encode_reexported_static_methods(ecx: @EncodeContext, match ecx.tcx.trait_methods_cache.find(&exp.def_id) { Some(methods) => { match ecx.tcx.items.find(&exp.def_id.node) { - Some(&ast_map::node_item(_, path)) => { - if mod_path != *path { + Some(&ast_map::node_item(item, path)) => { + let interner = ecx.tcx.sess.parse_sess.interner; + let original_name = ecx.tcx.sess.str_of(item.ident); + if mod_path != *path || *exp.name != *original_name { for methods.each |&m| { if m.explicit_self == ast::sty_static { encode_reexported_static_method(ecx, diff --git a/src/test/auxiliary/mod_trait_with_static_methods_lib.rs b/src/test/auxiliary/mod_trait_with_static_methods_lib.rs index 2099c6a2f2f2f..3591ff7931855 100644 --- a/src/test/auxiliary/mod_trait_with_static_methods_lib.rs +++ b/src/test/auxiliary/mod_trait_with_static_methods_lib.rs @@ -9,6 +9,15 @@ // except according to those terms. pub use sub_foo::Foo; +pub use Baz = self::Bar; + +pub trait Bar { + pub fn bar() -> Self; +} + +impl Bar for int { + pub fn bar() -> int { 84 } +} pub mod sub_foo { pub trait Foo { @@ -18,4 +27,5 @@ pub mod sub_foo { impl Foo for int { pub fn foo() -> int { 42 } } + } diff --git a/src/test/run-pass/trait_with_static_methods_cross_crate.rs b/src/test/run-pass/trait_with_static_methods_cross_crate.rs index 20dcbf3267b70..4402881c43ddd 100644 --- a/src/test/run-pass/trait_with_static_methods_cross_crate.rs +++ b/src/test/run-pass/trait_with_static_methods_cross_crate.rs @@ -13,7 +13,9 @@ extern mod mod_trait_with_static_methods_lib; use mod_trait_with_static_methods_lib::Foo; +use mod_trait_with_static_methods_lib::Baz; pub fn main() { assert_eq!(42, Foo::foo()); + assert_eq!(84, Baz::bar()); } From cac97d7ee565eef14b9e7385d1c088c1eb0a9295 Mon Sep 17 00:00:00 2001 From: Tom Lee Date: Sun, 12 May 2013 12:19:28 -0700 Subject: [PATCH 103/248] Remove unused variable. --- src/librustc/metadata/encoder.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 78adee4b4f2f1..110d17b9b15bf 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -387,7 +387,6 @@ fn encode_reexported_static_methods(ecx: @EncodeContext, Some(methods) => { match ecx.tcx.items.find(&exp.def_id.node) { Some(&ast_map::node_item(item, path)) => { - let interner = ecx.tcx.sess.parse_sess.interner; let original_name = ecx.tcx.sess.str_of(item.ident); if mod_path != *path || *exp.name != *original_name { for methods.each |&m| { From e3a91f60c58d537945abc4c83b1b9f6ddcbe21fe Mon Sep 17 00:00:00 2001 From: Tom Lee Date: Sat, 18 May 2013 21:31:55 -0700 Subject: [PATCH 104/248] Explain an odd conditional check. --- src/librustc/metadata/encoder.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 110d17b9b15bf..460da5d60b33f 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -388,6 +388,17 @@ fn encode_reexported_static_methods(ecx: @EncodeContext, match ecx.tcx.items.find(&exp.def_id.node) { Some(&ast_map::node_item(item, path)) => { let original_name = ecx.tcx.sess.str_of(item.ident); + + // + // We don't need to reexport static methods on traits + // declared in the same module as our `pub use ...` since + // that's done when we encode the trait item. + // + // The only exception is when the reexport *changes* the + // name e.g. `pub use Foo = self::Bar` -- we have + // encoded metadata for static methods relative to Bar, + // but not yet for Foo. + // if mod_path != *path || *exp.name != *original_name { for methods.each |&m| { if m.explicit_self == ast::sty_static { From b1e805694b914613ec30619764bec961e78bbbac Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 18:59:21 -0700 Subject: [PATCH 105/248] Add a better introduction for the io module. Let's actually give a top-level description of what's in here, eh? --- src/libcore/io.rs | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 77b486ca44619..d23f2fa7e2c75 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -10,7 +10,37 @@ /*! -Basic input/output +The `io` module contains basic input and output routines. + +A quick summary: + +## `Reader` and `Writer` traits + +These traits define the simplest amount of methods that anything that can do +input and output should implement. + +## `ReaderUtil` and `WriterUtil` traits + +Richer methods that allow you to do more. `Reader` only lets you read a certain +amount of bytes into a buffer, while `ReaderUtil` allows you to read a whole +line, for example. + +Generally, these richer methods are probably the ones you want to actually +use in day-to-day Rust. + +Furthermore, because there is an implementation of `ReaderUtil` for +``, when your input or output code implements `Reader`, you get +all of these methods for free. + +## `print` and `println` + +These very useful functions are defined here. You generally don't need to +import them, though, as the prelude already does. + +## `stdin`, `stdout`, and `stderr` + +These functions return references to the classic three file descriptors. They +implement `Reader` and `Writer`, where appropriate. */ From e42fcb958cd89d11dbe8f493cfac0a1fca4b1bb1 Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Sun, 19 May 2013 16:03:52 -0400 Subject: [PATCH 106/248] Implement unimplemented const binops --- src/librustc/lib/llvm.rs | 5 ++ src/librustc/middle/trans/consts.rs | 56 +++++++++++--- src/test/run-pass/const-binops.rs | 116 ++++++++++++++++++++++++++++ 3 files changed, 165 insertions(+), 12 deletions(-) create mode 100644 src/test/run-pass/const-binops.rs diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index d06bf1480c989..cdc128c6eeb61 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -220,6 +220,7 @@ pub mod llvm { use super::{ObjectFileRef, Opcode, PassManagerRef, PassManagerBuilderRef}; use super::{SectionIteratorRef, TargetDataRef, TypeKind, TypeRef, UseRef}; use super::{ValueRef}; + use super::{IntPredicate, RealPredicate}; use core::libc::{c_char, c_int, c_longlong, c_uint, c_ulonglong}; @@ -451,6 +452,10 @@ pub mod llvm { /* all zeroes */ #[fast_ffi] pub unsafe fn LLVMConstAllOnes(Ty: TypeRef) -> ValueRef; + #[fast_ffi] + pub unsafe fn LLVMConstICmp(Pred: IntPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef; + #[fast_ffi] + pub unsafe fn LLVMConstFCmp(Pred: RealPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef; /* only for int/vector */ #[fast_ffi] pub unsafe fn LLVMGetUndef(Ty: TypeRef) -> ValueRef; diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index e08cc536a701f..6df523976f2b0 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -9,8 +9,10 @@ // except according to those terms. use back::abi; -use lib::llvm::{llvm, SetLinkage, PrivateLinkage, - ValueRef, TypeRef, Bool, True, False}; +use lib::llvm::{llvm, SetLinkage, PrivateLinkage, ValueRef, TypeRef, Bool, True, False}; +use lib::llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE, + RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE}; + use metadata::csearch; use middle::const_eval; use middle::trans::adt; @@ -280,8 +282,8 @@ fn const_expr_unadjusted(cx: @CrateContext, e: @ast::expr) -> ValueRef { else if signed { llvm::LLVMConstSRem(te1, te2) } else { llvm::LLVMConstURem(te1, te2) } } - ast::and | - ast::or => cx.sess.span_unimpl(e.span, "binop logic"), + ast::and => llvm::LLVMConstAnd(te1, te2), + ast::or => llvm::LLVMConstOr(te1, te2), ast::bitxor => llvm::LLVMConstXor(te1, te2), ast::bitand => llvm::LLVMConstAnd(te1, te2), ast::bitor => llvm::LLVMConstOr(te1, te2), @@ -290,14 +292,44 @@ fn const_expr_unadjusted(cx: @CrateContext, e: @ast::expr) -> ValueRef { if signed { llvm::LLVMConstAShr(te1, te2) } else { llvm::LLVMConstLShr(te1, te2) } } - ast::eq | - ast::lt | - ast::le | - ast::ne | - ast::ge | - ast::gt => cx.sess.span_unimpl(e.span, "binop comparator") - } - } + ast::eq => { + if is_float { llvm::LLVMConstFCmp(RealOEQ, te1, te2) } + else { llvm::LLVMConstICmp(IntEQ, te1, te2) } + }, + ast::lt => { + if is_float { llvm::LLVMConstFCmp(RealOLT, te1, te2) } + else { + if signed { llvm::LLVMConstICmp(IntSLT, te1, te2) } + else { llvm::LLVMConstICmp(IntULT, te1, te2) } + } + }, + ast::le => { + if is_float { llvm::LLVMConstFCmp(RealOLE, te1, te2) } + else { + if signed { llvm::LLVMConstICmp(IntSLE, te1, te2) } + else { llvm::LLVMConstICmp(IntULE, te1, te2) } + } + }, + ast::ne => { + if is_float { llvm::LLVMConstFCmp(RealONE, te1, te2) } + else { llvm::LLVMConstICmp(IntNE, te1, te2) } + }, + ast::ge => { + if is_float { llvm::LLVMConstFCmp(RealOGE, te1, te2) } + else { + if signed { llvm::LLVMConstICmp(IntSGE, te1, te2) } + else { llvm::LLVMConstICmp(IntUGE, te1, te2) } + } + }, + ast::gt => { + if is_float { llvm::LLVMConstFCmp(RealOGT, te1, te2) } + else { + if signed { llvm::LLVMConstICmp(IntSGT, te1, te2) } + else { llvm::LLVMConstICmp(IntUGT, te1, te2) } + } + }, + }; + }, ast::expr_unary(u, e) => { let te = const_expr(cx, e); let ty = ty::expr_ty(cx.tcx, e); diff --git a/src/test/run-pass/const-binops.rs b/src/test/run-pass/const-binops.rs new file mode 100644 index 0000000000000..507f68dc3a146 --- /dev/null +++ b/src/test/run-pass/const-binops.rs @@ -0,0 +1,116 @@ +static a: int = -4 + 3; +static a2: uint = 3 + 3; +static b: float = 3.0 + 2.7; + +static c: int = 3 - 4; +static d: uint = 3 - 3; +static e: float = 3.0 - 2.7; + +static e2: int = -3 * 3; +static f: uint = 3 * 3; +static g: float = 3.3 * 3.3; + +static h: int = 3 / -1; +static i: uint = 3 / 3; +static j: float = 3.3 / 3.3; + +static n: bool = true && false; + +static o: bool = true || false; + +static p: int = 3 & 1; +static q: uint = 1 & 3; + +static r: int = 3 | 1; +static s: uint = 1 | 3; + +static t: int = 3 ^ 1; +static u: uint = 1 ^ 3; + +static v: int = 1 << 3; + +// NOTE: better shr coverage +static w: int = 1024 >> 4; +static x: uint = 1024 >> 4; + +static y: bool = 1 == 1; +static z: bool = 1.0 == 1.0; + +static aa: bool = 1 <= 2; +static ab: bool = -1 <= 2; +static ac: bool = 1.0 <= 2; + +static ad: bool = 1 < 2; +static ae: bool = -1 < 2; +static af: bool = 1.0 < 2; + +static ag: bool = 1 != 2; +static ah: bool = -1 != 2; +static ai: bool = 1.0 != 2; + +static aj: bool = 2 >= 1; +static ak: bool = 2 >= -2; +static al: bool = 1.0 >= -2; + +static am: bool = 2 > 1; +static an: bool = 2 > -2; +static ao: bool = 1.0 > -2; + +fn main() { + assert_eq!(a, -1); + assert_eq!(a2, 6); + assert_approx_eq!(b, 5.7); + + assert_eq!(c, -1); + assert_eq!(d, 0); + assert_approx_eq!(e, -0.3); + + assert_eq!(e2, -9); + assert_eq!(f, 9); + assert_approx_eq!(g, 10.89); + + assert_eq!(h, -3); + assert_eq!(i, 1); + assert_approx_eq!(j, 1.0); + + assert_eq!(n, false); + + assert_eq!(o, true); + + assert_eq!(p, 1); + assert_eq!(q, 1); + + assert_eq!(r, 3); + assert_eq!(s, 3); + + assert_eq!(t, 2); + assert_eq!(u, 2); + + assert_eq!(v, 8); + + assert_eq!(w, 64); + assert_eq!(x, 64); + + assert_eq!(y, true); + assert_eq!(z, true); + + assert_eq!(aa, true); + assert_eq!(ab, true); + assert_eq!(ac, true); + + assert_eq!(ad, true); + assert_eq!(ae, true); + assert_eq!(af, true); + + assert_eq!(ag, true); + assert_eq!(ah, true); + assert_eq!(ai, true); + + assert_eq!(aj, true); + assert_eq!(ak, true); + assert_eq!(al, true); + + assert_eq!(am, true); + assert_eq!(an, true); + assert_eq!(ao, true); +} From b97642758fb2c060ec689c540576d308fc081f1e Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Sun, 19 May 2013 20:18:56 -0400 Subject: [PATCH 107/248] Fix LLVMConst{I,F}Cmp --- src/librustc/lib/llvm.rs | 15 ++++++++++--- src/librustc/middle/trans/consts.rs | 35 +++++++++++++++-------------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index cdc128c6eeb61..bf3d09d848dad 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -220,7 +220,6 @@ pub mod llvm { use super::{ObjectFileRef, Opcode, PassManagerRef, PassManagerBuilderRef}; use super::{SectionIteratorRef, TargetDataRef, TypeKind, TypeRef, UseRef}; use super::{ValueRef}; - use super::{IntPredicate, RealPredicate}; use core::libc::{c_char, c_int, c_longlong, c_uint, c_ulonglong}; @@ -453,9 +452,9 @@ pub mod llvm { #[fast_ffi] pub unsafe fn LLVMConstAllOnes(Ty: TypeRef) -> ValueRef; #[fast_ffi] - pub unsafe fn LLVMConstICmp(Pred: IntPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef; + pub unsafe fn LLVMConstICmp(Pred: c_uint, V1: ValueRef, V2: ValueRef) -> ValueRef; #[fast_ffi] - pub unsafe fn LLVMConstFCmp(Pred: RealPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef; + pub unsafe fn LLVMConstFCmp(Pred: c_uint, V1: ValueRef, V2: ValueRef) -> ValueRef; /* only for int/vector */ #[fast_ffi] pub unsafe fn LLVMGetUndef(Ty: TypeRef) -> ValueRef; @@ -1919,6 +1918,16 @@ pub fn SetLinkage(Global: ValueRef, Link: Linkage) { } } +pub fn ConstICmp(Pred: IntPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef { + unsafe { + llvm::LLVMConstICmp(Pred as c_uint, V1, V2) + } +} +pub fn ConstFCmp(Pred: RealPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef { + unsafe { + llvm::LLVMConstICmp(Pred as c_uint, V1, V2) + } +} /* Memory-managed object interface to type handles. */ pub struct TypeNames { diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 6df523976f2b0..22014fa330414 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -9,7 +9,8 @@ // except according to those terms. use back::abi; -use lib::llvm::{llvm, SetLinkage, PrivateLinkage, ValueRef, TypeRef, Bool, True, False}; +use lib::llvm::{llvm, ConstFCmp, ConstICmp, SetLinkage, PrivateLinkage, ValueRef, TypeRef, Bool, + True, False}; use lib::llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE, RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE}; @@ -293,39 +294,39 @@ fn const_expr_unadjusted(cx: @CrateContext, e: @ast::expr) -> ValueRef { else { llvm::LLVMConstLShr(te1, te2) } } ast::eq => { - if is_float { llvm::LLVMConstFCmp(RealOEQ, te1, te2) } - else { llvm::LLVMConstICmp(IntEQ, te1, te2) } + if is_float { ConstFCmp(RealOEQ, te1, te2) } + else { ConstICmp(IntEQ, te1, te2) } }, ast::lt => { - if is_float { llvm::LLVMConstFCmp(RealOLT, te1, te2) } + if is_float { ConstFCmp(RealOLT, te1, te2) } else { - if signed { llvm::LLVMConstICmp(IntSLT, te1, te2) } - else { llvm::LLVMConstICmp(IntULT, te1, te2) } + if signed { ConstICmp(IntSLT, te1, te2) } + else { ConstICmp(IntULT, te1, te2) } } }, ast::le => { - if is_float { llvm::LLVMConstFCmp(RealOLE, te1, te2) } + if is_float { ConstFCmp(RealOLE, te1, te2) } else { - if signed { llvm::LLVMConstICmp(IntSLE, te1, te2) } - else { llvm::LLVMConstICmp(IntULE, te1, te2) } + if signed { ConstICmp(IntSLE, te1, te2) } + else { ConstICmp(IntULE, te1, te2) } } }, ast::ne => { - if is_float { llvm::LLVMConstFCmp(RealONE, te1, te2) } - else { llvm::LLVMConstICmp(IntNE, te1, te2) } + if is_float { ConstFCmp(RealONE, te1, te2) } + else { ConstICmp(IntNE, te1, te2) } }, ast::ge => { - if is_float { llvm::LLVMConstFCmp(RealOGE, te1, te2) } + if is_float { ConstFCmp(RealOGE, te1, te2) } else { - if signed { llvm::LLVMConstICmp(IntSGE, te1, te2) } - else { llvm::LLVMConstICmp(IntUGE, te1, te2) } + if signed { ConstICmp(IntSGE, te1, te2) } + else { ConstICmp(IntUGE, te1, te2) } } }, ast::gt => { - if is_float { llvm::LLVMConstFCmp(RealOGT, te1, te2) } + if is_float { ConstFCmp(RealOGT, te1, te2) } else { - if signed { llvm::LLVMConstICmp(IntSGT, te1, te2) } - else { llvm::LLVMConstICmp(IntUGT, te1, te2) } + if signed { ConstICmp(IntSGT, te1, te2) } + else { ConstICmp(IntUGT, te1, te2) } } }, }; From 808c5b8d4e479b5e0fd336f8290fda2f0c429257 Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Sun, 19 May 2013 22:08:59 -0400 Subject: [PATCH 108/248] Test fixes, use LLVMConstFCmp in ConstFCmp --- src/librustc/lib/llvm.rs | 12 ++++++------ src/test/run-pass/const-binops.rs | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index bf3d09d848dad..9198991e5360e 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -9,7 +9,7 @@ // except according to those terms. use core::hashmap::HashMap; -use core::libc::c_uint; +use core::libc::{c_uint, c_ushort}; pub type Opcode = u32; pub type Bool = c_uint; @@ -221,7 +221,7 @@ pub mod llvm { use super::{SectionIteratorRef, TargetDataRef, TypeKind, TypeRef, UseRef}; use super::{ValueRef}; - use core::libc::{c_char, c_int, c_longlong, c_uint, c_ulonglong}; + use core::libc::{c_char, c_int, c_longlong, c_ushort, c_uint, c_ulonglong}; #[link_args = "-Lrustllvm -lrustllvm"] #[link_name = "rustllvm"] @@ -452,9 +452,9 @@ pub mod llvm { #[fast_ffi] pub unsafe fn LLVMConstAllOnes(Ty: TypeRef) -> ValueRef; #[fast_ffi] - pub unsafe fn LLVMConstICmp(Pred: c_uint, V1: ValueRef, V2: ValueRef) -> ValueRef; + pub unsafe fn LLVMConstICmp(Pred: c_ushort, V1: ValueRef, V2: ValueRef) -> ValueRef; #[fast_ffi] - pub unsafe fn LLVMConstFCmp(Pred: c_uint, V1: ValueRef, V2: ValueRef) -> ValueRef; + pub unsafe fn LLVMConstFCmp(Pred: c_ushort, V1: ValueRef, V2: ValueRef) -> ValueRef; /* only for int/vector */ #[fast_ffi] pub unsafe fn LLVMGetUndef(Ty: TypeRef) -> ValueRef; @@ -1920,12 +1920,12 @@ pub fn SetLinkage(Global: ValueRef, Link: Linkage) { pub fn ConstICmp(Pred: IntPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef { unsafe { - llvm::LLVMConstICmp(Pred as c_uint, V1, V2) + llvm::LLVMConstICmp(Pred as c_ushort, V1, V2) } } pub fn ConstFCmp(Pred: RealPredicate, V1: ValueRef, V2: ValueRef) -> ValueRef { unsafe { - llvm::LLVMConstICmp(Pred as c_uint, V1, V2) + llvm::LLVMConstFCmp(Pred as c_ushort, V1, V2) } } /* Memory-managed object interface to type handles. */ diff --git a/src/test/run-pass/const-binops.rs b/src/test/run-pass/const-binops.rs index 507f68dc3a146..cd87ca3ab537e 100644 --- a/src/test/run-pass/const-binops.rs +++ b/src/test/run-pass/const-binops.rs @@ -38,23 +38,23 @@ static z: bool = 1.0 == 1.0; static aa: bool = 1 <= 2; static ab: bool = -1 <= 2; -static ac: bool = 1.0 <= 2; +static ac: bool = 1.0 <= 2.0; static ad: bool = 1 < 2; static ae: bool = -1 < 2; -static af: bool = 1.0 < 2; +static af: bool = 1.0 < 2.0; static ag: bool = 1 != 2; static ah: bool = -1 != 2; -static ai: bool = 1.0 != 2; +static ai: bool = 1.0 != 2.0; static aj: bool = 2 >= 1; static ak: bool = 2 >= -2; -static al: bool = 1.0 >= -2; +static al: bool = 1.0 >= -2.0; static am: bool = 2 > 1; static an: bool = 2 > -2; -static ao: bool = 1.0 > -2; +static ao: bool = 1.0 > -2.0; fn main() { assert_eq!(a, -1); @@ -63,7 +63,7 @@ fn main() { assert_eq!(c, -1); assert_eq!(d, 0); - assert_approx_eq!(e, -0.3); + assert_approx_eq!(e, 0.3); assert_eq!(e2, -9); assert_eq!(f, 9); From 91d3e7f1a0757bf314ab3a4c4be8f910e2355d35 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 20:39:02 -0600 Subject: [PATCH 109/248] Fix wording per feedback Thanks @catamorphism! --- src/libcore/io.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index d23f2fa7e2c75..ffb49177b64f2 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -16,13 +16,13 @@ A quick summary: ## `Reader` and `Writer` traits -These traits define the simplest amount of methods that anything that can do +These traits define the minimal set of methods that anything that can do input and output should implement. ## `ReaderUtil` and `WriterUtil` traits Richer methods that allow you to do more. `Reader` only lets you read a certain -amount of bytes into a buffer, while `ReaderUtil` allows you to read a whole +number of bytes into a buffer, while `ReaderUtil` allows you to read a whole line, for example. Generally, these richer methods are probably the ones you want to actually From 06d196ad5fe2d06eb32478b75c09c0a6063f5d9b Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 19:40:36 -0700 Subject: [PATCH 110/248] Removing some warnings from logging.rs These imports were not being used. --- src/libcore/logging.rs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/libcore/logging.rs b/src/libcore/logging.rs index b192333999ac4..e137c5d3034d2 100644 --- a/src/libcore/logging.rs +++ b/src/libcore/logging.rs @@ -14,10 +14,6 @@ use option::*; use either::*; use rt; use rt::logging::{Logger, StdErrLogger}; -use io; -use libc; -use repr; -use vec; use cast; use str; @@ -45,7 +41,6 @@ pub fn console_off() { #[lang="log_type"] pub fn log_type(level: u32, object: &T) { use container::Container; - use cast::transmute; use io; use libc; use repr; From dc57d15b69601e8d88e7ee71b578a1624e28f89e Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 20:00:39 -0700 Subject: [PATCH 111/248] Remove more warnings. Mostly of the 'unused imports' kind. --- src/libcore/rt/stack.rs | 4 +--- src/libcore/rt/uv/mod.rs | 3 --- src/libcore/rt/uv/uvio.rs | 1 - src/libcore/unstable/lang.rs | 1 - 4 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/libcore/rt/stack.rs b/src/libcore/rt/stack.rs index cab9c3390b2d7..ec56e65931c81 100644 --- a/src/libcore/rt/stack.rs +++ b/src/libcore/rt/stack.rs @@ -39,9 +39,7 @@ pub impl StackSegment { /// Point to the low end of the allocated stack fn start(&self) -> *uint { - unsafe { - vec::raw::to_ptr(self.buf) as *uint - } + vec::raw::to_ptr(self.buf) as *uint } /// Point one word beyond the high end of the allocated stack diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index ad59305830311..522c4a39d5844 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -44,9 +44,6 @@ use vec; use ptr; use cast; use str; -use option::*; -use str::raw::from_c_str; -use to_str::ToStr; use libc::{c_void, c_int, size_t, malloc, free}; use cast::transmute; use ptr::null; diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 8666d43a10048..8aa1860f3521b 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -11,7 +11,6 @@ use option::*; use result::*; use ops::Drop; -use old_iter::CopyableIter; use cell::{Cell, empty_cell}; use cast::transmute; use clone::Clone; diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index 1249392484d23..d59c8ba5a8ee4 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -16,7 +16,6 @@ use libc::{c_char, c_uchar, c_void, size_t, uintptr_t, c_int, STDERR_FILENO}; use managed::raw::BoxRepr; use str; use sys; -use cast::transmute; use rt::{context, OldTaskContext}; use rt::local_services::borrow_local_services; use option::{Option, Some, None}; From d3f70b141a43ebe02dcb3d62ffe2ae42da561aad Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 21:32:32 -0700 Subject: [PATCH 112/248] Fix many warnings. --- src/libcore/rt/uv/mod.rs | 4 ++-- src/librustc/middle/borrowck/gather_loans/lifetime.rs | 1 - src/librustc/middle/borrowck/gather_loans/mod.rs | 2 -- src/librustc/middle/borrowck/gather_loans/restrictions.rs | 1 - src/librustc/middle/borrowck/mod.rs | 2 -- src/librustc/middle/dataflow.rs | 1 - src/librustc/middle/trans/consts.rs | 1 - src/librustc/middle/trans/expr.rs | 2 +- src/librustc/middle/typeck/infer/combine.rs | 2 +- src/librustc/middle/typeck/infer/lattice.rs | 2 -- src/librustpkg/util.rs | 2 +- src/libsyntax/opt_vec.rs | 1 - src/libsyntax/parse/parser.rs | 4 ++-- 13 files changed, 7 insertions(+), 18 deletions(-) diff --git a/src/libcore/rt/uv/mod.rs b/src/libcore/rt/uv/mod.rs index ad59305830311..425c258b8fd5b 100644 --- a/src/libcore/rt/uv/mod.rs +++ b/src/libcore/rt/uv/mod.rs @@ -273,8 +273,8 @@ pub fn uv_error_to_io_error(uverr: UvError) -> IoError { ECONNREFUSED => ConnectionRefused, ECONNRESET => ConnectionReset, EPIPE => BrokenPipe, - e => { - rtdebug!("e %u", e as uint); + _ => { + rtdebug!("uverr.code %u", uverr.code as uint); // XXX: Need to map remaining uv error types OtherIoError } diff --git a/src/librustc/middle/borrowck/gather_loans/lifetime.rs b/src/librustc/middle/borrowck/gather_loans/lifetime.rs index e377bebcc2697..4916a827ccdcd 100644 --- a/src/librustc/middle/borrowck/gather_loans/lifetime.rs +++ b/src/librustc/middle/borrowck/gather_loans/lifetime.rs @@ -11,7 +11,6 @@ //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. -use core::prelude::*; use middle::borrowck::*; use mc = middle::mem_categorization; use middle::ty; diff --git a/src/librustc/middle/borrowck/gather_loans/mod.rs b/src/librustc/middle/borrowck/gather_loans/mod.rs index a422d99b6f5cf..3d2c318a87e2c 100644 --- a/src/librustc/middle/borrowck/gather_loans/mod.rs +++ b/src/librustc/middle/borrowck/gather_loans/mod.rs @@ -16,8 +16,6 @@ // their associated scopes. In phase two, checking loans, we will then make // sure that all of these loans are honored. -use core::prelude::*; - use middle::borrowck::*; use mc = middle::mem_categorization; use middle::pat_util; diff --git a/src/librustc/middle/borrowck/gather_loans/restrictions.rs b/src/librustc/middle/borrowck/gather_loans/restrictions.rs index 3760350dc268c..17bd2109bbe68 100644 --- a/src/librustc/middle/borrowck/gather_loans/restrictions.rs +++ b/src/librustc/middle/borrowck/gather_loans/restrictions.rs @@ -10,7 +10,6 @@ //! Computes the restrictions that result from a borrow. -use core::prelude::*; use middle::borrowck::*; use mc = middle::mem_categorization; use middle::ty; diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 0f01b2b1e418e..714c3c2cc95f5 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -10,8 +10,6 @@ /*! See doc.rs for a thorough explanation of the borrow checker */ -use core::prelude::*; - use mc = middle::mem_categorization; use middle::ty; use middle::typeck; diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 648daaf3cd1d3..56c2b9818cd3c 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -16,7 +16,6 @@ * GEN and KILL bits for each expression. */ -use core::prelude::*; use core::cast; use core::uint; use syntax::ast; diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index e08cc536a701f..f49b804f81320 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -27,7 +27,6 @@ use util::ppaux::{Repr, ty_to_str}; use core::libc::c_uint; use syntax::{ast, ast_util, ast_map}; -use util::ppaux::ty_to_str; pub fn const_lit(cx: @CrateContext, e: @ast::expr, lit: ast::lit) -> ValueRef { diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 51f17fcf47c4f..8883cc44d1213 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -145,7 +145,7 @@ use middle::trans::type_of; use middle::ty::struct_fields; use middle::ty::{AutoDerefRef, AutoAddEnv}; use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowVecRef, AutoBorrowFn, - AutoDerefRef, AutoAddEnv, AutoUnsafe}; + AutoUnsafe}; use middle::ty; use util::common::indenter; use util::ppaux::Repr; diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/typeck/infer/combine.rs index 0efecefa3580e..b318e6ff3f6b6 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/typeck/infer/combine.rs @@ -62,7 +62,7 @@ use middle::typeck::infer::glb::Glb; use middle::typeck::infer::lub::Lub; use middle::typeck::infer::sub::Sub; use middle::typeck::infer::to_str::InferStr; -use middle::typeck::infer::{cres, InferCtxt, ures, IntType, UintType}; +use middle::typeck::infer::{cres, InferCtxt, ures}; use util::common::indent; use core::result::{iter_vec2, map_vec2}; diff --git a/src/librustc/middle/typeck/infer/lattice.rs b/src/librustc/middle/typeck/infer/lattice.rs index 3c48e09c05747..57bab29664da8 100644 --- a/src/librustc/middle/typeck/infer/lattice.rs +++ b/src/librustc/middle/typeck/infer/lattice.rs @@ -41,8 +41,6 @@ use middle::typeck::infer::glb::Glb; use middle::typeck::infer::lub::Lub; use middle::typeck::infer::unify::*; use middle::typeck::infer::sub::Sub; -use middle::typeck::infer::lub::Lub; -use middle::typeck::infer::glb::Glb; use middle::typeck::infer::to_str::InferStr; use util::common::indenter; diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index 108a404eb7c02..0ae9539fecec3 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -16,7 +16,7 @@ use rustc::driver::{driver, session}; use rustc::metadata::filesearch; use std::getopts::groups::getopts; use std::semver; -use std::{term, getopts}; +use std::term; use syntax::ast_util::*; use syntax::codemap::{dummy_sp, spanned, dummy_spanned}; use syntax::ext::base::{mk_ctxt, ext_ctxt}; diff --git a/src/libsyntax/opt_vec.rs b/src/libsyntax/opt_vec.rs index fb3622396c951..288e80f610193 100644 --- a/src/libsyntax/opt_vec.rs +++ b/src/libsyntax/opt_vec.rs @@ -16,7 +16,6 @@ * other useful things like `push()` and `len()`. */ -use core::prelude::*; use core::old_iter; use core::old_iter::BaseIter; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 25b45a5f3b5cc..cfef9c4987958 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -30,10 +30,10 @@ use ast::{expr_ret, expr_self, expr_struct, expr_tup, expr_unary}; use ast::{expr_vec, expr_vstore, expr_vstore_mut_box}; use ast::{expr_vstore_slice, expr_vstore_box}; use ast::{expr_vstore_mut_slice, expr_while, extern_fn, field, fn_decl}; -use ast::{expr_vstore_uniq, TyClosure, TyBareFn, Onceness, Once, Many}; +use ast::{expr_vstore_uniq, Onceness, Once, Many}; use ast::{foreign_item, foreign_item_const, foreign_item_fn, foreign_mod}; use ast::{ident, impure_fn, inherited, item, item_, item_const}; -use ast::{item_const, item_enum, item_fn, item_foreign_mod, item_impl}; +use ast::{item_enum, item_fn, item_foreign_mod, item_impl}; use ast::{item_mac, item_mod, item_struct, item_trait, item_ty, lit, lit_}; use ast::{lit_bool, lit_float, lit_float_unsuffixed, lit_int}; use ast::{lit_int_unsuffixed, lit_nil, lit_str, lit_uint, local, m_const}; From dcc2879266ee6e733a4729b425da0ff25aeebd1f Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 19 May 2013 22:40:13 -0600 Subject: [PATCH 113/248] Add a few 'function's. This is now 100% consistent. Whoops! --- src/libcore/io.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 8be02947ddb21..ad4ced47ae540 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -92,7 +92,7 @@ pub trait Reader { * * The buffer must be at least `len` bytes long. * - * `read` is conceptually similar to C's `fread`. + * `read` is conceptually similar to C's `fread` function. * * # Examples * @@ -130,7 +130,7 @@ pub trait Reader { * Takes an optional SeekStyle, which affects how we seek from the * position. See `SeekStyle` docs for more details. * - * `seek` is conceptually similar to C's `fseek`. + * `seek` is conceptually similar to C's `fseek` function. * * # Examples * From 66319b027888ceddf024a5919e007caceaf369f3 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 19:46:54 -0700 Subject: [PATCH 114/248] Register snapshots --- src/libcore/cast.rs | 14 - src/libcore/char.rs | 35 - src/libcore/cleanup.rs | 27 - src/libcore/container.rs | 53 - src/libcore/gc.rs | 10 - src/libcore/hash.rs | 10 - src/libcore/hashmap.rs | 185 - src/libcore/io.rs | 44 - src/libcore/iter.rs | 47 +- src/libcore/iterator.rs | 20 - src/libcore/kinds.rs | 6 - src/libcore/num/f32.rs | 10 - src/libcore/num/f64.rs | 10 - src/libcore/num/int-template.rs | 28 - src/libcore/num/uint-template.rs | 29 - src/libcore/num/uint-template/uint.rs | 23 - src/libcore/old_iter.rs | 29 - src/libcore/option.rs | 18 - src/libcore/os.rs | 31 +- src/libcore/rt/comm.rs | 7 - src/libcore/rt/io/mod.rs | 8 - src/libcore/stackwalk.rs | 29 - src/libcore/str.rs | 382 +- src/libcore/task/spawn.rs | 5 - src/libcore/to_bytes.rs | 348 +- src/libcore/trie.rs | 75 - src/libcore/unicode.rs | 26 - src/libcore/unstable/intrinsics.rs | 5 - src/libcore/unstable/lang.rs | 38 - src/libcore/unstable/sync.rs | 24 - src/libcore/util.rs | 24 - src/libcore/vec.rs | 234 - src/librustc/metadata/csearch.rs | 21 - src/librustc/metadata/decoder.rs | 34 - src/librustc/metadata/filesearch.rs | 28 - src/librustc/middle/borrowck/check_loans.rs | 57 - src/librustc/middle/borrowck/mod.rs | 2 - src/librustc/middle/dataflow.rs | 58 - src/librustc/middle/lang_items.rs | 9 - src/librustc/middle/lint.rs | 33 - src/librustc/middle/resolve_stage0.rs | 5324 ----------------- src/librustc/middle/trans/common.rs | 29 - src/librustc/middle/trans/datum.rs | 7 - src/librustc/middle/ty.rs | 254 - src/librustc/middle/typeck/check/mod.rs | 9 - src/librustc/middle/typeck/check/regionck.rs | 20 - src/librustc/middle/typeck/coherence.rs | 21 - .../middle/typeck/infer/region_inference.rs | 35 - src/librustc/rustc.rc | 3 - src/librustc/util/enum_set.rs | 19 - src/libstd/bitv.rs | 47 - src/libstd/deque.rs | 12 - src/libstd/dlist.rs | 47 - src/libstd/ebml.rs | 41 - src/libstd/fileinput.rs | 56 - src/libstd/list.rs | 33 - src/libstd/net_url.rs | 7 - src/libstd/priority_queue.rs | 6 - src/libstd/rc.rs | 32 - src/libstd/smallintmap.rs | 48 - src/libstd/sort.rs | 20 - src/libstd/sort_stage0.rs | 1240 ---- src/libstd/std.rc | 6 - src/libstd/treemap.rs | 208 - src/libstd/workcache.rs | 11 - src/libsyntax/abi.rs | 39 - src/libsyntax/ast.rs | 108 - src/libsyntax/ast_util.rs | 9 - src/libsyntax/codemap.rs | 48 - src/libsyntax/ext/pipes/proto.rs | 15 - src/libsyntax/opt_vec.rs | 14 - src/libsyntax/parse/obsolete.rs | 8 - src/libsyntax/parse/token.rs | 8 - src/snapshots.txt | 8 + 74 files changed, 24 insertions(+), 9844 deletions(-) delete mode 100644 src/librustc/middle/resolve_stage0.rs delete mode 100644 src/libstd/sort_stage0.rs diff --git a/src/libcore/cast.rs b/src/libcore/cast.rs index 8b48376caac5e..4e71b62f10cd7 100644 --- a/src/libcore/cast.rs +++ b/src/libcore/cast.rs @@ -24,20 +24,6 @@ pub mod rusti { } /// Casts the value at `src` to U. The two types must have the same length. -#[cfg(not(stage0))] -pub unsafe fn transmute_copy(src: &T) -> U { - let mut dest: U = unstable::intrinsics::uninit(); - { - let dest_ptr: *mut u8 = rusti::transmute(&mut dest); - let src_ptr: *u8 = rusti::transmute(src); - unstable::intrinsics::memmove64(dest_ptr, - src_ptr, - sys::size_of::() as u64); - } - dest -} - -#[cfg(stage0)] pub unsafe fn transmute_copy(src: &T) -> U { let mut dest: U = unstable::intrinsics::init(); { diff --git a/src/libcore/char.rs b/src/libcore/char.rs index f977845eb8a58..bd70f59212d21 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -12,9 +12,6 @@ use option::{None, Option, Some}; use str; -#[cfg(stage0)] -use str::StrSlice; -#[cfg(not(stage0))] use str::{StrSlice, OwnedStr}; use u32; use uint; @@ -191,21 +188,6 @@ pub fn from_digit(num: uint, radix: uint) -> Option { } } -#[cfg(stage0)] -pub fn escape_unicode(c: char) -> ~str { - let s = u32::to_str_radix(c as u32, 16u); - let (c, pad) = (if c <= '\xff' { ('x', 2u) } - else if c <= '\uffff' { ('u', 4u) } - else { ('U', 8u) }); - assert!(str::len(s) <= pad); - let mut out = ~"\\"; - str::push_str(&mut out, str::from_char(c)); - for uint::range(str::len(s), pad) |_i| - { str::push_str(&mut out, ~"0"); } - str::push_str(&mut out, s); - out -} - /// /// Return the hexadecimal unicode escape of a char. /// @@ -215,7 +197,6 @@ pub fn escape_unicode(c: char) -> ~str { /// - chars in [0x100,0xffff] get 4-digit escapes: `\\uNNNN` /// - chars above 0x10000 get 8-digit escapes: `\\UNNNNNNNN` /// -#[cfg(not(stage0))] pub fn escape_unicode(c: char) -> ~str { let s = u32::to_str_radix(c as u32, 16u); let (c, pad) = cond!( @@ -258,23 +239,7 @@ pub fn escape_default(c: char) -> ~str { } } -#[cfg(stage0)] -pub fn len_utf8_bytes(c: char) -> uint { - static max_one_b: uint = 128u; - static max_two_b: uint = 2048u; - static max_three_b: uint = 65536u; - static max_four_b: uint = 2097152u; - - let code = c as uint; - if code < max_one_b { 1u } - else if code < max_two_b { 2u } - else if code < max_three_b { 3u } - else if code < max_four_b { 4u } - else { fail!("invalid character!") } -} - /// Returns the amount of bytes this character would need if encoded in utf8 -#[cfg(not(stage0))] pub fn len_utf8_bytes(c: char) -> uint { static MAX_ONE_B: uint = 128u; static MAX_TWO_B: uint = 2048u; diff --git a/src/libcore/cleanup.rs b/src/libcore/cleanup.rs index a5df97e3d574f..5796be7b1e4ce 100644 --- a/src/libcore/cleanup.rs +++ b/src/libcore/cleanup.rs @@ -127,33 +127,6 @@ struct AnnihilateStats { n_bytes_freed: uint } -#[cfg(stage0)] -unsafe fn each_live_alloc(read_next_before: bool, - f: &fn(box: *mut BoxRepr, uniq: bool) -> bool) { - //! Walks the internal list of allocations - - use managed; - - let task: *Task = transmute(rustrt::rust_get_task()); - let box = (*task).boxed_region.live_allocs; - let mut box: *mut BoxRepr = transmute(copy box); - while box != mut_null() { - let next_before = transmute(copy (*box).header.next); - let uniq = - (*box).header.ref_count == managed::raw::RC_MANAGED_UNIQUE; - - if !f(box, uniq) { - return; - } - - if read_next_before { - box = next_before; - } else { - box = transmute(copy (*box).header.next); - } - } -} -#[cfg(not(stage0))] unsafe fn each_live_alloc(read_next_before: bool, f: &fn(box: *mut BoxRepr, uniq: bool) -> bool) -> bool { //! Walks the internal list of allocations diff --git a/src/libcore/container.rs b/src/libcore/container.rs index 1d5d77649549e..505aa5881c5c2 100644 --- a/src/libcore/container.rs +++ b/src/libcore/container.rs @@ -30,31 +30,15 @@ pub trait Map: Mutable { fn contains_key(&self, key: &K) -> bool; // Visits all keys and values - #[cfg(stage0)] - fn each<'a>(&'a self, f: &fn(&K, &'a V) -> bool); - // Visits all keys and values - #[cfg(not(stage0))] fn each<'a>(&'a self, f: &fn(&K, &'a V) -> bool) -> bool; /// Visit all keys - #[cfg(stage0)] - fn each_key(&self, f: &fn(&K) -> bool); - /// Visit all keys - #[cfg(not(stage0))] fn each_key(&self, f: &fn(&K) -> bool) -> bool; /// Visit all values - #[cfg(stage0)] - fn each_value<'a>(&'a self, f: &fn(&'a V) -> bool); - /// Visit all values - #[cfg(not(stage0))] fn each_value<'a>(&'a self, f: &fn(&'a V) -> bool) -> bool; /// Iterate over the map and mutate the contained values - #[cfg(stage0)] - fn mutate_values(&mut self, f: &fn(&K, &mut V) -> bool); - /// Iterate over the map and mutate the contained values - #[cfg(not(stage0))] fn mutate_values(&mut self, f: &fn(&K, &mut V) -> bool) -> bool; /// Return a reference to the value corresponding to the key @@ -81,43 +65,6 @@ pub trait Map: Mutable { fn pop(&mut self, k: &K) -> Option; } -#[cfg(stage0)] -pub trait Set: Mutable { - /// Return true if the set contains a value - fn contains(&self, value: &T) -> bool; - - /// Add a value to the set. Return true if the value was not already - /// present in the set. - fn insert(&mut self, value: T) -> bool; - - /// Remove a value from the set. Return true if the value was - /// present in the set. - fn remove(&mut self, value: &T) -> bool; - - /// Return true if the set has no elements in common with `other`. - /// This is equivalent to checking for an empty intersection. - fn is_disjoint(&self, other: &Self) -> bool; - - /// Return true if the set is a subset of another - fn is_subset(&self, other: &Self) -> bool; - - /// Return true if the set is a superset of another - fn is_superset(&self, other: &Self) -> bool; - - /// Visit the values representing the difference - fn difference(&self, other: &Self, f: &fn(&T) -> bool); - - /// Visit the values representing the symmetric difference - fn symmetric_difference(&self, other: &Self, f: &fn(&T) -> bool); - - /// Visit the values representing the intersection - fn intersection(&self, other: &Self, f: &fn(&T) -> bool); - - /// Visit the values representing the union - fn union(&self, other: &Self, f: &fn(&T) -> bool); -} - -#[cfg(not(stage0))] pub trait Set: Mutable { /// Return true if the set contains a value fn contains(&self, value: &T) -> bool; diff --git a/src/libcore/gc.rs b/src/libcore/gc.rs index 6a427297cc22d..611b95a7745e4 100644 --- a/src/libcore/gc.rs +++ b/src/libcore/gc.rs @@ -171,11 +171,6 @@ unsafe fn _walk_safe_point(fp: *Word, sp: SafePoint, visitor: Visitor) -> bool { return true; } -#[cfg(stage0)] -unsafe fn walk_safe_point(fp: *Word, sp: SafePoint, visitor: Visitor) { - _walk_safe_point(fp, sp, visitor); -} -#[cfg(not(stage0))] unsafe fn walk_safe_point(fp: *Word, sp: SafePoint, visitor: Visitor) -> bool { _walk_safe_point(fp, sp, visitor) } @@ -303,11 +298,6 @@ unsafe fn _walk_gc_roots(mem: Memory, sentinel: **Word, visitor: Visitor) -> boo return true; } -#[cfg(stage0)] -unsafe fn walk_gc_roots(mem: Memory, sentinel: **Word, visitor: Visitor) { - _walk_gc_roots(mem, sentinel, visitor); -} -#[cfg(not(stage0))] unsafe fn walk_gc_roots(mem: Memory, sentinel: **Word, visitor: Visitor) -> bool { _walk_gc_roots(mem, sentinel, visitor) } diff --git a/src/libcore/hash.rs b/src/libcore/hash.rs index ebc15174c5c73..d116c966c5cb3 100644 --- a/src/libcore/hash.rs +++ b/src/libcore/hash.rs @@ -19,8 +19,6 @@ * CPRNG like rand::rng. */ -#[cfg(stage0)] -use cast; use container::Container; use old_iter::BaseIter; use rt::io::Writer; @@ -78,14 +76,6 @@ pub trait Streaming { fn reset(&mut self); } -// XXX: Ugly workaround for bootstrapping. -#[cfg(stage0)] -fn transmute_for_stage0<'a>(bytes: &'a [const u8]) -> &'a [u8] { - unsafe { - cast::transmute(bytes) - } -} -#[cfg(not(stage0))] fn transmute_for_stage0<'a>(bytes: &'a [u8]) -> &'a [u8] { bytes } diff --git a/src/libcore/hashmap.rs b/src/libcore/hashmap.rs index fe44bfba1140d..4770d38895192 100644 --- a/src/libcore/hashmap.rs +++ b/src/libcore/hashmap.rs @@ -87,22 +87,6 @@ priv impl HashMap { } #[inline(always)] - #[cfg(stage0)] - fn bucket_sequence(&self, hash: uint, - op: &fn(uint) -> bool) { - let start_idx = self.to_bucket(hash); - let len_buckets = self.buckets.len(); - let mut idx = start_idx; - loop { - if !op(idx) { return; } - idx = self.next_bucket(idx, len_buckets); - if idx == start_idx { - return; - } - } - } - #[inline(always)] - #[cfg(not(stage0))] fn bucket_sequence(&self, hash: uint, op: &fn(uint) -> bool) -> bool { let start_idx = self.to_bucket(hash); @@ -318,19 +302,6 @@ impl Map for HashMap { } /// Visit all key-value pairs - #[cfg(stage0)] - fn each<'a>(&'a self, blk: &fn(&K, &'a V) -> bool) { - for uint::range(0, self.buckets.len()) |i| { - for self.buckets[i].each |bucket| { - if !blk(&bucket.key, &bucket.value) { - return; - } - } - } - } - - /// Visit all key-value pairs - #[cfg(not(stage0))] fn each<'a>(&'a self, blk: &fn(&K, &'a V) -> bool) -> bool { for uint::range(0, self.buckets.len()) |i| { for self.buckets[i].each |bucket| { @@ -343,44 +314,16 @@ impl Map for HashMap { } /// Visit all keys - #[cfg(stage0)] - fn each_key(&self, blk: &fn(k: &K) -> bool) { - self.each(|k, _| blk(k)) - } - - /// Visit all keys - #[cfg(not(stage0))] fn each_key(&self, blk: &fn(k: &K) -> bool) -> bool { self.each(|k, _| blk(k)) } /// Visit all values - #[cfg(stage0)] - fn each_value<'a>(&'a self, blk: &fn(v: &'a V) -> bool) { - self.each(|_, v| blk(v)) - } - - /// Visit all values - #[cfg(not(stage0))] fn each_value<'a>(&'a self, blk: &fn(v: &'a V) -> bool) -> bool { self.each(|_, v| blk(v)) } /// Iterate over the map and mutate the contained values - #[cfg(stage0)] - fn mutate_values(&mut self, blk: &fn(&K, &mut V) -> bool) { - for uint::range(0, self.buckets.len()) |i| { - match self.buckets[i] { - Some(Bucket{key: ref key, value: ref mut value, _}) => { - if !blk(key, value) { return } - } - None => () - } - } - } - - /// Iterate over the map and mutate the contained values - #[cfg(not(stage0))] fn mutate_values(&mut self, blk: &fn(&K, &mut V) -> bool) -> bool { for uint::range(0, self.buckets.len()) |i| { match self.buckets[i] { @@ -402,19 +345,6 @@ impl Map for HashMap { } /// Return a mutable reference to the value corresponding to the key - #[cfg(stage0)] - fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> { - let idx = match self.bucket_for_key(k) { - FoundEntry(idx) => idx, - TableFull | FoundHole(_) => return None - }; - unsafe { - Some(::cast::transmute_mut_region(self.mut_value_for_bucket(idx))) - } - } - - /// Return a mutable reference to the value corresponding to the key - #[cfg(not(stage0))] fn find_mut<'a>(&'a mut self, k: &K) -> Option<&'a mut V> { let idx = match self.bucket_for_key(k) { FoundEntry(idx) => idx, @@ -485,38 +415,6 @@ pub impl HashMap { /// Return the value corresponding to the key in the map, or insert /// and return the value if it doesn't exist. - #[cfg(stage0)] - fn find_or_insert<'a>(&'a mut self, k: K, v: V) -> &'a V { - if self.size >= self.resize_at { - // n.b.: We could also do this after searching, so - // that we do not resize if this call to insert is - // simply going to update a key in place. My sense - // though is that it's worse to have to search through - // buckets to find the right spot twice than to just - // resize in this corner case. - self.expand(); - } - - let hash = k.hash_keyed(self.k0, self.k1) as uint; - let idx = match self.bucket_for_key_with_hash(hash, &k) { - TableFull => fail!("Internal logic error"), - FoundEntry(idx) => idx, - FoundHole(idx) => { - self.buckets[idx] = Some(Bucket{hash: hash, key: k, - value: v}); - self.size += 1; - idx - }, - }; - - unsafe { - ::cast::transmute_region(self.value_for_bucket(idx)) - } - } - - /// Return the value corresponding to the key in the map, or insert - /// and return the value if it doesn't exist. - #[cfg(not(stage0))] fn find_or_insert<'a>(&'a mut self, k: K, v: V) -> &'a V { if self.size >= self.resize_at { // n.b.: We could also do this after searching, so @@ -545,39 +443,6 @@ pub impl HashMap { /// Return the value corresponding to the key in the map, or create, /// insert, and return a new value if it doesn't exist. - #[cfg(stage0)] - fn find_or_insert_with<'a>(&'a mut self, k: K, f: &fn(&K) -> V) -> &'a V { - if self.size >= self.resize_at { - // n.b.: We could also do this after searching, so - // that we do not resize if this call to insert is - // simply going to update a key in place. My sense - // though is that it's worse to have to search through - // buckets to find the right spot twice than to just - // resize in this corner case. - self.expand(); - } - - let hash = k.hash_keyed(self.k0, self.k1) as uint; - let idx = match self.bucket_for_key_with_hash(hash, &k) { - TableFull => fail!("Internal logic error"), - FoundEntry(idx) => idx, - FoundHole(idx) => { - let v = f(&k); - self.buckets[idx] = Some(Bucket{hash: hash, key: k, - value: v}); - self.size += 1; - idx - }, - }; - - unsafe { - ::cast::transmute_region(self.value_for_bucket(idx)) - } - } - - /// Return the value corresponding to the key in the map, or create, - /// insert, and return a new value if it doesn't exist. - #[cfg(not(stage0))] fn find_or_insert_with<'a>(&'a mut self, k: K, f: &fn(&K) -> V) -> &'a V { if self.size >= self.resize_at { // n.b.: We could also do this after searching, so @@ -680,9 +545,6 @@ pub struct HashSet { impl BaseIter for HashSet { /// Visit all values in order - #[cfg(stage0)] - fn each(&self, f: &fn(&T) -> bool) { self.map.each_key(f) } - #[cfg(not(stage0))] fn each(&self, f: &fn(&T) -> bool) -> bool { self.map.each_key(f) } fn size_hint(&self) -> Option { Some(self.len()) } } @@ -734,32 +596,11 @@ impl Set for HashSet { } /// Visit the values representing the difference - #[cfg(stage0)] - fn difference(&self, other: &HashSet, f: &fn(&T) -> bool) { - for self.each |v| { - if !other.contains(v) { - if !f(v) { return } - } - } - } - - /// Visit the values representing the difference - #[cfg(not(stage0))] fn difference(&self, other: &HashSet, f: &fn(&T) -> bool) -> bool { self.each(|v| other.contains(v) || f(v)) } /// Visit the values representing the symmetric difference - #[cfg(stage0)] - fn symmetric_difference(&self, - other: &HashSet, - f: &fn(&T) -> bool) { - self.difference(other, f); - other.difference(self, f); - } - - /// Visit the values representing the symmetric difference - #[cfg(not(stage0))] fn symmetric_difference(&self, other: &HashSet, f: &fn(&T) -> bool) -> bool { @@ -767,37 +608,11 @@ impl Set for HashSet { } /// Visit the values representing the intersection - #[cfg(stage0)] - fn intersection(&self, other: &HashSet, f: &fn(&T) -> bool) { - for self.each |v| { - if other.contains(v) { - if !f(v) { return } - } - } - } - - /// Visit the values representing the intersection - #[cfg(not(stage0))] fn intersection(&self, other: &HashSet, f: &fn(&T) -> bool) -> bool { self.each(|v| !other.contains(v) || f(v)) } /// Visit the values representing the union - #[cfg(stage0)] - fn union(&self, other: &HashSet, f: &fn(&T) -> bool) { - for self.each |v| { - if !f(v) { return } - } - - for other.each |v| { - if !self.contains(v) { - if !f(v) { return } - } - } - } - - /// Visit the values representing the union - #[cfg(not(stage0))] fn union(&self, other: &HashSet, f: &fn(&T) -> bool) -> bool { self.each(f) && other.each(|v| self.contains(v) || f(v)) } diff --git a/src/libcore/io.rs b/src/libcore/io.rs index 7d76d8d30cd36..2ffd362519f15 100644 --- a/src/libcore/io.rs +++ b/src/libcore/io.rs @@ -282,9 +282,6 @@ pub trait ReaderUtil { * * None right now. */ - #[cfg(stage0)] - fn each_byte(&self, it: &fn(int) -> bool); - #[cfg(not(stage0))] fn each_byte(&self, it: &fn(int) -> bool) -> bool; /** @@ -294,9 +291,6 @@ pub trait ReaderUtil { * * None right now. */ - #[cfg(stage0)] - fn each_char(&self, it: &fn(char) -> bool); - #[cfg(not(stage0))] fn each_char(&self, it: &fn(char) -> bool) -> bool; /** @@ -306,9 +300,6 @@ pub trait ReaderUtil { * * None right now. */ - #[cfg(stage0)] - fn each_line(&self, it: &fn(&str) -> bool); - #[cfg(not(stage0))] fn each_line(&self, it: &fn(&str) -> bool) -> bool; /** @@ -720,13 +711,6 @@ impl ReaderUtil for T { bytes } - #[cfg(stage0)] - fn each_byte(&self, it: &fn(int) -> bool) { - while !self.eof() { - if !it(self.read_byte()) { break; } - } - } - #[cfg(not(stage0))] fn each_byte(&self, it: &fn(int) -> bool) -> bool { while !self.eof() { if !it(self.read_byte()) { return false; } @@ -734,13 +718,6 @@ impl ReaderUtil for T { return true; } - #[cfg(stage0)] - fn each_char(&self, it: &fn(char) -> bool) { - while !self.eof() { - if !it(self.read_char()) { break; } - } - } - #[cfg(not(stage0))] fn each_char(&self, it: &fn(char) -> bool) -> bool { while !self.eof() { if !it(self.read_char()) { return false; } @@ -748,27 +725,6 @@ impl ReaderUtil for T { return true; } - #[cfg(stage0)] - fn each_line(&self, it: &fn(s: &str) -> bool) { - while !self.eof() { - // include the \n, so that we can distinguish an entirely empty - // line read after "...\n", and the trailing empty line in - // "...\n\n". - let mut line = self.read_until('\n' as u8, true); - - // blank line at the end of the reader is ignored - if self.eof() && line.is_empty() { break; } - - // trim the \n, so that each_line is consistent with read_line - let n = str::len(line); - if line[n-1] == '\n' as u8 { - unsafe { str::raw::set_len(&mut line, n-1); } - } - - if !it(line) { break; } - } - } - #[cfg(not(stage0))] fn each_line(&self, it: &fn(s: &str) -> bool) -> bool { while !self.eof() { // include the \n, so that we can distinguish an entirely empty diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index ae4af3812d2d2..57a076bb0829b 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -40,17 +40,12 @@ much easier to implement. */ -#[cfg(not(stage0))] use cmp::Ord; -#[cfg(not(stage0))] use option::{Option, Some, None}; -#[cfg(not(stage0))] use vec::OwnedVector; -#[cfg(not(stage0))] use num::{One, Zero}; -#[cfg(not(stage0))] use ops::{Add, Mul}; +use cmp::Ord; +use option::{Option, Some, None}; +use vec::OwnedVector; +use num::{One, Zero}; +use ops::{Add, Mul}; -#[cfg(stage0)] -pub trait Times { - fn times(&self, it: &fn() -> bool); -} -#[cfg(not(stage0))] pub trait Times { fn times(&self, it: &fn() -> bool) -> bool; } @@ -67,7 +62,6 @@ pub trait Times { * ~~~ */ #[inline(always)] -#[cfg(not(stage0))] pub fn to_vec(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[T] { let mut v = ~[]; for iter |x| { v.push(x) } @@ -86,7 +80,6 @@ pub fn to_vec(iter: &fn(f: &fn(T) -> bool) -> bool) -> ~[T] { * ~~~~ */ #[inline(always)] -#[cfg(not(stage0))] pub fn any(predicate: &fn(T) -> bool, iter: &fn(f: &fn(T) -> bool) -> bool) -> bool { for iter |x| { @@ -108,29 +101,6 @@ pub fn any(predicate: &fn(T) -> bool, * ~~~~ */ #[inline(always)] -#[cfg(stage0)] -pub fn all(predicate: &fn(T) -> bool, - iter: &fn(f: &fn(T) -> bool)) -> bool { - for iter |x| { - if !predicate(x) { - return false; - } - } - return true; -} - -/** - * Return true if `predicate` is true for all values yielded by an internal iterator. - * - * # Example: - * - * ~~~~ - * assert!(all(|&x: &uint| x < 6, |f| uint::range(1, 6, f))); - * assert!(!all(|&x: &uint| x < 5, |f| uint::range(1, 6, f))); - * ~~~~ - */ -#[inline(always)] -#[cfg(not(stage0))] pub fn all(predicate: &fn(T) -> bool, iter: &fn(f: &fn(T) -> bool) -> bool) -> bool { // If we ever break, iter will return false, so this will only return true @@ -149,7 +119,6 @@ pub fn all(predicate: &fn(T) -> bool, * ~~~~ */ #[inline(always)] -#[cfg(not(stage0))] pub fn find(predicate: &fn(&T) -> bool, iter: &fn(f: &fn(T) -> bool) -> bool) -> Option { for iter |x| { @@ -171,7 +140,6 @@ pub fn find(predicate: &fn(&T) -> bool, * ~~~~ */ #[inline] -#[cfg(not(stage0))] pub fn max(iter: &fn(f: &fn(T) -> bool) -> bool) -> Option { let mut result = None; for iter |x| { @@ -198,7 +166,6 @@ pub fn max(iter: &fn(f: &fn(T) -> bool) -> bool) -> Option { * ~~~~ */ #[inline] -#[cfg(not(stage0))] pub fn min(iter: &fn(f: &fn(T) -> bool) -> bool) -> Option { let mut result = None; for iter |x| { @@ -223,7 +190,6 @@ pub fn min(iter: &fn(f: &fn(T) -> bool) -> bool) -> Option { * assert_eq!(fold(0i, |f| int::range(1, 5, f), |a, x| *a += x), 10); * ~~~~ */ -#[cfg(not(stage0))] #[inline] pub fn fold(start: T, iter: &fn(f: &fn(U) -> bool) -> bool, f: &fn(&mut T, U)) -> T { let mut result = start; @@ -247,7 +213,6 @@ pub fn fold(start: T, iter: &fn(f: &fn(U) -> bool) -> bool, f: &fn(&mut T, * } * ~~~~ */ -#[cfg(not(stage0))] #[inline] pub fn fold_ref(start: T, iter: &fn(f: &fn(&U) -> bool) -> bool, f: &fn(&mut T, &U)) -> T { let mut result = start; @@ -267,7 +232,6 @@ pub fn fold_ref(start: T, iter: &fn(f: &fn(&U) -> bool) -> bool, f: &fn(&m * assert_eq!(do sum |f| { xs.each(f) }, 10); * ~~~~ */ -#[cfg(not(stage0))] #[inline(always)] pub fn sum>(iter: &fn(f: &fn(&T) -> bool) -> bool) -> T { fold_ref(Zero::zero::(), iter, |a, x| *a = a.add(x)) @@ -283,7 +247,6 @@ pub fn sum>(iter: &fn(f: &fn(&T) -> bool) -> bool) -> T { * assert_eq!(do product |f| { xs.each(f) }, 24); * ~~~~ */ -#[cfg(not(stage0))] #[inline(always)] pub fn product>(iter: &fn(f: &fn(&T) -> bool) -> bool) -> T { fold_ref(One::one::(), iter, |a, x| *a = a.mul(x)) diff --git a/src/libcore/iterator.rs b/src/libcore/iterator.rs index ecf76a39fcdb5..a5679e6dbff20 100644 --- a/src/libcore/iterator.rs +++ b/src/libcore/iterator.rs @@ -43,11 +43,7 @@ pub trait IteratorUtil { fn take(self, n: uint) -> TakeIterator; fn scan<'r, St, B>(self, initial_state: St, f: &'r fn(&mut St, A) -> Option) -> ScanIterator<'r, A, B, Self, St>; - #[cfg(stage0)] - fn advance(&mut self, f: &fn(A) -> bool); - #[cfg(not(stage0))] fn advance(&mut self, f: &fn(A) -> bool) -> bool; - #[cfg(not(stage0))] fn to_vec(&mut self) -> ~[A]; fn nth(&mut self, n: uint) -> Option; fn last(&mut self) -> Option; @@ -121,21 +117,6 @@ impl> IteratorUtil for T { /// A shim implementing the `for` loop iteration protocol for iterator objects #[inline] - #[cfg(stage0)] - fn advance(&mut self, f: &fn(A) -> bool) { - loop { - match self.next() { - Some(x) => { - if !f(x) { return; } - } - None => { return; } - } - } - } - - /// A shim implementing the `for` loop iteration protocol for iterator objects - #[inline] - #[cfg(not(stage0))] fn advance(&mut self, f: &fn(A) -> bool) -> bool { loop { match self.next() { @@ -147,7 +128,6 @@ impl> IteratorUtil for T { } } - #[cfg(not(stage0))] #[inline(always)] fn to_vec(&mut self) -> ~[A] { iter::to_vec::(|f| self.advance(f)) diff --git a/src/libcore/kinds.rs b/src/libcore/kinds.rs index eeafc4cf786a5..d9b3e35b6b9d7 100644 --- a/src/libcore/kinds.rs +++ b/src/libcore/kinds.rs @@ -51,9 +51,3 @@ pub trait Owned { pub trait Const { // Empty. } - -#[lang="durable"] -#[cfg(stage0)] -pub trait Durable { - // Empty. -} diff --git a/src/libcore/num/f32.rs b/src/libcore/num/f32.rs index d580f7aa26c99..d5dc0dd4730e1 100644 --- a/src/libcore/num/f32.rs +++ b/src/libcore/num/f32.rs @@ -248,18 +248,8 @@ impl Orderable for f32 { if self.is_NaN() || other.is_NaN() { Float::NaN() } else { fmax(*self, *other) } } - #[cfg(stage0)] - #[inline(always)] - fn clamp(&self, mn: &f32, mx: &f32) -> f32 { - if self.is_NaN() { *self } - else if !(*self <= *mx) { *mx } - else if !(*self >= *mn) { *mn } - else { *self } - } - /// Returns the number constrained within the range `mn <= self <= mx`. /// If any of the numbers are `NaN` then `NaN` is returned. - #[cfg(not(stage0))] #[inline(always)] fn clamp(&self, mn: &f32, mx: &f32) -> f32 { cond!( diff --git a/src/libcore/num/f64.rs b/src/libcore/num/f64.rs index d140df30c4273..6e2496e2e4561 100644 --- a/src/libcore/num/f64.rs +++ b/src/libcore/num/f64.rs @@ -270,18 +270,8 @@ impl Orderable for f64 { if self.is_NaN() || other.is_NaN() { Float::NaN() } else { fmax(*self, *other) } } - #[cfg(stage0)] - #[inline(always)] - fn clamp(&self, mn: &f64, mx: &f64) -> f64 { - if self.is_NaN() { *self } - else if !(*self <= *mx) { *mx } - else if !(*self >= *mn) { *mn } - else { *self } - } - /// Returns the number constrained within the range `mn <= self <= mx`. /// If any of the numbers are `NaN` then `NaN` is returned. - #[cfg(not(stage0))] #[inline(always)] fn clamp(&self, mn: &f64, mx: &f64) -> f64 { cond!( diff --git a/src/libcore/num/int-template.rs b/src/libcore/num/int-template.rs index d0e6174ec637d..3c31a7d574518 100644 --- a/src/libcore/num/int-template.rs +++ b/src/libcore/num/int-template.rs @@ -108,37 +108,17 @@ pub fn _range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) -> bool { return true; } -#[cfg(stage0)] -pub fn range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) { - _range_step(start, stop, step, it); -} -#[cfg(not(stage0))] pub fn range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) -> bool { _range_step(start, stop, step, it) } #[inline(always)] -#[cfg(stage0)] -/// Iterate over the range [`lo`..`hi`) -pub fn range(lo: T, hi: T, it: &fn(T) -> bool) { - range_step(lo, hi, 1 as T, it); -} - -#[inline(always)] -#[cfg(not(stage0))] /// Iterate over the range [`lo`..`hi`) pub fn range(lo: T, hi: T, it: &fn(T) -> bool) -> bool { range_step(lo, hi, 1 as T, it) } #[inline(always)] -#[cfg(stage0)] -/// Iterate over the range [`hi`..`lo`) -pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) { - range_step(hi, lo, -1 as T, it); -} -#[inline(always)] -#[cfg(not(stage0))] /// Iterate over the range [`hi`..`lo`) pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) -> bool { range_step(hi, lo, -1 as T, it) @@ -187,15 +167,7 @@ impl Orderable for T { if *self > *other { *self } else { *other } } - #[cfg(stage0)] - #[inline(always)] - fn clamp(&self, mn: &T, mx: &T) -> T { - if *self > *mx { *mx } else - if *self < *mn { *mn } else { *self } - } - /// Returns the number constrained within the range `mn <= self <= mx`. - #[cfg(not(stage0))] #[inline(always)] fn clamp(&self, mn: &T, mx: &T) -> T { cond!( diff --git a/src/libcore/num/uint-template.rs b/src/libcore/num/uint-template.rs index f3e140945057c..66ff16cbeb1ef 100644 --- a/src/libcore/num/uint-template.rs +++ b/src/libcore/num/uint-template.rs @@ -77,38 +77,17 @@ pub fn _range_step(start: T, return true; } -#[cfg(stage0)] -pub fn range_step(start: T, stop: T, step: T_SIGNED, it: &fn(T) -> bool) { - _range_step(start, stop, step, it); -} -#[cfg(not(stage0))] pub fn range_step(start: T, stop: T, step: T_SIGNED, it: &fn(T) -> bool) -> bool { _range_step(start, stop, step, it) } #[inline(always)] -#[cfg(stage0)] -/// Iterate over the range [`lo`..`hi`) -pub fn range(lo: T, hi: T, it: &fn(T) -> bool) { - range_step(lo, hi, 1 as T_SIGNED, it); -} - -#[inline(always)] -#[cfg(not(stage0))] /// Iterate over the range [`lo`..`hi`) pub fn range(lo: T, hi: T, it: &fn(T) -> bool) -> bool { range_step(lo, hi, 1 as T_SIGNED, it) } #[inline(always)] -#[cfg(stage0)] -/// Iterate over the range [`hi`..`lo`) -pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) { - range_step(hi, lo, -1 as T_SIGNED, it); -} - -#[inline(always)] -#[cfg(not(stage0))] /// Iterate over the range [`hi`..`lo`) pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) -> bool { range_step(hi, lo, -1 as T_SIGNED, it) @@ -153,15 +132,7 @@ impl Orderable for T { if *self > *other { *self } else { *other } } - #[cfg(stage0)] - #[inline(always)] - fn clamp(&self, mn: &T, mx: &T) -> T { - if *self > *mx { *mx } else - if *self < *mn { *mn } else { *self } - } - /// Returns the number constrained within the range `mn <= self <= mx`. - #[cfg(not(stage0))] #[inline(always)] fn clamp(&self, mn: &T, mx: &T) -> T { cond!( diff --git a/src/libcore/num/uint-template/uint.rs b/src/libcore/num/uint-template/uint.rs index b4c9bb653712e..763c305f22149 100644 --- a/src/libcore/num/uint-template/uint.rs +++ b/src/libcore/num/uint-template/uint.rs @@ -154,29 +154,6 @@ pub mod inst { return true; } - #[cfg(stage0)] - impl iter::Times for uint { - #[inline(always)] - /// - /// A convenience form for basic iteration. Given a uint `x`, - /// `for x.times { ... }` executes the given block x times. - /// - /// Equivalent to `for uint::range(0, x) |_| { ... }`. - /// - /// Not defined on all integer types to permit unambiguous - /// use with integer literals of inferred integer-type as - /// the self-value (eg. `for 100.times { ... }`). - /// - fn times(&self, it: &fn() -> bool) { - let mut i = *self; - while i > 0 { - if !it() { break } - i -= 1; - } - } - } - - #[cfg(not(stage0))] impl iter::Times for uint { #[inline(always)] /// diff --git a/src/libcore/old_iter.rs b/src/libcore/old_iter.rs index 12b7ce1eb6ebb..389b643572cb6 100644 --- a/src/libcore/old_iter.rs +++ b/src/libcore/old_iter.rs @@ -22,39 +22,20 @@ use vec; /// A function used to initialize the elements of a sequence pub type InitOp<'self,T> = &'self fn(uint) -> T; -#[cfg(stage0)] -pub trait BaseIter { - fn each(&self, blk: &fn(v: &A) -> bool); - fn size_hint(&self) -> Option; -} -#[cfg(not(stage0))] pub trait BaseIter { fn each(&self, blk: &fn(v: &A) -> bool) -> bool; fn size_hint(&self) -> Option; } -#[cfg(stage0)] -pub trait ReverseIter: BaseIter { - fn each_reverse(&self, blk: &fn(&A) -> bool); -} -#[cfg(not(stage0))] pub trait ReverseIter: BaseIter { fn each_reverse(&self, blk: &fn(&A) -> bool) -> bool; } -#[cfg(stage0)] -pub trait MutableIter: BaseIter { - fn each_mut(&mut self, blk: &fn(&mut A) -> bool); -} -#[cfg(not(stage0))] pub trait MutableIter: BaseIter { fn each_mut(&mut self, blk: &fn(&mut A) -> bool) -> bool; } pub trait ExtendedIter { - #[cfg(stage0)] - fn eachi(&self, blk: &fn(uint, v: &A) -> bool); - #[cfg(not(stage0))] fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool; fn all(&self, blk: &fn(&A) -> bool) -> bool; fn any(&self, blk: &fn(&A) -> bool) -> bool; @@ -64,11 +45,6 @@ pub trait ExtendedIter { fn flat_map_to_vec>(&self, op: &fn(&A) -> IB) -> ~[B]; } -#[cfg(stage0)] -pub trait ExtendedMutableIter { - fn eachi_mut(&mut self, blk: &fn(uint, &mut A) -> bool); -} -#[cfg(not(stage0))] pub trait ExtendedMutableIter { fn eachi_mut(&mut self, blk: &fn(uint, &mut A) -> bool) -> bool; } @@ -127,11 +103,6 @@ pub fn _eachi>(this: &IA, blk: &fn(uint, &A) -> bool) -> bool { return true; } -#[cfg(stage0)] -pub fn eachi>(this: &IA, blk: &fn(uint, &A) -> bool) { - _eachi(this, blk); -} -#[cfg(not(stage0))] pub fn eachi>(this: &IA, blk: &fn(uint, &A) -> bool) -> bool { _eachi(this, blk) } diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 71c242bb69b3c..bc1ffcdc81ae4 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -112,13 +112,6 @@ impl> Add, Option> for Option { impl BaseIter for Option { /// Performs an operation on the contained value by reference #[inline(always)] - #[cfg(stage0)] - fn each<'a>(&'a self, f: &fn(x: &'a T) -> bool) { - match *self { None => (), Some(ref t) => { f(t); } } - } - /// Performs an operation on the contained value by reference - #[inline(always)] - #[cfg(not(stage0))] fn each<'a>(&'a self, f: &fn(x: &'a T) -> bool) -> bool { match *self { None => true, Some(ref t) => { f(t) } } } @@ -130,12 +123,6 @@ impl BaseIter for Option { } impl MutableIter for Option { - #[cfg(stage0)] - #[inline(always)] - fn each_mut<'a>(&'a mut self, f: &fn(&'a mut T) -> bool) { - match *self { None => (), Some(ref mut t) => { f(t); } } - } - #[cfg(not(stage0))] #[inline(always)] fn each_mut<'a>(&'a mut self, f: &fn(&'a mut T) -> bool) -> bool { match *self { None => true, Some(ref mut t) => { f(t) } } @@ -143,11 +130,6 @@ impl MutableIter for Option { } impl ExtendedIter for Option { - #[cfg(stage0)] - pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) { - old_iter::eachi(self, blk) - } - #[cfg(not(stage0))] pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool { old_iter::eachi(self, blk) } diff --git a/src/libcore/os.rs b/src/libcore/os.rs index 2625d03588be9..b6943462f068b 100644 --- a/src/libcore/os.rs +++ b/src/libcore/os.rs @@ -575,37 +575,8 @@ pub fn tmpdir() -> Path { getenv_nonempty("WINDIR")))).get_or_default(Path("C:\\Windows")) } } + /// Recursively walk a directory structure -#[cfg(stage0)] -pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) { - - walk_dir_(p, f); - - fn walk_dir_(p: &Path, f: &fn(&Path) -> bool) -> bool { - let mut keepgoing = true; - do list_dir(p).each |q| { - let path = &p.push(*q); - if !f(path) { - keepgoing = false; - false - } else { - if path_is_dir(path) { - if !walk_dir_(path, f) { - keepgoing = false; - false - } else { - true - } - } else { - true - } - } - } - return keepgoing; - } -} -/// Recursively walk a directory structure -#[cfg(not(stage0))] pub fn walk_dir(p: &Path, f: &fn(&Path) -> bool) -> bool { list_dir(p).each(|q| { let path = &p.push(*q); diff --git a/src/libcore/rt/comm.rs b/src/libcore/rt/comm.rs index 4b5732b2d3aec..93afbea82786a 100644 --- a/src/libcore/rt/comm.rs +++ b/src/libcore/rt/comm.rs @@ -22,9 +22,6 @@ use ops::Drop; use kinds::Owned; use rt::sched::Coroutine; use rt::local_sched; -#[cfg(stage0)] -use unstable::intrinsics::{atomic_xchg}; -#[cfg(not(stage0))] use unstable::intrinsics::{atomic_xchg, atomic_load}; use util::Void; use comm::{GenericChan, GenericSmartChan, GenericPort, Peekable}; @@ -210,10 +207,6 @@ impl PortOne { } impl Peekable for PortOne { - #[cfg(stage0)] - fn peek(&self) -> bool { fail!() } - - #[cfg(not(stage0))] fn peek(&self) -> bool { unsafe { let packet: *mut Packet = self.inner.packet(); diff --git a/src/libcore/rt/io/mod.rs b/src/libcore/rt/io/mod.rs index 802e069a738f0..0ec51a3aa941e 100644 --- a/src/libcore/rt/io/mod.rs +++ b/src/libcore/rt/io/mod.rs @@ -253,18 +253,13 @@ pub use self::stdio::println; pub use self::file::FileStream; pub use self::net::ip::IpAddr; -#[cfg(not(stage0))] pub use self::net::tcp::TcpListener; -#[cfg(not(stage0))] pub use self::net::tcp::TcpStream; pub use self::net::udp::UdpStream; // Some extension traits that all Readers and Writers get. -#[cfg(not(stage0))] // Requires condition! fixes pub use self::extensions::ReaderUtil; -#[cfg(not(stage0))] // Requires condition! fixes pub use self::extensions::ReaderByteConversions; -#[cfg(not(stage0))] // Requires condition! fixes pub use self::extensions::WriterByteConversions; /// Synchronous, non-blocking file I/O. @@ -272,7 +267,6 @@ pub mod file; /// Synchronous, non-blocking network I/O. pub mod net { - #[cfg(not(stage0))] pub mod tcp; pub mod udp; pub mod ip; @@ -288,7 +282,6 @@ pub mod mem; pub mod stdio; /// Implementations for Option -#[cfg(not(stage0))] // Requires condition! fixes mod option; /// Basic stream compression. XXX: Belongs with other flate code @@ -298,7 +291,6 @@ pub mod flate; pub mod comm_adapters; /// Extension traits -#[cfg(not(stage0))] // Requires condition! fixes mod extensions; /// Non-I/O things needed by the I/O module diff --git a/src/libcore/stackwalk.rs b/src/libcore/stackwalk.rs index e86416f249902..fbb6753723293 100644 --- a/src/libcore/stackwalk.rs +++ b/src/libcore/stackwalk.rs @@ -24,35 +24,6 @@ pub fn Frame(fp: *Word) -> Frame { } } -#[cfg(stage0)] -pub fn walk_stack(visit: &fn(Frame) -> bool) { - - debug!("beginning stack walk"); - - do frame_address |frame_pointer| { - let mut frame_address: *Word = unsafe { - transmute(frame_pointer) - }; - loop { - let fr = Frame(frame_address); - - debug!("frame: %x", unsafe { transmute(fr.fp) }); - visit(fr); - - unsafe { - let next_fp: **Word = transmute(frame_address); - frame_address = *next_fp; - if *frame_address == 0u { - debug!("encountered task_start_wrapper. ending walk"); - // This is the task_start_wrapper_frame. There is - // no stack beneath it and it is a foreign frame. - break; - } - } - } - } -} -#[cfg(not(stage0))] pub fn walk_stack(visit: &fn(Frame) -> bool) -> bool { debug!("beginning stack walk"); diff --git a/src/libcore/str.rs b/src/libcore/str.rs index a3cb180ed2653..a760ff8f26277 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -557,27 +557,12 @@ pub fn slice<'a>(s: &'a str, begin: uint, end: uint) -> &'a str { } /// Splits a string into substrings at each occurrence of a given character -#[cfg(stage0)] -pub fn each_split_char<'a>(s: &'a str, sep: char, it: &fn(&'a str) -> bool) { - each_split_char_inner(s, sep, len(s), true, true, it); -} - -/// Splits a string into substrings at each occurrence of a given character -#[cfg(not(stage0))] pub fn each_split_char<'a>(s: &'a str, sep: char, it: &fn(&'a str) -> bool) -> bool { each_split_char_inner(s, sep, len(s), true, true, it) } /// Like `each_split_char`, but a trailing empty string is omitted -#[cfg(stage0)] -pub fn each_split_char_no_trailing<'a>(s: &'a str, - sep: char, - it: &fn(&'a str) -> bool) { - each_split_char_inner(s, sep, len(s), true, false, it); -} -/// Like `each_split_char`, but a trailing empty string is omitted -#[cfg(not(stage0))] pub fn each_split_char_no_trailing<'a>(s: &'a str, sep: char, it: &fn(&'a str) -> bool) -> bool { @@ -590,20 +575,6 @@ pub fn each_split_char_no_trailing<'a>(s: &'a str, * * The character must be a valid UTF-8/ASCII character */ -#[cfg(stage0)] -pub fn each_splitn_char<'a>(s: &'a str, - sep: char, - count: uint, - it: &fn(&'a str) -> bool) { - each_split_char_inner(s, sep, count, true, true, it); -} -/** - * Splits a string into substrings at each occurrence of a given - * character up to 'count' times. - * - * The character must be a valid UTF-8/ASCII character - */ -#[cfg(not(stage0))] pub fn each_splitn_char<'a>(s: &'a str, sep: char, count: uint, @@ -612,14 +583,6 @@ pub fn each_splitn_char<'a>(s: &'a str, } /// Like `each_split_char`, but omits empty strings -#[cfg(stage0)] -pub fn each_split_char_nonempty<'a>(s: &'a str, - sep: char, - it: &fn(&'a str) -> bool) { - each_split_char_inner(s, sep, len(s), false, false, it); -} -/// Like `each_split_char`, but omits empty strings -#[cfg(not(stage0))] pub fn each_split_char_nonempty<'a>(s: &'a str, sep: char, it: &fn(&'a str) -> bool) -> bool { @@ -659,14 +622,6 @@ fn each_split_char_inner<'a>(s: &'a str, } /// Splits a string into substrings using a character function -#[cfg(stage0)] -pub fn each_split<'a>(s: &'a str, - sepfn: &fn(char) -> bool, - it: &fn(&'a str) -> bool) { - each_split_inner(s, sepfn, len(s), true, true, it); -} -/// Splits a string into substrings using a character function -#[cfg(not(stage0))] pub fn each_split<'a>(s: &'a str, sepfn: &fn(char) -> bool, it: &fn(&'a str) -> bool) -> bool { @@ -674,14 +629,6 @@ pub fn each_split<'a>(s: &'a str, } /// Like `each_split`, but a trailing empty string is omitted -#[cfg(stage0)] -pub fn each_split_no_trailing<'a>(s: &'a str, - sepfn: &fn(char) -> bool, - it: &fn(&'a str) -> bool) { - each_split_inner(s, sepfn, len(s), true, false, it); -} -/// Like `each_split`, but a trailing empty string is omitted -#[cfg(not(stage0))] pub fn each_split_no_trailing<'a>(s: &'a str, sepfn: &fn(char) -> bool, it: &fn(&'a str) -> bool) -> bool { @@ -692,18 +639,6 @@ pub fn each_split_no_trailing<'a>(s: &'a str, * Splits a string into substrings using a character function, cutting at * most `count` times. */ -#[cfg(stage0)] -pub fn each_splitn<'a>(s: &'a str, - sepfn: &fn(char) -> bool, - count: uint, - it: &fn(&'a str) -> bool) { - each_split_inner(s, sepfn, count, true, true, it); -} -/** - * Splits a string into substrings using a character function, cutting at - * most `count` times. - */ -#[cfg(not(stage0))] pub fn each_splitn<'a>(s: &'a str, sepfn: &fn(char) -> bool, count: uint, @@ -712,14 +647,6 @@ pub fn each_splitn<'a>(s: &'a str, } /// Like `each_split`, but omits empty strings -#[cfg(stage0)] -pub fn each_split_nonempty<'a>(s: &'a str, - sepfn: &fn(char) -> bool, - it: &fn(&'a str) -> bool) { - each_split_inner(s, sepfn, len(s), false, false, it); -} -/// Like `each_split`, but omits empty strings -#[cfg(not(stage0))] pub fn each_split_nonempty<'a>(s: &'a str, sepfn: &fn(char) -> bool, it: &fn(&'a str) -> bool) -> bool { @@ -754,36 +681,6 @@ fn each_split_inner<'a>(s: &'a str, } // See Issue #1932 for why this is a naive search -#[cfg(stage0)] -fn iter_matches<'a,'b>(s: &'a str, sep: &'b str, - f: &fn(uint, uint) -> bool) { - let sep_len = len(sep), l = len(s); - assert!(sep_len > 0u); - let mut i = 0u, match_start = 0u, match_i = 0u; - - while i < l { - if s[i] == sep[match_i] { - if match_i == 0u { match_start = i; } - match_i += 1u; - // Found a match - if match_i == sep_len { - if !f(match_start, i + 1u) { return; } - match_i = 0u; - } - i += 1u; - } else { - // Failed match, backtrack - if match_i > 0u { - match_i = 0u; - i = match_start + 1u; - } else { - i += 1u; - } - } - } -} -// See Issue #1932 for why this is a naive search -#[cfg(not(stage0))] fn iter_matches<'a,'b>(s: &'a str, sep: &'b str, f: &fn(uint, uint) -> bool) -> bool { let sep_len = len(sep), l = len(s); @@ -813,18 +710,6 @@ fn iter_matches<'a,'b>(s: &'a str, sep: &'b str, return true; } -#[cfg(stage0)] -fn iter_between_matches<'a,'b>(s: &'a str, - sep: &'b str, - f: &fn(uint, uint) -> bool) { - let mut last_end = 0u; - for iter_matches(s, sep) |from, to| { - if !f(last_end, from) { return; } - last_end = to; - } - f(last_end, len(s)); -} -#[cfg(not(stage0))] fn iter_between_matches<'a,'b>(s: &'a str, sep: &'b str, f: &fn(uint, uint) -> bool) -> bool { @@ -847,26 +732,6 @@ fn iter_between_matches<'a,'b>(s: &'a str, * assert!(v == ["", "XXX", "YYY", ""]); * ~~~ */ -#[cfg(stage0)] -pub fn each_split_str<'a,'b>(s: &'a str, - sep: &'b str, - it: &fn(&'a str) -> bool) { - for iter_between_matches(s, sep) |from, to| { - if !it( unsafe { raw::slice_bytes(s, from, to) } ) { return; } - } -} -/** - * Splits a string into a vector of the substrings separated by a given string - * - * # Example - * - * ~~~ - * let mut v = ~[]; - * for each_split_str(".XXX.YYY.", ".") |subs| { v.push(subs); } - * assert!(v == ["", "XXX", "YYY", ""]); - * ~~~ - */ -#[cfg(not(stage0))] pub fn each_split_str<'a,'b>(s: &'a str, sep: &'b str, it: &fn(&'a str) -> bool) -> bool { @@ -876,18 +741,6 @@ pub fn each_split_str<'a,'b>(s: &'a str, return true; } -#[cfg(stage0)] -pub fn each_split_str_nonempty<'a,'b>(s: &'a str, - sep: &'b str, - it: &fn(&'a str) -> bool) { - for iter_between_matches(s, sep) |from, to| { - if to > from { - if !it( unsafe { raw::slice_bytes(s, from, to) } ) { return; } - } - } -} - -#[cfg(not(stage0))] pub fn each_split_str_nonempty<'a,'b>(s: &'a str, sep: &'b str, it: &fn(&'a str) -> bool) -> bool { @@ -936,14 +789,6 @@ pub fn levdistance(s: &str, t: &str) -> uint { /** * Splits a string into substrings separated by LF ('\n'). */ -#[cfg(stage0)] -pub fn each_line<'a>(s: &'a str, it: &fn(&'a str) -> bool) { - each_split_char_no_trailing(s, '\n', it); -} -/** - * Splits a string into substrings separated by LF ('\n'). - */ -#[cfg(not(stage0))] pub fn each_line<'a>(s: &'a str, it: &fn(&'a str) -> bool) -> bool { each_split_char_no_trailing(s, '\n', it) } @@ -952,22 +797,6 @@ pub fn each_line<'a>(s: &'a str, it: &fn(&'a str) -> bool) -> bool { * Splits a string into substrings separated by LF ('\n') * and/or CR LF ("\r\n") */ -#[cfg(stage0)] -pub fn each_line_any<'a>(s: &'a str, it: &fn(&'a str) -> bool) { - for each_line(s) |s| { - let l = s.len(); - if l > 0u && s[l - 1u] == '\r' as u8 { - if !it( unsafe { raw::slice_bytes(s, 0, l - 1) } ) { return; } - } else { - if !it( s ) { return; } - } - } -} -/** - * Splits a string into substrings separated by LF ('\n') - * and/or CR LF ("\r\n") - */ -#[cfg(not(stage0))] pub fn each_line_any<'a>(s: &'a str, it: &fn(&'a str) -> bool) -> bool { for each_line(s) |s| { let l = s.len(); @@ -981,12 +810,6 @@ pub fn each_line_any<'a>(s: &'a str, it: &fn(&'a str) -> bool) -> bool { } /// Splits a string into substrings separated by whitespace -#[cfg(stage0)] -pub fn each_word<'a>(s: &'a str, it: &fn(&'a str) -> bool) { - each_split_nonempty(s, char::is_whitespace, it); -} -/// Splits a string into substrings separated by whitespace -#[cfg(not(stage0))] pub fn each_word<'a>(s: &'a str, it: &fn(&'a str) -> bool) -> bool { each_split_nonempty(s, char::is_whitespace, it) } @@ -1063,13 +886,6 @@ pub fn _each_split_within<'a>(ss: &'a str, return cont; } -#[cfg(stage0)] -pub fn each_split_within<'a>(ss: &'a str, - lim: uint, - it: &fn(&'a str) -> bool) { - _each_split_within(ss, lim, it); -} -#[cfg(not(stage0))] pub fn each_split_within<'a>(ss: &'a str, lim: uint, it: &fn(&'a str) -> bool) -> bool { @@ -1352,33 +1168,12 @@ pub fn map(ss: &str, ff: &fn(char) -> char) -> ~str { /// Iterate over the bytes in a string #[inline(always)] -#[cfg(stage0)] -pub fn each(s: &str, it: &fn(u8) -> bool) { - eachi(s, |_i, b| it(b)) -} -/// Iterate over the bytes in a string -#[inline(always)] -#[cfg(not(stage0))] pub fn each(s: &str, it: &fn(u8) -> bool) -> bool { eachi(s, |_i, b| it(b)) } /// Iterate over the bytes in a string, with indices #[inline(always)] -#[cfg(stage0)] -pub fn eachi(s: &str, it: &fn(uint, u8) -> bool) { - let mut pos = 0; - let len = s.len(); - - while pos < len { - if !it(pos, s[pos]) { break; } - pos += 1; - } -} - -/// Iterate over the bytes in a string, with indices -#[inline(always)] -#[cfg(not(stage0))] pub fn eachi(s: &str, it: &fn(uint, u8) -> bool) -> bool { let mut pos = 0; let len = s.len(); @@ -1392,30 +1187,12 @@ pub fn eachi(s: &str, it: &fn(uint, u8) -> bool) -> bool { /// Iterate over the bytes in a string in reverse #[inline(always)] -#[cfg(stage0)] -pub fn each_reverse(s: &str, it: &fn(u8) -> bool) { - eachi_reverse(s, |_i, b| it(b) ) -} -/// Iterate over the bytes in a string in reverse -#[inline(always)] -#[cfg(not(stage0))] pub fn each_reverse(s: &str, it: &fn(u8) -> bool) -> bool { eachi_reverse(s, |_i, b| it(b) ) } /// Iterate over the bytes in a string in reverse, with indices #[inline(always)] -#[cfg(stage0)] -pub fn eachi_reverse(s: &str, it: &fn(uint, u8) -> bool) { - let mut pos = s.len(); - while pos > 0 { - pos -= 1; - if !it(pos, s[pos]) { break; } - } -} -/// Iterate over the bytes in a string in reverse, with indices -#[inline(always)] -#[cfg(not(stage0))] pub fn eachi_reverse(s: &str, it: &fn(uint, u8) -> bool) -> bool { let mut pos = s.len(); while pos > 0 { @@ -1427,19 +1204,6 @@ pub fn eachi_reverse(s: &str, it: &fn(uint, u8) -> bool) -> bool { /// Iterate over each char of a string, without allocating #[inline(always)] -#[cfg(stage0)] -pub fn each_char(s: &str, it: &fn(char) -> bool) { - let mut i = 0; - let len = len(s); - while i < len { - let CharRange {ch, next} = char_range_at(s, i); - if !it(ch) { return; } - i = next; - } -} -/// Iterate over each char of a string, without allocating -#[inline(always)] -#[cfg(not(stage0))] pub fn each_char(s: &str, it: &fn(char) -> bool) -> bool { let mut i = 0; let len = len(s); @@ -1453,21 +1217,6 @@ pub fn each_char(s: &str, it: &fn(char) -> bool) -> bool { /// Iterates over the chars in a string, with indices #[inline(always)] -#[cfg(stage0)] -pub fn each_chari(s: &str, it: &fn(uint, char) -> bool) { - let mut pos = 0; - let mut ch_pos = 0u; - let len = s.len(); - while pos < len { - let CharRange {ch, next} = char_range_at(s, pos); - pos = next; - if !it(ch_pos, ch) { break; } - ch_pos += 1u; - } -} -/// Iterates over the chars in a string, with indices -#[inline(always)] -#[cfg(not(stage0))] pub fn each_chari(s: &str, it: &fn(uint, char) -> bool) -> bool { let mut pos = 0; let mut ch_pos = 0u; @@ -1483,35 +1232,12 @@ pub fn each_chari(s: &str, it: &fn(uint, char) -> bool) -> bool { /// Iterates over the chars in a string in reverse #[inline(always)] -#[cfg(stage0)] -pub fn each_char_reverse(s: &str, it: &fn(char) -> bool) { - each_chari_reverse(s, |_, c| it(c)) -} -/// Iterates over the chars in a string in reverse -#[inline(always)] -#[cfg(not(stage0))] pub fn each_char_reverse(s: &str, it: &fn(char) -> bool) -> bool { each_chari_reverse(s, |_, c| it(c)) } // Iterates over the chars in a string in reverse, with indices #[inline(always)] -#[cfg(stage0)] -pub fn each_chari_reverse(s: &str, it: &fn(uint, char) -> bool) { - let mut pos = s.len(); - let mut ch_pos = s.char_len(); - while pos > 0 { - let CharRange {ch, next} = char_range_at_reverse(s, pos); - pos = next; - ch_pos -= 1; - - if !it(ch_pos, ch) { break; } - - } -} -// Iterates over the chars in a string in reverse, with indices -#[inline(always)] -#[cfg(not(stage0))] pub fn each_chari_reverse(s: &str, it: &fn(uint, char) -> bool) -> bool { let mut pos = s.len(); let mut ch_pos = s.char_len(); @@ -2761,22 +2487,14 @@ pub trait StrSlice<'self> { fn contains<'a>(&self, needle: &'a str) -> bool; fn contains_char(&self, needle: char) -> bool; fn char_iter(&self) -> StrCharIterator<'self>; - #[cfg(stage0)] fn each(&self, it: &fn(u8) -> bool); - #[cfg(not(stage0))] fn each(&self, it: &fn(u8) -> bool) -> bool; - #[cfg(stage0)] fn eachi(&self, it: &fn(uint, u8) -> bool); - #[cfg(not(stage0))] fn eachi(&self, it: &fn(uint, u8) -> bool) -> bool; - #[cfg(stage0)] fn each_reverse(&self, it: &fn(u8) -> bool); - #[cfg(not(stage0))] fn each_reverse(&self, it: &fn(u8) -> bool) -> bool; - #[cfg(stage0)] fn eachi_reverse(&self, it: &fn(uint, u8) -> bool); - #[cfg(not(stage0))] fn eachi_reverse(&self, it: &fn(uint, u8) -> bool) -> bool; - #[cfg(stage0)] fn each_char(&self, it: &fn(char) -> bool); - #[cfg(not(stage0))] fn each_char(&self, it: &fn(char) -> bool) -> bool; - #[cfg(stage0)] fn each_chari(&self, it: &fn(uint, char) -> bool); - #[cfg(not(stage0))] fn each_chari(&self, it: &fn(uint, char) -> bool) -> bool; - #[cfg(stage0)] fn each_char_reverse(&self, it: &fn(char) -> bool); - #[cfg(not(stage0))] fn each_char_reverse(&self, it: &fn(char) -> bool) -> bool; - #[cfg(stage0)] fn each_chari_reverse(&self, it: &fn(uint, char) -> bool); - #[cfg(not(stage0))] fn each_chari_reverse(&self, it: &fn(uint, char) -> bool) -> bool; + fn each(&self, it: &fn(u8) -> bool) -> bool; + fn eachi(&self, it: &fn(uint, u8) -> bool) -> bool; + fn each_reverse(&self, it: &fn(u8) -> bool) -> bool; + fn eachi_reverse(&self, it: &fn(uint, u8) -> bool) -> bool; + fn each_char(&self, it: &fn(char) -> bool) -> bool; + fn each_chari(&self, it: &fn(uint, char) -> bool) -> bool; + fn each_char_reverse(&self, it: &fn(char) -> bool) -> bool; + fn each_chari_reverse(&self, it: &fn(uint, char) -> bool) -> bool; fn ends_with(&self, needle: &str) -> bool; fn is_empty(&self) -> bool; fn is_whitespace(&self) -> bool; @@ -2784,17 +2502,8 @@ pub trait StrSlice<'self> { fn len(&self) -> uint; fn char_len(&self) -> uint; fn slice(&self, begin: uint, end: uint) -> &'self str; - #[cfg(stage0)] - fn each_split(&self, sepfn: &fn(char) -> bool, it: &fn(&'self str) -> bool); - #[cfg(not(stage0))] fn each_split(&self, sepfn: &fn(char) -> bool, it: &fn(&'self str) -> bool) -> bool; - #[cfg(stage0)] - fn each_split_char(&self, sep: char, it: &fn(&'self str) -> bool); - #[cfg(not(stage0))] fn each_split_char(&self, sep: char, it: &fn(&'self str) -> bool) -> bool; - #[cfg(stage0)] - fn each_split_str<'a>(&self, sep: &'a str, it: &fn(&'self str) -> bool); - #[cfg(not(stage0))] fn each_split_str<'a>(&self, sep: &'a str, it: &fn(&'self str) -> bool) -> bool; fn starts_with<'a>(&self, needle: &'a str) -> bool; fn substr(&self, begin: uint, n: uint) -> &'self str; @@ -2848,83 +2557,34 @@ impl<'self> StrSlice<'self> for &'self str { /// Iterate over the bytes in a string #[inline] - #[cfg(stage0)] - fn each(&self, it: &fn(u8) -> bool) { each(*self, it) } - /// Iterate over the bytes in a string - #[inline] - #[cfg(not(stage0))] fn each(&self, it: &fn(u8) -> bool) -> bool { each(*self, it) } /// Iterate over the bytes in a string, with indices #[inline] - #[cfg(stage0)] - fn eachi(&self, it: &fn(uint, u8) -> bool) { eachi(*self, it) } - /// Iterate over the bytes in a string, with indices - #[inline] - #[cfg(not(stage0))] fn eachi(&self, it: &fn(uint, u8) -> bool) -> bool { eachi(*self, it) } /// Iterate over the bytes in a string #[inline] - #[cfg(stage0)] - fn each_reverse(&self, it: &fn(u8) -> bool) { each_reverse(*self, it) } - /// Iterate over the bytes in a string - #[inline] - #[cfg(not(stage0))] fn each_reverse(&self, it: &fn(u8) -> bool) -> bool { each_reverse(*self, it) } /// Iterate over the bytes in a string, with indices #[inline] - #[cfg(stage0)] - fn eachi_reverse(&self, it: &fn(uint, u8) -> bool) { - eachi_reverse(*self, it) - } - /// Iterate over the bytes in a string, with indices - #[inline] - #[cfg(not(stage0))] fn eachi_reverse(&self, it: &fn(uint, u8) -> bool) -> bool { eachi_reverse(*self, it) } /// Iterate over the chars in a string #[inline] - #[cfg(stage0)] - fn each_char(&self, it: &fn(char) -> bool) { each_char(*self, it) } - /// Iterate over the chars in a string - #[inline] - #[cfg(not(stage0))] fn each_char(&self, it: &fn(char) -> bool) -> bool { each_char(*self, it) } /// Iterate over the chars in a string, with indices #[inline] - #[cfg(stage0)] - fn each_chari(&self, it: &fn(uint, char) -> bool) { - each_chari(*self, it) - } - /// Iterate over the chars in a string, with indices - #[inline] - #[cfg(not(stage0))] fn each_chari(&self, it: &fn(uint, char) -> bool) -> bool { each_chari(*self, it) } /// Iterate over the chars in a string in reverse #[inline] - #[cfg(stage0)] - fn each_char_reverse(&self, it: &fn(char) -> bool) { - each_char_reverse(*self, it) - } - /// Iterate over the chars in a string in reverse - #[inline] - #[cfg(not(stage0))] fn each_char_reverse(&self, it: &fn(char) -> bool) -> bool { each_char_reverse(*self, it) } /// Iterate over the chars in a string in reverse, with indices from the /// end #[inline] - #[cfg(stage0)] - fn each_chari_reverse(&self, it: &fn(uint, char) -> bool) { - each_chari_reverse(*self, it) - } - /// Iterate over the chars in a string in reverse, with indices from the - /// end - #[inline] - #[cfg(not(stage0))] fn each_chari_reverse(&self, it: &fn(uint, char) -> bool) -> bool { each_chari_reverse(*self, it) } @@ -2969,13 +2629,6 @@ impl<'self> StrSlice<'self> for &'self str { } /// Splits a string into substrings using a character function #[inline] - #[cfg(stage0)] - fn each_split(&self, sepfn: &fn(char) -> bool, it: &fn(&'self str) -> bool) { - each_split(*self, sepfn, it) - } - /// Splits a string into substrings using a character function - #[inline] - #[cfg(not(stage0))] fn each_split(&self, sepfn: &fn(char) -> bool, it: &fn(&'self str) -> bool) -> bool { each_split(*self, sepfn, it) } @@ -2983,15 +2636,6 @@ impl<'self> StrSlice<'self> for &'self str { * Splits a string into substrings at each occurrence of a given character */ #[inline] - #[cfg(stage0)] - fn each_split_char(&self, sep: char, it: &fn(&'self str) -> bool) { - each_split_char(*self, sep, it) - } - /** - * Splits a string into substrings at each occurrence of a given character - */ - #[inline] - #[cfg(not(stage0))] fn each_split_char(&self, sep: char, it: &fn(&'self str) -> bool) -> bool { each_split_char(*self, sep, it) } @@ -3000,16 +2644,6 @@ impl<'self> StrSlice<'self> for &'self str { * string */ #[inline] - #[cfg(stage0)] - fn each_split_str<'a>(&self, sep: &'a str, it: &fn(&'self str) -> bool) { - each_split_str(*self, sep, it) - } - /** - * Splits a string into a vector of the substrings separated by a given - * string - */ - #[inline] - #[cfg(not(stage0))] fn each_split_str<'a>(&self, sep: &'a str, it: &fn(&'self str) -> bool) -> bool { each_split_str(*self, sep, it) } diff --git a/src/libcore/task/spawn.rs b/src/libcore/task/spawn.rs index 2ac8fc5f073ec..8d287b5c51f7d 100644 --- a/src/libcore/task/spawn.rs +++ b/src/libcore/task/spawn.rs @@ -110,11 +110,6 @@ fn taskset_remove(tasks: &mut TaskSet, task: *rust_task) { let was_present = tasks.remove(&task); assert!(was_present); } -#[cfg(stage0)] -pub fn taskset_each(tasks: &TaskSet, blk: &fn(v: *rust_task) -> bool) { - tasks.each(|k| blk(*k)) -} -#[cfg(not(stage0))] pub fn taskset_each(tasks: &TaskSet, blk: &fn(v: *rust_task) -> bool) -> bool { tasks.each(|k| blk(*k)) } diff --git a/src/libcore/to_bytes.rs b/src/libcore/to_bytes.rs index ad42881ffa028..5b66e94c1b456 100644 --- a/src/libcore/to_bytes.rs +++ b/src/libcore/to_bytes.rs @@ -22,11 +22,6 @@ use str; pub type Cb<'self> = &'self fn(buf: &[u8]) -> bool; -#[cfg(stage0)] -pub trait IterBytes { - fn iter_bytes(&self, lsb0: bool, f: Cb); -} - /** * A trait to implement in order to make a type hashable; * This works in combination with the trait `Hash::Hash`, and @@ -34,7 +29,6 @@ pub trait IterBytes { * modified when default methods and trait inheritence are * completed. */ -#[cfg(not(stage0))] pub trait IterBytes { /** * Call the provided callback `f` one or more times with @@ -53,16 +47,6 @@ pub trait IterBytes { fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool; } -#[cfg(stage0)] -impl IterBytes for bool { - #[inline(always)] - fn iter_bytes(&self, _lsb0: bool, f: Cb) { - f([ - *self as u8 - ]); - } -} -#[cfg(not(stage0))] impl IterBytes for bool { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { @@ -72,16 +56,6 @@ impl IterBytes for bool { } } -#[cfg(stage0)] -impl IterBytes for u8 { - #[inline(always)] - fn iter_bytes(&self, _lsb0: bool, f: Cb) { - f([ - *self - ]); - } -} -#[cfg(not(stage0))] impl IterBytes for u8 { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { @@ -91,24 +65,6 @@ impl IterBytes for u8 { } } -#[cfg(stage0)] -impl IterBytes for u16 { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - if lsb0 { - f([ - *self as u8, - (*self >> 8) as u8 - ]); - } else { - f([ - (*self >> 8) as u8, - *self as u8 - ]); - } - } -} -#[cfg(not(stage0))] impl IterBytes for u16 { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -126,28 +82,6 @@ impl IterBytes for u16 { } } -#[cfg(stage0)] -impl IterBytes for u32 { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - if lsb0 { - f([ - *self as u8, - (*self >> 8) as u8, - (*self >> 16) as u8, - (*self >> 24) as u8, - ]); - } else { - f([ - (*self >> 24) as u8, - (*self >> 16) as u8, - (*self >> 8) as u8, - *self as u8 - ]); - } - } -} -#[cfg(not(stage0))] impl IterBytes for u32 { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -169,36 +103,6 @@ impl IterBytes for u32 { } } -#[cfg(stage0)] -impl IterBytes for u64 { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - if lsb0 { - f([ - *self as u8, - (*self >> 8) as u8, - (*self >> 16) as u8, - (*self >> 24) as u8, - (*self >> 32) as u8, - (*self >> 40) as u8, - (*self >> 48) as u8, - (*self >> 56) as u8 - ]); - } else { - f([ - (*self >> 56) as u8, - (*self >> 48) as u8, - (*self >> 40) as u8, - (*self >> 32) as u8, - (*self >> 24) as u8, - (*self >> 16) as u8, - (*self >> 8) as u8, - *self as u8 - ]); - } - } -} -#[cfg(not(stage0))] impl IterBytes for u64 { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -228,14 +132,6 @@ impl IterBytes for u64 { } } -#[cfg(stage0)] -impl IterBytes for i8 { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for i8 { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -243,14 +139,6 @@ impl IterBytes for i8 { } } -#[cfg(stage0)] -impl IterBytes for i16 { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as u16).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for i16 { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -258,14 +146,6 @@ impl IterBytes for i16 { } } -#[cfg(stage0)] -impl IterBytes for i32 { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as u32).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for i32 { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -273,14 +153,6 @@ impl IterBytes for i32 { } } -#[cfg(stage0)] -impl IterBytes for i64 { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as u64).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for i64 { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -288,14 +160,6 @@ impl IterBytes for i64 { } } -#[cfg(stage0)] -impl IterBytes for char { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as u32).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for char { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -303,14 +167,7 @@ impl IterBytes for char { } } -#[cfg(target_word_size = "32", stage0)] -impl IterBytes for uint { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as u32).iter_bytes(lsb0, f) - } -} -#[cfg(target_word_size = "32", not(stage0))] +#[cfg(target_word_size = "32")] impl IterBytes for uint { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -318,14 +175,7 @@ impl IterBytes for uint { } } -#[cfg(target_word_size = "64", stage0)] -impl IterBytes for uint { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as u64).iter_bytes(lsb0, f) - } -} -#[cfg(target_word_size = "64", not(stage0))] +#[cfg(target_word_size = "64")] impl IterBytes for uint { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -333,14 +183,6 @@ impl IterBytes for uint { } } -#[cfg(stage0)] -impl IterBytes for int { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as uint).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for int { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -348,18 +190,6 @@ impl IterBytes for int { } } -#[cfg(stage0)] -impl<'self,A:IterBytes> IterBytes for &'self [A] { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - for (*self).each |elt| { - do elt.iter_bytes(lsb0) |bytes| { - f(bytes) - } - } - } -} -#[cfg(not(stage0))] impl<'self,A:IterBytes> IterBytes for &'self [A] { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -367,18 +197,6 @@ impl<'self,A:IterBytes> IterBytes for &'self [A] { } } -#[cfg(stage0)] -impl IterBytes for (A,B) { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - match *self { - (ref a, ref b) => { - iter_bytes_2(a, b, lsb0, f); - } - } - } -} -#[cfg(not(stage0))] impl IterBytes for (A,B) { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -388,18 +206,6 @@ impl IterBytes for (A,B) { } } -#[cfg(stage0)] -impl IterBytes for (A,B,C) { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - match *self { - (ref a, ref b, ref c) => { - iter_bytes_3(a, b, c, lsb0, f); - } - } - } -} -#[cfg(not(stage0))] impl IterBytes for (A,B,C) { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -416,14 +222,6 @@ fn borrow<'x,A>(a: &'x [A]) -> &'x [A] { a } -#[cfg(stage0)] -impl IterBytes for ~[A] { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - borrow(*self).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for ~[A] { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -431,14 +229,6 @@ impl IterBytes for ~[A] { } } -#[cfg(stage0)] -impl IterBytes for @[A] { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - borrow(*self).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for @[A] { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -449,57 +239,18 @@ impl IterBytes for @[A] { // NOTE: remove all of these after a snapshot, the new for-loop iteration // protocol makes these unnecessary. -#[cfg(stage0)] -pub fn iter_bytes_2(a: &A, b: &B, - lsb0: bool, z: Cb) { - let mut flag = true; - a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); -} -#[cfg(not(stage0))] #[inline(always)] pub fn iter_bytes_2(a: &A, b: &B, lsb0: bool, z: Cb) -> bool { a.iter_bytes(lsb0, z) && b.iter_bytes(lsb0, z) } -#[cfg(stage0)] -pub fn iter_bytes_3(a: &A, b: &B, c: &C, - lsb0: bool, z: Cb) { - let mut flag = true; - a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); -} -#[cfg(not(stage0))] pub fn iter_bytes_3(a: &A, b: &B, c: &C, lsb0: bool, z: Cb) -> bool { a.iter_bytes(lsb0, z) && b.iter_bytes(lsb0, z) && c.iter_bytes(lsb0, z) } -#[cfg(stage0)] -pub fn iter_bytes_4(a: &A, b: &B, c: &C, - d: &D, - lsb0: bool, z: Cb) { - let mut flag = true; - a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); -} -#[cfg(not(stage0))] pub fn iter_bytes_4(a: &A, b: &B, c: &C, - d: &D, e: &E, - lsb0: bool, z: Cb) { - let mut flag = true; - a.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - b.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - c.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - d.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); - if !flag { return; } - e.iter_bytes(lsb0, |bytes| {flag = z(bytes); flag}); -} -#[cfg(not(stage0))] pub fn iter_bytes_5 IterBytes for &'self str { - #[inline(always)] - fn iter_bytes(&self, _lsb0: bool, f: Cb) { - do str::byte_slice(*self) |bytes| { - f(bytes); - } - } -} -#[cfg(not(stage0))] impl<'self> IterBytes for &'self str { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { @@ -560,16 +281,6 @@ impl<'self> IterBytes for &'self str { } } -#[cfg(stage0)] -impl IterBytes for ~str { - #[inline(always)] - fn iter_bytes(&self, _lsb0: bool, f: Cb) { - do str::byte_slice(*self) |bytes| { - f(bytes); - } - } -} -#[cfg(not(stage0))] impl IterBytes for ~str { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { @@ -579,16 +290,6 @@ impl IterBytes for ~str { } } -#[cfg(stage0)] -impl IterBytes for @str { - #[inline(always)] - fn iter_bytes(&self, _lsb0: bool, f: Cb) { - do str::byte_slice(*self) |bytes| { - f(bytes); - } - } -} -#[cfg(not(stage0))] impl IterBytes for @str { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { @@ -598,17 +299,6 @@ impl IterBytes for @str { } } -#[cfg(stage0)] -impl IterBytes for Option { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - match *self { - Some(ref a) => iter_bytes_2(&0u8, a, lsb0, f), - None => 1u8.iter_bytes(lsb0, f) - } - } -} -#[cfg(not(stage0))] impl IterBytes for Option { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -619,14 +309,6 @@ impl IterBytes for Option { } } -#[cfg(stage0)] -impl<'self,A:IterBytes> IterBytes for &'self A { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (**self).iter_bytes(lsb0, f); - } -} -#[cfg(not(stage0))] impl<'self,A:IterBytes> IterBytes for &'self A { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -634,14 +316,6 @@ impl<'self,A:IterBytes> IterBytes for &'self A { } } -#[cfg(stage0)] -impl IterBytes for @A { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (**self).iter_bytes(lsb0, f); - } -} -#[cfg(not(stage0))] impl IterBytes for @A { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -649,14 +323,6 @@ impl IterBytes for @A { } } -#[cfg(stage0)] -impl IterBytes for ~A { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (**self).iter_bytes(lsb0, f); - } -} -#[cfg(not(stage0))] impl IterBytes for ~A { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { @@ -666,16 +332,6 @@ impl IterBytes for ~A { // NB: raw-pointer IterBytes does _not_ dereference // to the target; it just gives you the pointer-bytes. -#[cfg(stage0)] -impl IterBytes for *const A { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: Cb) { - (*self as uint).iter_bytes(lsb0, f); - } -} -// NB: raw-pointer IterBytes does _not_ dereference -// to the target; it just gives you the pointer-bytes. -#[cfg(not(stage0))] impl IterBytes for *const A { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: Cb) -> bool { diff --git a/src/libcore/trie.rs b/src/libcore/trie.rs index c9485654b50e4..13b892e700e1b 100644 --- a/src/libcore/trie.rs +++ b/src/libcore/trie.rs @@ -57,56 +57,24 @@ impl Map for TrieMap { /// Visit all key-value pairs in order #[inline(always)] - #[cfg(stage0)] - fn each<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) { - self.root.each(f); - } - - /// Visit all key-value pairs in order - #[inline(always)] - #[cfg(not(stage0))] fn each<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool { self.root.each(f) } /// Visit all keys in order #[inline(always)] - #[cfg(stage0)] - fn each_key(&self, f: &fn(&uint) -> bool) { - self.each(|k, _| f(k)) - } - - /// Visit all keys in order - #[inline(always)] - #[cfg(not(stage0))] fn each_key(&self, f: &fn(&uint) -> bool) -> bool { self.each(|k, _| f(k)) } /// Visit all values in order #[inline(always)] - #[cfg(stage0)] - fn each_value<'a>(&'a self, f: &fn(&'a T) -> bool) { - self.each(|_, v| f(v)) - } - - /// Visit all values in order - #[inline(always)] - #[cfg(not(stage0))] fn each_value<'a>(&'a self, f: &fn(&'a T) -> bool) -> bool { self.each(|_, v| f(v)) } /// Iterate over the map and mutate the contained values #[inline(always)] - #[cfg(stage0)] - fn mutate_values(&mut self, f: &fn(&uint, &mut T) -> bool) { - self.root.mutate_values(f); - } - - /// Iterate over the map and mutate the contained values - #[inline(always)] - #[cfg(not(stage0))] fn mutate_values(&mut self, f: &fn(&uint, &mut T) -> bool) -> bool { self.root.mutate_values(f) } @@ -183,40 +151,18 @@ pub impl TrieMap { /// Visit all key-value pairs in reverse order #[inline(always)] - #[cfg(stage0)] - fn each_reverse<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) { - self.root.each_reverse(f); - } - - /// Visit all key-value pairs in reverse order - #[inline(always)] - #[cfg(not(stage0))] fn each_reverse<'a>(&'a self, f: &fn(&uint, &'a T) -> bool) -> bool { self.root.each_reverse(f) } /// Visit all keys in reverse order #[inline(always)] - #[cfg(stage0)] - fn each_key_reverse(&self, f: &fn(&uint) -> bool) { - self.each_reverse(|k, _| f(k)) - } - /// Visit all keys in reverse order - #[inline(always)] - #[cfg(not(stage0))] fn each_key_reverse(&self, f: &fn(&uint) -> bool) -> bool { self.each_reverse(|k, _| f(k)) } /// Visit all values in reverse order #[inline(always)] - #[cfg(stage0)] - fn each_value_reverse(&self, f: &fn(&T) -> bool) { - self.each_reverse(|_, v| f(v)) - } - /// Visit all values in reverse order - #[inline(always)] - #[cfg(not(stage0))] fn each_value_reverse(&self, f: &fn(&T) -> bool) -> bool { self.each_reverse(|_, v| f(v)) } @@ -229,9 +175,6 @@ pub struct TrieSet { impl BaseIter for TrieSet { /// Visit all values in order #[inline(always)] - #[cfg(stage0)] - fn each(&self, f: &fn(&uint) -> bool) { self.map.each_key(f) } - #[cfg(not(stage0))] fn each(&self, f: &fn(&uint) -> bool) -> bool { self.map.each_key(f) } #[inline(always)] fn size_hint(&self) -> Option { Some(self.len()) } @@ -240,11 +183,6 @@ impl BaseIter for TrieSet { impl ReverseIter for TrieSet { /// Visit all values in reverse order #[inline(always)] - #[cfg(stage0)] - fn each_reverse(&self, f: &fn(&uint) -> bool) { - self.map.each_key_reverse(f) - } - #[cfg(not(stage0))] fn each_reverse(&self, f: &fn(&uint) -> bool) -> bool { self.map.each_key_reverse(f) } @@ -351,19 +289,6 @@ fn chunk(n: uint, idx: uint) -> uint { (n >> sh) & MASK } -#[cfg(stage0)] -fn find_mut<'r, T>(child: &'r mut Child, key: uint, idx: uint) -> Option<&'r mut T> { - unsafe { - (match *child { - External(_, ref value) => Some(cast::transmute_mut(value)), - Internal(ref x) => find_mut(cast::transmute_mut(&x.children[chunk(key, idx)]), - key, idx + 1), - Nothing => None - }).map_consume(|x| cast::transmute_mut_region(x)) - } -} - -#[cfg(not(stage0))] fn find_mut<'r, T>(child: &'r mut Child, key: uint, idx: uint) -> Option<&'r mut T> { match *child { External(_, ref mut value) => Some(value), diff --git a/src/libcore/unicode.rs b/src/libcore/unicode.rs index 3b7fdcc85be2f..d76da6fcc664f 100644 --- a/src/libcore/unicode.rs +++ b/src/libcore/unicode.rs @@ -14,19 +14,6 @@ pub mod general_category { - #[cfg(stage0)] - fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { - use cmp::{Equal, Less, Greater}; - use vec::bsearch; - use option::None; - (do bsearch(r) |&(lo,hi)| { - if lo <= c && c <= hi { Equal } - else if hi < c { Less } - else { Greater } - }) != None - } - - #[cfg(not(stage0))] fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { use cmp::{Equal, Less, Greater}; use vec::bsearch; @@ -1462,19 +1449,6 @@ pub mod general_category { } pub mod derived_property { - #[cfg(stage0)] - fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { - use cmp::{Equal, Less, Greater}; - use vec::bsearch; - use option::None; - (do bsearch(r) |&(lo,hi)| { - if lo <= c && c <= hi { Equal } - else if hi < c { Less } - else { Greater } - }) != None - } - - #[cfg(not(stage0))] fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { use cmp::{Equal, Less, Greater}; use vec::bsearch; diff --git a/src/libcore/unstable/intrinsics.rs b/src/libcore/unstable/intrinsics.rs index 1636abedf7a7d..f332ecc63fc7e 100644 --- a/src/libcore/unstable/intrinsics.rs +++ b/src/libcore/unstable/intrinsics.rs @@ -43,17 +43,13 @@ pub extern "rust-intrinsic" { pub fn atomic_cxchg_rel(dst: &mut int, old: int, src: int) -> int; /// Atomic load, sequentially consistent. - #[cfg(not(stage0))] pub fn atomic_load(src: &int) -> int; /// Atomic load, acquire ordering. - #[cfg(not(stage0))] pub fn atomic_load_acq(src: &int) -> int; /// Atomic store, sequentially consistent. - #[cfg(not(stage0))] pub fn atomic_store(dst: &mut int, val: int); /// Atomic store, release ordering. - #[cfg(not(stage0))] pub fn atomic_store_rel(dst: &mut int, val: int); /// Atomic exchange, sequentially consistent. @@ -111,7 +107,6 @@ pub extern "rust-intrinsic" { pub unsafe fn init() -> T; /// Create an uninitialized value. - #[cfg(not(stage0))] pub unsafe fn uninit() -> T; /// Move a value out of scope without running drop glue. diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index 1249392484d23..4b599d7562b09 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -269,15 +269,6 @@ pub unsafe fn local_free(ptr: *c_char) { } } -#[cfg(stage0)] -#[lang="borrow_as_imm"] -#[inline(always)] -pub unsafe fn borrow_as_imm(a: *u8) { - let a: *mut BoxRepr = transmute(a); - (*a).header.ref_count |= FROZEN_BIT; -} - -#[cfg(not(stage0))] #[lang="borrow_as_imm"] #[inline(always)] pub unsafe fn borrow_as_imm(a: *u8, file: *c_char, line: size_t) -> uint { @@ -296,7 +287,6 @@ pub unsafe fn borrow_as_imm(a: *u8, file: *c_char, line: size_t) -> uint { old_ref_count } -#[cfg(not(stage0))] #[lang="borrow_as_mut"] #[inline(always)] pub unsafe fn borrow_as_mut(a: *u8, file: *c_char, line: size_t) -> uint { @@ -316,7 +306,6 @@ pub unsafe fn borrow_as_mut(a: *u8, file: *c_char, line: size_t) -> uint { } -#[cfg(not(stage0))] #[lang="record_borrow"] pub unsafe fn record_borrow(a: *u8, old_ref_count: uint, file: *c_char, line: size_t) { @@ -332,7 +321,6 @@ pub unsafe fn record_borrow(a: *u8, old_ref_count: uint, } } -#[cfg(not(stage0))] #[lang="unrecord_borrow"] pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint, file: *c_char, line: size_t) { @@ -356,19 +344,6 @@ pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint, } } -#[cfg(stage0)] -#[lang="return_to_mut"] -#[inline(always)] -pub unsafe fn return_to_mut(a: *u8) { - // Sometimes the box is null, if it is conditionally frozen. - // See e.g. #4904. - if !a.is_null() { - let a: *mut BoxRepr = transmute(a); - (*a).header.ref_count &= !FROZEN_BIT; - } -} - -#[cfg(not(stage0))] #[lang="return_to_mut"] #[inline(always)] pub unsafe fn return_to_mut(a: *u8, orig_ref_count: uint, @@ -388,19 +363,6 @@ pub unsafe fn return_to_mut(a: *u8, orig_ref_count: uint, } } -#[cfg(stage0)] -#[lang="check_not_borrowed"] -#[inline(always)] -pub unsafe fn check_not_borrowed(a: *u8) { - let a: *mut BoxRepr = transmute(a); - if ((*a).header.ref_count & FROZEN_BIT) != 0 { - do str::as_buf("XXX") |file_p, _| { - fail_borrowed(a, file_p as *c_char, 0); - } - } -} - -#[cfg(not(stage0))] #[lang="check_not_borrowed"] #[inline(always)] pub unsafe fn check_not_borrowed(a: *u8, diff --git a/src/libcore/unstable/sync.rs b/src/libcore/unstable/sync.rs index 091031f51fd8a..734368c70c4a0 100644 --- a/src/libcore/unstable/sync.rs +++ b/src/libcore/unstable/sync.rs @@ -41,18 +41,6 @@ impl UnsafeAtomicRcBox { } #[inline(always)] - #[cfg(stage0)] - pub unsafe fn get(&self) -> *mut T - { - let mut data: ~AtomicRcBoxData = cast::transmute(self.data); - assert!(data.count > 0); - let r: *mut T = cast::transmute(data.data.get_mut_ref()); - cast::forget(data); - return r; - } - - #[inline(always)] - #[cfg(not(stage0))] pub unsafe fn get(&self) -> *mut T { let mut data: ~AtomicRcBoxData = cast::transmute(self.data); @@ -63,18 +51,6 @@ impl UnsafeAtomicRcBox { } #[inline(always)] - #[cfg(stage0)] - pub unsafe fn get_immut(&self) -> *T - { - let mut data: ~AtomicRcBoxData = cast::transmute(self.data); - assert!(data.count > 0); - let r: *T = cast::transmute(data.data.get_mut_ref()); - cast::forget(data); - return r; - } - - #[inline(always)] - #[cfg(not(stage0))] pub unsafe fn get_immut(&self) -> *T { let mut data: ~AtomicRcBoxData = cast::transmute(self.data); diff --git a/src/libcore/util.rs b/src/libcore/util.rs index eaf1e31d403ad..e2b91594d123c 100644 --- a/src/libcore/util.rs +++ b/src/libcore/util.rs @@ -60,7 +60,6 @@ pub fn swap(x: &mut T, y: &mut T) { * deinitialising or copying either one. */ #[inline] -#[cfg(not(stage0))] pub unsafe fn swap_ptr(x: *mut T, y: *mut T) { if x == y { return } @@ -78,29 +77,6 @@ pub unsafe fn swap_ptr(x: *mut T, y: *mut T) { cast::forget(tmp); } -/** - * Swap the values at two mutable locations of the same type, without - * deinitialising or copying either one. - */ -#[inline] -#[cfg(stage0)] -pub unsafe fn swap_ptr(x: *mut T, y: *mut T) { - if x == y { return } - - // Give ourselves some scratch space to work with - let mut tmp: T = intrinsics::init(); - let t = ptr::to_mut_unsafe_ptr(&mut tmp); - - // Perform the swap - ptr::copy_memory(t, x, 1); - ptr::copy_memory(x, y, 1); - ptr::copy_memory(y, t, 1); - - // y and t now point to the same thing, but we need to completely forget t - // because it's no longer relevant. - cast::forget(tmp); -} - /** * Replace the value at a mutable location with a new one, returning the old * value, without deinitialising or copying either one. diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index f12e70faa8f80..14dcde2381bf3 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -583,21 +583,6 @@ pub fn consume_reverse(mut v: ~[T], f: &fn(uint, v: T)) { } /// Remove the last element from a vector and return it -#[cfg(not(stage0))] -pub fn pop(v: &mut ~[T]) -> T { - let ln = v.len(); - if ln == 0 { - fail!("sorry, cannot vec::pop an empty vector") - } - let valptr = ptr::to_mut_unsafe_ptr(&mut v[ln - 1u]); - unsafe { - let val = util::replace_ptr(valptr, intrinsics::uninit()); - raw::set_len(v, ln - 1u); - val - } -} - -#[cfg(stage0)] pub fn pop(v: &mut ~[T]) -> T { let ln = v.len(); if ln == 0 { @@ -672,7 +657,6 @@ pub fn push_all(v: &mut ~[T], rhs: &const [T]) { } #[inline(always)] -#[cfg(not(stage0))] pub fn push_all_move(v: &mut ~[T], mut rhs: ~[T]) { let new_len = v.len() + rhs.len(); reserve(&mut *v, new_len); @@ -688,25 +672,7 @@ pub fn push_all_move(v: &mut ~[T], mut rhs: ~[T]) { } } -#[inline(always)] -#[cfg(stage0)] -pub fn push_all_move(v: &mut ~[T], mut rhs: ~[T]) { - let new_len = v.len() + rhs.len(); - reserve(&mut *v, new_len); - unsafe { - do as_mut_buf(rhs) |p, len| { - for uint::range(0, len) |i| { - let x = util::replace_ptr(ptr::mut_offset(p, i), - intrinsics::init()); - push(&mut *v, x); - } - } - raw::set_len(&mut rhs, 0); - } -} - /// Shorten a vector, dropping excess elements. -#[cfg(not(stage0))] pub fn truncate(v: &mut ~[T], newlen: uint) { do as_mut_buf(*v) |p, oldlen| { assert!(newlen <= oldlen); @@ -720,26 +686,10 @@ pub fn truncate(v: &mut ~[T], newlen: uint) { unsafe { raw::set_len(&mut *v, newlen); } } -/// Shorten a vector, dropping excess elements. -#[cfg(stage0)] -pub fn truncate(v: &mut ~[T], newlen: uint) { - do as_mut_buf(*v) |p, oldlen| { - assert!(newlen <= oldlen); - unsafe { - // This loop is optimized out for non-drop types. - for uint::range(newlen, oldlen) |i| { - util::replace_ptr(ptr::mut_offset(p, i), intrinsics::init()); - } - } - } - unsafe { raw::set_len(&mut *v, newlen); } -} - /** * Remove consecutive repeated elements from a vector; if the vector is * sorted, this removes all duplicates. */ -#[cfg(not(stage0))] pub fn dedup(v: &mut ~[T]) { unsafe { if v.len() < 1 { return; } @@ -773,45 +723,6 @@ pub fn dedup(v: &mut ~[T]) { } } -/** - * Remove consecutive repeated elements from a vector; if the vector is - * sorted, this removes all duplicates. - */ -#[cfg(stage0)] -pub fn dedup(v: &mut ~[T]) { - unsafe { - if v.len() < 1 { return; } - let mut last_written = 0, next_to_read = 1; - do as_const_buf(*v) |p, ln| { - // We have a mutable reference to v, so we can make arbitrary - // changes. (cf. push and pop) - let p = p as *mut T; - // last_written < next_to_read <= ln - while next_to_read < ln { - // last_written < next_to_read < ln - if *ptr::mut_offset(p, next_to_read) == - *ptr::mut_offset(p, last_written) { - util::replace_ptr(ptr::mut_offset(p, next_to_read), - intrinsics::init()); - } else { - last_written += 1; - // last_written <= next_to_read < ln - if next_to_read != last_written { - util::swap_ptr(ptr::mut_offset(p, last_written), - ptr::mut_offset(p, next_to_read)); - } - } - // last_written <= next_to_read < ln - next_to_read += 1; - // last_written < next_to_read <= ln - } - } - // last_written < next_to_read == ln - raw::set_len(v, last_written + 1); - } -} - - // Appending #[inline(always)] pub fn append(lhs: ~[T], rhs: &const [T]) -> ~[T] { @@ -1557,9 +1468,6 @@ pub fn _each<'r,T>(v: &'r [T], f: &fn(&'r T) -> bool) -> bool { return true; } -#[cfg(stage0)] -pub fn each<'r,T>(v: &'r [T], f: &fn(&'r T) -> bool) { _each(v, f); } -#[cfg(not(stage0))] pub fn each<'r,T>(v: &'r [T], f: &fn(&'r T) -> bool) -> bool { _each(v, f) } /// Like `each()`, but for the case where you have @@ -1584,11 +1492,6 @@ pub fn _each_mut<'r,T>(v: &'r mut [T], f: &fn(elem: &'r mut T) -> bool) -> bool return broke; } -#[cfg(stage0)] -pub fn each_mut<'r,T>(v: &'r mut [T], f: &fn(elem: &'r mut T) -> bool) { - _each_mut(v, f); -} -#[cfg(not(stage0))] pub fn each_mut<'r,T>(v: &'r mut [T], f: &fn(elem: &'r mut T) -> bool) -> bool { _each_mut(v, f) } @@ -1608,11 +1511,6 @@ pub fn _each_const(v: &const [T], f: &fn(elem: &const T) -> bool) -> bool { return true; } -#[cfg(stage0)] -pub fn each_const(v: &const [t], f: &fn(elem: &const t) -> bool) { - _each_const(v, f); -} -#[cfg(not(stage0))] pub fn each_const(v: &const [t], f: &fn(elem: &const t) -> bool) -> bool { _each_const(v, f) } @@ -1632,9 +1530,6 @@ pub fn _eachi<'r,T>(v: &'r [T], f: &fn(uint, v: &'r T) -> bool) -> bool { return true; } -#[cfg(stage0)] -pub fn eachi<'r,T>(v: &'r [T], f: &fn(uint, v: &'r T) -> bool) { _eachi(v, f); } -#[cfg(not(stage0))] pub fn eachi<'r,T>(v: &'r [T], f: &fn(uint, v: &'r T) -> bool) -> bool { _eachi(v, f) } @@ -1657,11 +1552,6 @@ pub fn _eachi_mut<'r,T>(v: &'r mut [T], return true; } -#[cfg(stage0)] -pub fn eachi_mut<'r,T>(v: &'r mut [T], f: &fn(uint, v: &'r mut T) -> bool) { - _eachi_mut(v, f); -} -#[cfg(not(stage0))] pub fn eachi_mut<'r,T>(v: &'r mut [T], f: &fn(uint, v: &'r mut T) -> bool) -> bool { _eachi_mut(v, f) @@ -1677,11 +1567,6 @@ pub fn _each_reverse<'r,T>(v: &'r [T], blk: &fn(v: &'r T) -> bool) -> bool { _eachi_reverse(v, |_i, v| blk(v)) } -#[cfg(stage0)] -pub fn each_reverse<'r,T>(v: &'r [T], blk: &fn(v: &'r T) -> bool) { - _each_reverse(v, blk); -} -#[cfg(not(stage0))] pub fn each_reverse<'r,T>(v: &'r [T], blk: &fn(v: &'r T) -> bool) -> bool { _each_reverse(v, blk) } @@ -1704,11 +1589,6 @@ pub fn _eachi_reverse<'r,T>(v: &'r [T], return true; } -#[cfg(stage0)] -pub fn eachi_reverse<'r,T>(v: &'r [T], blk: &fn(i: uint, v: &'r T) -> bool) { - _eachi_reverse(v, blk); -} -#[cfg(not(stage0))] pub fn eachi_reverse<'r,T>(v: &'r [T], blk: &fn(i: uint, v: &'r T) -> bool) -> bool { _eachi_reverse(v, blk) @@ -1732,11 +1612,6 @@ pub fn _each2(v1: &[U], v2: &[T], f: &fn(u: &U, t: &T) -> bool) -> bool { return true; } -#[cfg(stage0)] -pub fn each2(v1: &[U], v2: &[T], f: &fn(u: &U, t: &T) -> bool) { - _each2(v1, v2, f); -} -#[cfg(not(stage0))] pub fn each2(v1: &[U], v2: &[T], f: &fn(u: &U, t: &T) -> bool) -> bool { _each2(v1, v2, f) } @@ -1760,12 +1635,6 @@ pub fn _each2_mut(v1: &mut [U], v2: &mut [T], f: &fn(u: &mut U, t: &mut T) return true; } -#[cfg(stage0)] -pub fn each2_mut(v1: &mut [U], v2: &mut [T], f: &fn(u: &mut U, t: &mut T) -> bool) { - _each2_mut(v1, v2, f); -} - -#[cfg(not(stage0))] pub fn each2_mut(v1: &mut [U], v2: &mut [T], f: &fn(u: &mut U, t: &mut T) -> bool) -> bool { _each2_mut(v1, v2, f) } @@ -1838,29 +1707,6 @@ pub fn each_permutation(values: &[T], fun: &fn(perm : &[T]) -> bool) -> * ~~~ * */ -#[cfg(stage0)] -pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) { - assert!(1u <= n); - if n > v.len() { return; } - for uint::range(0, v.len() - n + 1) |i| { - if !it(v.slice(i, i + n)) { return } - } -} -/** - * Iterate over all contiguous windows of length `n` of the vector `v`. - * - * # Example - * - * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`, `[3,4]`) - * - * ~~~ - * for windowed(2, &[1,2,3,4]) |v| { - * io::println(fmt!("%?", v)); - * } - * ~~~ - * - */ -#[cfg(not(stage0))] pub fn windowed<'r, T>(n: uint, v: &'r [T], it: &fn(&'r [T]) -> bool) -> bool { assert!(1u <= n); if n > v.len() { return true; } @@ -2133,13 +1979,7 @@ pub trait ImmutableVector<'self, T> { fn last_opt(&self) -> Option<&'self T>; fn position(&self, f: &fn(t: &T) -> bool) -> Option; fn rposition(&self, f: &fn(t: &T) -> bool) -> Option; - #[cfg(stage0)] - fn each_reverse(&self, blk: &fn(&T) -> bool); - #[cfg(not(stage0))] fn each_reverse(&self, blk: &fn(&T) -> bool) -> bool; - #[cfg(stage0)] - fn eachi_reverse(&self, blk: &fn(uint, &T) -> bool); - #[cfg(not(stage0))] fn eachi_reverse(&self, blk: &fn(uint, &T) -> bool) -> bool; fn foldr<'a, U>(&'a self, z: U, p: &fn(t: &'a T, u: U) -> U) -> U; fn map(&self, f: &fn(t: &T) -> U) -> ~[U]; @@ -2226,25 +2066,11 @@ impl<'self,T> ImmutableVector<'self, T> for &'self [T] { /// Iterates over a vector's elements in reverse. #[inline] - #[cfg(stage0)] - fn each_reverse(&self, blk: &fn(&T) -> bool) { - each_reverse(*self, blk) - } - /// Iterates over a vector's elements in reverse. - #[inline] - #[cfg(not(stage0))] fn each_reverse(&self, blk: &fn(&T) -> bool) -> bool { each_reverse(*self, blk) } /// Iterates over a vector's elements and indices in reverse. - #[cfg(stage0)] - #[inline] - fn eachi_reverse(&self, blk: &fn(uint, &T) -> bool) { - eachi_reverse(*self, blk) - } - /// Iterates over a vector's elements and indices in reverse. - #[cfg(not(stage0))] #[inline] fn eachi_reverse(&self, blk: &fn(uint, &T) -> bool) -> bool { eachi_reverse(*self, blk) @@ -2780,12 +2606,6 @@ pub mod bytes { // ITERATION TRAIT METHODS impl<'self,A> old_iter::BaseIter for &'self [A] { - #[cfg(stage0)] - #[inline(always)] - fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) { - each(*self, blk) - } - #[cfg(not(stage0))] #[inline(always)] fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) -> bool { each(*self, blk) @@ -2796,12 +2616,6 @@ impl<'self,A> old_iter::BaseIter for &'self [A] { // FIXME(#4148): This should be redundant impl old_iter::BaseIter for ~[A] { - #[cfg(stage0)] - #[inline(always)] - fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) { - each(*self, blk) - } - #[cfg(not(stage0))] #[inline(always)] fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) -> bool { each(*self, blk) @@ -2812,12 +2626,6 @@ impl old_iter::BaseIter for ~[A] { // FIXME(#4148): This should be redundant impl old_iter::BaseIter for @[A] { - #[cfg(stage0)] - #[inline(always)] - fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) { - each(*self, blk) - } - #[cfg(not(stage0))] #[inline(always)] fn each<'a>(&'a self, blk: &fn(v: &'a A) -> bool) -> bool { each(*self, blk) @@ -2827,12 +2635,6 @@ impl old_iter::BaseIter for @[A] { } impl<'self,A> old_iter::MutableIter for &'self mut [A] { - #[cfg(stage0)] - #[inline(always)] - fn each_mut<'a>(&'a mut self, blk: &fn(v: &'a mut A) -> bool) { - each_mut(*self, blk) - } - #[cfg(not(stage0))] #[inline(always)] fn each_mut<'a>(&'a mut self, blk: &fn(v: &'a mut A) -> bool) -> bool { each_mut(*self, blk) @@ -2841,12 +2643,6 @@ impl<'self,A> old_iter::MutableIter for &'self mut [A] { // FIXME(#4148): This should be redundant impl old_iter::MutableIter for ~[A] { - #[cfg(stage0)] - #[inline(always)] - fn each_mut<'a>(&'a mut self, blk: &fn(v: &'a mut A) -> bool) { - each_mut(*self, blk) - } - #[cfg(not(stage0))] #[inline(always)] fn each_mut<'a>(&'a mut self, blk: &fn(v: &'a mut A) -> bool) -> bool { each_mut(*self, blk) @@ -2854,15 +2650,6 @@ impl old_iter::MutableIter for ~[A] { } // FIXME(#4148): This should be redundant -#[cfg(stage0)] -impl old_iter::MutableIter for @mut [A] { - #[inline(always)] - fn each_mut(&mut self, blk: &fn(v: &mut A) -> bool) { - each_mut(*self, blk) - } -} - -#[cfg(not(stage0))] impl old_iter::MutableIter for @mut [A] { #[inline(always)] fn each_mut(&mut self, blk: &fn(v: &mut A) -> bool) -> bool { @@ -2871,11 +2658,6 @@ impl old_iter::MutableIter for @mut [A] { } impl<'self,A> old_iter::ExtendedIter for &'self [A] { - #[cfg(stage0)] - pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) { - old_iter::eachi(self, blk) - } - #[cfg(not(stage0))] pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool { old_iter::eachi(self, blk) } @@ -2902,12 +2684,6 @@ impl<'self,A> old_iter::ExtendedIter for &'self [A] { impl<'self,A> old_iter::ExtendedMutableIter for &'self mut [A] { #[inline(always)] - #[cfg(stage0)] - pub fn eachi_mut(&mut self, blk: &fn(uint, v: &mut A) -> bool) { - eachi_mut(*self, blk) - } - #[inline(always)] - #[cfg(not(stage0))] pub fn eachi_mut(&mut self, blk: &fn(uint, v: &mut A) -> bool) -> bool { eachi_mut(*self, blk) } @@ -2915,11 +2691,6 @@ impl<'self,A> old_iter::ExtendedMutableIter for &'self mut [A] { // FIXME(#4148): This should be redundant impl old_iter::ExtendedIter for ~[A] { - #[cfg(stage0)] - pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) { - old_iter::eachi(self, blk) - } - #[cfg(not(stage0))] pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool { old_iter::eachi(self, blk) } @@ -2946,11 +2717,6 @@ impl old_iter::ExtendedIter for ~[A] { // FIXME(#4148): This should be redundant impl old_iter::ExtendedIter for @[A] { - #[cfg(stage0)] - pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) { - old_iter::eachi(self, blk) - } - #[cfg(not(stage0))] pub fn eachi(&self, blk: &fn(uint, v: &A) -> bool) -> bool { old_iter::eachi(self, blk) } diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 5a0820202a99a..9e0021831372c 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -44,15 +44,6 @@ pub fn get_type_param_count(cstore: @mut cstore::CStore, def: ast::def_id) } /// Iterates over all the language items in the given crate. -#[cfg(stage0)] -pub fn each_lang_item(cstore: @mut cstore::CStore, - cnum: ast::crate_num, - f: &fn(ast::node_id, uint) -> bool) { - let crate_data = cstore::get_crate_data(cstore, cnum); - decoder::each_lang_item(crate_data, f) -} -/// Iterates over all the language items in the given crate. -#[cfg(not(stage0))] pub fn each_lang_item(cstore: @mut cstore::CStore, cnum: ast::crate_num, f: &fn(ast::node_id, uint) -> bool) -> bool { @@ -61,18 +52,6 @@ pub fn each_lang_item(cstore: @mut cstore::CStore, } /// Iterates over all the paths in the given crate. -#[cfg(stage0)] -pub fn each_path(cstore: @mut cstore::CStore, - cnum: ast::crate_num, - f: &fn(&str, decoder::def_like) -> bool) { - let crate_data = cstore::get_crate_data(cstore, cnum); - let get_crate_data: decoder::GetCrateDataCb = |cnum| { - cstore::get_crate_data(cstore, cnum) - }; - decoder::each_path(cstore.intr, crate_data, get_crate_data, f); -} -/// Iterates over all the paths in the given crate. -#[cfg(not(stage0))] pub fn each_path(cstore: @mut cstore::CStore, cnum: ast::crate_num, f: &fn(&str, decoder::def_like) -> bool) -> bool { diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 8779cab87f62f..a7131e51ef7e8 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -196,15 +196,6 @@ fn item_def_id(d: ebml::Doc, cdata: cmd) -> ast::def_id { |d| parse_def_id(d))); } -#[cfg(stage0)] -fn each_reexport(d: ebml::Doc, f: &fn(ebml::Doc) -> bool) { - for reader::tagged_docs(d, tag_items_data_item_reexport) |reexport_doc| { - if !f(reexport_doc) { - return; - } - } -} -#[cfg(not(stage0))] fn each_reexport(d: ebml::Doc, f: &fn(ebml::Doc) -> bool) -> bool { for reader::tagged_docs(d, tag_items_data_item_reexport) |reexport_doc| { if !f(reexport_doc) { @@ -465,24 +456,6 @@ fn def_like_to_def(def_like: def_like) -> ast::def { } /// Iterates over the language items in the given crate. -#[cfg(stage0)] -pub fn each_lang_item(cdata: cmd, f: &fn(ast::node_id, uint) -> bool) { - let root = reader::Doc(cdata.data); - let lang_items = reader::get_doc(root, tag_lang_items); - for reader::tagged_docs(lang_items, tag_lang_items_item) |item_doc| { - let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id); - let id = reader::doc_as_u32(id_doc) as uint; - let node_id_doc = reader::get_doc(item_doc, - tag_lang_items_item_node_id); - let node_id = reader::doc_as_u32(node_id_doc) as ast::node_id; - - if !f(node_id, id) { - break; - } - } -} -/// Iterates over the language items in the given crate. -#[cfg(not(stage0))] pub fn each_lang_item(cdata: cmd, f: &fn(ast::node_id, uint) -> bool) -> bool { let root = reader::Doc(cdata.data); let lang_items = reader::get_doc(root, tag_lang_items); @@ -588,13 +561,6 @@ pub fn _each_path(intr: @ident_interner, cdata: cmd, return broken; } -#[cfg(stage0)] -pub fn each_path(intr: @ident_interner, cdata: cmd, - get_crate_data: GetCrateDataCb, - f: &fn(&str, def_like) -> bool) { - _each_path(intr, cdata, get_crate_data, f); -} -#[cfg(not(stage0))] pub fn each_path(intr: @ident_interner, cdata: cmd, get_crate_data: GetCrateDataCb, f: &fn(&str, def_like) -> bool) -> bool { diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 82d46c03101e4..3bf8237df944c 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -21,9 +21,6 @@ pub fn pick_file(file: Path, path: &Path) -> Option { pub trait FileSearch { fn sysroot(&self) -> @Path; - #[cfg(stage0)] - fn for_each_lib_search_path(&self, f: &fn(&Path) -> bool); - #[cfg(not(stage0))] fn for_each_lib_search_path(&self, f: &fn(&Path) -> bool) -> bool; fn get_target_lib_path(&self) -> Path; fn get_target_lib_file_path(&self, file: &Path) -> Path; @@ -40,31 +37,6 @@ pub fn mk_filesearch(maybe_sysroot: &Option<@Path>, } impl FileSearch for FileSearchImpl { fn sysroot(&self) -> @Path { self.sysroot } - #[cfg(stage0)] - fn for_each_lib_search_path(&self, f: &fn(&Path) -> bool) { - debug!("filesearch: searching additional lib search paths"); - // a little weird - self.addl_lib_search_paths.each(f); - - debug!("filesearch: searching target lib path"); - if !f(&make_target_lib_path(self.sysroot, - self.target_triple)) { - return; - } - debug!("filesearch: searching rustpkg lib path nearest"); - if match get_rustpkg_lib_path_nearest() { - result::Ok(ref p) => f(p), - result::Err(_) => true - } { - return; - } - debug!("filesearch: searching rustpkg lib path"); - match get_rustpkg_lib_path() { - result::Ok(ref p) => f(p), - result::Err(_) => true - }; - } - #[cfg(not(stage0))] fn for_each_lib_search_path(&self, f: &fn(&Path) -> bool) -> bool { debug!("filesearch: searching additional lib search paths"); // a little weird diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index b33b64921b406..8c66037e8385f 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -67,25 +67,6 @@ enum MoveError { pub impl<'self> CheckLoanCtxt<'self> { fn tcx(&self) -> ty::ctxt { self.bccx.tcx } - #[cfg(stage0)] - fn each_issued_loan(&self, - scope_id: ast::node_id, - op: &fn(&Loan) -> bool) - { - //! Iterates over each loan that that has been issued - //! on entrance to `scope_id`, regardless of whether it is - //! actually *in scope* at that point. Sometimes loans - //! are issued for future scopes and thus they may have been - //! *issued* but not yet be in effect. - - for self.dfcx.each_bit_on_entry(scope_id) |loan_index| { - let loan = &self.all_loans[loan_index]; - if !op(loan) { - return; - } - } - } - #[cfg(not(stage0))] fn each_issued_loan(&self, scope_id: ast::node_id, op: &fn(&Loan) -> bool) -> bool @@ -105,24 +86,6 @@ pub impl<'self> CheckLoanCtxt<'self> { return true; } - #[cfg(stage0)] - fn each_in_scope_loan(&self, - scope_id: ast::node_id, - op: &fn(&Loan) -> bool) - { - //! Like `each_issued_loan()`, but only considers loans that are - //! currently in scope. - - let region_maps = self.tcx().region_maps; - for self.each_issued_loan(scope_id) |loan| { - if region_maps.is_subscope_of(scope_id, loan.kill_scope) { - if !op(loan) { - return; - } - } - } - } - #[cfg(not(stage0))] fn each_in_scope_loan(&self, scope_id: ast::node_id, op: &fn(&Loan) -> bool) -> bool @@ -141,26 +104,6 @@ pub impl<'self> CheckLoanCtxt<'self> { return true; } - #[cfg(stage0)] - fn each_in_scope_restriction(&self, - scope_id: ast::node_id, - loan_path: @LoanPath, - op: &fn(&Loan, &Restriction) -> bool) - { - //! Iterates through all the in-scope restrictions for the - //! given `loan_path` - - for self.each_in_scope_loan(scope_id) |loan| { - for loan.restrictions.each |restr| { - if restr.loan_path == loan_path { - if !op(loan, restr) { - return; - } - } - } - } - } - #[cfg(not(stage0))] fn each_in_scope_restriction(&self, scope_id: ast::node_id, loan_path: @LoanPath, diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 0f01b2b1e418e..1e6df883e1796 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -21,8 +21,6 @@ use middle::dataflow::DataFlowOperator; use util::common::stmt_set; use util::ppaux::{note_and_explain_region, Repr}; -#[cfg(stage0)] -use core; // NOTE: this can be removed after the next snapshot use core::hashmap::{HashSet, HashMap}; use core::io; use core::result::{Result}; diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 648daaf3cd1d3..4508c50435d3f 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -182,20 +182,6 @@ impl DataFlowContext { } - #[cfg(stage0)] - pub fn each_bit_on_entry(&self, - id: ast::node_id, - f: &fn(uint) -> bool) { - //! Iterates through each bit that is set on entry to `id`. - //! Only useful after `propagate()` has been called. - - let (start, end) = self.compute_id_range(id); - let on_entry = vec::slice(self.on_entry, start, end); - debug!("each_bit_on_entry(id=%?, on_entry=%s)", - id, bits_to_str(on_entry)); - self.each_bit(on_entry, f); - } - #[cfg(not(stage0))] pub fn each_bit_on_entry(&self, id: ast::node_id, f: &fn(uint) -> bool) -> bool { @@ -209,19 +195,6 @@ impl DataFlowContext { self.each_bit(on_entry, f) } - #[cfg(stage0)] - pub fn each_gen_bit(&self, - id: ast::node_id, - f: &fn(uint) -> bool) { - //! Iterates through each bit in the gen set for `id`. - - let (start, end) = self.compute_id_range(id); - let gens = vec::slice(self.gens, start, end); - debug!("each_gen_bit(id=%?, gens=%s)", - id, bits_to_str(gens)); - self.each_bit(gens, f) - } - #[cfg(not(stage0))] pub fn each_gen_bit(&self, id: ast::node_id, f: &fn(uint) -> bool) -> bool { @@ -234,37 +207,6 @@ impl DataFlowContext { self.each_bit(gens, f) } - #[cfg(stage0)] - fn each_bit(&self, - words: &[uint], - f: &fn(uint) -> bool) { - //! Helper for iterating over the bits in a bit set. - - for words.eachi |word_index, &word| { - if word != 0 { - let base_index = word_index * uint::bits; - for uint::range(0, uint::bits) |offset| { - let bit = 1 << offset; - if (word & bit) != 0 { - // NB: we round up the total number of bits - // that we store in any given bit set so that - // it is an even multiple of uint::bits. This - // means that there may be some stray bits at - // the end that do not correspond to any - // actual value. So before we callback, check - // whether the bit_index is greater than the - // actual value the user specified and stop - // iterating if so. - let bit_index = base_index + offset; - if bit_index >= self.bits_per_id || !f(bit_index) { - return; - } - } - } - } - } - } - #[cfg(not(stage0))] fn each_bit(&self, words: &[uint], f: &fn(uint) -> bool) -> bool { diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index e2b4684696a90..24ee587b2f986 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -86,15 +86,6 @@ pub impl LanguageItems { } } - #[cfg(stage0)] - fn each_item(&self, f: &fn(def_id: def_id, i: uint) -> bool) { - for self.items.eachi |i, &item| { - if !f(item.get(), i) { - break; - } - } - } - #[cfg(not(stage0))] fn each_item(&self, f: &fn(def_id: def_id, i: uint) -> bool) -> bool { self.items.eachi(|i, &item| f(item.get(), i)) } diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 591b196bd6fc7..079fb21a4fef9 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -419,39 +419,6 @@ impl Context { } } -#[cfg(stage0)] -pub fn each_lint(sess: session::Session, - attrs: &[ast::attribute], - f: &fn(@ast::meta_item, level, &~str) -> bool) -{ - for [allow, warn, deny, forbid].each |&level| { - let level_name = level_to_str(level); - let attrs = attr::find_attrs_by_name(attrs, level_name); - for attrs.each |attr| { - let meta = attr.node.value; - let metas = match meta.node { - ast::meta_list(_, ref metas) => metas, - _ => { - sess.span_err(meta.span, ~"malformed lint attribute"); - loop; - } - }; - for metas.each |meta| { - match meta.node { - ast::meta_word(lintname) => { - if !f(*meta, level, lintname) { - return; - } - } - _ => { - sess.span_err(meta.span, ~"malformed lint attribute"); - } - } - } - } - } -} -#[cfg(not(stage0))] pub fn each_lint(sess: session::Session, attrs: &[ast::attribute], f: &fn(@ast::meta_item, level, &~str) -> bool) -> bool diff --git a/src/librustc/middle/resolve_stage0.rs b/src/librustc/middle/resolve_stage0.rs deleted file mode 100644 index aefbcbaa87e96..0000000000000 --- a/src/librustc/middle/resolve_stage0.rs +++ /dev/null @@ -1,5324 +0,0 @@ -// Copyright 2012 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 driver::session; -use driver::session::Session; -use metadata::csearch::{each_path, get_trait_method_def_ids}; -use metadata::csearch::get_method_name_and_explicit_self; -use metadata::csearch::get_static_methods_if_impl; -use metadata::csearch::get_type_name_if_impl; -use metadata::cstore::find_extern_mod_stmt_cnum; -use metadata::decoder::{def_like, dl_def, dl_field, dl_impl}; -use middle::lang_items::LanguageItems; -use middle::lint::{allow, level, warn}; -use middle::pat_util::pat_bindings; - -use syntax::ast::{RegionTyParamBound, TraitTyParamBound, _mod, add, arm}; -use syntax::ast::{binding_mode, bitand, bitor, bitxor, blk}; -use syntax::ast::{bind_infer, bind_by_ref, bind_by_copy}; -use syntax::ast::{crate, decl_item, def, def_arg, def_binding}; -use syntax::ast::{def_const, def_foreign_mod, def_fn, def_id, def_label}; -use syntax::ast::{def_local, def_mod, def_prim_ty, def_region, def_self}; -use syntax::ast::{def_self_ty, def_static_method, def_struct, def_ty}; -use syntax::ast::{def_ty_param, def_typaram_binder, def_trait}; -use syntax::ast::{def_upvar, def_use, def_variant, expr, expr_assign_op}; -use syntax::ast::{expr_binary, expr_break, expr_field}; -use syntax::ast::{expr_fn_block, expr_index, expr_method_call, expr_path}; -use syntax::ast::{def_prim_ty, def_region, def_self, def_ty, def_ty_param}; -use syntax::ast::{def_upvar, def_use, def_variant, div, eq}; -use syntax::ast::{expr, expr_again, expr_assign_op}; -use syntax::ast::{expr_index, expr_loop}; -use syntax::ast::{expr_path, expr_self, expr_struct, expr_unary, fn_decl}; -use syntax::ast::{foreign_item, foreign_item_const, foreign_item_fn, ge}; -use syntax::ast::Generics; -use syntax::ast::{gt, ident, inherited, item, item_struct}; -use syntax::ast::{item_const, item_enum, item_fn, item_foreign_mod}; -use syntax::ast::{item_impl, item_mac, item_mod, item_trait, item_ty, le}; -use syntax::ast::{local, local_crate, lt, method, mul}; -use syntax::ast::{named_field, ne, neg, node_id, pat, pat_enum, pat_ident}; -use syntax::ast::{Path, pat_lit, pat_range, pat_struct}; -use syntax::ast::{prim_ty, private, provided}; -use syntax::ast::{public, required, rem, explicit_self_, shl, shr, stmt_decl}; -use syntax::ast::{struct_field, struct_variant_kind}; -use syntax::ast::{sty_static, subtract, trait_ref, tuple_variant_kind, Ty}; -use syntax::ast::{ty_bool, ty_char, ty_f, ty_f32, ty_f64, ty_float, ty_i}; -use syntax::ast::{ty_i16, ty_i32, ty_i64, ty_i8, ty_int, TyParam, ty_path}; -use syntax::ast::{ty_str, ty_u, ty_u16, ty_u32, ty_u64, ty_u8, ty_uint}; -use syntax::ast::unnamed_field; -use syntax::ast::{variant, view_item, view_item_extern_mod}; -use syntax::ast::{view_item_use, view_path_glob, view_path_list}; -use syntax::ast::{view_path_simple, anonymous, named, not}; -use syntax::ast::{unsafe_fn}; -use syntax::ast_util::{def_id_of_def, local_def}; -use syntax::ast_util::{path_to_ident, walk_pat, trait_method_to_ty_method}; -use syntax::ast_util::{Privacy, Public, Private}; -use syntax::ast_util::{variant_visibility_to_privacy, visibility_to_privacy}; -use syntax::attr::{attr_metas, contains_name, attrs_contains_name}; -use syntax::parse::token::ident_interner; -use syntax::parse::token::special_idents; -use syntax::print::pprust::path_to_str; -use syntax::codemap::{span, dummy_sp}; -use syntax::visit::{default_visitor, mk_vt, Visitor, visit_block}; -use syntax::visit::{visit_crate, visit_expr, visit_expr_opt}; -use syntax::visit::{visit_foreign_item, visit_item}; -use syntax::visit::{visit_mod, visit_ty, vt}; -use syntax::opt_vec::OptVec; - -use core::option::Some; -use core::str::each_split_str; -use core::hashmap::{HashMap, HashSet}; -use core::util; - -// Definition mapping -pub type DefMap = @mut HashMap; - -pub struct binding_info { - span: span, - binding_mode: binding_mode, -} - -// Map from the name in a pattern to its binding mode. -pub type BindingMap = HashMap; - -// Implementation resolution -// -// FIXME #4946: This kind of duplicates information kept in -// ty::method. Maybe it should go away. - -pub struct MethodInfo { - did: def_id, - n_tps: uint, - ident: ident, - explicit_self: explicit_self_ -} - -pub struct Impl { - did: def_id, - ident: ident, - methods: ~[@MethodInfo] -} - -// Trait method resolution -pub type TraitMap = HashMap; - -// This is the replacement export map. It maps a module to all of the exports -// within. -pub type ExportMap2 = @mut HashMap; - -pub struct Export2 { - name: @~str, // The name of the target. - def_id: def_id, // The definition of the target. - reexport: bool, // Whether this is a reexport. -} - -#[deriving(Eq)] -pub enum PatternBindingMode { - RefutableMode, - LocalIrrefutableMode, - ArgumentIrrefutableMode, -} - -#[deriving(Eq)] -pub enum Namespace { - TypeNS, - ValueNS -} - -/// A NamespaceResult represents the result of resolving an import in -/// a particular namespace. The result is either definitely-resolved, -/// definitely- unresolved, or unknown. -pub enum NamespaceResult { - /// Means that resolve hasn't gathered enough information yet to determine - /// whether the name is bound in this namespace. (That is, it hasn't - /// resolved all `use` directives yet.) - UnknownResult, - /// Means that resolve has determined that the name is definitely - /// not bound in the namespace. - UnboundResult, - /// Means that resolve has determined that the name is bound in the Module - /// argument, and specified by the NameBindings argument. - BoundResult(@mut Module, @mut NameBindings) -} - -pub impl NamespaceResult { - fn is_unknown(&self) -> bool { - match *self { - UnknownResult => true, - _ => false - } - } -} - -pub enum NameDefinition { - NoNameDefinition, //< The name was unbound. - ChildNameDefinition(def), //< The name identifies an immediate child. - ImportNameDefinition(def) //< The name identifies an import. -} - -#[deriving(Eq)] -pub enum Mutability { - Mutable, - Immutable -} - -pub enum SelfBinding { - NoSelfBinding, - HasSelfBinding(node_id, bool /* is implicit */) -} - -pub type ResolveVisitor = vt<()>; - -/// Contains data for specific types of import directives. -pub enum ImportDirectiveSubclass { - SingleImport(ident /* target */, ident /* source */), - GlobImport -} - -/// The context that we thread through while building the reduced graph. -pub enum ReducedGraphParent { - ModuleReducedGraphParent(@mut Module) -} - -pub enum ResolveResult { - Failed, // Failed to resolve the name. - Indeterminate, // Couldn't determine due to unresolved globs. - Success(T) // Successfully resolved the import. -} - -pub impl ResolveResult { - fn failed(&self) -> bool { - match *self { Failed => true, _ => false } - } - fn indeterminate(&self) -> bool { - match *self { Indeterminate => true, _ => false } - } -} - -pub enum TypeParameters<'self> { - NoTypeParameters, //< No type parameters. - HasTypeParameters(&'self Generics, //< Type parameters. - node_id, //< ID of the enclosing item - - // The index to start numbering the type parameters at. - // This is zero if this is the outermost set of type - // parameters, or equal to the number of outer type - // parameters. For example, if we have: - // - // impl I { - // fn method() { ... } - // } - // - // The index at the method site will be 1, because the - // outer T had index 0. - uint, - - // The kind of the rib used for type parameters. - RibKind) -} - -// The rib kind controls the translation of argument or local definitions -// (`def_arg` or `def_local`) to upvars (`def_upvar`). - -pub enum RibKind { - // No translation needs to be applied. - NormalRibKind, - - // We passed through a function scope at the given node ID. Translate - // upvars as appropriate. - FunctionRibKind(node_id /* func id */, node_id /* body id */), - - // We passed through an impl or trait and are now in one of its - // methods. Allow references to ty params that that impl or trait - // binds. Disallow any other upvars (including other ty params that are - // upvars). - // parent; method itself - MethodRibKind(node_id, MethodSort), - - // We passed through a function *item* scope. Disallow upvars. - OpaqueFunctionRibKind, - - // We're in a constant item. Can't refer to dynamic stuff. - ConstantItemRibKind -} - -// Methods can be required or provided. Required methods only occur in traits. -pub enum MethodSort { - Required, - Provided(node_id) -} - -// The X-ray flag indicates that a context has the X-ray privilege, which -// allows it to reference private names. Currently, this is used for the test -// runner. -// -// FIXME #4947: The X-ray flag is kind of questionable in the first -// place. It might be better to introduce an expr_xray_path instead. - -#[deriving(Eq)] -pub enum XrayFlag { - NoXray, //< Private items cannot be accessed. - Xray //< Private items can be accessed. -} - -pub enum UseLexicalScopeFlag { - DontUseLexicalScope, - UseLexicalScope -} - -pub enum SearchThroughModulesFlag { - DontSearchThroughModules, - SearchThroughModules -} - -pub enum ModulePrefixResult { - NoPrefixFound, - PrefixFound(@mut Module, uint) -} - -#[deriving(Eq)] -pub enum AllowCapturingSelfFlag { - AllowCapturingSelf, //< The "self" definition can be captured. - DontAllowCapturingSelf, //< The "self" definition cannot be captured. -} - -#[deriving(Eq)] -enum NameSearchType { - SearchItemsAndPublicImports, //< Search items and public imports. - SearchItemsAndAllImports, //< Search items and all imports. -} - -pub enum BareIdentifierPatternResolution { - FoundStructOrEnumVariant(def), - FoundConst(def), - BareIdentifierPatternUnresolved -} - -// Specifies how duplicates should be handled when adding a child item if -// another item exists with the same name in some namespace. -#[deriving(Eq)] -pub enum DuplicateCheckingMode { - ForbidDuplicateModules, - ForbidDuplicateTypes, - ForbidDuplicateValues, - ForbidDuplicateTypesAndValues, - OverwriteDuplicates -} - -// Returns the namespace associated with the given duplicate checking mode, -// or fails for OverwriteDuplicates. This is used for error messages. -pub fn namespace_for_duplicate_checking_mode(mode: DuplicateCheckingMode) - -> Namespace { - match mode { - ForbidDuplicateModules | ForbidDuplicateTypes | - ForbidDuplicateTypesAndValues => TypeNS, - ForbidDuplicateValues => ValueNS, - OverwriteDuplicates => fail!("OverwriteDuplicates has no namespace") - } -} - -/// One local scope. -pub struct Rib { - bindings: @mut HashMap, - self_binding: @mut Option, - kind: RibKind, -} - -pub fn Rib(kind: RibKind) -> Rib { - Rib { - bindings: @mut HashMap::new(), - self_binding: @mut None, - kind: kind - } -} - - -/// One import directive. -pub struct ImportDirective { - privacy: Privacy, - module_path: ~[ident], - subclass: @ImportDirectiveSubclass, - span: span, -} - -pub fn ImportDirective(privacy: Privacy, - module_path: ~[ident], - subclass: @ImportDirectiveSubclass, - span: span) - -> ImportDirective { - ImportDirective { - privacy: privacy, - module_path: module_path, - subclass: subclass, - span: span - } -} - -/// The item that an import resolves to. -pub struct Target { - target_module: @mut Module, - bindings: @mut NameBindings, -} - -pub fn Target(target_module: @mut Module, - bindings: @mut NameBindings) - -> Target { - Target { - target_module: target_module, - bindings: bindings - } -} - -/// An ImportResolution represents a particular `use` directive. -pub struct ImportResolution { - /// The privacy of this `use` directive (whether it's `use` or - /// `pub use`. - privacy: Privacy, - span: span, - - // The number of outstanding references to this name. When this reaches - // zero, outside modules can count on the targets being correct. Before - // then, all bets are off; future imports could override this name. - - outstanding_references: uint, - - /// The value that this `use` directive names, if there is one. - value_target: Option, - /// The type that this `use` directive names, if there is one. - type_target: Option, - - /// There exists one state per import statement - state: @mut ImportState, -} - -pub fn ImportResolution(privacy: Privacy, - span: span, - state: @mut ImportState) -> ImportResolution { - ImportResolution { - privacy: privacy, - span: span, - outstanding_references: 0, - value_target: None, - type_target: None, - state: state, - } -} - -pub impl ImportResolution { - fn target_for_namespace(&self, namespace: Namespace) -> Option { - match namespace { - TypeNS => return copy self.type_target, - ValueNS => return copy self.value_target - } - } -} - -pub struct ImportState { - used: bool, - warned: bool -} - -pub fn ImportState() -> ImportState { - ImportState{ used: false, warned: false } -} - -/// The link from a module up to its nearest parent node. -pub enum ParentLink { - NoParentLink, - ModuleParentLink(@mut Module, ident), - BlockParentLink(@mut Module, node_id) -} - -/// The type of module this is. -pub enum ModuleKind { - NormalModuleKind, - ExternModuleKind, - TraitModuleKind, - AnonymousModuleKind, -} - -/// One node in the tree of modules. -pub struct Module { - parent_link: ParentLink, - def_id: Option, - kind: ModuleKind, - - children: @mut HashMap, - imports: @mut ~[@ImportDirective], - - // The external module children of this node that were declared with - // `extern mod`. - external_module_children: @mut HashMap, - - // The anonymous children of this node. Anonymous children are pseudo- - // modules that are implicitly created around items contained within - // blocks. - // - // For example, if we have this: - // - // fn f() { - // fn g() { - // ... - // } - // } - // - // There will be an anonymous module created around `g` with the ID of the - // entry block for `f`. - - anonymous_children: @mut HashMap, - - // The status of resolving each import in this module. - import_resolutions: @mut HashMap, - - // The number of unresolved globs that this module exports. - glob_count: uint, - - // The index of the import we're resolving. - resolved_import_count: uint, -} - -pub fn Module(parent_link: ParentLink, - def_id: Option, - kind: ModuleKind) - -> Module { - Module { - parent_link: parent_link, - def_id: def_id, - kind: kind, - children: @mut HashMap::new(), - imports: @mut ~[], - external_module_children: @mut HashMap::new(), - anonymous_children: @mut HashMap::new(), - import_resolutions: @mut HashMap::new(), - glob_count: 0, - resolved_import_count: 0 - } -} - -pub impl Module { - fn all_imports_resolved(&self) -> bool { - let imports = &mut *self.imports; - return imports.len() == self.resolved_import_count; - } -} - -// Records a possibly-private type definition. -pub struct TypeNsDef { - privacy: Privacy, - module_def: Option<@mut Module>, - type_def: Option -} - -// Records a possibly-private value definition. -pub struct ValueNsDef { - privacy: Privacy, - def: def, -} - -// Records the definitions (at most one for each namespace) that a name is -// bound to. -pub struct NameBindings { - type_def: Option, //< Meaning in type namespace. - value_def: Option, //< Meaning in value namespace. - - // For error reporting - // FIXME (#3783): Merge me into TypeNsDef and ValueNsDef. - type_span: Option, - value_span: Option, -} - -pub impl NameBindings { - /// Creates a new module in this set of name bindings. - fn define_module(@mut self, - privacy: Privacy, - parent_link: ParentLink, - def_id: Option, - kind: ModuleKind, - sp: span) { - // Merges the module with the existing type def or creates a new one. - let module_ = @mut Module(parent_link, def_id, kind); - match self.type_def { - None => { - self.type_def = Some(TypeNsDef { - privacy: privacy, - module_def: Some(module_), - type_def: None - }); - } - Some(copy type_def) => { - self.type_def = Some(TypeNsDef { - privacy: privacy, - module_def: Some(module_), - .. type_def - }); - } - } - self.type_span = Some(sp); - } - - /// Records a type definition. - fn define_type(@mut self, privacy: Privacy, def: def, sp: span) { - // Merges the type with the existing type def or creates a new one. - match self.type_def { - None => { - self.type_def = Some(TypeNsDef { - privacy: privacy, - module_def: None, - type_def: Some(def) - }); - } - Some(copy type_def) => { - self.type_def = Some(TypeNsDef { - privacy: privacy, - type_def: Some(def), - .. type_def - }); - } - } - self.type_span = Some(sp); - } - - /// Records a value definition. - fn define_value(@mut self, privacy: Privacy, def: def, sp: span) { - self.value_def = Some(ValueNsDef { privacy: privacy, def: def }); - self.value_span = Some(sp); - } - - /// Returns the module node if applicable. - fn get_module_if_available(&self) -> Option<@mut Module> { - match self.type_def { - Some(ref type_def) => (*type_def).module_def, - None => None - } - } - - /** - * Returns the module node. Fails if this node does not have a module - * definition. - */ - fn get_module(@mut self) -> @mut Module { - match self.get_module_if_available() { - None => { - fail!("get_module called on a node with no module \ - definition!") - } - Some(module_def) => module_def - } - } - - fn defined_in_namespace(&self, namespace: Namespace) -> bool { - match namespace { - TypeNS => return self.type_def.is_some(), - ValueNS => return self.value_def.is_some() - } - } - - fn defined_in_public_namespace(&self, namespace: Namespace) -> bool { - match namespace { - TypeNS => match self.type_def { - Some(def) => def.privacy != Private, - None => false - }, - ValueNS => match self.value_def { - Some(def) => def.privacy != Private, - None => false - } - } - } - - fn def_for_namespace(&self, namespace: Namespace) -> Option { - match namespace { - TypeNS => { - match self.type_def { - None => None, - Some(ref type_def) => { - // FIXME (#3784): This is reallllly questionable. - // Perhaps the right thing to do is to merge def_mod - // and def_ty. - match (*type_def).type_def { - Some(type_def) => Some(type_def), - None => { - match (*type_def).module_def { - Some(module_def) => { - let module_def = &mut *module_def; - module_def.def_id.map(|def_id| - def_mod(*def_id)) - } - None => None - } - } - } - } - } - } - ValueNS => { - match self.value_def { - None => None, - Some(value_def) => Some(value_def.def) - } - } - } - } - - fn privacy_for_namespace(&self, namespace: Namespace) -> Option { - match namespace { - TypeNS => { - match self.type_def { - None => None, - Some(ref type_def) => Some((*type_def).privacy) - } - } - ValueNS => { - match self.value_def { - None => None, - Some(value_def) => Some(value_def.privacy) - } - } - } - } - - fn span_for_namespace(&self, namespace: Namespace) -> Option { - if self.defined_in_namespace(namespace) { - match namespace { - TypeNS => self.type_span, - ValueNS => self.value_span, - } - } else { - None - } - } -} - -pub fn NameBindings() -> NameBindings { - NameBindings { - type_def: None, - value_def: None, - type_span: None, - value_span: None - } -} - -/// Interns the names of the primitive types. -pub struct PrimitiveTypeTable { - primitive_types: HashMap, -} - -pub impl PrimitiveTypeTable { - fn intern(&mut self, intr: @ident_interner, string: &str, - primitive_type: prim_ty) { - let ident = intr.intern(string); - self.primitive_types.insert(ident, primitive_type); - } -} - -pub fn PrimitiveTypeTable(intr: @ident_interner) -> PrimitiveTypeTable { - let mut table = PrimitiveTypeTable { - primitive_types: HashMap::new() - }; - - table.intern(intr, "bool", ty_bool); - table.intern(intr, "char", ty_int(ty_char)); - table.intern(intr, "float", ty_float(ty_f)); - table.intern(intr, "f32", ty_float(ty_f32)); - table.intern(intr, "f64", ty_float(ty_f64)); - table.intern(intr, "int", ty_int(ty_i)); - table.intern(intr, "i8", ty_int(ty_i8)); - table.intern(intr, "i16", ty_int(ty_i16)); - table.intern(intr, "i32", ty_int(ty_i32)); - table.intern(intr, "i64", ty_int(ty_i64)); - table.intern(intr, "str", ty_str); - table.intern(intr, "uint", ty_uint(ty_u)); - table.intern(intr, "u8", ty_uint(ty_u8)); - table.intern(intr, "u16", ty_uint(ty_u16)); - table.intern(intr, "u32", ty_uint(ty_u32)); - table.intern(intr, "u64", ty_uint(ty_u64)); - - return table; -} - - -pub fn namespace_to_str(ns: Namespace) -> ~str { - match ns { - TypeNS => ~"type", - ValueNS => ~"value", - } -} - -pub fn Resolver(session: Session, - lang_items: LanguageItems, - crate: @crate) - -> Resolver { - let graph_root = @mut NameBindings(); - - graph_root.define_module(Public, - NoParentLink, - Some(def_id { crate: 0, node: 0 }), - NormalModuleKind, - crate.span); - - let current_module = graph_root.get_module(); - - let this = Resolver { - session: @session, - lang_items: copy lang_items, - crate: crate, - - // The outermost module has def ID 0; this is not reflected in the - // AST. - - graph_root: graph_root, - - trait_info: HashMap::new(), - structs: HashSet::new(), - - unresolved_imports: 0, - - current_module: current_module, - value_ribs: ~[], - type_ribs: ~[], - label_ribs: ~[], - - xray_context: NoXray, - current_trait_refs: None, - - self_ident: special_idents::self_, - type_self_ident: special_idents::type_self, - - primitive_type_table: @PrimitiveTypeTable(session. - parse_sess.interner), - - namespaces: ~[ TypeNS, ValueNS ], - - attr_main_fn: None, - main_fns: ~[], - - start_fn: None, - - def_map: @mut HashMap::new(), - export_map2: @mut HashMap::new(), - trait_map: HashMap::new(), - - intr: session.intr() - }; - - this -} - -/// The main resolver class. -pub struct Resolver { - session: @Session, - lang_items: LanguageItems, - crate: @crate, - - intr: @ident_interner, - - graph_root: @mut NameBindings, - - trait_info: HashMap>, - structs: HashSet, - - // The number of imports that are currently unresolved. - unresolved_imports: uint, - - // The module that represents the current item scope. - current_module: @mut Module, - - // The current set of local scopes, for values. - // FIXME #4948: Reuse ribs to avoid allocation. - value_ribs: ~[@Rib], - - // The current set of local scopes, for types. - type_ribs: ~[@Rib], - - // The current set of local scopes, for labels. - label_ribs: ~[@Rib], - - // Whether the current context is an X-ray context. An X-ray context is - // allowed to access private names of any module. - xray_context: XrayFlag, - - // The trait that the current context can refer to. - current_trait_refs: Option<~[def_id]>, - - // The ident for the keyword "self". - self_ident: ident, - // The ident for the non-keyword "Self". - type_self_ident: ident, - - // The idents for the primitive types. - primitive_type_table: @PrimitiveTypeTable, - - // The four namespaces. - namespaces: ~[Namespace], - - // The function that has attribute named 'main' - attr_main_fn: Option<(node_id, span)>, - - // The functions that could be main functions - main_fns: ~[Option<(node_id, span)>], - - // The function that has the attribute 'start' on it - start_fn: Option<(node_id, span)>, - - def_map: DefMap, - export_map2: ExportMap2, - trait_map: TraitMap, -} - -pub impl Resolver { - /// The main name resolution procedure. - fn resolve(@mut self) { - self.build_reduced_graph(); - self.session.abort_if_errors(); - - self.resolve_imports(); - self.session.abort_if_errors(); - - self.record_exports(); - self.session.abort_if_errors(); - - self.resolve_crate(); - self.session.abort_if_errors(); - - self.check_duplicate_main(); - self.check_for_unused_imports_if_necessary(); - } - - // - // Reduced graph building - // - // Here we build the "reduced graph": the graph of the module tree without - // any imports resolved. - // - - /// Constructs the reduced graph for the entire crate. - fn build_reduced_graph(@mut self) { - let initial_parent = - ModuleReducedGraphParent(self.graph_root.get_module()); - visit_crate(self.crate, initial_parent, mk_vt(@Visitor { - visit_item: |item, context, visitor| - self.build_reduced_graph_for_item(item, context, visitor), - - visit_foreign_item: |foreign_item, context, visitor| - self.build_reduced_graph_for_foreign_item(foreign_item, - context, - visitor), - - visit_view_item: |view_item, context, visitor| - self.build_reduced_graph_for_view_item(view_item, - context, - visitor), - - visit_block: |block, context, visitor| - self.build_reduced_graph_for_block(block, - context, - visitor), - - .. *default_visitor() - })); - } - - /// Returns the current module tracked by the reduced graph parent. - fn get_module_from_parent(@mut self, - reduced_graph_parent: ReducedGraphParent) - -> @mut Module { - match reduced_graph_parent { - ModuleReducedGraphParent(module_) => { - return module_; - } - } - } - - /** - * Adds a new child item to the module definition of the parent node and - * returns its corresponding name bindings as well as the current parent. - * Or, if we're inside a block, creates (or reuses) an anonymous module - * corresponding to the innermost block ID and returns the name bindings - * as well as the newly-created parent. - * - * If this node does not have a module definition and we are not inside - * a block, fails. - */ - fn add_child(@mut self, - name: ident, - reduced_graph_parent: ReducedGraphParent, - duplicate_checking_mode: DuplicateCheckingMode, - // For printing errors - sp: span) - -> (@mut NameBindings, ReducedGraphParent) { - - // If this is the immediate descendant of a module, then we add the - // child name directly. Otherwise, we create or reuse an anonymous - // module and add the child to that. - - let module_; - match reduced_graph_parent { - ModuleReducedGraphParent(parent_module) => { - module_ = parent_module; - } - } - - // Add or reuse the child. - let new_parent = ModuleReducedGraphParent(module_); - match module_.children.find(&name) { - None => { - let child = @mut NameBindings(); - module_.children.insert(name, child); - return (child, new_parent); - } - Some(child) => { - // Enforce the duplicate checking mode: - // - // * If we're requesting duplicate module checking, check that - // there isn't a module in the module with the same name. - // - // * If we're requesting duplicate type checking, check that - // there isn't a type in the module with the same name. - // - // * If we're requesting duplicate value checking, check that - // there isn't a value in the module with the same name. - // - // * If we're requesting duplicate type checking and duplicate - // value checking, check that there isn't a duplicate type - // and a duplicate value with the same name. - // - // * If no duplicate checking was requested at all, do - // nothing. - - let mut is_duplicate = false; - match duplicate_checking_mode { - ForbidDuplicateModules => { - is_duplicate = - child.get_module_if_available().is_some(); - } - ForbidDuplicateTypes => { - match child.def_for_namespace(TypeNS) { - Some(def_mod(_)) | None => {} - Some(_) => is_duplicate = true - } - } - ForbidDuplicateValues => { - is_duplicate = child.defined_in_namespace(ValueNS); - } - ForbidDuplicateTypesAndValues => { - match child.def_for_namespace(TypeNS) { - Some(def_mod(_)) | None => {} - Some(_) => is_duplicate = true - }; - if child.defined_in_namespace(ValueNS) { - is_duplicate = true; - } - } - OverwriteDuplicates => {} - } - if duplicate_checking_mode != OverwriteDuplicates && - is_duplicate { - // Return an error here by looking up the namespace that - // had the duplicate. - let ns = namespace_for_duplicate_checking_mode( - duplicate_checking_mode); - self.session.span_err(sp, - fmt!("duplicate definition of %s %s", - namespace_to_str(ns), - *self.session.str_of(name))); - for child.span_for_namespace(ns).each |sp| { - self.session.span_note(*sp, - fmt!("first definition of %s %s here:", - namespace_to_str(ns), - *self.session.str_of(name))); - } - } - return (*child, new_parent); - } - } - } - - fn block_needs_anonymous_module(@mut self, block: &blk) -> bool { - // If the block has view items, we need an anonymous module. - if block.node.view_items.len() > 0 { - return true; - } - - // Check each statement. - for block.node.stmts.each |statement| { - match statement.node { - stmt_decl(declaration, _) => { - match declaration.node { - decl_item(_) => { - return true; - } - _ => { - // Keep searching. - } - } - } - _ => { - // Keep searching. - } - } - } - - // If we found neither view items nor items, we don't need to create - // an anonymous module. - - return false; - } - - fn get_parent_link(@mut self, - parent: ReducedGraphParent, - name: ident) - -> ParentLink { - match parent { - ModuleReducedGraphParent(module_) => { - return ModuleParentLink(module_, name); - } - } - } - - /// Constructs the reduced graph for one item. - fn build_reduced_graph_for_item(@mut self, - item: @item, - parent: ReducedGraphParent, - visitor: vt) { - let ident = item.ident; - let sp = item.span; - let privacy = visibility_to_privacy(item.vis); - - match item.node { - item_mod(ref module_) => { - let (name_bindings, new_parent) = - self.add_child(ident, parent, ForbidDuplicateModules, sp); - - let parent_link = self.get_parent_link(new_parent, ident); - let def_id = def_id { crate: 0, node: item.id }; - name_bindings.define_module(privacy, - parent_link, - Some(def_id), - NormalModuleKind, - sp); - - let new_parent = - ModuleReducedGraphParent(name_bindings.get_module()); - - visit_mod(module_, sp, item.id, new_parent, visitor); - } - - item_foreign_mod(ref fm) => { - let new_parent = match fm.sort { - named => { - let (name_bindings, new_parent) = - self.add_child(ident, parent, - ForbidDuplicateModules, sp); - - let parent_link = self.get_parent_link(new_parent, - ident); - let def_id = def_id { crate: 0, node: item.id }; - name_bindings.define_module(privacy, - parent_link, - Some(def_id), - ExternModuleKind, - sp); - - ModuleReducedGraphParent(name_bindings.get_module()) - } - - // For anon foreign mods, the contents just go in the - // current scope - anonymous => parent - }; - - visit_item(item, new_parent, visitor); - } - - // These items live in the value namespace. - item_const(*) => { - let (name_bindings, _) = - self.add_child(ident, parent, ForbidDuplicateValues, sp); - - name_bindings.define_value - (privacy, def_const(local_def(item.id)), sp); - } - item_fn(_, purity, _, _, _) => { - let (name_bindings, new_parent) = - self.add_child(ident, parent, ForbidDuplicateValues, sp); - - let def = def_fn(local_def(item.id), purity); - name_bindings.define_value(privacy, def, sp); - visit_item(item, new_parent, visitor); - } - - // These items live in the type namespace. - item_ty(*) => { - let (name_bindings, _) = - self.add_child(ident, parent, ForbidDuplicateTypes, sp); - - name_bindings.define_type - (privacy, def_ty(local_def(item.id)), sp); - } - - item_enum(ref enum_definition, _) => { - let (name_bindings, new_parent) = - self.add_child(ident, parent, ForbidDuplicateTypes, sp); - - name_bindings.define_type - (privacy, def_ty(local_def(item.id)), sp); - - for (*enum_definition).variants.each |variant| { - self.build_reduced_graph_for_variant(variant, - local_def(item.id), - // inherited => privacy of the enum item - variant_visibility_to_privacy(variant.node.vis, - privacy == Public), - new_parent, - visitor); - } - } - - // These items live in both the type and value namespaces. - item_struct(struct_def, _) => { - let (name_bindings, new_parent) = - self.add_child(ident, parent, ForbidDuplicateTypes, sp); - - name_bindings.define_type( - privacy, def_ty(local_def(item.id)), sp); - - // If this struct is tuple-like or enum-like, define a name - // in the value namespace. - match struct_def.ctor_id { - None => {} - Some(ctor_id) => { - name_bindings.define_value( - privacy, - def_struct(local_def(ctor_id)), - sp); - } - } - - // Record the def ID of this struct. - self.structs.insert(local_def(item.id)); - - visit_item(item, new_parent, visitor); - } - - item_impl(_, trait_ref_opt, ty, ref methods) => { - // If this implements an anonymous trait and it has static - // methods, then add all the static methods within to a new - // module, if the type was defined within this module. - // - // FIXME (#3785): This is quite unsatisfactory. Perhaps we - // should modify anonymous traits to only be implementable in - // the same module that declared the type. - - // Bail out early if there are no static methods. - let mut has_static_methods = false; - for methods.each |method| { - match method.explicit_self.node { - sty_static => has_static_methods = true, - _ => {} - } - } - - // If there are static methods, then create the module - // and add them. - match (trait_ref_opt, ty) { - (None, @Ty { node: ty_path(path, _), _ }) if - has_static_methods && path.idents.len() == 1 => { - // Create the module. - let name = path_to_ident(path); - let (name_bindings, new_parent) = - self.add_child(name, - parent, - ForbidDuplicateModules, - sp); - - let parent_link = self.get_parent_link(new_parent, - ident); - let def_id = local_def(item.id); - name_bindings.define_module(Public, - parent_link, - Some(def_id), - TraitModuleKind, - sp); - - let new_parent = ModuleReducedGraphParent( - name_bindings.get_module()); - - // For each static method... - for methods.each |method| { - match method.explicit_self.node { - sty_static => { - // Add the static method to the - // module. - let ident = method.ident; - let (method_name_bindings, _) = - self.add_child( - ident, - new_parent, - ForbidDuplicateValues, - method.span); - let def = def_fn(local_def(method.id), - method.purity); - method_name_bindings.define_value( - Public, def, method.span); - } - _ => {} - } - } - } - _ => {} - } - - visit_item(item, parent, visitor); - } - - item_trait(_, _, ref methods) => { - let (name_bindings, new_parent) = - self.add_child(ident, parent, ForbidDuplicateTypes, sp); - - // If the trait has static methods, then add all the static - // methods within to a new module. - // - // We only need to create the module if the trait has static - // methods, so check that first. - let mut has_static_methods = false; - for (*methods).each |method| { - let ty_m = trait_method_to_ty_method(method); - match ty_m.explicit_self.node { - sty_static => { - has_static_methods = true; - break; - } - _ => {} - } - } - - // Create the module if necessary. - let module_parent_opt; - if has_static_methods { - let parent_link = self.get_parent_link(parent, ident); - name_bindings.define_module(privacy, - parent_link, - Some(local_def(item.id)), - TraitModuleKind, - sp); - module_parent_opt = Some(ModuleReducedGraphParent( - name_bindings.get_module())); - } else { - module_parent_opt = None; - } - - // Add the names of all the methods to the trait info. - let mut method_names = HashSet::new(); - for methods.each |method| { - let ty_m = trait_method_to_ty_method(method); - - let ident = ty_m.ident; - // Add it to the trait info if not static, - // add it as a name in the trait module otherwise. - match ty_m.explicit_self.node { - sty_static => { - let def = def_static_method( - local_def(ty_m.id), - Some(local_def(item.id)), - ty_m.purity); - - let (method_name_bindings, _) = - self.add_child(ident, - module_parent_opt.get(), - ForbidDuplicateValues, - ty_m.span); - method_name_bindings.define_value(Public, - def, - ty_m.span); - } - _ => { - method_names.insert(ident); - } - } - } - - let def_id = local_def(item.id); - self.trait_info.insert(def_id, method_names); - - name_bindings.define_type(privacy, def_trait(def_id), sp); - visit_item(item, new_parent, visitor); - } - - item_mac(*) => { - fail!("item macros unimplemented") - } - } - } - - // Constructs the reduced graph for one variant. Variants exist in the - // type and/or value namespaces. - fn build_reduced_graph_for_variant(@mut self, - variant: &variant, - item_id: def_id, - parent_privacy: Privacy, - parent: ReducedGraphParent, - _visitor: vt) { - let ident = variant.node.name; - let (child, _) = self.add_child(ident, parent, ForbidDuplicateValues, - variant.span); - - let privacy; - match variant.node.vis { - public => privacy = Public, - private => privacy = Private, - inherited => privacy = parent_privacy - } - - match variant.node.kind { - tuple_variant_kind(_) => { - child.define_value(privacy, - def_variant(item_id, - local_def(variant.node.id)), - variant.span); - } - struct_variant_kind(_) => { - child.define_type(privacy, - def_variant(item_id, - local_def(variant.node.id)), - variant.span); - self.structs.insert(local_def(variant.node.id)); - } - } - } - - /** - * Constructs the reduced graph for one 'view item'. View items consist - * of imports and use directives. - */ - fn build_reduced_graph_for_view_item(@mut self, - view_item: @view_item, - parent: ReducedGraphParent, - _visitor: vt) { - let privacy = visibility_to_privacy(view_item.vis); - match view_item.node { - view_item_use(ref view_paths) => { - for view_paths.each |view_path| { - // Extract and intern the module part of the path. For - // globs and lists, the path is found directly in the AST; - // for simple paths we have to munge the path a little. - - let mut module_path = ~[]; - match view_path.node { - view_path_simple(_, full_path, _) => { - let path_len = full_path.idents.len(); - assert!(path_len != 0); - - for full_path.idents.eachi |i, ident| { - if i != path_len - 1 { - module_path.push(*ident); - } - } - } - - view_path_glob(module_ident_path, _) | - view_path_list(module_ident_path, _, _) => { - for module_ident_path.idents.each |ident| { - module_path.push(*ident); - } - } - } - - // Build up the import directives. - let module_ = self.get_module_from_parent(parent); - match view_path.node { - view_path_simple(binding, full_path, _) => { - let source_ident = *full_path.idents.last(); - let subclass = @SingleImport(binding, - source_ident); - self.build_import_directive(privacy, - module_, - module_path, - subclass, - view_path.span); - } - view_path_list(_, ref source_idents, _) => { - for source_idents.each |source_ident| { - let name = source_ident.node.name; - let subclass = @SingleImport(name, name); - self.build_import_directive(privacy, - module_, - copy module_path, - subclass, - source_ident.span); - } - } - view_path_glob(_, _) => { - self.build_import_directive(privacy, - module_, - module_path, - @GlobImport, - view_path.span); - } - } - } - } - - view_item_extern_mod(name, _, node_id) => { - match find_extern_mod_stmt_cnum(self.session.cstore, - node_id) { - Some(crate_id) => { - let def_id = def_id { crate: crate_id, node: 0 }; - let parent_link = ModuleParentLink - (self.get_module_from_parent(parent), name); - let external_module = @mut Module(parent_link, - Some(def_id), - NormalModuleKind); - - parent.external_module_children.insert( - name, - external_module); - - self.build_reduced_graph_for_external_crate( - external_module); - } - None => {} // Ignore. - } - } - } - } - - /// Constructs the reduced graph for one foreign item. - fn build_reduced_graph_for_foreign_item(@mut self, - foreign_item: @foreign_item, - parent: ReducedGraphParent, - visitor: - vt) { - let name = foreign_item.ident; - let (name_bindings, new_parent) = - self.add_child(name, parent, ForbidDuplicateValues, - foreign_item.span); - - match foreign_item.node { - foreign_item_fn(_, _, ref generics) => { - let def = def_fn(local_def(foreign_item.id), unsafe_fn); - name_bindings.define_value(Public, def, foreign_item.span); - - do self.with_type_parameter_rib( - HasTypeParameters( - generics, foreign_item.id, 0, NormalRibKind)) - { - visit_foreign_item(foreign_item, new_parent, visitor); - } - } - foreign_item_const(*) => { - let def = def_const(local_def(foreign_item.id)); - name_bindings.define_value(Public, def, foreign_item.span); - - visit_foreign_item(foreign_item, new_parent, visitor); - } - } - } - - fn build_reduced_graph_for_block(@mut self, - block: &blk, - parent: ReducedGraphParent, - visitor: vt) { - let new_parent; - if self.block_needs_anonymous_module(block) { - let block_id = block.node.id; - - debug!("(building reduced graph for block) creating a new \ - anonymous module for block %d", - block_id); - - let parent_module = self.get_module_from_parent(parent); - let new_module = @mut Module( - BlockParentLink(parent_module, block_id), - None, - AnonymousModuleKind); - parent_module.anonymous_children.insert(block_id, new_module); - new_parent = ModuleReducedGraphParent(new_module); - } else { - new_parent = parent; - } - - visit_block(block, new_parent, visitor); - } - - fn handle_external_def(@mut self, - def: def, - modules: &mut HashMap, - child_name_bindings: @mut NameBindings, - final_ident: &str, - ident: ident, - new_parent: ReducedGraphParent) { - match def { - def_mod(def_id) | def_foreign_mod(def_id) => { - match child_name_bindings.type_def { - Some(TypeNsDef { module_def: Some(copy module_def), _ }) => { - debug!("(building reduced graph for external crate) \ - already created module"); - module_def.def_id = Some(def_id); - modules.insert(def_id, module_def); - } - Some(_) | None => { - debug!("(building reduced graph for \ - external crate) building module \ - %s", final_ident); - let parent_link = self.get_parent_link(new_parent, ident); - - // FIXME (#5074): this should be a match on find - if !modules.contains_key(&def_id) { - child_name_bindings.define_module(Public, - parent_link, - Some(def_id), - NormalModuleKind, - dummy_sp()); - modules.insert(def_id, - child_name_bindings.get_module()); - } else { - let existing_module = *modules.get(&def_id); - // Create an import resolution to - // avoid creating cycles in the - // module graph. - - let resolution = - @mut ImportResolution(Public, - dummy_sp(), - @mut ImportState()); - resolution.outstanding_references = 0; - - match existing_module.parent_link { - NoParentLink | - BlockParentLink(*) => { - fail!("can't happen"); - } - ModuleParentLink(parent_module, ident) => { - let name_bindings = parent_module.children.get( - &ident); - resolution.type_target = - Some(Target(parent_module, *name_bindings)); - } - } - - debug!("(building reduced graph for external crate) \ - ... creating import resolution"); - - new_parent.import_resolutions.insert(ident, resolution); - } - } - } - } - def_fn(*) | def_static_method(*) | def_const(*) | - def_variant(*) => { - debug!("(building reduced graph for external \ - crate) building value %s", final_ident); - child_name_bindings.define_value(Public, def, dummy_sp()); - } - def_trait(def_id) => { - debug!("(building reduced graph for external \ - crate) building type %s", final_ident); - - // If this is a trait, add all the method names - // to the trait info. - - let method_def_ids = get_trait_method_def_ids(self.session.cstore, - def_id); - let mut interned_method_names = HashSet::new(); - for method_def_ids.each |&method_def_id| { - let (method_name, explicit_self) = - get_method_name_and_explicit_self(self.session.cstore, - method_def_id); - - debug!("(building reduced graph for \ - external crate) ... adding \ - trait method '%s'", - *self.session.str_of(method_name)); - - // Add it to the trait info if not static. - if explicit_self != sty_static { - interned_method_names.insert(method_name); - } - } - self.trait_info.insert(def_id, interned_method_names); - - child_name_bindings.define_type(Public, def, dummy_sp()); - } - def_ty(_) => { - debug!("(building reduced graph for external \ - crate) building type %s", final_ident); - - child_name_bindings.define_type(Public, def, dummy_sp()); - } - def_struct(def_id) => { - debug!("(building reduced graph for external \ - crate) building type %s", - final_ident); - child_name_bindings.define_type(Public, def, dummy_sp()); - self.structs.insert(def_id); - } - def_self(*) | def_arg(*) | def_local(*) | - def_prim_ty(*) | def_ty_param(*) | def_binding(*) | - def_use(*) | def_upvar(*) | def_region(*) | - def_typaram_binder(*) | def_label(*) | def_self_ty(*) => { - fail!("didn't expect `%?`", def); - } - } - } - - /** - * Builds the reduced graph rooted at the 'use' directive for an external - * crate. - */ - fn build_reduced_graph_for_external_crate(@mut self, root: @mut Module) { - let mut modules = HashMap::new(); - - // Create all the items reachable by paths. - for each_path(self.session.cstore, root.def_id.get().crate) - |path_string, def_like| { - - debug!("(building reduced graph for external crate) found path \ - entry: %s (%?)", - path_string, def_like); - - let mut pieces = ~[]; - for each_split_str(path_string, "::") |s| { pieces.push(s.to_owned()) } - let final_ident_str = pieces.pop(); - let final_ident = self.session.ident_of(final_ident_str); - - // Find the module we need, creating modules along the way if we - // need to. - - let mut current_module = root; - for pieces.each |ident_str| { - let ident = self.session.ident_of(/*bad*/copy *ident_str); - // Create or reuse a graph node for the child. - let (child_name_bindings, new_parent) = - self.add_child(ident, - ModuleReducedGraphParent(current_module), - OverwriteDuplicates, - dummy_sp()); - - // Define or reuse the module node. - match child_name_bindings.type_def { - None => { - debug!("(building reduced graph for external crate) \ - autovivifying missing type def %s", - *ident_str); - let parent_link = self.get_parent_link(new_parent, - ident); - child_name_bindings.define_module(Public, - parent_link, - None, - NormalModuleKind, - dummy_sp()); - } - Some(copy type_ns_def) - if type_ns_def.module_def.is_none() => { - debug!("(building reduced graph for external crate) \ - autovivifying missing module def %s", - *ident_str); - let parent_link = self.get_parent_link(new_parent, - ident); - child_name_bindings.define_module(Public, - parent_link, - None, - NormalModuleKind, - dummy_sp()); - } - _ => {} // Fall through. - } - - current_module = child_name_bindings.get_module(); - } - - match def_like { - dl_def(def) => { - // Add the new child item. - let (child_name_bindings, new_parent) = - self.add_child(final_ident, - ModuleReducedGraphParent( - current_module), - OverwriteDuplicates, - dummy_sp()); - - self.handle_external_def(def, - &mut modules, - child_name_bindings, - *self.session.str_of( - final_ident), - final_ident, - new_parent); - } - dl_impl(def) => { - // We only process static methods of impls here. - match get_type_name_if_impl(self.session.cstore, def) { - None => {} - Some(final_ident) => { - let static_methods_opt = - get_static_methods_if_impl( - self.session.cstore, def); - match static_methods_opt { - Some(ref static_methods) if - static_methods.len() >= 1 => { - debug!("(building reduced graph for \ - external crate) processing \ - static methods for type name %s", - *self.session.str_of( - final_ident)); - - let (child_name_bindings, new_parent) = - self.add_child(final_ident, - ModuleReducedGraphParent( - current_module), - OverwriteDuplicates, - dummy_sp()); - - // Process the static methods. First, - // create the module. - let type_module; - match child_name_bindings.type_def { - Some(TypeNsDef { - module_def: Some(copy module_def), - _ - }) => { - // We already have a module. This - // is OK. - type_module = module_def; - } - Some(_) | None => { - let parent_link = - self.get_parent_link( - new_parent, final_ident); - child_name_bindings.define_module( - Public, - parent_link, - Some(def), - NormalModuleKind, - dummy_sp()); - type_module = - child_name_bindings. - get_module(); - } - } - - // Add each static method to the module. - let new_parent = ModuleReducedGraphParent( - type_module); - for static_methods.each - |static_method_info| { - let ident = static_method_info.ident; - debug!("(building reduced graph for \ - external crate) creating \ - static method '%s'", - *self.session.str_of(ident)); - - let (method_name_bindings, _) = - self.add_child( - ident, - new_parent, - OverwriteDuplicates, - dummy_sp()); - let def = def_fn( - static_method_info.def_id, - static_method_info.purity); - method_name_bindings.define_value( - Public, def, dummy_sp()); - } - } - - // Otherwise, do nothing. - Some(_) | None => {} - } - } - } - } - dl_field => { - debug!("(building reduced graph for external crate) \ - ignoring field"); - } - } - } - } - - /// Creates and adds an import directive to the given module. - fn build_import_directive(@mut self, - privacy: Privacy, - module_: @mut Module, - module_path: ~[ident], - subclass: @ImportDirectiveSubclass, - span: span) { - let directive = @ImportDirective(privacy, module_path, - subclass, span); - module_.imports.push(directive); - - // Bump the reference count on the name. Or, if this is a glob, set - // the appropriate flag. - - match *subclass { - SingleImport(target, _) => { - debug!("(building import directive) building import \ - directive: privacy %? %s::%s", - privacy, - self.idents_to_str(directive.module_path), - *self.session.str_of(target)); - - match module_.import_resolutions.find(&target) { - Some(resolution) => { - debug!("(building import directive) bumping \ - reference"); - resolution.outstanding_references += 1; - } - None => { - debug!("(building import directive) creating new"); - let state = @mut ImportState(); - let resolution = @mut ImportResolution(privacy, - span, - state); - let name = self.idents_to_str(directive.module_path); - // Don't warn about unused intrinsics because they're - // automatically appended to all files - if name == ~"intrinsic::rusti" { - resolution.state.warned = true; - } - resolution.outstanding_references = 1; - module_.import_resolutions.insert(target, resolution); - } - } - } - GlobImport => { - // Set the glob flag. This tells us that we don't know the - // module's exports ahead of time. - - module_.glob_count += 1; - } - } - - self.unresolved_imports += 1; - } - - // Import resolution - // - // This is a fixed-point algorithm. We resolve imports until our efforts - // are stymied by an unresolved import; then we bail out of the current - // module and continue. We terminate successfully once no more imports - // remain or unsuccessfully when no forward progress in resolving imports - // is made. - - /** - * Resolves all imports for the crate. This method performs the fixed- - * point iteration. - */ - fn resolve_imports(@mut self) { - let mut i = 0; - let mut prev_unresolved_imports = 0; - loop { - debug!("(resolving imports) iteration %u, %u imports left", - i, self.unresolved_imports); - - let module_root = self.graph_root.get_module(); - self.resolve_imports_for_module_subtree(module_root); - - if self.unresolved_imports == 0 { - debug!("(resolving imports) success"); - break; - } - - if self.unresolved_imports == prev_unresolved_imports { - self.session.err(~"failed to resolve imports"); - self.report_unresolved_imports(module_root); - break; - } - - i += 1; - prev_unresolved_imports = self.unresolved_imports; - } - } - - /// Attempts to resolve imports for the given module and all of its - /// submodules. - fn resolve_imports_for_module_subtree(@mut self, module_: @mut Module) { - debug!("(resolving imports for module subtree) resolving %s", - self.module_to_str(module_)); - self.resolve_imports_for_module(module_); - - for module_.children.each_value |&child_node| { - match child_node.get_module_if_available() { - None => { - // Nothing to do. - } - Some(child_module) => { - self.resolve_imports_for_module_subtree(child_module); - } - } - } - - for module_.anonymous_children.each_value |&child_module| { - self.resolve_imports_for_module_subtree(child_module); - } - } - - /// Attempts to resolve imports for the given module only. - fn resolve_imports_for_module(@mut self, module: @mut Module) { - if module.all_imports_resolved() { - debug!("(resolving imports for module) all imports resolved for \ - %s", - self.module_to_str(module)); - return; - } - - let imports = &mut *module.imports; - let import_count = imports.len(); - while module.resolved_import_count < import_count { - let import_index = module.resolved_import_count; - let import_directive = imports[import_index]; - match self.resolve_import_for_module(module, import_directive) { - Failed => { - // We presumably emitted an error. Continue. - let msg = fmt!("failed to resolve import: %s", - *self.import_path_to_str( - import_directive.module_path, - *import_directive.subclass)); - self.session.span_err(import_directive.span, msg); - } - Indeterminate => { - // Bail out. We'll come around next time. - break; - } - Success(()) => { - // Good. Continue. - } - } - - module.resolved_import_count += 1; - } - } - - fn idents_to_str(@mut self, idents: &[ident]) -> ~str { - let mut first = true; - let mut result = ~""; - for idents.each |ident| { - if first { first = false; } else { result += "::" }; - result += *self.session.str_of(*ident); - }; - return result; - } - - fn import_directive_subclass_to_str(@mut self, - subclass: ImportDirectiveSubclass) - -> @~str { - match subclass { - SingleImport(_target, source) => self.session.str_of(source), - GlobImport => @~"*" - } - } - - fn import_path_to_str(@mut self, - idents: &[ident], - subclass: ImportDirectiveSubclass) - -> @~str { - if idents.is_empty() { - self.import_directive_subclass_to_str(subclass) - } else { - @fmt!("%s::%s", - self.idents_to_str(idents), - *self.import_directive_subclass_to_str(subclass)) - } - } - - /// Attempts to resolve the given import. The return value indicates - /// failure if we're certain the name does not exist, indeterminate if we - /// don't know whether the name exists at the moment due to other - /// currently-unresolved imports, or success if we know the name exists. - /// If successful, the resolved bindings are written into the module. - fn resolve_import_for_module(@mut self, module_: @mut Module, - import_directive: @ImportDirective) - -> ResolveResult<()> { - let mut resolution_result = Failed; - let module_path = &import_directive.module_path; - - debug!("(resolving import for module) resolving import `%s::...` in \ - `%s`", - self.idents_to_str(*module_path), - self.module_to_str(module_)); - - // First, resolve the module path for the directive, if necessary. - let containing_module = if module_path.len() == 0 { - // Use the crate root. - Some(self.graph_root.get_module()) - } else { - match self.resolve_module_path_for_import(module_, - *module_path, - DontUseLexicalScope, - import_directive.span) { - - Failed => None, - Indeterminate => { - resolution_result = Indeterminate; - None - } - Success(containing_module) => Some(containing_module), - } - }; - - match containing_module { - None => {} - Some(containing_module) => { - // We found the module that the target is contained - // within. Attempt to resolve the import within it. - - match *import_directive.subclass { - SingleImport(target, source) => { - resolution_result = - self.resolve_single_import(module_, - containing_module, - target, - source); - } - GlobImport => { - let span = import_directive.span; - let privacy = import_directive.privacy; - resolution_result = - self.resolve_glob_import(privacy, - module_, - containing_module, - span); - } - } - } - } - - // Decrement the count of unresolved imports. - match resolution_result { - Success(()) => { - assert!(self.unresolved_imports >= 1); - self.unresolved_imports -= 1; - } - _ => { - // Nothing to do here; just return the error. - } - } - - // Decrement the count of unresolved globs if necessary. But only if - // the resolution result is indeterminate -- otherwise we'll stop - // processing imports here. (See the loop in - // resolve_imports_for_module.) - - if !resolution_result.indeterminate() { - match *import_directive.subclass { - GlobImport => { - assert!(module_.glob_count >= 1); - module_.glob_count -= 1; - } - SingleImport(*) => { - // Ignore. - } - } - } - - return resolution_result; - } - - fn create_name_bindings_from_module(module: @mut Module) -> NameBindings { - NameBindings { - type_def: Some(TypeNsDef { - privacy: Public, - module_def: Some(module), - type_def: None, - }), - value_def: None, - type_span: None, - value_span: None, - } - } - - fn resolve_single_import(@mut self, - module_: @mut Module, - containing_module: @mut Module, - target: ident, - source: ident) - -> ResolveResult<()> { - debug!("(resolving single import) resolving `%s` = `%s::%s` from \ - `%s`", - *self.session.str_of(target), - self.module_to_str(containing_module), - *self.session.str_of(source), - self.module_to_str(module_)); - - // We need to resolve both namespaces for this to succeed. - // - // FIXME #4949: See if there's some way of handling namespaces in - // a more generic way. We have two of them; it seems worth - // doing... - - let mut value_result = UnknownResult; - let mut type_result = UnknownResult; - - // Search for direct children of the containing module. - match containing_module.children.find(&source) { - None => { - // Continue. - } - Some(child_name_bindings) => { - if child_name_bindings.defined_in_namespace(ValueNS) { - value_result = BoundResult(containing_module, - *child_name_bindings); - } - if child_name_bindings.defined_in_namespace(TypeNS) { - type_result = BoundResult(containing_module, - *child_name_bindings); - } - } - } - - // Unless we managed to find a result in both namespaces (unlikely), - // search imports as well. - match (value_result, type_result) { - (BoundResult(*), BoundResult(*)) => { - // Continue. - } - _ => { - // If there is an unresolved glob at this point in the - // containing module, bail out. We don't know enough to be - // able to resolve this import. - - if containing_module.glob_count > 0 { - debug!("(resolving single import) unresolved glob; \ - bailing out"); - return Indeterminate; - } - - // Now search the exported imports within the containing - // module. - - match containing_module.import_resolutions.find(&source) { - None => { - // The containing module definitely doesn't have an - // exported import with the name in question. We can - // therefore accurately report that the names are - // unbound. - - if value_result.is_unknown() { - value_result = UnboundResult; - } - if type_result.is_unknown() { - type_result = UnboundResult; - } - } - Some(import_resolution) - if import_resolution.outstanding_references - == 0 => { - - fn get_binding(import_resolution: - @mut ImportResolution, - namespace: Namespace) - -> NamespaceResult { - - // Import resolutions must be declared with "pub" - // in order to be exported. - if import_resolution.privacy == Private { - return UnboundResult; - } - - match (*import_resolution). - target_for_namespace(namespace) { - None => { - return UnboundResult; - } - Some(target) => { - import_resolution.state.used = true; - return BoundResult(target.target_module, - target.bindings); - } - } - } - - // The name is an import which has been fully - // resolved. We can, therefore, just follow it. - if value_result.is_unknown() { - value_result = get_binding(*import_resolution, - ValueNS); - } - if type_result.is_unknown() { - type_result = get_binding(*import_resolution, - TypeNS); - } - } - Some(_) => { - // The import is unresolved. Bail out. - debug!("(resolving single import) unresolved import; \ - bailing out"); - return Indeterminate; - } - } - } - } - - // If we didn't find a result in the type namespace, search the - // external modules. - match type_result { - BoundResult(*) => {} - _ => { - match containing_module.external_module_children - .find(&source) { - None => {} // Continue. - Some(module) => { - let name_bindings = - @mut Resolver::create_name_bindings_from_module( - *module); - type_result = BoundResult(containing_module, - name_bindings); - } - } - } - } - - // We've successfully resolved the import. Write the results in. - assert!(module_.import_resolutions.contains_key(&target)); - let import_resolution = module_.import_resolutions.get(&target); - - match value_result { - BoundResult(target_module, name_bindings) => { - import_resolution.value_target = - Some(Target(target_module, name_bindings)); - } - UnboundResult => { /* Continue. */ } - UnknownResult => { - fail!("value result should be known at this point"); - } - } - match type_result { - BoundResult(target_module, name_bindings) => { - import_resolution.type_target = - Some(Target(target_module, name_bindings)); - } - UnboundResult => { /* Continue. */ } - UnknownResult => { - fail!("type result should be known at this point"); - } - } - - let i = import_resolution; - match (i.value_target, i.type_target) { - // If this name wasn't found in either namespace, it's definitely - // unresolved. - (None, None) => { return Failed; } - // If it's private, it's also unresolved. - (Some(t), None) | (None, Some(t)) => { - let bindings = &mut *t.bindings; - match bindings.type_def { - Some(ref type_def) => { - if type_def.privacy == Private { - return Failed; - } - } - _ => () - } - match bindings.value_def { - Some(ref value_def) => { - if value_def.privacy == Private { - return Failed; - } - } - _ => () - } - } - // It's also an error if there's both a type and a value with this - // name, but both are private - (Some(val), Some(ty)) => { - match (val.bindings.value_def, ty.bindings.value_def) { - (Some(ref value_def), Some(ref type_def)) => - if value_def.privacy == Private - && type_def.privacy == Private { - return Failed; - }, - _ => () - } - } - } - - assert!(import_resolution.outstanding_references >= 1); - import_resolution.outstanding_references -= 1; - - debug!("(resolving single import) successfully resolved import"); - return Success(()); - } - - // Resolves a glob import. Note that this function cannot fail; it either - // succeeds or bails out (as importing * from an empty module or a module - // that exports nothing is valid). - fn resolve_glob_import(@mut self, - privacy: Privacy, - module_: @mut Module, - containing_module: @mut Module, - span: span) - -> ResolveResult<()> { - // This function works in a highly imperative manner; it eagerly adds - // everything it can to the list of import resolutions of the module - // node. - debug!("(resolving glob import) resolving %? glob import", privacy); - let state = @mut ImportState(); - - // We must bail out if the node has unresolved imports of any kind - // (including globs). - if !(*containing_module).all_imports_resolved() { - debug!("(resolving glob import) target module has unresolved \ - imports; bailing out"); - return Indeterminate; - } - - assert_eq!(containing_module.glob_count, 0); - - // Add all resolved imports from the containing module. - for containing_module.import_resolutions.each - |ident, target_import_resolution| { - - debug!("(resolving glob import) writing module resolution \ - %? into `%s`", - target_import_resolution.type_target.is_none(), - self.module_to_str(module_)); - - // Here we merge two import resolutions. - match module_.import_resolutions.find(ident) { - None if target_import_resolution.privacy == Public => { - // Simple: just copy the old import resolution. - let new_import_resolution = - @mut ImportResolution(privacy, - target_import_resolution.span, - state); - new_import_resolution.value_target = - copy target_import_resolution.value_target; - new_import_resolution.type_target = - copy target_import_resolution.type_target; - - module_.import_resolutions.insert - (*ident, new_import_resolution); - } - None => { /* continue ... */ } - Some(dest_import_resolution) => { - // Merge the two import resolutions at a finer-grained - // level. - - match target_import_resolution.value_target { - None => { - // Continue. - } - Some(copy value_target) => { - dest_import_resolution.value_target = - Some(value_target); - } - } - match target_import_resolution.type_target { - None => { - // Continue. - } - Some(copy type_target) => { - dest_import_resolution.type_target = - Some(type_target); - } - } - } - } - } - - let merge_import_resolution = |ident, - name_bindings: @mut NameBindings| { - let dest_import_resolution; - match module_.import_resolutions.find(&ident) { - None => { - // Create a new import resolution from this child. - dest_import_resolution = @mut ImportResolution(privacy, - span, - state); - module_.import_resolutions.insert - (ident, dest_import_resolution); - } - Some(existing_import_resolution) => { - dest_import_resolution = *existing_import_resolution; - } - } - - debug!("(resolving glob import) writing resolution `%s` in `%s` \ - to `%s`, privacy=%?", - *self.session.str_of(ident), - self.module_to_str(containing_module), - self.module_to_str(module_), - copy dest_import_resolution.privacy); - - // Merge the child item into the import resolution. - if name_bindings.defined_in_public_namespace(ValueNS) { - debug!("(resolving glob import) ... for value target"); - dest_import_resolution.value_target = - Some(Target(containing_module, name_bindings)); - } - if name_bindings.defined_in_public_namespace(TypeNS) { - debug!("(resolving glob import) ... for type target"); - dest_import_resolution.type_target = - Some(Target(containing_module, name_bindings)); - } - }; - - // Add all children from the containing module. - for containing_module.children.each |&ident, name_bindings| { - merge_import_resolution(ident, *name_bindings); - } - - // Add external module children from the containing module. - for containing_module.external_module_children.each - |&ident, module| { - let name_bindings = - @mut Resolver::create_name_bindings_from_module(*module); - merge_import_resolution(ident, name_bindings); - } - - debug!("(resolving glob import) successfully resolved import"); - return Success(()); - } - - /// Resolves the given module path from the given root `module_`. - fn resolve_module_path_from_root(@mut self, - module_: @mut Module, - module_path: &[ident], - index: uint, - span: span, - mut name_search_type: NameSearchType) - -> ResolveResult<@mut Module> { - let mut search_module = module_; - let mut index = index; - let module_path_len = module_path.len(); - - // Resolve the module part of the path. This does not involve looking - // upward though scope chains; we simply resolve names directly in - // modules as we go. - - while index < module_path_len { - let name = module_path[index]; - match self.resolve_name_in_module(search_module, - name, - TypeNS, - name_search_type) { - Failed => { - self.session.span_err(span, ~"unresolved name"); - return Failed; - } - Indeterminate => { - debug!("(resolving module path for import) module \ - resolution is indeterminate: %s", - *self.session.str_of(name)); - return Indeterminate; - } - Success(target) => { - // Check to see whether there are type bindings, and, if - // so, whether there is a module within. - match target.bindings.type_def { - Some(copy type_def) => { - match type_def.module_def { - None => { - // Not a module. - self.session.span_err(span, - fmt!("not a \ - module: %s", - *self.session. - str_of( - name))); - return Failed; - } - Some(copy module_def) => { - search_module = module_def; - } - } - } - None => { - // There are no type bindings at all. - self.session.span_err(span, - fmt!("not a module: %s", - *self.session.str_of( - name))); - return Failed; - } - } - } - } - - index += 1; - - // After the first element of the path, allow searching through - // items and imports unconditionally. This allows things like: - // - // pub mod core { - // pub use vec; - // } - // - // pub mod something_else { - // use core::vec; - // } - - name_search_type = SearchItemsAndPublicImports; - } - - return Success(search_module); - } - - /// Attempts to resolve the module part of an import directive or path - /// rooted at the given module. - fn resolve_module_path_for_import(@mut self, - module_: @mut Module, - module_path: &[ident], - use_lexical_scope: UseLexicalScopeFlag, - span: span) - -> ResolveResult<@mut Module> { - let module_path_len = module_path.len(); - assert!(module_path_len > 0); - - debug!("(resolving module path for import) processing `%s` rooted at \ - `%s`", - self.idents_to_str(module_path), - self.module_to_str(module_)); - - // Resolve the module prefix, if any. - let module_prefix_result = self.resolve_module_prefix(module_, - module_path); - - let search_module; - let start_index; - match module_prefix_result { - Failed => { - self.session.span_err(span, ~"unresolved name"); - return Failed; - } - Indeterminate => { - debug!("(resolving module path for import) indeterminate; \ - bailing"); - return Indeterminate; - } - Success(NoPrefixFound) => { - // There was no prefix, so we're considering the first element - // of the path. How we handle this depends on whether we were - // instructed to use lexical scope or not. - match use_lexical_scope { - DontUseLexicalScope => { - // This is a crate-relative path. We will start the - // resolution process at index zero. - search_module = self.graph_root.get_module(); - start_index = 0; - } - UseLexicalScope => { - // This is not a crate-relative path. We resolve the - // first component of the path in the current lexical - // scope and then proceed to resolve below that. - let result = self.resolve_module_in_lexical_scope( - module_, - module_path[0]); - match result { - Failed => { - self.session.span_err(span, - ~"unresolved name"); - return Failed; - } - Indeterminate => { - debug!("(resolving module path for import) \ - indeterminate; bailing"); - return Indeterminate; - } - Success(containing_module) => { - search_module = containing_module; - start_index = 1; - } - } - } - } - } - Success(PrefixFound(containing_module, index)) => { - search_module = containing_module; - start_index = index; - } - } - - self.resolve_module_path_from_root(search_module, - module_path, - start_index, - span, - SearchItemsAndPublicImports) - } - - /// Invariant: This must only be called during main resolution, not during - /// import resolution. - fn resolve_item_in_lexical_scope(@mut self, - module_: @mut Module, - name: ident, - namespace: Namespace, - search_through_modules: - SearchThroughModulesFlag) - -> ResolveResult { - debug!("(resolving item in lexical scope) resolving `%s` in \ - namespace %? in `%s`", - *self.session.str_of(name), - namespace, - self.module_to_str(module_)); - - // The current module node is handled specially. First, check for - // its immediate children. - match module_.children.find(&name) { - Some(name_bindings) - if name_bindings.defined_in_namespace(namespace) => { - return Success(Target(module_, *name_bindings)); - } - Some(_) | None => { /* Not found; continue. */ } - } - - // Now check for its import directives. We don't have to have resolved - // all its imports in the usual way; this is because chains of - // adjacent import statements are processed as though they mutated the - // current scope. - match module_.import_resolutions.find(&name) { - None => { - // Not found; continue. - } - Some(import_resolution) => { - match (*import_resolution).target_for_namespace(namespace) { - None => { - // Not found; continue. - debug!("(resolving item in lexical scope) found \ - import resolution, but not in namespace %?", - namespace); - } - Some(target) => { - debug!("(resolving item in lexical scope) using \ - import resolution"); - import_resolution.state.used = true; - return Success(copy target); - } - } - } - } - - // Search for external modules. - if namespace == TypeNS { - match module_.external_module_children.find(&name) { - None => {} - Some(module) => { - let name_bindings = - @mut Resolver::create_name_bindings_from_module( - *module); - return Success(Target(module_, name_bindings)); - } - } - } - - // Finally, proceed up the scope chain looking for parent modules. - let mut search_module = module_; - loop { - // Go to the next parent. - match search_module.parent_link { - NoParentLink => { - // No more parents. This module was unresolved. - debug!("(resolving item in lexical scope) unresolved \ - module"); - return Failed; - } - ModuleParentLink(parent_module_node, _) => { - match search_through_modules { - DontSearchThroughModules => { - match search_module.kind { - NormalModuleKind => { - // We stop the search here. - debug!("(resolving item in lexical \ - scope) unresolved module: not \ - searching through module \ - parents"); - return Failed; - } - ExternModuleKind | - TraitModuleKind | - AnonymousModuleKind => { - search_module = parent_module_node; - } - } - } - SearchThroughModules => { - search_module = parent_module_node; - } - } - } - BlockParentLink(parent_module_node, _) => { - search_module = parent_module_node; - } - } - - // Resolve the name in the parent module. - match self.resolve_name_in_module(search_module, - name, - namespace, - SearchItemsAndAllImports) { - Failed => { - // Continue up the search chain. - } - Indeterminate => { - // We couldn't see through the higher scope because of an - // unresolved import higher up. Bail. - - debug!("(resolving item in lexical scope) indeterminate \ - higher scope; bailing"); - return Indeterminate; - } - Success(target) => { - // We found the module. - return Success(copy target); - } - } - } - } - - /** Resolves a module name in the current lexical scope. */ - fn resolve_module_in_lexical_scope(@mut self, - module_: @mut Module, - name: ident) - -> ResolveResult<@mut Module> { - // If this module is an anonymous module, resolve the item in the - // lexical scope. Otherwise, resolve the item from the crate root. - let resolve_result = self.resolve_item_in_lexical_scope( - module_, name, TypeNS, DontSearchThroughModules); - match resolve_result { - Success(target) => { - let bindings = &mut *target.bindings; - match bindings.type_def { - Some(ref type_def) => { - match (*type_def).module_def { - None => { - error!("!!! (resolving module in lexical \ - scope) module wasn't actually a \ - module!"); - return Failed; - } - Some(module_def) => { - return Success(module_def); - } - } - } - None => { - error!("!!! (resolving module in lexical scope) module - wasn't actually a module!"); - return Failed; - } - } - } - Indeterminate => { - debug!("(resolving module in lexical scope) indeterminate; \ - bailing"); - return Indeterminate; - } - Failed => { - debug!("(resolving module in lexical scope) failed to \ - resolve"); - return Failed; - } - } - } - - /** - * Returns the nearest normal module parent of the given module. - */ - fn get_nearest_normal_module_parent(@mut self, module_: @mut Module) - -> Option<@mut Module> { - let mut module_ = module_; - loop { - match module_.parent_link { - NoParentLink => return None, - ModuleParentLink(new_module, _) | - BlockParentLink(new_module, _) => { - match new_module.kind { - NormalModuleKind => return Some(new_module), - ExternModuleKind | - TraitModuleKind | - AnonymousModuleKind => module_ = new_module, - } - } - } - } - } - - /** - * Returns the nearest normal module parent of the given module, or the - * module itself if it is a normal module. - */ - fn get_nearest_normal_module_parent_or_self(@mut self, - module_: @mut Module) - -> @mut Module { - match module_.kind { - NormalModuleKind => return module_, - ExternModuleKind | TraitModuleKind | AnonymousModuleKind => { - match self.get_nearest_normal_module_parent(module_) { - None => module_, - Some(new_module) => new_module - } - } - } - } - - /** - * Resolves a "module prefix". A module prefix is one of (a) `self::`; - * (b) some chain of `super::`. - */ - fn resolve_module_prefix(@mut self, - module_: @mut Module, - module_path: &[ident]) - -> ResolveResult { - let interner = self.session.parse_sess.interner; - - // Start at the current module if we see `self` or `super`, or at the - // top of the crate otherwise. - let mut containing_module; - let mut i; - if *interner.get(module_path[0]) == ~"self" { - containing_module = - self.get_nearest_normal_module_parent_or_self(module_); - i = 1; - } else if *interner.get(module_path[0]) == ~"super" { - containing_module = - self.get_nearest_normal_module_parent_or_self(module_); - i = 0; // We'll handle `super` below. - } else { - return Success(NoPrefixFound); - } - - // Now loop through all the `super`s we find. - while i < module_path.len() && - *interner.get(module_path[i]) == ~"super" { - debug!("(resolving module prefix) resolving `super` at %s", - self.module_to_str(containing_module)); - match self.get_nearest_normal_module_parent(containing_module) { - None => return Failed, - Some(new_module) => { - containing_module = new_module; - i += 1; - } - } - } - - debug!("(resolving module prefix) finished resolving prefix at %s", - self.module_to_str(containing_module)); - - return Success(PrefixFound(containing_module, i)); - } - - /// Attempts to resolve the supplied name in the given module for the - /// given namespace. If successful, returns the target corresponding to - /// the name. - fn resolve_name_in_module(@mut self, - module_: @mut Module, - name: ident, - namespace: Namespace, - name_search_type: NameSearchType) - -> ResolveResult { - debug!("(resolving name in module) resolving `%s` in `%s`", - *self.session.str_of(name), - self.module_to_str(module_)); - - // First, check the direct children of the module. - match module_.children.find(&name) { - Some(name_bindings) - if name_bindings.defined_in_namespace(namespace) => { - debug!("(resolving name in module) found node as child"); - return Success(Target(module_, *name_bindings)); - } - Some(_) | None => { - // Continue. - } - } - - // Next, check the module's imports if necessary. - - // If this is a search of all imports, we should be done with glob - // resolution at this point. - if name_search_type == SearchItemsAndAllImports { - assert_eq!(module_.glob_count, 0); - } - - // Check the list of resolved imports. - match module_.import_resolutions.find(&name) { - Some(import_resolution) => { - if import_resolution.privacy == Public && - import_resolution.outstanding_references != 0 { - debug!("(resolving name in module) import \ - unresolved; bailing out"); - return Indeterminate; - } - - match import_resolution.target_for_namespace(namespace) { - None => { - debug!("(resolving name in module) name found, \ - but not in namespace %?", - namespace); - } - Some(target) - if name_search_type == - SearchItemsAndAllImports || - import_resolution.privacy == Public => { - debug!("(resolving name in module) resolved to \ - import"); - import_resolution.state.used = true; - return Success(copy target); - } - Some(_) => { - debug!("(resolving name in module) name found, \ - but not public"); - } - } - } - None => {} // Continue. - } - - // Finally, search through external children. - if namespace == TypeNS { - match module_.external_module_children.find(&name) { - None => {} - Some(module) => { - let name_bindings = - @mut Resolver::create_name_bindings_from_module( - *module); - return Success(Target(module_, name_bindings)); - } - } - } - - // We're out of luck. - debug!("(resolving name in module) failed to resolve %s", - *self.session.str_of(name)); - return Failed; - } - - fn report_unresolved_imports(@mut self, module_: @mut Module) { - let index = module_.resolved_import_count; - let imports: &mut ~[@ImportDirective] = &mut *module_.imports; - let import_count = imports.len(); - if index != import_count { - let sn = self.session.codemap.span_to_snippet(imports[index].span); - if str::contains(sn, "::") { - self.session.span_err(imports[index].span, ~"unresolved import"); - } else { - let err = fmt!("unresolved import (maybe you meant `%s::*`?)", - sn.slice(0, sn.len() - 1)); // -1 to adjust for semicolon - self.session.span_err(imports[index].span, err); - } - } - - // Descend into children and anonymous children. - for module_.children.each_value |&child_node| { - match child_node.get_module_if_available() { - None => { - // Continue. - } - Some(child_module) => { - self.report_unresolved_imports(child_module); - } - } - } - - for module_.anonymous_children.each_value |&module_| { - self.report_unresolved_imports(module_); - } - } - - // Export recording - // - // This pass simply determines what all "export" keywords refer to and - // writes the results into the export map. - // - // FIXME #4953 This pass will be removed once exports change to per-item. - // Then this operation can simply be performed as part of item (or import) - // processing. - - fn record_exports(@mut self) { - let root_module = self.graph_root.get_module(); - self.record_exports_for_module_subtree(root_module); - } - - fn record_exports_for_module_subtree(@mut self, module_: @mut Module) { - // If this isn't a local crate, then bail out. We don't need to record - // exports for nonlocal crates. - - match module_.def_id { - Some(def_id) if def_id.crate == local_crate => { - // OK. Continue. - debug!("(recording exports for module subtree) recording \ - exports for local module"); - } - None => { - // Record exports for the root module. - debug!("(recording exports for module subtree) recording \ - exports for root module"); - } - Some(_) => { - // Bail out. - debug!("(recording exports for module subtree) not recording \ - exports for `%s`", - self.module_to_str(module_)); - return; - } - } - - self.record_exports_for_module(module_); - - for module_.children.each_value |&child_name_bindings| { - match child_name_bindings.get_module_if_available() { - None => { - // Nothing to do. - } - Some(child_module) => { - self.record_exports_for_module_subtree(child_module); - } - } - } - - for module_.anonymous_children.each_value |&child_module| { - self.record_exports_for_module_subtree(child_module); - } - } - - fn record_exports_for_module(@mut self, module_: @mut Module) { - let mut exports2 = ~[]; - - self.add_exports_for_module(&mut exports2, module_); - match /*bad*/copy module_.def_id { - Some(def_id) => { - self.export_map2.insert(def_id.node, exports2); - debug!("(computing exports) writing exports for %d (some)", - def_id.node); - } - None => {} - } - } - - fn add_exports_of_namebindings(@mut self, - exports2: &mut ~[Export2], - ident: ident, - namebindings: @mut NameBindings, - ns: Namespace, - reexport: bool) { - match (namebindings.def_for_namespace(ns), - namebindings.privacy_for_namespace(ns)) { - (Some(d), Some(Public)) => { - debug!("(computing exports) YES: %s '%s' => %?", - if reexport { ~"reexport" } else { ~"export"}, - *self.session.str_of(ident), - def_id_of_def(d)); - exports2.push(Export2 { - reexport: reexport, - name: self.session.str_of(ident), - def_id: def_id_of_def(d) - }); - } - (Some(_), Some(privacy)) => { - debug!("(computing reexports) NO: privacy %?", privacy); - } - (d_opt, p_opt) => { - debug!("(computing reexports) NO: %?, %?", d_opt, p_opt); - } - } - } - - fn add_exports_for_module(@mut self, - exports2: &mut ~[Export2], - module_: @mut Module) { - for module_.children.each |ident, namebindings| { - debug!("(computing exports) maybe export '%s'", - *self.session.str_of(*ident)); - self.add_exports_of_namebindings(&mut *exports2, - *ident, - *namebindings, - TypeNS, - false); - self.add_exports_of_namebindings(&mut *exports2, - *ident, - *namebindings, - ValueNS, - false); - } - - for module_.import_resolutions.each |ident, importresolution| { - if importresolution.privacy != Public { - debug!("(computing exports) not reexporting private `%s`", - *self.session.str_of(*ident)); - loop; - } - for [ TypeNS, ValueNS ].each |ns| { - match importresolution.target_for_namespace(*ns) { - Some(target) => { - debug!("(computing exports) maybe reexport '%s'", - *self.session.str_of(*ident)); - self.add_exports_of_namebindings(&mut *exports2, - *ident, - target.bindings, - *ns, - true) - } - _ => () - } - } - } - } - - // AST resolution - // - // We maintain a list of value ribs and type ribs. - // - // Simultaneously, we keep track of the current position in the module - // graph in the `current_module` pointer. When we go to resolve a name in - // the value or type namespaces, we first look through all the ribs and - // then query the module graph. When we resolve a name in the module - // namespace, we can skip all the ribs (since nested modules are not - // allowed within blocks in Rust) and jump straight to the current module - // graph node. - // - // Named implementations are handled separately. When we find a method - // call, we consult the module node to find all of the implementations in - // scope. This information is lazily cached in the module node. We then - // generate a fake "implementation scope" containing all the - // implementations thus found, for compatibility with old resolve pass. - - fn with_scope(@mut self, name: Option, f: &fn()) { - let orig_module = self.current_module; - - // Move down in the graph. - match name { - None => { - // Nothing to do. - } - Some(name) => { - match orig_module.children.find(&name) { - None => { - debug!("!!! (with scope) didn't find `%s` in `%s`", - *self.session.str_of(name), - self.module_to_str(orig_module)); - } - Some(name_bindings) => { - match (*name_bindings).get_module_if_available() { - None => { - debug!("!!! (with scope) didn't find module \ - for `%s` in `%s`", - *self.session.str_of(name), - self.module_to_str(orig_module)); - } - Some(module_) => { - self.current_module = module_; - } - } - } - } - } - } - - f(); - - self.current_module = orig_module; - } - - // Wraps the given definition in the appropriate number of `def_upvar` - // wrappers. - - fn upvarify(@mut self, - ribs: &mut ~[@Rib], - rib_index: uint, - def_like: def_like, - span: span, - allow_capturing_self: AllowCapturingSelfFlag) - -> Option { - let mut def; - let is_ty_param; - - match def_like { - dl_def(d @ def_local(*)) | dl_def(d @ def_upvar(*)) | - dl_def(d @ def_arg(*)) | dl_def(d @ def_binding(*)) => { - def = d; - is_ty_param = false; - } - dl_def(d @ def_ty_param(*)) => { - def = d; - is_ty_param = true; - } - dl_def(d @ def_self(*)) - if allow_capturing_self == DontAllowCapturingSelf => { - def = d; - is_ty_param = false; - } - _ => { - return Some(def_like); - } - } - - let mut rib_index = rib_index + 1; - while rib_index < ribs.len() { - match ribs[rib_index].kind { - NormalRibKind => { - // Nothing to do. Continue. - } - FunctionRibKind(function_id, body_id) => { - if !is_ty_param { - def = def_upvar(def_id_of_def(def).node, - @def, - function_id, - body_id); - } - } - MethodRibKind(item_id, _) => { - // If the def is a ty param, and came from the parent - // item, it's ok - match def { - def_ty_param(did, _) - if self.def_map.find(&did.node).map_consume(|x| *x) - == Some(def_typaram_binder(item_id)) => { - // ok - } - _ => { - if !is_ty_param { - // This was an attempt to access an upvar inside a - // named function item. This is not allowed, so we - // report an error. - - self.session.span_err( - span, - ~"attempted dynamic environment-capture"); - } else { - // This was an attempt to use a type parameter outside - // its scope. - - self.session.span_err(span, - ~"attempt to use a type \ - argument out of scope"); - } - - return None; - } - } - } - OpaqueFunctionRibKind => { - if !is_ty_param { - // This was an attempt to access an upvar inside a - // named function item. This is not allowed, so we - // report an error. - - self.session.span_err( - span, - ~"attempted dynamic environment-capture"); - } else { - // This was an attempt to use a type parameter outside - // its scope. - - self.session.span_err(span, - ~"attempt to use a type \ - argument out of scope"); - } - - return None; - } - ConstantItemRibKind => { - // Still doesn't deal with upvars - self.session.span_err(span, - ~"attempt to use a non-constant \ - value in a constant"); - - } - } - - rib_index += 1; - } - - return Some(dl_def(def)); - } - - fn search_ribs(@mut self, - ribs: &mut ~[@Rib], - name: ident, - span: span, - allow_capturing_self: AllowCapturingSelfFlag) - -> Option { - // FIXME #4950: This should not use a while loop. - // FIXME #4950: Try caching? - - let mut i = ribs.len(); - while i != 0 { - i -= 1; - match ribs[i].bindings.find(&name) { - Some(&def_like) => { - return self.upvarify(ribs, i, def_like, span, - allow_capturing_self); - } - None => { - // Continue. - } - } - } - - return None; - } - - fn resolve_crate(@mut self) { - debug!("(resolving crate) starting"); - - visit_crate(self.crate, (), mk_vt(@Visitor { - visit_item: |item, _context, visitor| - self.resolve_item(item, visitor), - visit_arm: |arm, _context, visitor| - self.resolve_arm(arm, visitor), - visit_block: |block, _context, visitor| - self.resolve_block(block, visitor), - visit_expr: |expr, _context, visitor| - self.resolve_expr(expr, visitor), - visit_local: |local, _context, visitor| - self.resolve_local(local, visitor), - visit_ty: |ty, _context, visitor| - self.resolve_type(ty, visitor), - .. *default_visitor() - })); - } - - fn resolve_item(@mut self, item: @item, visitor: ResolveVisitor) { - debug!("(resolving item) resolving %s", - *self.session.str_of(item.ident)); - - // Items with the !resolve_unexported attribute are X-ray contexts. - // This is used to allow the test runner to run unexported tests. - let orig_xray_flag = self.xray_context; - if contains_name(attr_metas(item.attrs), - ~"!resolve_unexported") { - self.xray_context = Xray; - } - - match item.node { - - // enum item: resolve all the variants' discrs, - // then resolve the ty params - item_enum(ref enum_def, ref generics) => { - for (*enum_def).variants.each() |variant| { - for variant.node.disr_expr.each |dis_expr| { - // resolve the discriminator expr - // as a constant - self.with_constant_rib(|| { - self.resolve_expr(*dis_expr, visitor); - }); - } - } - - // n.b. the discr expr gets visted twice. - // but maybe it's okay since the first time will signal an - // error if there is one? -- tjc - do self.with_type_parameter_rib( - HasTypeParameters( - generics, item.id, 0, NormalRibKind)) { - visit_item(item, (), visitor); - } - } - - item_ty(_, ref generics) => { - do self.with_type_parameter_rib - (HasTypeParameters(generics, item.id, 0, - NormalRibKind)) - || { - - visit_item(item, (), visitor); - } - } - - item_impl(ref generics, - implemented_traits, - self_type, - ref methods) => { - self.resolve_implementation(item.id, - generics, - implemented_traits, - self_type, - *methods, - visitor); - } - - item_trait(ref generics, ref traits, ref methods) => { - // Create a new rib for the self type. - let self_type_rib = @Rib(NormalRibKind); - self.type_ribs.push(self_type_rib); - self_type_rib.bindings.insert(self.type_self_ident, - dl_def(def_self_ty(item.id))); - - // Create a new rib for the trait-wide type parameters. - do self.with_type_parameter_rib - (HasTypeParameters(generics, item.id, 0, - NormalRibKind)) { - - self.resolve_type_parameters(&generics.ty_params, - visitor); - - // Resolve derived traits. - for traits.each |trt| { - match self.resolve_path(trt.path, TypeNS, true, - visitor) { - None => - self.session.span_err(trt.path.span, - ~"attempt to derive a \ - nonexistent trait"), - Some(def) => { - // Write a mapping from the trait ID to the - // definition of the trait into the definition - // map. - - debug!("(resolving trait) found trait def: \ - %?", def); - - self.record_def(trt.ref_id, def); - } - } - } - - for (*methods).each |method| { - // Create a new rib for the method-specific type - // parameters. - // - // FIXME #4951: Do we need a node ID here? - - match *method { - required(ref ty_m) => { - do self.with_type_parameter_rib - (HasTypeParameters(&ty_m.generics, - item.id, - generics.ty_params.len(), - MethodRibKind(item.id, Required))) { - - // Resolve the method-specific type - // parameters. - self.resolve_type_parameters( - &ty_m.generics.ty_params, - visitor); - - for ty_m.decl.inputs.each |argument| { - self.resolve_type(argument.ty, visitor); - } - - self.resolve_type(ty_m.decl.output, visitor); - } - } - provided(m) => { - self.resolve_method(MethodRibKind(item.id, - Provided(m.id)), - m, - generics.ty_params.len(), - visitor) - } - } - } - } - - self.type_ribs.pop(); - } - - item_struct(ref struct_def, ref generics) => { - self.resolve_struct(item.id, - generics, - struct_def.fields, - visitor); - } - - item_mod(ref module_) => { - do self.with_scope(Some(item.ident)) { - self.resolve_module(module_, item.span, item.ident, - item.id, visitor); - } - } - - item_foreign_mod(ref foreign_module) => { - do self.with_scope(Some(item.ident)) { - for foreign_module.items.each |foreign_item| { - match foreign_item.node { - foreign_item_fn(_, _, ref generics) => { - self.with_type_parameter_rib( - HasTypeParameters( - generics, foreign_item.id, 0, - NormalRibKind), - || visit_foreign_item(*foreign_item, (), - visitor)); - } - foreign_item_const(_) => { - visit_foreign_item(*foreign_item, (), - visitor); - } - } - } - } - } - - item_fn(ref fn_decl, _, _, ref generics, ref block) => { - // If this is the main function, we must record it in the - // session. - - // FIXME #4404 android JNI hacks - if !*self.session.building_library || - self.session.targ_cfg.os == session::os_android { - - if self.attr_main_fn.is_none() && - item.ident == special_idents::main { - - self.main_fns.push(Some((item.id, item.span))); - } - - if attrs_contains_name(item.attrs, ~"main") { - if self.attr_main_fn.is_none() { - self.attr_main_fn = Some((item.id, item.span)); - } else { - self.session.span_err( - item.span, - ~"multiple 'main' functions"); - } - } - - if attrs_contains_name(item.attrs, ~"start") { - if self.start_fn.is_none() { - self.start_fn = Some((item.id, item.span)); - } else { - self.session.span_err( - item.span, - ~"multiple 'start' functions"); - } - } - } - - self.resolve_function(OpaqueFunctionRibKind, - Some(fn_decl), - HasTypeParameters - (generics, - item.id, - 0, - OpaqueFunctionRibKind), - block, - NoSelfBinding, - visitor); - } - - item_const(*) => { - self.with_constant_rib(|| { - visit_item(item, (), visitor); - }); - } - - item_mac(*) => { - fail!("item macros unimplemented") - } - } - - self.xray_context = orig_xray_flag; - } - - fn with_type_parameter_rib(@mut self, - type_parameters: TypeParameters, - f: &fn()) { - match type_parameters { - HasTypeParameters(generics, node_id, initial_index, - rib_kind) => { - - let function_type_rib = @Rib(rib_kind); - self.type_ribs.push(function_type_rib); - - for generics.ty_params.eachi |index, type_parameter| { - let name = type_parameter.ident; - debug!("with_type_parameter_rib: %d %d", node_id, - type_parameter.id); - let def_like = dl_def(def_ty_param - (local_def(type_parameter.id), - index + initial_index)); - // Associate this type parameter with - // the item that bound it - self.record_def(type_parameter.id, - def_typaram_binder(node_id)); - function_type_rib.bindings.insert(name, def_like); - } - } - - NoTypeParameters => { - // Nothing to do. - } - } - - f(); - - match type_parameters { - HasTypeParameters(*) => { - self.type_ribs.pop(); - } - - NoTypeParameters => { - // Nothing to do. - } - } - } - - fn with_label_rib(@mut self, f: &fn()) { - self.label_ribs.push(@Rib(NormalRibKind)); - f(); - self.label_ribs.pop(); - } - - fn with_constant_rib(@mut self, f: &fn()) { - self.value_ribs.push(@Rib(ConstantItemRibKind)); - f(); - self.value_ribs.pop(); - } - - fn resolve_function(@mut self, - rib_kind: RibKind, - optional_declaration: Option<&fn_decl>, - type_parameters: TypeParameters, - block: &blk, - self_binding: SelfBinding, - visitor: ResolveVisitor) { - // Create a value rib for the function. - let function_value_rib = @Rib(rib_kind); - self.value_ribs.push(function_value_rib); - - // Create a label rib for the function. - let function_label_rib = @Rib(rib_kind); - self.label_ribs.push(function_label_rib); - - // If this function has type parameters, add them now. - do self.with_type_parameter_rib(type_parameters) { - // Resolve the type parameters. - match type_parameters { - NoTypeParameters => { - // Continue. - } - HasTypeParameters(ref generics, _, _, _) => { - self.resolve_type_parameters(&generics.ty_params, - visitor); - } - } - - // Add self to the rib, if necessary. - match self_binding { - NoSelfBinding => { - // Nothing to do. - } - HasSelfBinding(self_node_id, is_implicit) => { - let def_like = dl_def(def_self(self_node_id, - is_implicit)); - *function_value_rib.self_binding = Some(def_like); - } - } - - // Add each argument to the rib. - match optional_declaration { - None => { - // Nothing to do. - } - Some(declaration) => { - for declaration.inputs.each |argument| { - let binding_mode = ArgumentIrrefutableMode; - let mutability = - if argument.is_mutbl {Mutable} else {Immutable}; - self.resolve_pattern(argument.pat, - binding_mode, - mutability, - None, - visitor); - - self.resolve_type(argument.ty, visitor); - - debug!("(resolving function) recorded argument"); - } - - self.resolve_type(declaration.output, visitor); - } - } - - // Resolve the function body. - self.resolve_block(block, visitor); - - debug!("(resolving function) leaving function"); - } - - self.label_ribs.pop(); - self.value_ribs.pop(); - } - - fn resolve_type_parameters(@mut self, - type_parameters: &OptVec, - visitor: ResolveVisitor) { - for type_parameters.each |type_parameter| { - for type_parameter.bounds.each |&bound| { - match bound { - TraitTyParamBound(tref) => { - self.resolve_trait_reference(tref, visitor) - } - RegionTyParamBound => {} - } - } - } - } - - fn resolve_trait_reference(@mut self, - trait_reference: &trait_ref, - visitor: ResolveVisitor) { - match self.resolve_path(trait_reference.path, TypeNS, true, visitor) { - None => { - self.session.span_err(trait_reference.path.span, - ~"attempt to implement an \ - unknown trait"); - } - Some(def) => { - self.record_def(trait_reference.ref_id, def); - } - } - } - - fn resolve_struct(@mut self, - id: node_id, - generics: &Generics, - fields: &[@struct_field], - visitor: ResolveVisitor) { - // If applicable, create a rib for the type parameters. - do self.with_type_parameter_rib(HasTypeParameters - (generics, id, 0, - OpaqueFunctionRibKind)) { - - // Resolve the type parameters. - self.resolve_type_parameters(&generics.ty_params, visitor); - - // Resolve fields. - for fields.each |field| { - self.resolve_type(field.node.ty, visitor); - } - } - } - - // Does this really need to take a RibKind or is it always going - // to be NormalRibKind? - fn resolve_method(@mut self, - rib_kind: RibKind, - method: @method, - outer_type_parameter_count: uint, - visitor: ResolveVisitor) { - let method_generics = &method.generics; - let type_parameters = - HasTypeParameters(method_generics, - method.id, - outer_type_parameter_count, - rib_kind); - // we only have self ty if it is a non static method - let self_binding = match method.explicit_self.node { - sty_static => { NoSelfBinding } - _ => { HasSelfBinding(method.self_id, false) } - }; - - self.resolve_function(rib_kind, - Some(&method.decl), - type_parameters, - &method.body, - self_binding, - visitor); - } - - fn resolve_implementation(@mut self, - id: node_id, - generics: &Generics, - opt_trait_reference: Option<@trait_ref>, - self_type: @Ty, - methods: &[@method], - visitor: ResolveVisitor) { - // If applicable, create a rib for the type parameters. - let outer_type_parameter_count = generics.ty_params.len(); - do self.with_type_parameter_rib(HasTypeParameters - (generics, id, 0, - NormalRibKind)) { - // Resolve the type parameters. - self.resolve_type_parameters(&generics.ty_params, - visitor); - - // Resolve the trait reference, if necessary. - let original_trait_refs; - match opt_trait_reference { - Some(trait_reference) => { - self.resolve_trait_reference(trait_reference, visitor); - - // Record the current set of trait references. - let mut new_trait_refs = ~[]; - for self.def_map.find(&trait_reference.ref_id).each |&def| { - new_trait_refs.push(def_id_of_def(*def)); - } - original_trait_refs = Some(util::replace( - &mut self.current_trait_refs, - Some(new_trait_refs))); - } - None => { - original_trait_refs = None; - } - } - - // Resolve the self type. - self.resolve_type(self_type, visitor); - - for methods.each |method| { - // We also need a new scope for the method-specific - // type parameters. - self.resolve_method(MethodRibKind( - id, - Provided(method.id)), - *method, - outer_type_parameter_count, - visitor); -/* - let borrowed_type_parameters = &method.tps; - self.resolve_function(MethodRibKind( - id, - Provided(method.id)), - Some(@method.decl), - HasTypeParameters - (borrowed_type_parameters, - method.id, - outer_type_parameter_count, - NormalRibKind), - method.body, - HasSelfBinding(method.self_id), - visitor); -*/ - } - - // Restore the original trait references. - match original_trait_refs { - Some(r) => { self.current_trait_refs = r; } - None => () - } - } - } - - fn resolve_module(@mut self, - module_: &_mod, - span: span, - _name: ident, - id: node_id, - visitor: ResolveVisitor) { - // Write the implementations in scope into the module metadata. - debug!("(resolving module) resolving module ID %d", id); - visit_mod(module_, span, id, (), visitor); - } - - fn resolve_local(@mut self, local: @local, visitor: ResolveVisitor) { - let mutability = if local.node.is_mutbl {Mutable} else {Immutable}; - - // Resolve the type. - self.resolve_type(local.node.ty, visitor); - - // Resolve the initializer, if necessary. - match local.node.init { - None => { - // Nothing to do. - } - Some(initializer) => { - self.resolve_expr(initializer, visitor); - } - } - - // Resolve the pattern. - self.resolve_pattern(local.node.pat, LocalIrrefutableMode, mutability, - None, visitor); - } - - fn binding_mode_map(@mut self, pat: @pat) -> BindingMap { - let mut result = HashMap::new(); - do pat_bindings(self.def_map, pat) |binding_mode, _id, sp, path| { - let ident = path_to_ident(path); - result.insert(ident, - binding_info {span: sp, - binding_mode: binding_mode}); - } - return result; - } - - fn check_consistent_bindings(@mut self, arm: &arm) { - if arm.pats.len() == 0 { return; } - let map_0 = self.binding_mode_map(arm.pats[0]); - for arm.pats.eachi() |i, p| { - let map_i = self.binding_mode_map(*p); - - for map_0.each |&key, &binding_0| { - match map_i.find(&key) { - None => { - self.session.span_err( - p.span, - fmt!("variable `%s` from pattern #1 is \ - not bound in pattern #%u", - *self.session.str_of(key), i + 1)); - } - Some(binding_i) => { - if binding_0.binding_mode != binding_i.binding_mode { - self.session.span_err( - binding_i.span, - fmt!("variable `%s` is bound with different \ - mode in pattern #%u than in pattern #1", - *self.session.str_of(key), i + 1)); - } - } - } - } - - for map_i.each |&key, &binding| { - if !map_0.contains_key(&key) { - self.session.span_err( - binding.span, - fmt!("variable `%s` from pattern #%u is \ - not bound in pattern #1", - *self.session.str_of(key), i + 1)); - } - } - } - } - - fn resolve_arm(@mut self, arm: &arm, visitor: ResolveVisitor) { - self.value_ribs.push(@Rib(NormalRibKind)); - - let bindings_list = @mut HashMap::new(); - for arm.pats.each |pattern| { - self.resolve_pattern(*pattern, RefutableMode, Immutable, - Some(bindings_list), visitor); - } - - // This has to happen *after* we determine which - // pat_idents are variants - self.check_consistent_bindings(arm); - - visit_expr_opt(arm.guard, (), visitor); - self.resolve_block(&arm.body, visitor); - - self.value_ribs.pop(); - } - - fn resolve_block(@mut self, block: &blk, visitor: ResolveVisitor) { - debug!("(resolving block) entering block"); - self.value_ribs.push(@Rib(NormalRibKind)); - - // Move down in the graph, if there's an anonymous module rooted here. - let orig_module = self.current_module; - match self.current_module.anonymous_children.find(&block.node.id) { - None => { /* Nothing to do. */ } - Some(&anonymous_module) => { - debug!("(resolving block) found anonymous module, moving \ - down"); - self.current_module = anonymous_module; - } - } - - // Descend into the block. - visit_block(block, (), visitor); - - // Move back up. - self.current_module = orig_module; - - self.value_ribs.pop(); - debug!("(resolving block) leaving block"); - } - - fn resolve_type(@mut self, ty: @Ty, visitor: ResolveVisitor) { - match ty.node { - // Like path expressions, the interpretation of path types depends - // on whether the path has multiple elements in it or not. - - ty_path(path, path_id) => { - // This is a path in the type namespace. Walk through scopes - // scopes looking for it. - let mut result_def = None; - - // First, check to see whether the name is a primitive type. - if path.idents.len() == 1 { - let name = *path.idents.last(); - - match self.primitive_type_table - .primitive_types - .find(&name) { - - Some(&primitive_type) => { - result_def = - Some(def_prim_ty(primitive_type)); - } - None => { - // Continue. - } - } - } - - match result_def { - None => { - match self.resolve_path(path, TypeNS, true, visitor) { - Some(def) => { - debug!("(resolving type) resolved `%s` to \ - type %?", - *self.session.str_of( - *path.idents.last()), - def); - result_def = Some(def); - } - None => { - result_def = None; - } - } - } - Some(_) => { - // Continue. - } - } - - match result_def { - Some(def) => { - // Write the result into the def map. - debug!("(resolving type) writing resolution for `%s` \ - (id %d)", - self.idents_to_str(path.idents), - path_id); - self.record_def(path_id, def); - } - None => { - self.session.span_err - (ty.span, fmt!("use of undeclared type name `%s`", - self.idents_to_str(path.idents))); - } - } - } - - _ => { - // Just resolve embedded types. - visit_ty(ty, (), visitor); - } - } - } - - fn resolve_pattern(@mut self, - pattern: @pat, - mode: PatternBindingMode, - mutability: Mutability, - // Maps idents to the node ID for the (outermost) - // pattern that binds them - bindings_list: Option<@mut HashMap>, - visitor: ResolveVisitor) { - let pat_id = pattern.id; - do walk_pat(pattern) |pattern| { - match pattern.node { - pat_ident(binding_mode, path, _) - if !path.global && path.idents.len() == 1 => { - - // The meaning of pat_ident with no type parameters - // depends on whether an enum variant or unit-like struct - // with that name is in scope. The probing lookup has to - // be careful not to emit spurious errors. Only matching - // patterns (match) can match nullary variants or - // unit-like structs. For binding patterns (let), matching - // such a value is simply disallowed (since it's rarely - // what you want). - - let ident = path.idents[0]; - - match self.resolve_bare_identifier_pattern(ident) { - FoundStructOrEnumVariant(def) - if mode == RefutableMode => { - debug!("(resolving pattern) resolving `%s` to \ - struct or enum variant", - *self.session.str_of(ident)); - - self.enforce_default_binding_mode( - pattern, - binding_mode, - "an enum variant"); - self.record_def(pattern.id, def); - } - FoundStructOrEnumVariant(_) => { - self.session.span_err(pattern.span, - fmt!("declaration of `%s` \ - shadows an enum \ - variant or unit-like \ - struct in scope", - *self.session - .str_of(ident))); - } - FoundConst(def) if mode == RefutableMode => { - debug!("(resolving pattern) resolving `%s` to \ - constant", - *self.session.str_of(ident)); - - self.enforce_default_binding_mode( - pattern, - binding_mode, - "a constant"); - self.record_def(pattern.id, def); - } - FoundConst(_) => { - self.session.span_err(pattern.span, - ~"only refutable patterns \ - allowed here"); - } - BareIdentifierPatternUnresolved => { - debug!("(resolving pattern) binding `%s`", - *self.session.str_of(ident)); - - let is_mutable = mutability == Mutable; - - let def = match mode { - RefutableMode => { - // For pattern arms, we must use - // `def_binding` definitions. - - def_binding(pattern.id, binding_mode) - } - LocalIrrefutableMode => { - // But for locals, we use `def_local`. - def_local(pattern.id, is_mutable) - } - ArgumentIrrefutableMode => { - // And for function arguments, `def_arg`. - def_arg(pattern.id, is_mutable) - } - }; - - // Record the definition so that later passes - // will be able to distinguish variants from - // locals in patterns. - - self.record_def(pattern.id, def); - - // Add the binding to the local ribs, if it - // doesn't already exist in the bindings list. (We - // must not add it if it's in the bindings list - // because that breaks the assumptions later - // passes make about or-patterns.) - - match bindings_list { - Some(bindings_list) - if !bindings_list.contains_key(&ident) => { - let this = &mut *self; - let last_rib = this.value_ribs[ - this.value_ribs.len() - 1]; - last_rib.bindings.insert(ident, - dl_def(def)); - bindings_list.insert(ident, pat_id); - } - Some(b) => { - if b.find(&ident) == Some(&pat_id) { - // Then this is a duplicate variable - // in the same disjunct, which is an - // error - self.session.span_err(pattern.span, - fmt!("Identifier %s is bound more \ - than once in the same pattern", - path_to_str(path, self.session - .intr()))); - } - // Not bound in the same pattern: do nothing - } - None => { - let this = &mut *self; - let last_rib = this.value_ribs[ - this.value_ribs.len() - 1]; - last_rib.bindings.insert(ident, - dl_def(def)); - } - } - } - } - - // Check the types in the path pattern. - for path.types.each |ty| { - self.resolve_type(*ty, visitor); - } - } - - pat_ident(binding_mode, path, _) => { - // This must be an enum variant, struct, or constant. - match self.resolve_path(path, ValueNS, false, visitor) { - Some(def @ def_variant(*)) | - Some(def @ def_struct(*)) => { - self.record_def(pattern.id, def); - } - Some(def @ def_const(*)) => { - self.enforce_default_binding_mode( - pattern, - binding_mode, - "a constant"); - self.record_def(pattern.id, def); - } - Some(_) => { - self.session.span_err( - path.span, - fmt!("not an enum variant or constant: %s", - *self.session.str_of( - *path.idents.last()))); - } - None => { - self.session.span_err(path.span, - ~"unresolved enum variant"); - } - } - - // Check the types in the path pattern. - for path.types.each |ty| { - self.resolve_type(*ty, visitor); - } - } - - pat_enum(path, _) => { - // This must be an enum variant, struct or const. - match self.resolve_path(path, ValueNS, false, visitor) { - Some(def @ def_fn(*)) | - Some(def @ def_variant(*)) | - Some(def @ def_struct(*)) | - Some(def @ def_const(*)) => { - self.record_def(pattern.id, def); - } - Some(_) => { - self.session.span_err( - path.span, - fmt!("not an enum variant, struct or const: %s", - *self.session.str_of( - *path.idents.last()))); - } - None => { - self.session.span_err(path.span, - ~"unresolved enum variant, \ - struct or const"); - } - } - - // Check the types in the path pattern. - for path.types.each |ty| { - self.resolve_type(*ty, visitor); - } - } - - pat_lit(expr) => { - self.resolve_expr(expr, visitor); - } - - pat_range(first_expr, last_expr) => { - self.resolve_expr(first_expr, visitor); - self.resolve_expr(last_expr, visitor); - } - - pat_struct(path, _, _) => { - let structs: &mut HashSet = &mut self.structs; - match self.resolve_path(path, TypeNS, false, visitor) { - Some(def_ty(class_id)) - if structs.contains(&class_id) => { - let class_def = def_struct(class_id); - self.record_def(pattern.id, class_def); - } - Some(definition @ def_struct(class_id)) - if structs.contains(&class_id) => { - self.record_def(pattern.id, definition); - } - Some(definition @ def_variant(_, variant_id)) - if structs.contains(&variant_id) => { - self.record_def(pattern.id, definition); - } - result => { - debug!("(resolving pattern) didn't find struct \ - def: %?", result); - self.session.span_err( - path.span, - fmt!("`%s` does not name a structure", - self.idents_to_str(path.idents))); - } - } - } - - _ => { - // Nothing to do. - } - } - } - } - - fn resolve_bare_identifier_pattern(@mut self, name: ident) - -> BareIdentifierPatternResolution { - match self.resolve_item_in_lexical_scope(self.current_module, - name, - ValueNS, - SearchThroughModules) { - Success(target) => { - match target.bindings.value_def { - None => { - fail!("resolved name in the value namespace to a \ - set of name bindings with no def?!"); - } - Some(def) => { - match def.def { - def @ def_variant(*) | def @ def_struct(*) => { - return FoundStructOrEnumVariant(def); - } - def @ def_const(*) => { - return FoundConst(def); - } - _ => { - return BareIdentifierPatternUnresolved; - } - } - } - } - } - - Indeterminate => { - fail!("unexpected indeterminate result"); - } - - Failed => { - return BareIdentifierPatternUnresolved; - } - } - } - - /// If `check_ribs` is true, checks the local definitions first; i.e. - /// doesn't skip straight to the containing module. - fn resolve_path(@mut self, - path: @Path, - namespace: Namespace, - check_ribs: bool, - visitor: ResolveVisitor) - -> Option { - // First, resolve the types. - for path.types.each |ty| { - self.resolve_type(*ty, visitor); - } - - if path.global { - return self.resolve_crate_relative_path(path, - self.xray_context, - namespace); - } - - if path.idents.len() > 1 { - return self.resolve_module_relative_path(path, - self.xray_context, - namespace); - } - - return self.resolve_identifier(*path.idents.last(), - namespace, - check_ribs, - path.span); - } - - fn resolve_identifier(@mut self, - identifier: ident, - namespace: Namespace, - check_ribs: bool, - span: span) - -> Option { - if check_ribs { - match self.resolve_identifier_in_local_ribs(identifier, - namespace, - span) { - Some(def) => { - return Some(def); - } - None => { - // Continue. - } - } - } - - return self.resolve_item_by_identifier_in_lexical_scope(identifier, - namespace); - } - - // FIXME #4952: Merge me with resolve_name_in_module? - fn resolve_definition_of_name_in_module(@mut self, - containing_module: @mut Module, - name: ident, - namespace: Namespace, - xray: XrayFlag) - -> NameDefinition { - // First, search children. - match containing_module.children.find(&name) { - Some(child_name_bindings) => { - match (child_name_bindings.def_for_namespace(namespace), - child_name_bindings.privacy_for_namespace(namespace)) { - (Some(def), Some(Public)) => { - // Found it. Stop the search here. - return ChildNameDefinition(def); - } - (Some(def), _) if xray == Xray => { - // Found it. Stop the search here. - return ChildNameDefinition(def); - } - (Some(_), _) | (None, _) => { - // Continue. - } - } - } - None => { - // Continue. - } - } - - // Next, search import resolutions. - match containing_module.import_resolutions.find(&name) { - Some(import_resolution) if import_resolution.privacy == Public || - xray == Xray => { - match (*import_resolution).target_for_namespace(namespace) { - Some(target) => { - match (target.bindings.def_for_namespace(namespace), - target.bindings.privacy_for_namespace( - namespace)) { - (Some(def), Some(Public)) => { - // Found it. - import_resolution.state.used = true; - return ImportNameDefinition(def); - } - (Some(_), _) | (None, _) => { - // This can happen with external impls, due to - // the imperfect way we read the metadata. - } - } - } - None => {} - } - } - Some(_) | None => {} // Continue. - } - - // Finally, search through external children. - if namespace == TypeNS { - match containing_module.external_module_children.find(&name) { - None => {} - Some(module) => { - match module.def_id { - None => {} // Continue. - Some(def_id) => { - return ChildNameDefinition(def_mod(def_id)); - } - } - } - } - } - - return NoNameDefinition; - } - - fn intern_module_part_of_path(@mut self, path: @Path) -> ~[ident] { - let mut module_path_idents = ~[]; - for path.idents.eachi |index, ident| { - if index == path.idents.len() - 1 { - break; - } - - module_path_idents.push(*ident); - } - - return module_path_idents; - } - - fn resolve_module_relative_path(@mut self, - path: @Path, - xray: XrayFlag, - namespace: Namespace) - -> Option { - let module_path_idents = self.intern_module_part_of_path(path); - - let containing_module; - match self.resolve_module_path_for_import(self.current_module, - module_path_idents, - UseLexicalScope, - path.span) { - Failed => { - self.session.span_err(path.span, - fmt!("use of undeclared module `%s`", - self.idents_to_str( - module_path_idents))); - return None; - } - - Indeterminate => { - fail!("indeterminate unexpected"); - } - - Success(resulting_module) => { - containing_module = resulting_module; - } - } - - let name = *path.idents.last(); - match self.resolve_definition_of_name_in_module(containing_module, - name, - namespace, - xray) { - NoNameDefinition => { - // We failed to resolve the name. Report an error. - return None; - } - ChildNameDefinition(def) | ImportNameDefinition(def) => { - return Some(def); - } - } - } - - /// Invariant: This must be called only during main resolution, not during - /// import resolution. - fn resolve_crate_relative_path(@mut self, - path: @Path, - xray: XrayFlag, - namespace: Namespace) - -> Option { - let module_path_idents = self.intern_module_part_of_path(path); - - let root_module = self.graph_root.get_module(); - - let containing_module; - match self.resolve_module_path_from_root(root_module, - module_path_idents, - 0, - path.span, - SearchItemsAndAllImports) { - Failed => { - self.session.span_err(path.span, - fmt!("use of undeclared module `::%s`", - self.idents_to_str( - module_path_idents))); - return None; - } - - Indeterminate => { - fail!("indeterminate unexpected"); - } - - Success(resulting_module) => { - containing_module = resulting_module; - } - } - - let name = *path.idents.last(); - match self.resolve_definition_of_name_in_module(containing_module, - name, - namespace, - xray) { - NoNameDefinition => { - // We failed to resolve the name. Report an error. - return None; - } - ChildNameDefinition(def) | ImportNameDefinition(def) => { - return Some(def); - } - } - } - - fn resolve_identifier_in_local_ribs(@mut self, - ident: ident, - namespace: Namespace, - span: span) - -> Option { - // Check the local set of ribs. - let search_result; - match namespace { - ValueNS => { - search_result = self.search_ribs(&mut self.value_ribs, ident, - span, - DontAllowCapturingSelf); - } - TypeNS => { - search_result = self.search_ribs(&mut self.type_ribs, ident, - span, AllowCapturingSelf); - } - } - - match search_result { - Some(dl_def(def)) => { - debug!("(resolving path in local ribs) resolved `%s` to \ - local: %?", - *self.session.str_of(ident), - def); - return Some(def); - } - Some(dl_field) | Some(dl_impl(_)) | None => { - return None; - } - } - } - - fn resolve_self_value_in_local_ribs(@mut self, span: span) - -> Option { - // FIXME #4950: This should not use a while loop. - let ribs = &mut self.value_ribs; - let mut i = ribs.len(); - while i != 0 { - i -= 1; - match *ribs[i].self_binding { - Some(def_like) => { - match self.upvarify(ribs, - i, - def_like, - span, - DontAllowCapturingSelf) { - Some(dl_def(def)) => return Some(def), - _ => { - self.session.span_bug(span, - ~"self wasn't mapped to a \ - def?!") - } - } - } - None => {} - } - } - - None - } - - fn resolve_item_by_identifier_in_lexical_scope(@mut self, - ident: ident, - namespace: Namespace) - -> Option { - // Check the items. - match self.resolve_item_in_lexical_scope(self.current_module, - ident, - namespace, - DontSearchThroughModules) { - Success(target) => { - match (*target.bindings).def_for_namespace(namespace) { - None => { - // This can happen if we were looking for a type and - // found a module instead. Modules don't have defs. - return None; - } - Some(def) => { - debug!("(resolving item path in lexical scope) \ - resolved `%s` to item", - *self.session.str_of(ident)); - return Some(def); - } - } - } - Indeterminate => { - fail!("unexpected indeterminate result"); - } - Failed => { - return None; - } - } - } - - fn find_best_match_for_name(@mut self, name: &str, max_distance: uint) -> Option<~str> { - let this = &mut *self; - - let mut maybes: ~[~str] = ~[]; - let mut values: ~[uint] = ~[]; - - let mut j = this.value_ribs.len(); - while j != 0 { - j -= 1; - for this.value_ribs[j].bindings.each_key |&k| { - vec::push(&mut maybes, copy *this.session.str_of(k)); - vec::push(&mut values, uint::max_value); - } - } - - let mut smallest = 0; - for maybes.eachi |i, &other| { - - values[i] = str::levdistance(name, other); - - if values[i] <= values[smallest] { - smallest = i; - } - } - - if values.len() > 0 && - values[smallest] != uint::max_value && - values[smallest] < str::len(name) + 2 && - values[smallest] <= max_distance && - maybes[smallest] != name.to_owned() { - - Some(vec::swap_remove(&mut maybes, smallest)) - - } else { - None - } - } - - fn name_exists_in_scope_struct(@mut self, name: &str) -> bool { - let this = &mut *self; - - let mut i = this.type_ribs.len(); - while i != 0 { - i -= 1; - match this.type_ribs[i].kind { - MethodRibKind(node_id, _) => - for this.crate.node.module.items.each |item| { - if item.id == node_id { - match item.node { - item_struct(class_def, _) => { - for class_def.fields.each |field| { - match field.node.kind { - unnamed_field => {}, - named_field(ident, _) => { - if str::eq_slice(*this.session.str_of(ident), - name) { - return true - } - } - } - } - } - _ => {} - } - } - }, - _ => {} - } - } - return false; - } - - fn resolve_expr(@mut self, expr: @expr, visitor: ResolveVisitor) { - // First, record candidate traits for this expression if it could - // result in the invocation of a method call. - - self.record_candidate_traits_for_expr_if_necessary(expr); - - // Next, resolve the node. - match expr.node { - // The interpretation of paths depends on whether the path has - // multiple elements in it or not. - - expr_path(path) => { - // This is a local path in the value namespace. Walk through - // scopes looking for it. - - match self.resolve_path(path, ValueNS, true, visitor) { - Some(def) => { - // Write the result into the def map. - debug!("(resolving expr) resolved `%s`", - self.idents_to_str(path.idents)); - self.record_def(expr.id, def); - } - None => { - let wrong_name = self.idents_to_str( - path.idents); - if self.name_exists_in_scope_struct(wrong_name) { - self.session.span_err(expr.span, - fmt!("unresolved name: `%s`. \ - Did you mean: `self.%s`?", - wrong_name, - wrong_name)); - } - else { - // limit search to 5 to reduce the number - // of stupid suggestions - match self.find_best_match_for_name(wrong_name, 5) { - Some(m) => { - self.session.span_err(expr.span, - fmt!("unresolved name: `%s`. \ - Did you mean: `%s`?", - wrong_name, m)); - } - None => { - self.session.span_err(expr.span, - fmt!("unresolved name: `%s`.", - wrong_name)); - } - } - } - } - } - - visit_expr(expr, (), visitor); - } - - expr_fn_block(ref fn_decl, ref block) => { - self.resolve_function(FunctionRibKind(expr.id, block.node.id), - Some(fn_decl), - NoTypeParameters, - block, - NoSelfBinding, - visitor); - } - - expr_struct(path, _, _) => { - // Resolve the path to the structure it goes to. - let structs: &mut HashSet = &mut self.structs; - match self.resolve_path(path, TypeNS, false, visitor) { - Some(def_ty(class_id)) | Some(def_struct(class_id)) - if structs.contains(&class_id) => { - let class_def = def_struct(class_id); - self.record_def(expr.id, class_def); - } - Some(definition @ def_variant(_, class_id)) - if structs.contains(&class_id) => { - self.record_def(expr.id, definition); - } - _ => { - self.session.span_err( - path.span, - fmt!("`%s` does not name a structure", - self.idents_to_str(path.idents))); - } - } - - visit_expr(expr, (), visitor); - } - - expr_loop(_, Some(label)) => { - do self.with_label_rib { - let this = &mut *self; - let def_like = dl_def(def_label(expr.id)); - let rib = this.label_ribs[this.label_ribs.len() - 1]; - rib.bindings.insert(label, def_like); - - visit_expr(expr, (), visitor); - } - } - - expr_break(Some(label)) | expr_again(Some(label)) => { - match self.search_ribs(&mut self.label_ribs, label, expr.span, - DontAllowCapturingSelf) { - None => - self.session.span_err(expr.span, - fmt!("use of undeclared label \ - `%s`", - *self.session.str_of( - label))), - Some(dl_def(def @ def_label(_))) => { - self.record_def(expr.id, def) - } - Some(_) => { - self.session.span_bug(expr.span, - ~"label wasn't mapped to a \ - label def!") - } - } - } - - expr_self => { - match self.resolve_self_value_in_local_ribs(expr.span) { - None => { - self.session.span_err(expr.span, - ~"`self` is not allowed in \ - this context") - } - Some(def) => self.record_def(expr.id, def), - } - } - - _ => { - visit_expr(expr, (), visitor); - } - } - } - - fn record_candidate_traits_for_expr_if_necessary(@mut self, expr: @expr) { - match expr.node { - expr_field(_, ident, _) => { - let traits = self.search_for_traits_containing_method(ident); - self.trait_map.insert(expr.id, @mut traits); - } - expr_method_call(_, ident, _, _, _) => { - let traits = self.search_for_traits_containing_method(ident); - self.trait_map.insert(expr.id, @mut traits); - } - expr_binary(add, _, _) | expr_assign_op(add, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.add_trait()); - } - expr_binary(subtract, _, _) | expr_assign_op(subtract, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.sub_trait()); - } - expr_binary(mul, _, _) | expr_assign_op(mul, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.mul_trait()); - } - expr_binary(div, _, _) | expr_assign_op(div, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.div_trait()); - } - expr_binary(rem, _, _) | expr_assign_op(rem, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.rem_trait()); - } - expr_binary(bitxor, _, _) | expr_assign_op(bitxor, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.bitxor_trait()); - } - expr_binary(bitand, _, _) | expr_assign_op(bitand, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.bitand_trait()); - } - expr_binary(bitor, _, _) | expr_assign_op(bitor, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.bitor_trait()); - } - expr_binary(shl, _, _) | expr_assign_op(shl, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.shl_trait()); - } - expr_binary(shr, _, _) | expr_assign_op(shr, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.shr_trait()); - } - expr_binary(lt, _, _) | expr_binary(le, _, _) | - expr_binary(ge, _, _) | expr_binary(gt, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.ord_trait()); - } - expr_binary(eq, _, _) | expr_binary(ne, _, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.eq_trait()); - } - expr_unary(neg, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.neg_trait()); - } - expr_unary(not, _) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.not_trait()); - } - expr_index(*) => { - self.add_fixed_trait_for_expr(expr.id, - self.lang_items.index_trait()); - } - _ => { - // Nothing to do. - } - } - } - - fn search_for_traits_containing_method(@mut self, - name: ident) - -> ~[def_id] { - debug!("(searching for traits containing method) looking for '%s'", - *self.session.str_of(name)); - - let mut found_traits = ~[]; - let mut search_module = self.current_module; - loop { - // Look for the current trait. - match /*bad*/copy self.current_trait_refs { - Some(trait_def_ids) => { - for trait_def_ids.each |trait_def_id| { - self.add_trait_info_if_containing_method( - &mut found_traits, *trait_def_id, name); - } - } - None => { - // Nothing to do. - } - } - - // Look for trait children. - for search_module.children.each_value |&child_name_bindings| { - match child_name_bindings.def_for_namespace(TypeNS) { - Some(def) => { - match def { - def_trait(trait_def_id) => { - self.add_trait_info_if_containing_method( - &mut found_traits, trait_def_id, name); - } - _ => { - // Continue. - } - } - } - None => { - // Continue. - } - } - } - - // Look for imports. - for search_module.import_resolutions.each_value - |&import_resolution| { - - match import_resolution.target_for_namespace(TypeNS) { - None => { - // Continue. - } - Some(target) => { - match target.bindings.def_for_namespace(TypeNS) { - Some(def) => { - match def { - def_trait(trait_def_id) => { - let added = self. - add_trait_info_if_containing_method( - &mut found_traits, - trait_def_id, name); - if added { - import_resolution.state.used = - true; - } - } - _ => { - // Continue. - } - } - } - None => { - // Continue. - } - } - } - } - } - - // Move to the next parent. - match search_module.parent_link { - NoParentLink => { - // Done. - break; - } - ModuleParentLink(parent_module, _) | - BlockParentLink(parent_module, _) => { - search_module = parent_module; - } - } - } - - return found_traits; - } - - fn add_trait_info_if_containing_method(&self, - found_traits: &mut ~[def_id], - trait_def_id: def_id, - name: ident) - -> bool { - debug!("(adding trait info if containing method) trying trait %d:%d \ - for method '%s'", - trait_def_id.crate, - trait_def_id.node, - *self.session.str_of(name)); - - match self.trait_info.find(&trait_def_id) { - Some(trait_info) if trait_info.contains(&name) => { - debug!("(adding trait info if containing method) found trait \ - %d:%d for method '%s'", - trait_def_id.crate, - trait_def_id.node, - *self.session.str_of(name)); - found_traits.push(trait_def_id); - true - } - Some(_) | None => { - false - } - } - } - - fn add_fixed_trait_for_expr(@mut self, - expr_id: node_id, - trait_id: def_id) { - self.trait_map.insert(expr_id, @mut ~[trait_id]); - } - - fn record_def(@mut self, node_id: node_id, def: def) { - debug!("(recording def) recording %? for %?", def, node_id); - self.def_map.insert(node_id, def); - } - - fn enforce_default_binding_mode(@mut self, - pat: @pat, - pat_binding_mode: binding_mode, - descr: &str) { - match pat_binding_mode { - bind_infer => {} - bind_by_copy => { - self.session.span_err( - pat.span, - fmt!("cannot use `copy` binding mode with %s", - descr)); - } - bind_by_ref(*) => { - self.session.span_err( - pat.span, - fmt!("cannot use `ref` binding mode with %s", - descr)); - } - } - } - - // - // main function checking - // - // be sure that there is only one main function - // - fn check_duplicate_main(@mut self) { - let this = &mut *self; - if this.attr_main_fn.is_none() && this.start_fn.is_none() { - if this.main_fns.len() >= 1u { - let mut i = 1u; - while i < this.main_fns.len() { - let (_, dup_main_span) = this.main_fns[i].unwrap(); - this.session.span_err( - dup_main_span, - ~"multiple 'main' functions"); - i += 1; - } - *this.session.entry_fn = this.main_fns[0]; - *this.session.entry_type = Some(session::EntryMain); - } - } else if !this.start_fn.is_none() { - *this.session.entry_fn = this.start_fn; - *this.session.entry_type = Some(session::EntryStart); - } else { - *this.session.entry_fn = this.attr_main_fn; - *this.session.entry_type = Some(session::EntryMain); - } - } - - // - // Unused import checking - // - // Although this is a lint pass, it lives in here because it depends on - // resolve data structures. - // - - fn unused_import_lint_level(@mut self, _: @mut Module) -> level { warn } - - fn check_for_unused_imports_if_necessary(@mut self) { - if self.unused_import_lint_level(self.current_module) == allow { - return; - } - - let root_module = self.graph_root.get_module(); - self.check_for_unused_imports_in_module_subtree(root_module); - } - - fn check_for_unused_imports_in_module_subtree(@mut self, - module_: @mut Module) { - // If this isn't a local crate, then bail out. We don't need to check - // for unused imports in external crates. - - match module_.def_id { - Some(def_id) if def_id.crate == local_crate => { - // OK. Continue. - } - None => { - // Check for unused imports in the root module. - } - Some(_) => { - // Bail out. - debug!("(checking for unused imports in module subtree) not \ - checking for unused imports for `%s`", - self.module_to_str(module_)); - return; - } - } - - self.check_for_unused_imports_in_module(module_); - - for module_.children.each_value |&child_name_bindings| { - match (*child_name_bindings).get_module_if_available() { - None => { - // Nothing to do. - } - Some(child_module) => { - self.check_for_unused_imports_in_module_subtree - (child_module); - } - } - } - - for module_.anonymous_children.each_value |&child_module| { - self.check_for_unused_imports_in_module_subtree(child_module); - } - } - - fn check_for_unused_imports_in_module(@mut self, module_: @mut Module) { - for module_.import_resolutions.each_value |&import_resolution| { - // Ignore dummy spans for things like automatically injected - // imports for the prelude, and also don't warn about the same - // import statement being unused more than once. Furthermore, if - // the import is public, then we can't be sure whether it's unused - // or not so don't warn about it. - if !import_resolution.state.used && - !import_resolution.state.warned && - import_resolution.span != dummy_sp() && - import_resolution.privacy != Public { - // I swear I work in not(stage0)! - } - } - } - - - // - // Diagnostics - // - // Diagnostics are not particularly efficient, because they're rarely - // hit. - // - - /// A somewhat inefficient routine to obtain the name of a module. - fn module_to_str(@mut self, module_: @mut Module) -> ~str { - let mut idents = ~[]; - let mut current_module = module_; - loop { - match current_module.parent_link { - NoParentLink => { - break; - } - ModuleParentLink(module_, name) => { - idents.push(name); - current_module = module_; - } - BlockParentLink(module_, _) => { - idents.push(special_idents::opaque); - current_module = module_; - } - } - } - - if idents.len() == 0 { - return ~"???"; - } - return self.idents_to_str(vec::reversed(idents)); - } - - fn dump_module(@mut self, module_: @mut Module) { - debug!("Dump of module `%s`:", self.module_to_str(module_)); - - debug!("Children:"); - for module_.children.each_key |&name| { - debug!("* %s", *self.session.str_of(name)); - } - - debug!("Import resolutions:"); - for module_.import_resolutions.each |name, import_resolution| { - let mut value_repr; - match import_resolution.target_for_namespace(ValueNS) { - None => { value_repr = ~""; } - Some(_) => { - value_repr = ~" value:?"; - // FIXME #4954 - } - } - - let mut type_repr; - match import_resolution.target_for_namespace(TypeNS) { - None => { type_repr = ~""; } - Some(_) => { - type_repr = ~" type:?"; - // FIXME #4954 - } - } - - debug!("* %s:%s%s", *self.session.str_of(*name), - value_repr, type_repr); - } - } -} - -pub struct CrateMap { - def_map: DefMap, - exp_map2: ExportMap2, - trait_map: TraitMap -} - -/// Entry point to crate resolution. -pub fn resolve_crate(session: Session, - lang_items: LanguageItems, - crate: @crate) - -> CrateMap { - let resolver = @mut Resolver(session, lang_items, crate); - resolver.resolve(); - let @Resolver{def_map, export_map2, trait_map, _} = resolver; - CrateMap { - def_map: def_map, - exp_map2: export_map2, - trait_map: trait_map - } -} diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 547b54a6ef50f..0274ecbfd1dd4 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -1367,21 +1367,6 @@ pub struct mono_id_ { pub type mono_id = @mono_id_; -#[cfg(stage0)] -impl to_bytes::IterBytes for mono_param_id { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - mono_precise(t, ref mids) => - to_bytes::iter_bytes_3(&0u8, &ty::type_id(t), mids, lsb0, f), - - mono_any => 1u8.iter_bytes(lsb0, f), - - mono_repr(ref a, ref b, ref c, ref d) => - to_bytes::iter_bytes_5(&2u8, a, b, c, d, lsb0, f) - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for mono_param_id { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { @@ -1396,26 +1381,12 @@ impl to_bytes::IterBytes for mono_param_id { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for MonoDataClass { - fn iter_bytes(&self, lsb0: bool, f:to_bytes::Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for MonoDataClass { fn iter_bytes(&self, lsb0: bool, f:to_bytes::Cb) -> bool { (*self as u8).iter_bytes(lsb0, f) } } -#[cfg(stage0)] -impl to_bytes::IterBytes for mono_id_ { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.def, &self.params, lsb0, f); - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for mono_id_ { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_2(&self.def, &self.params, lsb0, f) diff --git a/src/librustc/middle/trans/datum.rs b/src/librustc/middle/trans/datum.rs index 13b072c6f632b..4a9a907d5b7c0 100644 --- a/src/librustc/middle/trans/datum.rs +++ b/src/librustc/middle/trans/datum.rs @@ -154,13 +154,6 @@ pub impl DatumMode { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for DatumMode { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as uint).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for DatumMode { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as uint).iter_bytes(lsb0, f) diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 9ea3259e9699c..b80b4855538ec 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -26,8 +26,6 @@ use util::ppaux::{Repr, UserString}; use util::common::{indenter}; use util::enum_set::{EnumSet, CLike}; -#[cfg(stage0)] -use core; // NOTE: this can be removed after the next snapshot use core::ptr::to_unsafe_ptr; use core::to_bytes; use core::hashmap::{HashMap, HashSet}; @@ -136,13 +134,6 @@ pub struct creader_cache_key { type creader_cache = @mut HashMap; -#[cfg(stage0)] -impl to_bytes::IterBytes for creader_cache_key { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_3(&self.cnum, &self.pos, &self.len, lsb0, f); - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for creader_cache_key { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_3(&self.cnum, &self.pos, &self.len, lsb0, f) @@ -167,15 +158,6 @@ impl cmp::Eq for intern_key { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for intern_key { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - unsafe { - (*self.sty).iter_bytes(lsb0, f); - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for intern_key { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { unsafe { @@ -408,27 +390,12 @@ pub struct FnSig { output: t } -#[cfg(stage0)] -impl to_bytes::IterBytes for BareFnTy { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_3(&self.purity, &self.abis, &self.sig, lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for BareFnTy { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_3(&self.purity, &self.abis, &self.sig, lsb0, f) } } -#[cfg(stage0)] -impl to_bytes::IterBytes for ClosureTy { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_5(&self.purity, &self.sigil, &self.onceness, - &self.region, &self.sig, lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for ClosureTy { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_5(&self.purity, &self.sigil, &self.onceness, @@ -747,17 +714,6 @@ pub enum InferTy { FloatVar(FloatVid) } -#[cfg(stage0)] -impl to_bytes::IterBytes for InferTy { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - TyVar(ref tv) => to_bytes::iter_bytes_2(&0u8, tv, lsb0, f), - IntVar(ref iv) => to_bytes::iter_bytes_2(&1u8, iv, lsb0, f), - FloatVar(ref fv) => to_bytes::iter_bytes_2(&2u8, fv, lsb0, f), - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for InferTy { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { @@ -774,16 +730,6 @@ pub enum InferRegion { ReSkolemized(uint, bound_region) } -#[cfg(stage0)] -impl to_bytes::IterBytes for InferRegion { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - ReVar(ref rv) => to_bytes::iter_bytes_2(&0u8, rv, lsb0, f), - ReSkolemized(ref v, _) => to_bytes::iter_bytes_2(&1u8, v, lsb0, f) - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for InferRegion { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { @@ -872,52 +818,24 @@ impl ToStr for IntVarValue { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for TyVid { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.to_uint().iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for TyVid { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { self.to_uint().iter_bytes(lsb0, f) } } -#[cfg(stage0)] -impl to_bytes::IterBytes for IntVid { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.to_uint().iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for IntVid { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { self.to_uint().iter_bytes(lsb0, f) } } -#[cfg(stage0)] -impl to_bytes::IterBytes for FloatVid { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.to_uint().iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for FloatVid { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { self.to_uint().iter_bytes(lsb0, f) } } -#[cfg(stage0)] -impl to_bytes::IterBytes for RegionVid { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.to_uint().iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for RegionVid { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { self.to_uint().iter_bytes(lsb0, f) @@ -2718,22 +2636,6 @@ impl cmp::TotalEq for bound_region { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for vstore { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - vstore_fixed(ref u) => - to_bytes::iter_bytes_2(&0u8, u, lsb0, f), - - vstore_uniq => 1u8.iter_bytes(lsb0, f), - vstore_box => 2u8.iter_bytes(lsb0, f), - - vstore_slice(ref r) => - to_bytes::iter_bytes_2(&3u8, r, lsb0, f), - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for vstore { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { @@ -2749,15 +2651,6 @@ impl to_bytes::IterBytes for vstore { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for substs { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_3(&self.self_r, - &self.self_ty, - &self.tps, lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for substs { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_3(&self.self_r, @@ -2766,14 +2659,6 @@ impl to_bytes::IterBytes for substs { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for mt { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.ty, - &self.mutbl, lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for mt { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_2(&self.ty, @@ -2781,14 +2666,6 @@ impl to_bytes::IterBytes for mt { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for field { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.ident, - &self.mt, lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for field { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_2(&self.ident, @@ -2796,15 +2673,6 @@ impl to_bytes::IterBytes for field { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for FnSig { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.inputs, - &self.output, - lsb0, f); - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for FnSig { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_2(&self.inputs, @@ -2813,82 +2681,6 @@ impl to_bytes::IterBytes for FnSig { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for sty { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - ty_nil => 0u8.iter_bytes(lsb0, f), - ty_bool => 1u8.iter_bytes(lsb0, f), - - ty_int(ref t) => - to_bytes::iter_bytes_2(&2u8, t, lsb0, f), - - ty_uint(ref t) => - to_bytes::iter_bytes_2(&3u8, t, lsb0, f), - - ty_float(ref t) => - to_bytes::iter_bytes_2(&4u8, t, lsb0, f), - - ty_estr(ref v) => - to_bytes::iter_bytes_2(&5u8, v, lsb0, f), - - ty_enum(ref did, ref substs) => - to_bytes::iter_bytes_3(&6u8, did, substs, lsb0, f), - - ty_box(ref mt) => - to_bytes::iter_bytes_2(&7u8, mt, lsb0, f), - - ty_evec(ref mt, ref v) => - to_bytes::iter_bytes_3(&8u8, mt, v, lsb0, f), - - ty_unboxed_vec(ref mt) => - to_bytes::iter_bytes_2(&9u8, mt, lsb0, f), - - ty_tup(ref ts) => - to_bytes::iter_bytes_2(&10u8, ts, lsb0, f), - - ty_bare_fn(ref ft) => - to_bytes::iter_bytes_2(&12u8, ft, lsb0, f), - - ty_self(ref did) => to_bytes::iter_bytes_2(&13u8, did, lsb0, f), - - ty_infer(ref v) => - to_bytes::iter_bytes_2(&14u8, v, lsb0, f), - - ty_param(ref p) => - to_bytes::iter_bytes_2(&15u8, p, lsb0, f), - - ty_type => 16u8.iter_bytes(lsb0, f), - ty_bot => 17u8.iter_bytes(lsb0, f), - - ty_ptr(ref mt) => - to_bytes::iter_bytes_2(&18u8, mt, lsb0, f), - - ty_uniq(ref mt) => - to_bytes::iter_bytes_2(&19u8, mt, lsb0, f), - - ty_trait(ref did, ref substs, ref v, ref mutbl) => - to_bytes::iter_bytes_5(&20u8, did, substs, v, mutbl, lsb0, f), - - ty_opaque_closure_ptr(ref ck) => - to_bytes::iter_bytes_2(&21u8, ck, lsb0, f), - - ty_opaque_box => 22u8.iter_bytes(lsb0, f), - - ty_struct(ref did, ref substs) => - to_bytes::iter_bytes_3(&23u8, did, substs, lsb0, f), - - ty_rptr(ref r, ref mt) => - to_bytes::iter_bytes_3(&24u8, r, mt, lsb0, f), - - ty_err => 25u8.iter_bytes(lsb0, f), - - ty_closure(ref ct) => - to_bytes::iter_bytes_2(&26u8, ct, lsb0, f), - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for sty { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { @@ -4499,52 +4291,6 @@ pub fn determine_inherited_purity(parent: (ast::purity, ast::node_id), // Here, the supertraits are the transitive closure of the supertrait // relation on the supertraits from each bounded trait's constraint // list. -#[cfg(stage0)] -pub fn each_bound_trait_and_supertraits(tcx: ctxt, - bounds: &ParamBounds, - f: &fn(@TraitRef) -> bool) { - for bounds.trait_bounds.each |&bound_trait_ref| { - let mut supertrait_set = HashMap::new(); - let mut trait_refs = ~[]; - let mut i = 0; - - // Seed the worklist with the trait from the bound - supertrait_set.insert(bound_trait_ref.def_id, ()); - trait_refs.push(bound_trait_ref); - - // Add the given trait ty to the hash map - while i < trait_refs.len() { - debug!("each_bound_trait_and_supertraits(i=%?, trait_ref=%s)", - i, trait_refs[i].repr(tcx)); - - if !f(trait_refs[i]) { - return; - } - - // Add supertraits to supertrait_set - let supertrait_refs = trait_ref_supertraits(tcx, trait_refs[i]); - for supertrait_refs.each |&supertrait_ref| { - debug!("each_bound_trait_and_supertraits(supertrait_ref=%s)", - supertrait_ref.repr(tcx)); - - let d_id = supertrait_ref.def_id; - if !supertrait_set.contains_key(&d_id) { - // FIXME(#5527) Could have same trait multiple times - supertrait_set.insert(d_id, ()); - trait_refs.push(supertrait_ref); - } - } - - i += 1; - } - } -} -// Iterate over a type parameter's bounded traits and any supertraits -// of those traits, ignoring kinds. -// Here, the supertraits are the transitive closure of the supertrait -// relation on the supertraits from each bounded trait's constraint -// list. -#[cfg(not(stage0))] pub fn each_bound_trait_and_supertraits(tcx: ctxt, bounds: &ParamBounds, f: &fn(@TraitRef) -> bool) -> bool { diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 6e272b9410f49..54537397c6263 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -828,15 +828,6 @@ pub impl FnCtxt { } } - #[cfg(stage0)] - fn opt_node_ty_substs(&self, id: ast::node_id, - f: &fn(&ty::substs) -> bool) { - match self.inh.node_type_substs.find(&id) { - Some(s) => { f(s); } - None => () - } - } - #[cfg(not(stage0))] fn opt_node_ty_substs(&self, id: ast::node_id, f: &fn(&ty::substs) -> bool) -> bool { match self.inh.node_type_substs.find(&id) { diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index ecec07ec51287..3f3df7bf83824 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -118,26 +118,6 @@ pub impl Rcx { } /// Try to resolve the type for the given node. - #[config(stage0)] - fn resolve_expr_type_adjusted(@mut self, expr: @ast::expr) -> ty::t { - let ty_unadjusted = self.resolve_node_type(expr.id); - if ty::type_is_error(ty_unadjusted) || ty::type_is_bot(ty_unadjusted) { - ty_unadjusted - } else { - let tcx = self.fcx.tcx(); - let adjustments = self.fcx.inh.adjustments; - match adjustments.find_copy(&expr.id) { - None => ty_unadjusted, - Some(adjustment) => { - ty::adjust_ty(tcx, expr.span, ty_unadjusted, - Some(adjustment)) - } - } - } - } - - /// Try to resolve the type for the given node. - #[config(not(stage0))] fn resolve_expr_type_adjusted(@mut self, expr: @ast::expr) -> ty::t { let ty_unadjusted = self.resolve_node_type(expr.id); if ty::type_is_error(ty_unadjusted) || ty::type_is_bot(ty_unadjusted) { diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index aeb360dc3f2fc..f133a010f83ab 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -524,27 +524,6 @@ pub impl CoherenceChecker { } } - #[cfg(stage0)] - fn each_provided_trait_method(&self, - trait_did: ast::def_id, - f: &fn(@ty::Method) -> bool) { - // Make a list of all the names of the provided methods. - // XXX: This is horrible. - let mut provided_method_idents = HashSet::new(); - let tcx = self.crate_context.tcx; - for ty::provided_trait_methods(tcx, trait_did).each |ident| { - provided_method_idents.insert(*ident); - } - - for ty::trait_methods(tcx, trait_did).each |&method| { - if provided_method_idents.contains(&method.ident) { - if !f(method) { - break; - } - } - } - } - #[cfg(not(stage0))] fn each_provided_trait_method(&self, trait_did: ast::def_id, f: &fn(x: @ty::Method) -> bool) -> bool { diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index 1437494e5f86e..89041bffd0941 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -544,8 +544,6 @@ use middle::typeck::infer::cres; use util::common::indenter; use util::ppaux::note_and_explain_region; -#[cfg(stage0)] -use core; // NOTE: this can be removed after next snapshot use core::cell::{Cell, empty_cell}; use core::hashmap::{HashMap, HashSet}; use core::to_bytes; @@ -561,22 +559,6 @@ enum Constraint { ConstrainVarSubReg(RegionVid, Region) } -#[cfg(stage0)] -impl to_bytes::IterBytes for Constraint { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - ConstrainVarSubVar(ref v0, ref v1) => - to_bytes::iter_bytes_3(&0u8, v0, v1, lsb0, f), - - ConstrainRegSubVar(ref ra, ref va) => - to_bytes::iter_bytes_3(&1u8, ra, va, lsb0, f), - - ConstrainVarSubReg(ref va, ref ra) => - to_bytes::iter_bytes_3(&2u8, va, ra, lsb0, f) - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for Constraint { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { @@ -1773,23 +1755,6 @@ pub impl RegionVarBindings { } } - #[cfg(stage0)] - fn each_edge(&mut self, - graph: &Graph, - node_idx: RegionVid, - dir: Direction, - op: &fn(edge: &GraphEdge) -> bool) { - let mut edge_idx = - graph.nodes[node_idx.to_uint()].head_edge[dir as uint]; - while edge_idx != uint::max_value { - let edge_ptr = &graph.edges[edge_idx]; - if !op(edge_ptr) { - return; - } - edge_idx = edge_ptr.next_edge[dir as uint]; - } - } - #[cfg(not(stage0))] fn each_edge(&mut self, graph: &Graph, node_idx: RegionVid, diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index e3d19e3855925..72eef2ba4132c 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -75,9 +75,6 @@ pub mod middle { } pub mod ty; pub mod subst; - #[cfg(stage0)] #[path = "resolve_stage0.rs"] - pub mod resolve; - #[cfg(not(stage0))] pub mod resolve; #[path = "typeck/mod.rs"] pub mod typeck; diff --git a/src/librustc/util/enum_set.rs b/src/librustc/util/enum_set.rs index 2e6c4ee3eaa8e..49750c5690955 100644 --- a/src/librustc/util/enum_set.rs +++ b/src/librustc/util/enum_set.rs @@ -8,9 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[cfg(stage0)] -use core; - #[deriving(Eq, IterBytes)] pub struct EnumSet { // We must maintain the invariant that no bits are set @@ -60,22 +57,6 @@ pub impl EnumSet { (self.bits & bit(e)) != 0 } - #[cfg(stage0)] - fn each(&self, f: &fn(E) -> bool) { - let mut bits = self.bits; - let mut index = 0; - while bits != 0 { - if (bits & 1) != 0 { - let e = CLike::from_uint(index); - if !f(e) { - return; - } - } - index += 1; - bits >>= 1; - } - } - #[cfg(not(stage0))] fn each(&self, f: &fn(E) -> bool) -> bool { let mut bits = self.bits; let mut index = 0; diff --git a/src/libstd/bitv.rs b/src/libstd/bitv.rs index f0632e550fa68..9d22107931e9e 100644 --- a/src/libstd/bitv.rs +++ b/src/libstd/bitv.rs @@ -143,17 +143,6 @@ pub impl BigBitv { } #[inline(always)] - #[cfg(stage0)] - fn each_storage(&mut self, op: &fn(v: &mut uint) -> bool) { - for uint::range(0, self.storage.len()) |i| { - let mut w = self.storage[i]; - let b = op(&mut w); - self.storage[i] = w; - if !b { break; } - } - } - #[inline(always)] - #[cfg(not(stage0))] fn each_storage(&mut self, op: &fn(v: &mut uint) -> bool) -> bool { uint::range(0, self.storage.len(), |i| op(&mut self.storage[i])) } @@ -199,19 +188,6 @@ pub impl BigBitv { } #[inline(always)] - #[cfg(stage0)] - fn equals(&self, b: &BigBitv, nbits: uint) -> bool { - let len = b.storage.len(); - for uint::iterate(0, len) |i| { - let mask = big_mask(nbits, i); - if mask & self.storage[i] != mask & b.storage[i] { - return false; - } - } - } - - #[inline(always)] - #[cfg(not(stage0))] fn equals(&self, b: &BigBitv, nbits: uint) -> bool { let len = b.storage.len(); for uint::iterate(0, len) |i| { @@ -407,16 +383,6 @@ pub impl Bitv { } #[inline(always)] - #[cfg(stage0)] - fn each(&self, f: &fn(bool) -> bool) { - let mut i = 0; - while i < self.nbits { - if !f(self.get(i)) { break; } - i += 1; - } - } - #[inline(always)] - #[cfg(not(stage0))] fn each(&self, f: &fn(bool) -> bool) -> bool { let mut i = 0; while i < self.nbits { @@ -519,15 +485,6 @@ pub impl Bitv { true } - #[cfg(stage0)] - fn ones(&self, f: &fn(uint) -> bool) { - for uint::range(0, self.nbits) |i| { - if self.get(i) { - if !f(i) { break } - } - } - } - #[cfg(not(stage0))] fn ones(&self, f: &fn(uint) -> bool) -> bool { uint::range(0, self.nbits, |i| !self.get(i) || f(i)) } @@ -697,7 +654,6 @@ pub impl BitvSet { } } -#[cfg(not(stage0))] impl BaseIter for BitvSet { fn size_hint(&self) -> Option { Some(self.len()) } @@ -711,7 +667,6 @@ impl BaseIter for BitvSet { } } -#[cfg(not(stage0))] impl cmp::Eq for BitvSet { fn eq(&self, other: &BitvSet) -> bool { if self.size != other.size { @@ -745,7 +700,6 @@ impl Mutable for BitvSet { } } -#[cfg(not(stage0))] impl Set for BitvSet { fn contains(&self, value: &uint) -> bool { *value < self.bitv.storage.len() * uint::bits && self.bitv.get(*value) @@ -849,7 +803,6 @@ impl Set for BitvSet { } } -#[cfg(not(stage0))] priv impl BitvSet { /// Visits each of the words that the two bit vectors (self and other) /// both have in common. The three yielded arguments are (bit location, diff --git a/src/libstd/deque.rs b/src/libstd/deque.rs index eac765de00636..60f1607417789 100644 --- a/src/libstd/deque.rs +++ b/src/libstd/deque.rs @@ -65,23 +65,11 @@ pub impl Deque { } /// Iterate over the elements in the deque - #[cfg(stage0)] - fn each(&self, f: &fn(&T) -> bool) { - self.eachi(|_i, e| f(e)) - } - /// Iterate over the elements in the deque - #[cfg(not(stage0))] fn each(&self, f: &fn(&T) -> bool) -> bool { self.eachi(|_i, e| f(e)) } /// Iterate over the elements in the deque by index - #[cfg(stage0)] - fn eachi(&self, f: &fn(uint, &T) -> bool) { - uint::range(0, self.nelts, |i| f(i, self.get(i as int))) - } - /// Iterate over the elements in the deque by index - #[cfg(not(stage0))] fn eachi(&self, f: &fn(uint, &T) -> bool) -> bool { uint::range(0, self.nelts, |i| f(i, self.get(i as int))) } diff --git a/src/libstd/dlist.rs b/src/libstd/dlist.rs index e0b4d746d5317..100543d7d98c7 100644 --- a/src/libstd/dlist.rs +++ b/src/libstd/dlist.rs @@ -391,17 +391,6 @@ pub impl DList { } /// Iterate over nodes. - #[cfg(stage0)] - fn each_node(@mut self, f: &fn(@mut DListNode) -> bool) { - let mut link = self.peek_n(); - while link.is_some() { - let nobe = link.get(); - if !f(nobe) { break; } - link = nobe.next_link(); - } - } - /// Iterate over nodes. - #[cfg(not(stage0))] fn each_node(@mut self, f: &fn(@mut DListNode) -> bool) -> bool { let mut link = self.peek_n(); while link.is_some() { @@ -508,42 +497,6 @@ impl BaseIter for @mut DList { * allow for e.g. breadth-first search with in-place enqueues), but * removing the current node is forbidden. */ - #[cfg(stage0)] - fn each(&self, f: &fn(v: &T) -> bool) { - let mut link = self.peek_n(); - while link.is_some() { - let nobe = link.get(); - assert!(nobe.linked); - - { - let frozen_nobe = &*nobe; - if !f(&frozen_nobe.data) { break; } - } - - // Check (weakly) that the user didn't do a remove. - if self.size == 0 { - fail!("The dlist became empty during iteration??") - } - if !nobe.linked || - (!((nobe.prev.is_some() - || managed::mut_ptr_eq(self.hd.expect(~"headless dlist?"), - nobe)) - && (nobe.next.is_some() - || managed::mut_ptr_eq(self.tl.expect(~"tailless dlist?"), - nobe)))) { - fail!("Removing a dlist node during iteration is forbidden!") - } - link = nobe.next_link(); - } - } - /** - * Iterates through the current contents. - * - * Attempts to access this dlist during iteration are allowed (to - * allow for e.g. breadth-first search with in-place enqueues), but - * removing the current node is forbidden. - */ - #[cfg(not(stage0))] fn each(&self, f: &fn(v: &T) -> bool) -> bool { let mut link = self.peek_n(); while link.is_some() { diff --git a/src/libstd/ebml.rs b/src/libstd/ebml.rs index 8d550081d1e7a..a7c18ebf5cdc8 100644 --- a/src/libstd/ebml.rs +++ b/src/libstd/ebml.rs @@ -200,20 +200,6 @@ pub mod reader { } } - #[cfg(stage0)] - pub fn docs(d: Doc, it: &fn(uint, Doc) -> bool) { - let mut pos = d.start; - while pos < d.end { - let elt_tag = vuint_at(*d.data, pos); - let elt_size = vuint_at(*d.data, elt_tag.next); - pos = elt_size.next + elt_size.val; - let doc = Doc { data: d.data, start: elt_size.next, end: pos }; - if !it(elt_tag.val, doc) { - break; - } - } - } - #[cfg(not(stage0))] pub fn docs(d: Doc, it: &fn(uint, Doc) -> bool) -> bool { let mut pos = d.start; while pos < d.end { @@ -228,23 +214,6 @@ pub mod reader { return true; } - #[cfg(stage0)] - pub fn tagged_docs(d: Doc, tg: uint, it: &fn(Doc) -> bool) { - let mut pos = d.start; - while pos < d.end { - let elt_tag = vuint_at(*d.data, pos); - let elt_size = vuint_at(*d.data, elt_tag.next); - pos = elt_size.next + elt_size.val; - if elt_tag.val == tg { - let doc = Doc { data: d.data, start: elt_size.next, - end: pos }; - if !it(doc) { - break; - } - } - } - } - #[cfg(not(stage0))] pub fn tagged_docs(d: Doc, tg: uint, it: &fn(Doc) -> bool) -> bool { let mut pos = d.start; while pos < d.end { @@ -655,16 +624,6 @@ pub mod writer { fail!("vint to write too big: %?", n); } - #[cfg(stage0)] - pub fn Encoder(w: @io::Writer) -> Encoder { - let size_positions: ~[uint] = ~[]; - Encoder { - writer: w, - mut size_positions: size_positions - } - } - - #[cfg(not(stage0))] pub fn Encoder(w: @io::Writer) -> Encoder { let size_positions: ~[uint] = ~[]; Encoder { diff --git a/src/libstd/fileinput.rs b/src/libstd/fileinput.rs index a31827f95d1ae..25e248414cdf1 100644 --- a/src/libstd/fileinput.rs +++ b/src/libstd/fileinput.rs @@ -254,17 +254,6 @@ impl FileInput { (line numbers and file names, see documentation for `FileInputState`). Otherwise identical to `lines_each`. */ - #[cfg(stage0)] - pub fn each_line_state(&self, - f: &fn(&str, FileInputState) -> bool) { - self.each_line(|line| f(line, copy self.fi.state)); - } - /** - Apply `f` to each line successively, along with some state - (line numbers and file names, see documentation for - `FileInputState`). Otherwise identical to `lines_each`. - */ - #[cfg(not(stage0))] pub fn each_line_state(&self, f: &fn(&str, FileInputState) -> bool) -> bool { self.each_line(|line| f(line, copy self.fi.state)) @@ -377,17 +366,6 @@ reading from `stdin`). Fails when attempting to read from a file that can't be opened. */ -#[cfg(stage0)] -pub fn input(f: &fn(&str) -> bool) { - FileInput::from_args().each_line(f); -} -/** -Iterate directly over the command line arguments (no arguments implies -reading from `stdin`). - -Fails when attempting to read from a file that can't be opened. -*/ -#[cfg(not(stage0))] pub fn input(f: &fn(&str) -> bool) -> bool { let i = FileInput::from_args(); i.each_line(f) @@ -400,18 +378,6 @@ provided at each call. Fails when attempting to read from a file that can't be opened. */ -#[cfg(stage0)] -pub fn input_state(f: &fn(&str, FileInputState) -> bool) { - FileInput::from_args().each_line_state(f); -} -/** -Iterate directly over the command line arguments (no arguments -implies reading from `stdin`) with the current state of the iteration -provided at each call. - -Fails when attempting to read from a file that can't be opened. -*/ -#[cfg(not(stage0))] pub fn input_state(f: &fn(&str, FileInputState) -> bool) -> bool { let i = FileInput::from_args(); i.each_line_state(f) @@ -422,16 +388,6 @@ Iterate over a vector of files (an empty vector implies just `stdin`). Fails when attempting to read from a file that can't be opened. */ -#[cfg(stage0)] -pub fn input_vec(files: ~[Option], f: &fn(&str) -> bool) { - FileInput::from_vec(files).each_line(f); -} -/** -Iterate over a vector of files (an empty vector implies just `stdin`). - -Fails when attempting to read from a file that can't be opened. -*/ -#[cfg(not(stage0))] pub fn input_vec(files: ~[Option], f: &fn(&str) -> bool) -> bool { let i = FileInput::from_vec(files); i.each_line(f) @@ -443,18 +399,6 @@ with the current state of the iteration provided at each call. Fails when attempting to read from a file that can't be opened. */ -#[cfg(stage0)] -pub fn input_vec_state(files: ~[Option], - f: &fn(&str, FileInputState) -> bool) { - FileInput::from_vec(files).each_line_state(f); -} -/** -Iterate over a vector of files (an empty vector implies just `stdin`) -with the current state of the iteration provided at each call. - -Fails when attempting to read from a file that can't be opened. -*/ -#[cfg(not(stage0))] pub fn input_vec_state(files: ~[Option], f: &fn(&str, FileInputState) -> bool) -> bool { let i = FileInput::from_vec(files); diff --git a/src/libstd/list.rs b/src/libstd/list.rs index ae3251b961c18..3a916233db817 100644 --- a/src/libstd/list.rs +++ b/src/libstd/list.rs @@ -140,21 +140,6 @@ pub fn iter(l: @List, f: &fn(&T)) { } /// Iterate over a list -#[cfg(stage0)] -pub fn each(l: @List, f: &fn(&T) -> bool) { - let mut cur = l; - loop { - cur = match *cur { - Cons(ref hd, tl) => { - if !f(hd) { return; } - tl - } - Nil => break - } - } -} -/// Iterate over a list -#[cfg(not(stage0))] pub fn each(l: @List, f: &fn(&T) -> bool) -> bool { let mut cur = l; loop { @@ -170,24 +155,6 @@ pub fn each(l: @List, f: &fn(&T) -> bool) -> bool { impl MutList { /// Iterate over a mutable list - #[cfg(stage0)] - pub fn each(@mut self, f: &fn(&mut T) -> bool) { - let mut cur = self; - loop { - let borrowed = &mut *cur; - cur = match *borrowed { - MutCons(ref mut hd, tl) => { - if !f(hd) { - return; - } - tl - } - MutNil => break - } - } - } - /// Iterate over a mutable list - #[cfg(not(stage0))] pub fn each(@mut self, f: &fn(&mut T) -> bool) -> bool { let mut cur = self; loop { diff --git a/src/libstd/net_url.rs b/src/libstd/net_url.rs index ef503817b55af..19e0dc1441275 100644 --- a/src/libstd/net_url.rs +++ b/src/libstd/net_url.rs @@ -703,13 +703,6 @@ impl ToStr for Url { } } -#[cfg(stage0)] -impl IterBytes for Url { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.to_str().iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl IterBytes for Url { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { self.to_str().iter_bytes(lsb0, f) diff --git a/src/libstd/priority_queue.rs b/src/libstd/priority_queue.rs index b54fc81aac11c..2f5d12d08073b 100644 --- a/src/libstd/priority_queue.rs +++ b/src/libstd/priority_queue.rs @@ -22,12 +22,6 @@ impl BaseIter for PriorityQueue { /// Visit all values in the underlying vector. /// /// The values are **not** visited in order. - #[cfg(stage0)] - fn each(&self, f: &fn(&T) -> bool) { self.data.each(f) } - /// Visit all values in the underlying vector. - /// - /// The values are **not** visited in order. - #[cfg(not(stage0))] fn each(&self, f: &fn(&T) -> bool) -> bool { self.data.each(f) } fn size_hint(&self) -> Option { self.data.size_hint() } diff --git a/src/libstd/rc.rs b/src/libstd/rc.rs index cc1492ba4489e..02f824b911302 100644 --- a/src/libstd/rc.rs +++ b/src/libstd/rc.rs @@ -61,7 +61,6 @@ pub impl Rc { } #[unsafe_destructor] -#[cfg(not(stage0))] impl Drop for Rc { fn finalize(&self) { unsafe { @@ -74,21 +73,6 @@ impl Drop for Rc { } } -#[unsafe_destructor] -#[cfg(stage0)] -impl Drop for Rc { - fn finalize(&self) { - unsafe { - (*self.ptr).count -= 1; - if (*self.ptr).count == 0 { - util::replace_ptr(self.ptr, intrinsics::init()); - free(self.ptr as *c_void) - } - } - } -} - - impl Clone for Rc { /// Return a shallow copy of the reference counted pointer. #[inline] @@ -157,7 +141,6 @@ mod test_rc { #[abi = "rust-intrinsic"] extern "rust-intrinsic" { fn init() -> T; - #[cfg(not(stage0))] fn uninit() -> T; } @@ -228,7 +211,6 @@ pub impl RcMut { } #[unsafe_destructor] -#[cfg(not(stage0))] impl Drop for RcMut { fn finalize(&self) { unsafe { @@ -241,20 +223,6 @@ impl Drop for RcMut { } } -#[unsafe_destructor] -#[cfg(stage0)] -impl Drop for RcMut { - fn finalize(&self) { - unsafe { - (*self.ptr).count -= 1; - if (*self.ptr).count == 0 { - util::replace_ptr(self.ptr, init()); - free(self.ptr as *c_void) - } - } - } -} - impl Clone for RcMut { /// Return a shallow copy of the reference counted pointer. #[inline] diff --git a/src/libstd/smallintmap.rs b/src/libstd/smallintmap.rs index a336bd54a61aa..3c1f53b25f7f8 100644 --- a/src/libstd/smallintmap.rs +++ b/src/libstd/smallintmap.rs @@ -51,18 +51,6 @@ impl Map for SmallIntMap { } /// Visit all key-value pairs in order - #[cfg(stage0)] - fn each<'a>(&'a self, it: &fn(&uint, &'a V) -> bool) { - for uint::range(0, self.v.len()) |i| { - match self.v[i] { - Some(ref elt) => if !it(&i, elt) { break }, - None => () - } - } - } - - /// Visit all key-value pairs in order - #[cfg(not(stage0))] fn each<'a>(&'a self, it: &fn(&uint, &'a V) -> bool) -> bool { for uint::range(0, self.v.len()) |i| { match self.v[i] { @@ -73,41 +61,17 @@ impl Map for SmallIntMap { return true; } - /// Visit all keys in order - #[cfg(stage0)] - fn each_key(&self, blk: &fn(key: &uint) -> bool) { - self.each(|k, _| blk(k)) - } - #[cfg(not(stage0))] /// Visit all keys in order fn each_key(&self, blk: &fn(key: &uint) -> bool) -> bool { self.each(|k, _| blk(k)) } /// Visit all values in order - #[cfg(stage0)] - fn each_value<'a>(&'a self, blk: &fn(value: &'a V) -> bool) { - self.each(|_, v| blk(v)) - } - - /// Visit all values in order - #[cfg(not(stage0))] fn each_value<'a>(&'a self, blk: &fn(value: &'a V) -> bool) -> bool { self.each(|_, v| blk(v)) } /// Iterate over the map and mutate the contained values - #[cfg(stage0)] - fn mutate_values(&mut self, it: &fn(&uint, &mut V) -> bool) { - for uint::range(0, self.v.len()) |i| { - match self.v[i] { - Some(ref mut elt) => if !it(&i, elt) { return; }, - None => () - } - } - } - /// Iterate over the map and mutate the contained values - #[cfg(not(stage0))] fn mutate_values(&mut self, it: &fn(&uint, &mut V) -> bool) -> bool { for uint::range(0, self.v.len()) |i| { match self.v[i] { @@ -187,18 +151,6 @@ pub impl SmallIntMap { fn new() -> SmallIntMap { SmallIntMap{v: ~[]} } /// Visit all key-value pairs in reverse order - #[cfg(stage0)] - fn each_reverse<'a>(&'a self, it: &fn(uint, &'a V) -> bool) { - for uint::range_rev(self.v.len(), 0) |i| { - match self.v[i - 1] { - Some(ref elt) => if !it(i - 1, elt) { break }, - None => () - } - } - } - - /// Visit all key-value pairs in reverse order - #[cfg(not(stage0))] fn each_reverse<'a>(&'a self, it: &fn(uint, &'a V) -> bool) -> bool { for uint::range_rev(self.v.len(), 0) |i| { match self.v[i - 1] { diff --git a/src/libstd/sort.rs b/src/libstd/sort.rs index ca752a482981a..d896fa8c096f7 100644 --- a/src/libstd/sort.rs +++ b/src/libstd/sort.rs @@ -61,26 +61,6 @@ pub fn merge_sort(v: &[T], le: Le) -> ~[T] { } } -#[cfg(stage0)] -fn part(arr: &mut [T], left: uint, - right: uint, pivot: uint, compare_func: Le) -> uint { - swap(&mut arr[pivot], &mut arr[right]); - let mut storage_index: uint = left; - let mut i: uint = left; - while i < right { - let a: &mut T = &mut arr[i]; - let b: &mut T = &mut arr[right]; - if compare_func(a, b) { - swap(&mut arr[i], &mut arr[storage_index]); - storage_index += 1; - } - i += 1; - } - swap(&mut arr[storage_index], &mut arr[right]); - return storage_index; -} - -#[cfg(not(stage0))] fn part(arr: &mut [T], left: uint, right: uint, pivot: uint, compare_func: Le) -> uint { vec::swap(arr, pivot, right); diff --git a/src/libstd/sort_stage0.rs b/src/libstd/sort_stage0.rs deleted file mode 100644 index cdef8e220ceed..0000000000000 --- a/src/libstd/sort_stage0.rs +++ /dev/null @@ -1,1240 +0,0 @@ -// Copyright 2012 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. - -//! Sorting methods - -use core::cmp::{Eq, Ord}; -use core::vec::len; -use core::vec; -use core::util; - -type Le<'self, T> = &'self fn(v1: &T, v2: &T) -> bool; - -/** - * Merge sort. Returns a new vector containing the sorted list. - * - * Has worst case O(n log n) performance, best case O(n), but - * is not space efficient. This is a stable sort. - */ -pub fn merge_sort(v: &const [T], le: Le) -> ~[T] { - type Slice = (uint, uint); - - return merge_sort_(v, (0u, len(v)), le); - - fn merge_sort_(v: &const [T], slice: Slice, le: Le) - -> ~[T] { - let begin = slice.first(); - let end = slice.second(); - - let v_len = end - begin; - if v_len == 0 { return ~[]; } - if v_len == 1 { return ~[v[begin]]; } - - let mid = v_len / 2 + begin; - let a = (begin, mid); - let b = (mid, end); - return merge(le, merge_sort_(v, a, le), merge_sort_(v, b, le)); - } - - fn merge(le: Le, a: &[T], b: &[T]) -> ~[T] { - let mut rs = vec::with_capacity(len(a) + len(b)); - let a_len = len(a); - let mut a_ix = 0; - let b_len = len(b); - let mut b_ix = 0; - while a_ix < a_len && b_ix < b_len { - if le(&a[a_ix], &b[b_ix]) { - rs.push(a[a_ix]); - a_ix += 1; - } else { rs.push(b[b_ix]); b_ix += 1; } - } - rs.push_all(vec::slice(a, a_ix, a_len)); - rs.push_all(vec::slice(b, b_ix, b_len)); - rs - } -} - -#[cfg(stage0)] -fn part(arr: &mut [T], left: uint, - right: uint, pivot: uint, compare_func: Le) -> uint { - vec::swap(arr, pivot, right); - let mut storage_index: uint = left; - let mut i: uint = left; - while i < right { - let a: &mut T = &mut arr[i]; - let b: &mut T = &mut arr[right]; - if compare_func(a, b) { - vec::swap(arr, i, storage_index); - storage_index += 1; - } - i += 1; - } - vec::swap(arr, storage_index, right); - return storage_index; -} - -#[cfg(not(stage0))] -fn part(arr: &mut [T], left: uint, - right: uint, pivot: uint, compare_func: Le) -> uint { - vec::swap(arr, pivot, right); - let mut storage_index: uint = left; - let mut i: uint = left; - while i < right { - if compare_func(&arr[i], &arr[right]) { - vec::swap(arr, i, storage_index); - storage_index += 1; - } - i += 1; - } - vec::swap(arr, storage_index, right); - return storage_index; -} - -fn qsort(arr: &mut [T], left: uint, - right: uint, compare_func: Le) { - if right > left { - let pivot = (left + right) / 2u; - let new_pivot = part::(arr, left, right, pivot, compare_func); - if new_pivot != 0u { - // Need to do this check before recursing due to overflow - qsort::(arr, left, new_pivot - 1u, compare_func); - } - qsort::(arr, new_pivot + 1u, right, compare_func); - } -} - -/** - * Quicksort. Sorts a mut vector in place. - * - * Has worst case O(n^2) performance, average case O(n log n). - * This is an unstable sort. - */ -pub fn quick_sort(arr: &mut [T], compare_func: Le) { - if len::(arr) == 0u { return; } - qsort::(arr, 0u, len::(arr) - 1u, compare_func); -} - -fn qsort3(arr: &mut [T], left: int, right: int) { - if right <= left { return; } - let v: T = arr[right]; - let mut i: int = left - 1; - let mut j: int = right; - let mut p: int = i; - let mut q: int = j; - loop { - i += 1; - while arr[i] < v { i += 1; } - j -= 1; - while v < arr[j] { - if j == left { break; } - j -= 1; - } - if i >= j { break; } - vec::swap(arr, i as uint, j as uint); - if arr[i] == v { - p += 1; - vec::swap(arr, p as uint, i as uint); - } - if v == arr[j] { - q -= 1; - vec::swap(arr, j as uint, q as uint); - } - } - vec::swap(arr, i as uint, right as uint); - j = i - 1; - i += 1; - let mut k: int = left; - while k < p { - vec::swap(arr, k as uint, j as uint); - k += 1; - j -= 1; - if k == len::(arr) as int { break; } - } - k = right - 1; - while k > q { - vec::swap(arr, i as uint, k as uint); - k -= 1; - i += 1; - if k == 0 { break; } - } - qsort3::(arr, left, j); - qsort3::(arr, i, right); -} - -/** - * Fancy quicksort. Sorts a mut vector in place. - * - * Based on algorithm presented by ~[Sedgewick and Bentley] - * (http://www.cs.princeton.edu/~rs/talks/QuicksortIsOptimal.pdf). - * According to these slides this is the algorithm of choice for - * 'randomly ordered keys, abstract compare' & 'small number of key values'. - * - * This is an unstable sort. - */ -pub fn quick_sort3(arr: &mut [T]) { - if arr.len() <= 1 { return; } - let len = arr.len() - 1; // FIXME(#5074) nested calls - qsort3(arr, 0, (len - 1) as int); -} - -pub trait Sort { - fn qsort(self); -} - -impl<'self, T:Copy + Ord + Eq> Sort for &'self mut [T] { - fn qsort(self) { quick_sort3(self); } -} - -static MIN_MERGE: uint = 64; -static MIN_GALLOP: uint = 7; -static INITIAL_TMP_STORAGE: uint = 128; - -pub fn tim_sort(array: &mut [T]) { - let size = array.len(); - if size < 2 { - return; - } - - if size < MIN_MERGE { - let init_run_len = count_run_ascending(array); - binarysort(array, init_run_len); - return; - } - - let mut ms = MergeState(); - let min_run = min_run_length(size); - - let mut idx = 0; - let mut remaining = size; - loop { - let run_len: uint = { - // This scope contains the slice `arr` here: - let arr = vec::mut_slice(array, idx, size); - let mut run_len: uint = count_run_ascending(arr); - - if run_len < min_run { - let force = if remaining <= min_run {remaining} else {min_run}; - let slice = vec::mut_slice(arr, 0, force); - binarysort(slice, run_len); - run_len = force; - } - - run_len - }; - - ms.push_run(idx, run_len); - ms.merge_collapse(array); - - idx += run_len; - remaining -= run_len; - if remaining == 0 { break; } - } - - ms.merge_force_collapse(array); -} - -fn binarysort(array: &mut [T], start: uint) { - let size = array.len(); - let mut start = start; - assert!(start <= size); - - if start == 0 { start += 1; } - - while start < size { - let pivot = array[start]; - let mut left = 0; - let mut right = start; - assert!(left <= right); - - while left < right { - let mid = (left + right) >> 1; - if pivot < array[mid] { - right = mid; - } else { - left = mid+1; - } - } - assert_eq!(left, right); - let n = start-left; - - copy_vec(array, left+1, array, left, n); - array[left] = pivot; - start += 1; - } -} - -// Reverse the order of elements in a slice, in place -fn reverse_slice(v: &mut [T], start: uint, end:uint) { - let mut i = start; - while i < end / 2 { - vec::swap(v, i, end - i - 1); - i += 1; - } -} - -fn min_run_length(n: uint) -> uint { - let mut n = n; - let mut r = 0; // becomes 1 if any 1 bits are shifted off - - while n >= MIN_MERGE { - r |= n & 1; - n >>= 1; - } - return n + r; -} - -fn count_run_ascending(array: &mut [T]) -> uint { - let size = array.len(); - assert!(size > 0); - if size == 1 { return 1; } - - let mut run = 2; - if array[1] < array[0] { - while run < size && array[run] < array[run-1] { - run += 1; - } - reverse_slice(array, 0, run); - } else { - while run < size && array[run] >= array[run-1] { - run += 1; - } - } - - return run; -} - -fn gallop_left(key: &const T, - array: &const [T], - hint: uint) - -> uint { - let size = array.len(); - assert!(size != 0 && hint < size); - - let mut last_ofs = 0; - let mut ofs = 1; - - if *key > array[hint] { - // Gallop right until array[hint+last_ofs] < key <= array[hint+ofs] - let max_ofs = size - hint; - while ofs < max_ofs && *key > array[hint+ofs] { - last_ofs = ofs; - ofs = (ofs << 1) + 1; - if ofs < last_ofs { ofs = max_ofs; } // uint overflow guard - } - if ofs > max_ofs { ofs = max_ofs; } - - last_ofs += hint; - ofs += hint; - } else { - let max_ofs = hint + 1; - while ofs < max_ofs && *key <= array[hint-ofs] { - last_ofs = ofs; - ofs = (ofs << 1) + 1; - if ofs < last_ofs { ofs = max_ofs; } // uint overflow guard - } - - if ofs > max_ofs { ofs = max_ofs; } - - let tmp = last_ofs; - last_ofs = hint - ofs; - ofs = hint - tmp; - } - assert!((last_ofs < ofs || last_ofs+1 < ofs+1) && ofs <= size); - - last_ofs += 1; - while last_ofs < ofs { - let m = last_ofs + ((ofs - last_ofs) >> 1); - if *key > array[m] { - last_ofs = m+1; - } else { - ofs = m; - } - } - assert_eq!(last_ofs, ofs); - return ofs; -} - -fn gallop_right(key: &const T, - array: &const [T], - hint: uint) - -> uint { - let size = array.len(); - assert!(size != 0 && hint < size); - - let mut last_ofs = 0; - let mut ofs = 1; - - if *key >= array[hint] { - // Gallop right until array[hint+last_ofs] <= key < array[hint+ofs] - let max_ofs = size - hint; - while ofs < max_ofs && *key >= array[hint+ofs] { - last_ofs = ofs; - ofs = (ofs << 1) + 1; - if ofs < last_ofs { ofs = max_ofs; } - } - if ofs > max_ofs { ofs = max_ofs; } - - last_ofs += hint; - ofs += hint; - } else { - // Gallop left until array[hint-ofs] <= key < array[hint-last_ofs] - let max_ofs = hint + 1; - while ofs < max_ofs && *key < array[hint-ofs] { - last_ofs = ofs; - ofs = (ofs << 1) + 1; - if ofs < last_ofs { ofs = max_ofs; } - } - if ofs > max_ofs { ofs = max_ofs; } - - let tmp = last_ofs; - last_ofs = hint - ofs; - ofs = hint - tmp; - } - - assert!((last_ofs < ofs || last_ofs+1 < ofs+1) && ofs <= size); - - last_ofs += 1; - while last_ofs < ofs { - let m = last_ofs + ((ofs - last_ofs) >> 1); - - if *key >= array[m] { - last_ofs = m + 1; - } else { - ofs = m; - } - } - assert_eq!(last_ofs, ofs); - return ofs; -} - -struct RunState { - base: uint, - len: uint, -} - -struct MergeState { - min_gallop: uint, - runs: ~[RunState], -} - -// Fixme (#3853) Move into MergeState -fn MergeState() -> MergeState { - MergeState { - min_gallop: MIN_GALLOP, - runs: ~[], - } -} - -impl MergeState { - fn push_run(&mut self, run_base: uint, run_len: uint) { - let tmp = RunState{base: run_base, len: run_len}; - self.runs.push(tmp); - } - - fn merge_at(&mut self, n: uint, array: &mut [T]) { - let size = self.runs.len(); - assert!(size >= 2); - assert!(n == size-2 || n == size-3); - - let mut b1 = self.runs[n].base; - let mut l1 = self.runs[n].len; - let b2 = self.runs[n+1].base; - let l2 = self.runs[n+1].len; - - assert!(l1 > 0 && l2 > 0); - assert_eq!(b1 + l1, b2); - - self.runs[n].len = l1 + l2; - if n == size-3 { - self.runs[n+1].base = self.runs[n+2].base; - self.runs[n+1].len = self.runs[n+2].len; - } - - let k = { // constrain lifetime of slice below - let slice = vec::mut_slice(array, b1, b1+l1); - gallop_right(&const array[b2], slice, 0) - }; - b1 += k; - l1 -= k; - if l1 != 0 { - let l2 = { // constrain lifetime of slice below - let slice = vec::mut_slice(array, b2, b2+l2); - gallop_left(&const array[b1+l1-1],slice,l2-1) - }; - if l2 > 0 { - if l1 <= l2 { - self.merge_lo(array, b1, l1, b2, l2); - } else { - self.merge_hi(array, b1, l1, b2, l2); - } - } - } - self.runs.pop(); - } - - fn merge_lo(&mut self, array: &mut [T], base1: uint, len1: uint, - base2: uint, len2: uint) { - assert!(len1 != 0 && len2 != 0 && base1+len1 == base2); - - let mut tmp = ~[]; - for uint::range(base1, base1+len1) |i| { - tmp.push(array[i]); - } - - let mut c1 = 0; - let mut c2 = base2; - let mut dest = base1; - let mut len1 = len1; - let mut len2 = len2; - - vec::swap(array, dest, c2); - dest += 1; c2 += 1; len2 -= 1; - - if len2 == 0 { - copy_vec(array, dest, tmp, 0, len1); - return; - } - if len1 == 1 { - copy_vec(array, dest, array, c2, len2); - util::swap(&mut array[dest+len2], &mut tmp[c1]); - return; - } - - let mut min_gallop = self.min_gallop; - loop { - let mut count1 = 0; - let mut count2 = 0; - let mut break_outer = false; - - loop { - assert!(len1 > 1 && len2 != 0); - if array[c2] < tmp[c1] { - vec::swap(array, dest, c2); - dest += 1; c2 += 1; len2 -= 1; - count2 += 1; count1 = 0; - if len2 == 0 { - break_outer = true; - } - } else { - util::swap(&mut array[dest], &mut tmp[c1]); - dest += 1; c1 += 1; len1 -= 1; - count1 += 1; count2 = 0; - if len1 == 1 { - break_outer = true; - } - } - if break_outer || ((count1 | count2) >= min_gallop) { - break; - } - } - if break_outer { break; } - - // Start to gallop - loop { - assert!(len1 > 1 && len2 != 0); - - let tmp_view = vec::const_slice(tmp, c1, c1+len1); - count1 = gallop_right(&const array[c2], tmp_view, 0); - if count1 != 0 { - copy_vec(array, dest, tmp, c1, count1); - dest += count1; c1 += count1; len1 -= count1; - if len1 <= 1 { break_outer = true; break; } - } - vec::swap(array, dest, c2); - dest += 1; c2 += 1; len2 -= 1; - if len2 == 0 { break_outer = true; break; } - - let tmp_view = vec::const_slice(array, c2, c2+len2); - count2 = gallop_left(&const tmp[c1], tmp_view, 0); - if count2 != 0 { - copy_vec(array, dest, array, c2, count2); - dest += count2; c2 += count2; len2 -= count2; - if len2 == 0 { break_outer = true; break; } - } - util::swap(&mut array[dest], &mut tmp[c1]); - dest += 1; c1 += 1; len1 -= 1; - if len1 == 1 { break_outer = true; break; } - min_gallop -= 1; - if !(count1 >= MIN_GALLOP || count2 >= MIN_GALLOP) { - break; - } - } - if break_outer { break; } - if min_gallop < 0 { min_gallop = 0; } - min_gallop += 2; // Penalize for leaving gallop - } - self.min_gallop = if min_gallop < 1 { 1 } else { min_gallop }; - - if len1 == 1 { - assert!(len2 > 0); - copy_vec(array, dest, array, c2, len2); - util::swap(&mut array[dest+len2], &mut tmp[c1]); - } else if len1 == 0 { - fail!("Comparison violates its contract!"); - } else { - assert_eq!(len2, 0); - assert!(len1 > 1); - copy_vec(array, dest, tmp, c1, len1); - } - } - - fn merge_hi(&mut self, array: &mut [T], base1: uint, len1: uint, - base2: uint, len2: uint) { - assert!(len1 != 1 && len2 != 0 && base1+len1 == base2); - - let mut tmp = ~[]; - for uint::range(base2, base2+len2) |i| { - tmp.push(array[i]); - } - - let mut c1 = base1 + len1 - 1; - let mut c2 = len2 - 1; - let mut dest = base2 + len2 - 1; - let mut len1 = len1; - let mut len2 = len2; - - vec::swap(array, dest, c1); - dest -= 1; c1 -= 1; len1 -= 1; - - if len1 == 0 { - copy_vec(array, dest-(len2-1), tmp, 0, len2); - return; - } - if len2 == 1 { - dest -= len1; - c1 -= len1; - copy_vec(array, dest+1, array, c1+1, len1); - util::swap(&mut array[dest], &mut tmp[c2]); - return; - } - - let mut min_gallop = self.min_gallop; - loop { - let mut count1 = 0; - let mut count2 = 0; - let mut break_outer = false; - - loop { - assert!(len1 != 0 && len2 > 1); - if tmp[c2] < array[c1] { - vec::swap(array, dest, c1); - dest -= 1; c1 -= 1; len1 -= 1; - count1 += 1; count2 = 0; - if len1 == 0 { - break_outer = true; - } - } else { - util::swap(&mut array[dest], &mut tmp[c2]); - dest -= 1; c2 -= 1; len2 -= 1; - count2 += 1; count1 = 0; - if len2 == 1 { - break_outer = true; - } - } - if break_outer || ((count1 | count2) >= min_gallop) { - break; - } - } - if break_outer { break; } - - // Start to gallop - loop { - assert!(len2 > 1 && len1 != 0); - - { // constrain scope of tmp_view: - let tmp_view = vec::mut_slice (array, base1, base1+len1); - count1 = len1 - gallop_right( - &const tmp[c2], tmp_view, len1-1); - } - - if count1 != 0 { - dest -= count1; c1 -= count1; len1 -= count1; - copy_vec(array, dest+1, array, c1+1, count1); - if len1 == 0 { break_outer = true; break; } - } - - util::swap(&mut array[dest], &mut tmp[c2]); - dest -= 1; c2 -= 1; len2 -= 1; - if len2 == 1 { break_outer = true; break; } - - let count2; - { // constrain scope of tmp_view - let tmp_view = vec::mut_slice(tmp, 0, len2); - count2 = len2 - gallop_left(&const array[c1], - tmp_view, - len2-1); - } - - if count2 != 0 { - dest -= count2; c2 -= count2; len2 -= count2; - copy_vec(array, dest+1, tmp, c2+1, count2); - if len2 <= 1 { break_outer = true; break; } - } - vec::swap(array, dest, c1); - dest -= 1; c1 -= 1; len1 -= 1; - if len1 == 0 { break_outer = true; break; } - min_gallop -= 1; - if !(count1 >= MIN_GALLOP || count2 >= MIN_GALLOP) { - break; - } - } - - if break_outer { break; } - if min_gallop < 0 { min_gallop = 0; } - min_gallop += 2; // Penalize for leaving gallop - } - self.min_gallop = if min_gallop < 1 { 1 } else { min_gallop }; - - if len2 == 1 { - assert!(len1 > 0); - dest -= len1; - c1 -= len1; - copy_vec(array, dest+1, array, c1+1, len1); - util::swap(&mut array[dest], &mut tmp[c2]); - } else if len2 == 0 { - fail!("Comparison violates its contract!"); - } else { - assert_eq!(len1, 0); - assert!(len2 != 0); - copy_vec(array, dest-(len2-1), tmp, 0, len2); - } - } - - fn merge_collapse(&mut self, array: &mut [T]) { - while self.runs.len() > 1 { - let mut n = self.runs.len()-2; - if n > 0 && - self.runs[n-1].len <= self.runs[n].len + self.runs[n+1].len - { - if self.runs[n-1].len < self.runs[n+1].len { n -= 1; } - } else if self.runs[n].len <= self.runs[n+1].len { - /* keep going */ - } else { - break; - } - self.merge_at(n, array); - } - } - - fn merge_force_collapse(&mut self, array: &mut [T]) { - while self.runs.len() > 1 { - let mut n = self.runs.len()-2; - if n > 0 { - if self.runs[n-1].len < self.runs[n+1].len { - n -= 1; - } - } - self.merge_at(n, array); - } - } -} - -#[inline(always)] -fn copy_vec(dest: &mut [T], - s1: uint, - from: &const [T], - s2: uint, - len: uint) { - assert!(s1+len <= dest.len() && s2+len <= from.len()); - - let mut slice = ~[]; - for uint::range(s2, s2+len) |i| { - slice.push(from[i]); - } - - for slice.eachi |i, v| { - dest[s1+i] = *v; - } -} - -#[cfg(test)] -mod test_qsort3 { - use sort::*; - - use core::vec; - - fn check_sort(v1: &mut [int], v2: &mut [int]) { - let len = vec::len::(v1); - quick_sort3::(v1); - let mut i = 0; - while i < len { - // debug!(v2[i]); - assert_eq!(v2[i], v1[i]); - i += 1; - } - } - - #[test] - fn test() { - { - let mut v1 = ~[3, 7, 4, 5, 2, 9, 5, 8]; - let mut v2 = ~[2, 3, 4, 5, 5, 7, 8, 9]; - check_sort(v1, v2); - } - { - let mut v1 = ~[1, 1, 1]; - let mut v2 = ~[1, 1, 1]; - check_sort(v1, v2); - } - { - let mut v1: ~[int] = ~[]; - let mut v2: ~[int] = ~[]; - check_sort(v1, v2); - } - { let mut v1 = ~[9]; let mut v2 = ~[9]; check_sort(v1, v2); } - { - let mut v1 = ~[9, 3, 3, 3, 9]; - let mut v2 = ~[3, 3, 3, 9, 9]; - check_sort(v1, v2); - } - } -} - -#[cfg(test)] -mod test_qsort { - use sort::*; - - use core::int; - use core::vec; - - fn check_sort(v1: &mut [int], v2: &mut [int]) { - let len = vec::len::(v1); - fn leual(a: &int, b: &int) -> bool { *a <= *b } - quick_sort::(v1, leual); - let mut i = 0u; - while i < len { - // debug!(v2[i]); - assert_eq!(v2[i], v1[i]); - i += 1; - } - } - - #[test] - fn test() { - { - let mut v1 = ~[3, 7, 4, 5, 2, 9, 5, 8]; - let mut v2 = ~[2, 3, 4, 5, 5, 7, 8, 9]; - check_sort(v1, v2); - } - { - let mut v1 = ~[1, 1, 1]; - let mut v2 = ~[1, 1, 1]; - check_sort(v1, v2); - } - { - let mut v1: ~[int] = ~[]; - let mut v2: ~[int] = ~[]; - check_sort(v1, v2); - } - { let mut v1 = ~[9]; let mut v2 = ~[9]; check_sort(v1, v2); } - { - let mut v1 = ~[9, 3, 3, 3, 9]; - let mut v2 = ~[3, 3, 3, 9, 9]; - check_sort(v1, v2); - } - } - - // Regression test for #750 - #[test] - fn test_simple() { - let mut names = ~[2, 1, 3]; - - let expected = ~[1, 2, 3]; - - do quick_sort(names) |x, y| { int::le(*x, *y) }; - - let immut_names = names; - - let pairs = vec::zip_slice(expected, immut_names); - for pairs.each |p| { - let (a, b) = *p; - debug!("%d %d", a, b); - assert_eq!(a, b); - } - } -} - -#[cfg(test)] -mod tests { - - use sort::*; - - use core::vec; - - fn check_sort(v1: &[int], v2: &[int]) { - let len = vec::len::(v1); - pub fn le(a: &int, b: &int) -> bool { *a <= *b } - let f = le; - let v3 = merge_sort::(v1, f); - let mut i = 0u; - while i < len { - debug!(v3[i]); - assert_eq!(v3[i], v2[i]); - i += 1; - } - } - - #[test] - fn test() { - { - let v1 = ~[3, 7, 4, 5, 2, 9, 5, 8]; - let v2 = ~[2, 3, 4, 5, 5, 7, 8, 9]; - check_sort(v1, v2); - } - { let v1 = ~[1, 1, 1]; let v2 = ~[1, 1, 1]; check_sort(v1, v2); } - { let v1:~[int] = ~[]; let v2:~[int] = ~[]; check_sort(v1, v2); } - { let v1 = ~[9]; let v2 = ~[9]; check_sort(v1, v2); } - { - let v1 = ~[9, 3, 3, 3, 9]; - let v2 = ~[3, 3, 3, 9, 9]; - check_sort(v1, v2); - } - } - - #[test] - fn test_merge_sort_mutable() { - pub fn le(a: &int, b: &int) -> bool { *a <= *b } - let mut v1 = ~[3, 2, 1]; - let v2 = merge_sort(v1, le); - assert_eq!(v2, ~[1, 2, 3]); - } - - #[test] - fn test_merge_sort_stability() { - // tjc: funny that we have to use parens - fn ile(x: &(&'static str), y: &(&'static str)) -> bool - { - // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use - // to_ascii_consume and to_str_consume to not do a unnecessary copy. - // (Actually, could just remove the to_str_* call, but needs an deriving(Ord) on - // Ascii) - let x = x.to_ascii().to_lower().to_str_ascii(); - let y = y.to_ascii().to_lower().to_str_ascii(); - x <= y - } - - let names1 = ~["joe bob", "Joe Bob", "Jack Brown", "JOE Bob", - "Sally Mae", "JOE BOB", "Alex Andy"]; - let names2 = ~["Alex Andy", "Jack Brown", "joe bob", "Joe Bob", - "JOE Bob", "JOE BOB", "Sally Mae"]; - let names3 = merge_sort(names1, ile); - assert_eq!(names3, names2); - } -} - -#[cfg(test)] -mod test_tim_sort { - use sort::tim_sort; - use core::rand::RngUtil; - - struct CVal { - val: float, - } - - impl Ord for CVal { - fn lt(&self, other: &CVal) -> bool { - let rng = rand::rng(); - if rng.gen::() > 0.995 { fail!("It's happening!!!"); } - (*self).val < other.val - } - fn le(&self, other: &CVal) -> bool { (*self).val <= other.val } - fn gt(&self, other: &CVal) -> bool { (*self).val > other.val } - fn ge(&self, other: &CVal) -> bool { (*self).val >= other.val } - } - - fn check_sort(v1: &mut [int], v2: &mut [int]) { - let len = vec::len::(v1); - tim_sort::(v1); - let mut i = 0u; - while i < len { - // debug!(v2[i]); - assert_eq!(v2[i], v1[i]); - i += 1u; - } - } - - #[test] - fn test() { - { - let mut v1 = ~[3, 7, 4, 5, 2, 9, 5, 8]; - let mut v2 = ~[2, 3, 4, 5, 5, 7, 8, 9]; - check_sort(v1, v2); - } - { - let mut v1 = ~[1, 1, 1]; - let mut v2 = ~[1, 1, 1]; - check_sort(v1, v2); - } - { - let mut v1: ~[int] = ~[]; - let mut v2: ~[int] = ~[]; - check_sort(v1, v2); - } - { let mut v1 = ~[9]; let mut v2 = ~[9]; check_sort(v1, v2); } - { - let mut v1 = ~[9, 3, 3, 3, 9]; - let mut v2 = ~[3, 3, 3, 9, 9]; - check_sort(v1, v2); - } - } - - #[test] - #[should_fail] - #[cfg(unix)] - fn crash_test() { - let rng = rand::rng(); - let mut arr = do vec::from_fn(1000) |_i| { - CVal { val: rng.gen() } - }; - - tim_sort(arr); - fail!("Guarantee the fail"); - } - - struct DVal { val: uint } - - impl Ord for DVal { - fn lt(&self, _x: &DVal) -> bool { true } - fn le(&self, _x: &DVal) -> bool { true } - fn gt(&self, _x: &DVal) -> bool { true } - fn ge(&self, _x: &DVal) -> bool { true } - } - - #[test] - fn test_bad_Ord_impl() { - let rng = rand::rng(); - let mut arr = do vec::from_fn(500) |_i| { - DVal { val: rng.gen() } - }; - - tim_sort(arr); - } -} - -#[cfg(test)] -mod big_tests { - use sort::*; - use core::rand::RngUtil; - - #[test] - fn test_unique() { - let low = 5; - let high = 10; - tabulate_unique(low, high); - } - - #[test] - fn test_managed() { - let low = 5; - let high = 10; - tabulate_managed(low, high); - } - - fn multiplyVec(arr: &const [T], num: uint) -> ~[T] { - let size = arr.len(); - let res = do vec::from_fn(num) |i| { - arr[i % size] - }; - res - } - - fn makeRange(n: uint) -> ~[uint] { - let one = do vec::from_fn(n) |i| { i }; - let mut two = copy one; - vec::reverse(two); - vec::append(two, one) - } - - fn tabulate_unique(lo: uint, hi: uint) { - fn isSorted(arr: &const [T]) { - for uint::range(0, arr.len()-1) |i| { - if arr[i] > arr[i+1] { - fail!("Array not sorted"); - } - } - } - - let rng = rand::rng(); - - for uint::range(lo, hi) |i| { - let n = 1 << i; - let mut arr: ~[float] = do vec::from_fn(n) |_i| { - rng.gen() - }; - - tim_sort(arr); // *sort - isSorted(arr); - - vec::reverse(arr); - tim_sort(arr); // \sort - isSorted(arr); - - tim_sort(arr); // /sort - isSorted(arr); - - for 3.times { - let i1 = rng.gen_uint_range(0, n); - let i2 = rng.gen_uint_range(0, n); - vec::swap(arr, i1, i2); - } - tim_sort(arr); // 3sort - isSorted(arr); - - if n >= 10 { - let size = arr.len(); - let mut idx = 1; - while idx <= 10 { - arr[size-idx] = rng.gen(); - idx += 1; - } - } - tim_sort(arr); // +sort - isSorted(arr); - - for (n/100).times { - let idx = rng.gen_uint_range(0, n); - arr[idx] = rng.gen(); - } - tim_sort(arr); - isSorted(arr); - - let mut arr = if n > 4 { - let part = vec::slice(arr, 0, 4); - multiplyVec(part, n) - } else { arr }; - tim_sort(arr); // ~sort - isSorted(arr); - - let mut arr = vec::from_elem(n, -0.5); - tim_sort(arr); // =sort - isSorted(arr); - - let half = n / 2; - let mut arr = makeRange(half).map(|i| *i as float); - tim_sort(arr); // !sort - isSorted(arr); - } - } - - fn tabulate_managed(lo: uint, hi: uint) { - fn isSorted(arr: &const [@T]) { - for uint::range(0, arr.len()-1) |i| { - if arr[i] > arr[i+1] { - fail!("Array not sorted"); - } - } - } - - let rng = rand::rng(); - - for uint::range(lo, hi) |i| { - let n = 1 << i; - let arr: ~[@float] = do vec::from_fn(n) |_i| { - @rng.gen() - }; - let mut arr = arr; - - tim_sort(arr); // *sort - isSorted(arr); - - vec::reverse(arr); - tim_sort(arr); // \sort - isSorted(arr); - - tim_sort(arr); // /sort - isSorted(arr); - - for 3.times { - let i1 = rng.gen_uint_range(0, n); - let i2 = rng.gen_uint_range(0, n); - vec::swap(arr, i1, i2); - } - tim_sort(arr); // 3sort - isSorted(arr); - - if n >= 10 { - let size = arr.len(); - let mut idx = 1; - while idx <= 10 { - arr[size-idx] = @rng.gen(); - idx += 1; - } - } - tim_sort(arr); // +sort - isSorted(arr); - - for (n/100).times { - let idx = rng.gen_uint_range(0, n); - arr[idx] = @rng.gen(); - } - tim_sort(arr); - isSorted(arr); - - let mut arr = if n > 4 { - let part = vec::slice(arr, 0, 4); - multiplyVec(part, n) - } else { arr }; - tim_sort(arr); // ~sort - isSorted(arr); - - let mut arr = vec::from_elem(n, @(-0.5)); - tim_sort(arr); // =sort - isSorted(arr); - - let half = n / 2; - let mut arr = makeRange(half).map(|i| @(*i as float)); - tim_sort(arr); // !sort - isSorted(arr); - } - } - - struct LVal<'self> { - val: uint, - key: &'self fn(@uint), - } - - #[unsafe_destructor] - impl<'self> Drop for LVal<'self> { - fn finalize(&self) { - let x = unsafe { local_data::local_data_get(self.key) }; - match x { - Some(@y) => { - unsafe { - local_data::local_data_set(self.key, @(y+1)); - } - } - _ => fail!("Expected key to work"), - } - } - } - - impl<'self> Ord for LVal<'self> { - fn lt<'a>(&self, other: &'a LVal<'self>) -> bool { - (*self).val < other.val - } - fn le<'a>(&self, other: &'a LVal<'self>) -> bool { - (*self).val <= other.val - } - fn gt<'a>(&self, other: &'a LVal<'self>) -> bool { - (*self).val > other.val - } - fn ge<'a>(&self, other: &'a LVal<'self>) -> bool { - (*self).val >= other.val - } - } -} - -// Local Variables: -// mode: rust; -// fill-column: 78; -// indent-tabs-mode: nil -// c-basic-offset: 4 -// buffer-file-coding-system: utf-8-unix -// End: diff --git a/src/libstd/std.rc b/src/libstd/std.rc index d29791449b61c..72f06f0befa25 100644 --- a/src/libstd/std.rc +++ b/src/libstd/std.rc @@ -63,18 +63,12 @@ pub mod flatpipes; pub mod bitv; pub mod deque; -#[cfg(not(stage0))] pub mod fun_treemap; pub mod list; pub mod priority_queue; pub mod rope; pub mod smallintmap; -#[cfg(stage0)] -#[path="sort_stage0.rs"] -pub mod sort; - -#[cfg(not(stage0))] pub mod sort; pub mod dlist; diff --git a/src/libstd/treemap.rs b/src/libstd/treemap.rs index e4026d7306ffe..93f8d06ee0836 100644 --- a/src/libstd/treemap.rs +++ b/src/libstd/treemap.rs @@ -105,45 +105,21 @@ impl Map for TreeMap { } /// Visit all key-value pairs in order - #[cfg(stage0)] - fn each<'a>(&'a self, f: &fn(&'a K, &'a V) -> bool) { - each(&self.root, f); - } - /// Visit all key-value pairs in order - #[cfg(not(stage0))] fn each<'a>(&'a self, f: &fn(&'a K, &'a V) -> bool) -> bool { each(&self.root, f) } /// Visit all keys in order - #[cfg(stage0)] - fn each_key(&self, f: &fn(&K) -> bool) { - self.each(|k, _| f(k)) - } - /// Visit all keys in order - #[cfg(not(stage0))] fn each_key(&self, f: &fn(&K) -> bool) -> bool { self.each(|k, _| f(k)) } /// Visit all values in order - #[cfg(stage0)] - fn each_value<'a>(&'a self, f: &fn(&'a V) -> bool) { - self.each(|_, v| f(v)) - } - /// Visit all values in order - #[cfg(not(stage0))] fn each_value<'a>(&'a self, f: &fn(&'a V) -> bool) -> bool { self.each(|_, v| f(v)) } /// Iterate over the map and mutate the contained values - #[cfg(stage0)] - fn mutate_values(&mut self, f: &fn(&K, &mut V) -> bool) { - mutate_values(&mut self.root, f); - } - /// Iterate over the map and mutate the contained values - #[cfg(not(stage0))] fn mutate_values(&mut self, f: &fn(&K, &mut V) -> bool) -> bool { mutate_values(&mut self.root, f) } @@ -201,33 +177,6 @@ impl Map for TreeMap { } } -#[cfg(stage0)] -pub impl TreeMap { - /// Create an empty TreeMap - fn new() -> TreeMap { TreeMap{root: None, length: 0} } - - /// Visit all key-value pairs in reverse order - fn each_reverse<'a>(&'a self, f: &fn(&'a K, &'a V) -> bool) { - each_reverse(&self.root, f); - } - - /// Visit all keys in reverse order - fn each_key_reverse(&self, f: &fn(&K) -> bool) { - self.each_reverse(|k, _| f(k)) - } - - /// Visit all values in reverse order - fn each_value_reverse(&self, f: &fn(&V) -> bool) { - self.each_reverse(|_, v| f(v)) - } - - /// Get a lazy iterator over the key-value pairs in the map. - /// Requires that it be frozen (immutable). - fn iter<'a>(&'a self) -> TreeMapIterator<'a, K, V> { - TreeMapIterator{stack: ~[], node: &self.root} - } -} -#[cfg(not(stage0))] pub impl TreeMap { /// Create an empty TreeMap fn new() -> TreeMap { TreeMap{root: None, length: 0} } @@ -297,11 +246,6 @@ pub struct TreeSet { impl BaseIter for TreeSet { /// Visit all values in order #[inline(always)] - #[cfg(stage0)] - fn each(&self, f: &fn(&T) -> bool) { self.map.each_key(f) } - /// Visit all values in order - #[inline(always)] - #[cfg(not(stage0))] fn each(&self, f: &fn(&T) -> bool) -> bool { self.map.each_key(f) } #[inline(always)] fn size_hint(&self) -> Option { Some(self.len()) } @@ -309,13 +253,6 @@ impl BaseIter for TreeSet { impl ReverseIter for TreeSet { /// Visit all values in reverse order - #[cfg(stage0)] - #[inline(always)] - fn each_reverse(&self, f: &fn(&T) -> bool) { - self.map.each_key_reverse(f) - } - /// Visit all values in reverse order - #[cfg(not(stage0))] #[inline(always)] fn each_reverse(&self, f: &fn(&T) -> bool) -> bool { self.map.each_key_reverse(f) @@ -424,37 +361,6 @@ impl Set for TreeSet { } /// Visit the values (in-order) representing the difference - #[cfg(stage0)] - fn difference(&self, other: &TreeSet, f: &fn(&T) -> bool) { - let mut x = self.iter(); - let mut y = other.iter(); - - let mut a = x.next(); - let mut b = y.next(); - - while a.is_some() { - if b.is_none() { - return do a.while_some() |a1| { - if f(a1) { x.next() } else { None } - } - } - - let a1 = a.unwrap(); - let b1 = b.unwrap(); - - let cmp = a1.cmp(b1); - - if cmp == Less { - if !f(a1) { return } - a = x.next(); - } else { - if cmp == Equal { a = x.next() } - b = y.next(); - } - } - } - /// Visit the values (in-order) representing the difference - #[cfg(not(stage0))] fn difference(&self, other: &TreeSet, f: &fn(&T) -> bool) -> bool { let mut x = self.iter(); let mut y = other.iter(); @@ -484,45 +390,6 @@ impl Set for TreeSet { } /// Visit the values (in-order) representing the symmetric difference - #[cfg(stage0)] - fn symmetric_difference(&self, other: &TreeSet, - f: &fn(&T) -> bool) { - let mut x = self.iter(); - let mut y = other.iter(); - - let mut a = x.next(); - let mut b = y.next(); - - while a.is_some() { - if b.is_none() { - return do a.while_some() |a1| { - if f(a1) { x.next() } else { None } - } - } - - let a1 = a.unwrap(); - let b1 = b.unwrap(); - - let cmp = a1.cmp(b1); - - if cmp == Less { - if !f(a1) { return } - a = x.next(); - } else { - if cmp == Greater { - if !f(b1) { return } - } else { - a = x.next(); - } - b = y.next(); - } - } - do b.while_some |b1| { - if f(b1) { y.next() } else { None } - } - } - /// Visit the values (in-order) representing the symmetric difference - #[cfg(not(stage0))] fn symmetric_difference(&self, other: &TreeSet, f: &fn(&T) -> bool) -> bool { let mut x = self.iter(); @@ -557,32 +424,6 @@ impl Set for TreeSet { } /// Visit the values (in-order) representing the intersection - #[cfg(stage0)] - fn intersection(&self, other: &TreeSet, f: &fn(&T) -> bool) { - let mut x = self.iter(); - let mut y = other.iter(); - - let mut a = x.next(); - let mut b = y.next(); - - while a.is_some() && b.is_some() { - let a1 = a.unwrap(); - let b1 = b.unwrap(); - - let cmp = a1.cmp(b1); - - if cmp == Less { - a = x.next(); - } else { - if cmp == Equal { - if !f(a1) { return } - } - b = y.next(); - } - } - } - /// Visit the values (in-order) representing the intersection - #[cfg(not(stage0))] fn intersection(&self, other: &TreeSet, f: &fn(&T) -> bool) -> bool { let mut x = self.iter(); let mut y = other.iter(); @@ -609,43 +450,6 @@ impl Set for TreeSet { } /// Visit the values (in-order) representing the union - #[cfg(stage0)] - fn union(&self, other: &TreeSet, f: &fn(&T) -> bool) { - let mut x = self.iter(); - let mut y = other.iter(); - - let mut a = x.next(); - let mut b = y.next(); - - while a.is_some() { - if b.is_none() { - return do a.while_some() |a1| { - if f(a1) { x.next() } else { None } - } - } - - let a1 = a.unwrap(); - let b1 = b.unwrap(); - - let cmp = a1.cmp(b1); - - if cmp == Greater { - if !f(b1) { return } - b = y.next(); - } else { - if !f(a1) { return } - if cmp == Equal { - b = y.next(); - } - a = x.next(); - } - } - do b.while_some |b1| { - if f(b1) { y.next() } else { None } - } - } - /// Visit the values (in-order) representing the union - #[cfg(not(stage0))] fn union(&self, other: &TreeSet, f: &fn(&T) -> bool) -> bool { let mut x = self.iter(); let mut y = other.iter(); @@ -713,24 +517,12 @@ pub impl TreeNode { } } -#[cfg(stage0)] -fn each<'r, K: TotalOrd, V>(_: &'r Option<~TreeNode>, - _: &fn(&'r K, &'r V) -> bool) -> bool { - fail!("don't use me in stage0!") -} -#[cfg(not(stage0))] fn each<'r, K: TotalOrd, V>(node: &'r Option<~TreeNode>, f: &fn(&'r K, &'r V) -> bool) -> bool { node.each(|x| each(&x.left, f) && f(&x.key, &x.value) && each(&x.right, f)) } -#[cfg(stage0)] -fn each_reverse<'r, K: TotalOrd, V>(_: &'r Option<~TreeNode>, - _: &fn(&'r K, &'r V) -> bool) -> bool { - fail!("don't use me in stage0!") -} -#[cfg(not(stage0))] fn each_reverse<'r, K: TotalOrd, V>(node: &'r Option<~TreeNode>, f: &fn(&'r K, &'r V) -> bool) -> bool { node.each(|x| each_reverse(&x.right, f) && f(&x.key, &x.value) && diff --git a/src/libstd/workcache.rs b/src/libstd/workcache.rs index 3889650d012e0..ee57bf2f3a1b5 100644 --- a/src/libstd/workcache.rs +++ b/src/libstd/workcache.rs @@ -97,17 +97,6 @@ struct WorkKey { name: ~str } -#[cfg(stage0)] -impl to_bytes::IterBytes for WorkKey { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - let mut flag = true; - self.kind.iter_bytes(lsb0, |bytes| {flag = f(bytes); flag}); - if !flag { return; } - self.name.iter_bytes(lsb0, f); - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for WorkKey { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 1b166dcf36618..e67b5d118d365 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -79,20 +79,6 @@ static AbiDatas: &'static [AbiData] = &[ AbiData {abi: RustIntrinsic, name: "rust-intrinsic", abi_arch: RustArch}, ]; -#[cfg(stage0)] -fn each_abi(op: &fn(abi: Abi) -> bool) { - /*! - * - * Iterates through each of the defined ABIs. - */ - - for AbiDatas.each |abi_data| { - if !op(abi_data.abi) { - return; - } - } -} -#[cfg(not(stage0))] fn each_abi(op: &fn(abi: Abi) -> bool) -> bool { /*! * @@ -197,17 +183,6 @@ pub impl AbiSet { self.bits |= (1 << abi.index()); } - #[cfg(stage0)] - fn each(&self, op: &fn(abi: Abi) -> bool) { - for each_abi |abi| { - if self.contains(abi) { - if !op(abi) { - return; - } - } - } - } - #[cfg(not(stage0))] fn each(&self, op: &fn(abi: Abi) -> bool) -> bool { each_abi(|abi| !self.contains(abi) || op(abi)) } @@ -265,26 +240,12 @@ pub impl AbiSet { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for Abi { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.index().iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for Abi { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { self.index().iter_bytes(lsb0, f) } } -#[cfg(stage0)] -impl to_bytes::IterBytes for AbiSet { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.bits.iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for AbiSet { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { self.bits.iter_bytes(lsb0, f) diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index dcbbd7ab53111..241450e7130a2 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -95,14 +95,6 @@ impl Decodable for ident { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for ident { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - self.repr.iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for ident { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { @@ -120,14 +112,6 @@ pub struct Lifetime { ident: ident } -#[cfg(stage0)] -impl to_bytes::IterBytes for Lifetime { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_3(&self.id, &self.span, &self.ident, lsb0, f) - } -} - -#[cfg(not(stage0))] impl to_bytes::IterBytes for Lifetime { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_3(&self.id, &self.span, &self.ident, lsb0, f) @@ -279,21 +263,6 @@ pub enum binding_mode { bind_infer } -#[cfg(stage0)] -impl to_bytes::IterBytes for binding_mode { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - bind_by_copy => 0u8.iter_bytes(lsb0, f), - - bind_by_ref(ref m) => - to_bytes::iter_bytes_2(&1u8, m, lsb0, f), - - bind_infer => - 2u8.iter_bytes(lsb0, f), - } - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for binding_mode { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { @@ -334,13 +303,6 @@ pub enum pat_ { #[deriving(Eq, Encodable, Decodable)] pub enum mutability { m_mutbl, m_imm, m_const, } -#[cfg(stage0)] -impl to_bytes::IterBytes for mutability { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for mutability { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as u8).iter_bytes(lsb0, f) @@ -354,13 +316,6 @@ pub enum Sigil { ManagedSigil } -#[cfg(stage0)] -impl to_bytes::IterBytes for Sigil { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as uint).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for Sigil { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as uint).iter_bytes(lsb0, f) @@ -718,13 +673,6 @@ impl ToStr for int_ty { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for int_ty { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for int_ty { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as u8).iter_bytes(lsb0, f) @@ -740,13 +688,6 @@ impl ToStr for uint_ty { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for uint_ty { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for uint_ty { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as u8).iter_bytes(lsb0, f) @@ -762,13 +703,6 @@ impl ToStr for float_ty { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for float_ty { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for float_ty { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as u8).iter_bytes(lsb0, f) @@ -808,13 +742,6 @@ impl ToStr for Onceness { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for Onceness { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as uint).iter_bytes(lsb0, f); - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for Onceness { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as uint).iter_bytes(lsb0, f) @@ -861,13 +788,6 @@ pub enum ty_ { ty_infer, } -#[cfg(stage0)] -impl to_bytes::IterBytes for Ty { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.span.lo, &self.span.hi, lsb0, f); - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for Ty { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_2(&self.span.lo, &self.span.hi, lsb0, f) @@ -925,13 +845,6 @@ impl ToStr for purity { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for purity { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for purity { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as u8).iter_bytes(lsb0, f) @@ -945,13 +858,6 @@ pub enum ret_style { return_val, // everything else } -#[cfg(stage0)] -impl to_bytes::IterBytes for ret_style { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as u8).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for ret_style { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (*self as u8).iter_bytes(lsb0, f) @@ -967,20 +873,6 @@ pub enum explicit_self_ { sty_uniq(mutability) // `~self` } -#[cfg(stage0)] -impl to_bytes::IterBytes for explicit_self_ { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - sty_static => 0u8.iter_bytes(lsb0, f), - sty_value => 1u8.iter_bytes(lsb0, f), - sty_region(ref lft, ref mutbl) => to_bytes::iter_bytes_3(&2u8, &lft, mutbl, lsb0, f), - sty_box(ref mutbl) => to_bytes::iter_bytes_2(&3u8, mutbl, lsb0, f), - sty_uniq(ref mutbl) => to_bytes::iter_bytes_2(&4u8, mutbl, lsb0, f), - } - } -} - -#[cfg(not(stage0))] impl to_bytes::IterBytes for explicit_self_ { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index d4a67d61d94b6..bb6d13b283118 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -191,15 +191,6 @@ pub fn is_call_expr(e: @expr) -> bool { } // This makes def_id hashable -#[cfg(stage0)] -impl to_bytes::IterBytes for def_id { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.crate, &self.node, lsb0, f); - } -} -// This makes def_id hashable -#[cfg(not(stage0))] impl to_bytes::IterBytes for def_id { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 61921fbf090f2..2e235982a0f92 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -65,13 +65,6 @@ impl Sub for BytePos { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for BytePos { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (**self).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for BytePos { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (**self).iter_bytes(lsb0, f) @@ -90,13 +83,6 @@ impl cmp::Ord for CharPos { fn gt(&self, other: &CharPos) -> bool { **self > **other } } -#[cfg(stage0)] -impl to_bytes::IterBytes for CharPos { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (**self).iter_bytes(lsb0, f) - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for CharPos { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { (**self).iter_bytes(lsb0, f) @@ -150,14 +136,6 @@ impl Decodable for span { } } -#[cfg(stage0)] -impl to_bytes::IterBytes for span { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_3(&self.lo, &self.hi, &self.expn_info, lsb0, f); - } -} - -#[cfg(not(stage0))] impl to_bytes::IterBytes for span { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_3(&self.lo, &self.hi, &self.expn_info, lsb0, f) @@ -211,14 +189,6 @@ pub struct FileMapAndLine {fm: @FileMap, line: uint} pub struct FileMapAndBytePos {fm: @FileMap, pos: BytePos} pub struct NameAndSpan {name: ~str, span: Option} -#[cfg(stage0)] -impl to_bytes::IterBytes for NameAndSpan { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.name, &self.span, lsb0, f) - } -} - -#[cfg(not(stage0))] impl to_bytes::IterBytes for NameAndSpan { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_2(&self.name, &self.span, lsb0, f) @@ -230,14 +200,6 @@ pub struct CallInfo { callee: NameAndSpan } -#[cfg(stage0)] -impl to_bytes::IterBytes for CallInfo { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - to_bytes::iter_bytes_2(&self.call_site, &self.callee, lsb0, f) - } -} - -#[cfg(not(stage0))] impl to_bytes::IterBytes for CallInfo { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { to_bytes::iter_bytes_2(&self.call_site, &self.callee, lsb0, f) @@ -249,16 +211,6 @@ pub enum ExpnInfo { ExpandedFrom(CallInfo) } -#[cfg(stage0)] -impl to_bytes::IterBytes for ExpnInfo { - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - match *self { - ExpandedFrom(ref call_info) => to_bytes::iter_bytes_2(&0u8, call_info, lsb0, f) - } - } -} - -#[cfg(not(stage0))] impl to_bytes::IterBytes for ExpnInfo { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { diff --git a/src/libsyntax/ext/pipes/proto.rs b/src/libsyntax/ext/pipes/proto.rs index f897eb787e566..7bf58bc6f324c 100644 --- a/src/libsyntax/ext/pipes/proto.rs +++ b/src/libsyntax/ext/pipes/proto.rs @@ -100,21 +100,6 @@ pub impl state_ { /// Iterate over the states that can be reached in one message /// from this state. - #[cfg(stage0)] - fn reachable(&self, f: &fn(state) -> bool) { - for self.messages.each |m| { - match *m { - message(_, _, _, _, Some(next_state { state: ref id, _ })) => { - let state = self.proto.get_state((*id)); - if !f(state) { break } - } - _ => () - } - } - } - /// Iterate over the states that can be reached in one message - /// from this state. - #[cfg(not(stage0))] fn reachable(&self, f: &fn(state) -> bool) -> bool { for self.messages.each |m| { match *m { diff --git a/src/libsyntax/opt_vec.rs b/src/libsyntax/opt_vec.rs index fb3622396c951..db1e95d5ad510 100644 --- a/src/libsyntax/opt_vec.rs +++ b/src/libsyntax/opt_vec.rs @@ -131,14 +131,6 @@ impl Eq for OptVec { } impl BaseIter for OptVec { - #[cfg(stage0)] - fn each(&self, blk: &fn(v: &A) -> bool) { - match *self { - Empty => {} - Vec(ref v) => v.each(blk) - } - } - #[cfg(not(stage0))] fn each(&self, blk: &fn(v: &A) -> bool) -> bool { match *self { Empty => true, @@ -153,12 +145,6 @@ impl BaseIter for OptVec { impl old_iter::ExtendedIter for OptVec { #[inline(always)] - #[cfg(stage0)] - fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) { - old_iter::eachi(self, blk) - } - #[inline(always)] - #[cfg(not(stage0))] fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) -> bool { old_iter::eachi(self, blk) } diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 859fde90e2998..0ce3ab4b3e171 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -64,14 +64,6 @@ pub enum ObsoleteSyntax { ObsoleteNamedExternModule, } -#[cfg(stage0)] -impl to_bytes::IterBytes for ObsoleteSyntax { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (*self as uint).iter_bytes(lsb0, f); - } -} -#[cfg(not(stage0))] impl to_bytes::IterBytes for ObsoleteSyntax { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 36f241b64279a..88fa538908923 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -349,14 +349,6 @@ impl<'self> Equiv<@~str> for StringRef<'self> { fn equiv(&self, other: &@~str) -> bool { str::eq_slice(**self, **other) } } -#[cfg(stage0)] -impl<'self> to_bytes::IterBytes for StringRef<'self> { - #[inline(always)] - fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) { - (**self).iter_bytes(lsb0, f); - } -} -#[cfg(not(stage0))] impl<'self> to_bytes::IterBytes for StringRef<'self> { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { diff --git a/src/snapshots.txt b/src/snapshots.txt index c643b4dd25d43..a68d2205cfba8 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,11 @@ +S 2013-05-17 2d28d64 + macos-i386 abadafb33c9f858543351c822fb468195163559f + macos-x86_64 4a484693f73bcc8ce2a85708fd4f0c3f6e34969d + winnt-i386 558dac018b2b6dbb23841772e1f4b9591558850c + freebsd-x86_64 59ca6fc1eae2d160525c705928d551dd8993e01c + linux-i386 2d3e61efe30f55176c72b3dbe31d693630f59abd + linux-x86_64 86ecc1833df8e28d08ff3a9a952ec424abdcb157 + S 2013-05-03 213f7b2 macos-i386 0bf8b88ea01cc4cdd81ac4db1d301ea9b3371f13 macos-x86_64 2da3990639ab5a9c9d51b3478c437cb459de84e3 From a9c7d3f7757ee67fd5d068b0ebfb5a95d8e4d2cc Mon Sep 17 00:00:00 2001 From: Olivier Saut Date: Mon, 20 May 2013 12:06:37 +0200 Subject: [PATCH 115/248] Typo corrected and updated copyright years --- src/libstd/arc.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libstd/arc.rs b/src/libstd/arc.rs index f0158acfa79fa..8d50c3068785b 100644 --- a/src/libstd/arc.rs +++ b/src/libstd/arc.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -21,7 +21,7 @@ use core::unstable::sync::UnsafeAtomicRcBox; use core::ptr; use core::task; -/// As sync::condvar, a mechanism for unlock-and-descheduling and signalling. +/// As sync::condvar, a mechanism for unlock-and-descheduling and signaling. pub struct Condvar<'self> { is_mutex: bool, failed: &'self mut bool, From 3f232bc4a01d102599de0565ff769acdc06bac53 Mon Sep 17 00:00:00 2001 From: Olivier Saut Date: Mon, 20 May 2013 12:07:14 +0200 Subject: [PATCH 116/248] Add ARC::get method and implements the function from it. Add an example showing a simple use of ARC. --- src/libstd/arc.rs | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/src/libstd/arc.rs b/src/libstd/arc.rs index 8d50c3068785b..9c7db35f6f206 100644 --- a/src/libstd/arc.rs +++ b/src/libstd/arc.rs @@ -8,9 +8,33 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/** +/*! * Concurrency-enabled mechanisms for sharing mutable and/or immutable state * between tasks. + * + * # Example + * + * In this example, a large vector of floats is shared between several tasks. + * With simple pipes, without ARC, a copy would have to be made for each task. + * + * ~~~ + * extern mod std; + * use std::arc; + * let numbers=vec::from_fn(100, |ind| (ind as float)*rand::random()); + * let shared_numbers=arc::ARC(numbers); + * + * for 10.times { + * let (port, chan) = stream(); + * chan.send(shared_numbers.clone()); + * + * do spawn { + * let shared_numbers=port.recv(); + * let local_numbers=shared_numbers.get(); + * + * // Work with the local numbers + * } + * } + * ~~~ */ use sync; @@ -93,9 +117,14 @@ pub fn ARC(data: T) -> ARC { * wrapper. */ pub fn get<'a, T:Const + Owned>(rc: &'a ARC) -> &'a T { - unsafe { &*rc.x.get_immut() } + rc.get() } +impl ARC { + pub fn get<'a>(&'a self) -> &'a T { + unsafe { &*self.x.get_immut() } + } +} /** * Duplicate an atomically reference counted wrapper. * @@ -508,6 +537,7 @@ mod tests { c.send(arc::clone(&arc_v)); assert_eq!((*arc::get(&arc_v))[2], 3); + assert_eq!(arc_v.get()[4], 5); info!(arc_v); } From 09efd472a9ed60be6daa62d9339b0c5e6db92ee4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Steinbrink?= Date: Mon, 20 May 2013 11:51:43 +0200 Subject: [PATCH 117/248] Remove outdated function transmute_for_stage0 The function was a workaround for bootstrapping that isn't required anymore and just degrades hashmap performance, as it doesn't get inlined cross-crate and turns a no-op into a call. --- src/libcore/hash.rs | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/src/libcore/hash.rs b/src/libcore/hash.rs index d116c966c5cb3..69312f3a97b8c 100644 --- a/src/libcore/hash.rs +++ b/src/libcore/hash.rs @@ -76,16 +76,12 @@ pub trait Streaming { fn reset(&mut self); } -fn transmute_for_stage0<'a>(bytes: &'a [u8]) -> &'a [u8] { - bytes -} - impl Hash for A { #[inline(always)] fn hash_keyed(&self, k0: u64, k1: u64) -> u64 { let mut s = State::new(k0, k1); for self.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } s.result_u64() } @@ -95,10 +91,10 @@ fn hash_keyed_2(a: &A, b: &B, k0: u64, k1: u64) -> u64 { let mut s = State::new(k0, k1); for a.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for b.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } s.result_u64() } @@ -108,13 +104,13 @@ fn hash_keyed_3(a: &A, b: &B, c: &C, k0: u64, k1: u64) -> u64 { let mut s = State::new(k0, k1); for a.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for b.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for c.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } s.result_u64() } @@ -132,16 +128,16 @@ fn hash_keyed_4 u64 { let mut s = State::new(k0, k1); for a.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for b.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for c.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for d.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } s.result_u64() } @@ -161,19 +157,19 @@ fn hash_keyed_5 u64 { let mut s = State::new(k0, k1); for a.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for b.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for c.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for d.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } for e.iter_bytes(true) |bytes| { - s.input(transmute_for_stage0(bytes)); + s.input(bytes); } s.result_u64() } From eef03c39cf2f25f2e2182a68d0fcad14f378d5ac Mon Sep 17 00:00:00 2001 From: Brendan Zabarauskas Date: Mon, 20 May 2013 22:07:11 +1000 Subject: [PATCH 118/248] Update to stop unsolicited copying and mark methods as unsafe --- src/libcore/ptr.rs | 40 +++++++++++++++++++++++++++++----------- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 6254d3349d3d9..dfd3858436410 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -210,7 +210,7 @@ pub unsafe fn array_each(arr: **T, cb: &fn(*T)) { pub trait Ptr { fn is_null(&const self) -> bool; fn is_not_null(&const self) -> bool; - fn to_option(&const self) -> Option; + unsafe fn to_option(&const self) -> Option<&T>; fn offset(&self, count: uint) -> Self; } @@ -224,11 +224,20 @@ impl Ptr for *T { #[inline(always)] fn is_not_null(&const self) -> bool { is_not_null(*self) } - /// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`. + /// + /// Returns `None` if the pointer is null, or else returns the value wrapped + /// in `Some`. + /// + /// # Safety Notes + /// + /// While this method is useful for null-safety, it is important to note + /// that this is still an unsafe operation because the returned value could + /// be pointing to invalid memory. + /// #[inline(always)] - fn to_option(&const self) -> Option { + unsafe fn to_option(&const self) -> Option<&T> { if self.is_null() { None } else { - Some(unsafe { **self }) + Some(cast::transmute(*self)) } } @@ -247,11 +256,20 @@ impl Ptr for *mut T { #[inline(always)] fn is_not_null(&const self) -> bool { is_not_null(*self) } - /// Returns `None` if the pointer is null, or else returns the value wrapped in `Some`. + /// + /// Returns `None` if the pointer is null, or else returns the value wrapped + /// in `Some`. + /// + /// # Safety Notes + /// + /// While this method is useful for null-safety, it is important to note + /// that this is still an unsafe operation because the returned value could + /// be pointing to invalid memory. + /// #[inline(always)] - fn to_option(&const self) -> Option { + unsafe fn to_option(&const self) -> Option<&T> { if self.is_null() { None } else { - Some(unsafe { **self }) + Some(cast::transmute(*self)) } } @@ -442,19 +460,19 @@ pub mod ptr_tests { } #[test] - #[allow(unused_mut)] fn test_to_option() { let p: *int = null(); + // FIXME (#6641): Usage of unsafe methods in safe code doesn't cause an error. assert_eq!(p.to_option(), None); let q: *int = &2; - assert_eq!(q.to_option(), Some(2)); + assert_eq!(q.to_option().unwrap(), &2); // FIXME (#6641) let p: *mut int = mut_null(); - assert_eq!(p.to_option(), None); + assert_eq!(p.to_option(), None); // FIXME (#6641) let q: *mut int = &mut 2; - assert_eq!(q.to_option(), Some(2)); + assert_eq!(q.to_option().unwrap(), &2); // FIXME (#6641) } #[test] From 17dfebf883053ea84ef3fcf6b928d4a210c1012e Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Tue, 21 May 2013 00:41:56 +0900 Subject: [PATCH 119/248] Remove legacy_modes --- src/librustc/driver/driver.rs | 2 +- src/librustc/middle/ty.rs | 15 +-------------- src/librustc/middle/typeck/infer/test.rs | 2 +- 3 files changed, 3 insertions(+), 16 deletions(-) diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 572397b7f8af2..00621573b886a 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -239,7 +239,7 @@ pub fn compile_rest(sess: Session, let (llmod, link_meta) = { let ty_cx = ty::mk_ctxt(sess, def_map, ast_map, freevars, - region_map, rp_set, lang_items, crate); + region_map, rp_set, lang_items); // passes are timed inside typeck let (method_map, vtable_map) = typeck::check_crate( diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index b80b4855538ec..1a2a84ceae856 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -232,7 +232,6 @@ struct ctxt_ { diag: @syntax::diagnostic::span_handler, interner: @mut HashMap, next_id: @mut uint, - legacy_modes: bool, cstore: @mut metadata::cstore::CStore, sess: session::Session, def_map: resolve::DefMap, @@ -906,24 +905,12 @@ pub fn mk_ctxt(s: session::Session, freevars: freevars::freevar_map, region_maps: @mut middle::region::RegionMaps, region_paramd_items: middle::region::region_paramd_items, - lang_items: middle::lang_items::LanguageItems, - crate: @ast::crate) + lang_items: middle::lang_items::LanguageItems) -> ctxt { - let mut legacy_modes = false; - for crate.node.attrs.each |attribute| { - match attribute.node.value.node { - ast::meta_word(w) if *w == ~"legacy_modes" => { - legacy_modes = true; - } - _ => {} - } - } - @ctxt_ { diag: s.diagnostic(), interner: @mut HashMap::new(), next_id: @mut primitives::LAST_PRIMITIVE_ID, - legacy_modes: legacy_modes, cstore: s.cstore, sess: s, def_map: dm, diff --git a/src/librustc/middle/typeck/infer/test.rs b/src/librustc/middle/typeck/infer/test.rs index 1d24a4dbd4f91..f2a72e07a5739 100644 --- a/src/librustc/middle/typeck/infer/test.rs +++ b/src/librustc/middle/typeck/infer/test.rs @@ -67,7 +67,7 @@ fn setup_env(test_name: &str, source_string: &str) -> Env { cfg, parse_sess); let tcx = ty::mk_ctxt(sess, dm, amap, freevars, region_map, - region_paramd_items, lang_items, crate); + region_paramd_items, lang_items); let infcx = infer::new_infer_ctxt(tcx); From eb3f47a40a5578f50a9071b430ad95840640a344 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 20 May 2013 09:17:19 -0700 Subject: [PATCH 120/248] Remove two warnings about unneccesary safe blocks. Since a snapshot was done last night, these are good to go. --- src/libstd/fileinput.rs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/libstd/fileinput.rs b/src/libstd/fileinput.rs index 25e248414cdf1..d9a932fbe7c54 100644 --- a/src/libstd/fileinput.rs +++ b/src/libstd/fileinput.rs @@ -210,9 +210,7 @@ impl FileInput { pub fn next_file(&self) -> bool { // No more files - // unsafe block can be removed after the next snapshot - // (next one after 2013-05-03) - if unsafe { self.fi.files.is_empty() } { + if self.fi.files.is_empty() { self.fi.current_reader = None; return false; } @@ -324,9 +322,7 @@ impl io::Reader for FileInput { fn eof(&self) -> bool { // we've run out of files, and current_reader is either None or eof. - // unsafe block can be removed after the next snapshot - // (next one after 2013-05-03) - (unsafe { self.fi.files.is_empty() }) && + self.fi.files.is_empty() && match self.fi.current_reader { None => true, Some(r) => r.eof() } } From b5be7d8a2c0e9132d16bda0acfe97774d923531c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Steinbrink?= Date: Mon, 20 May 2013 18:40:29 +0200 Subject: [PATCH 121/248] Avoid range checks in HashMap::each() --- src/libcore/hashmap.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libcore/hashmap.rs b/src/libcore/hashmap.rs index 4770d38895192..e6ccb7a1d6b23 100644 --- a/src/libcore/hashmap.rs +++ b/src/libcore/hashmap.rs @@ -303,9 +303,9 @@ impl Map for HashMap { /// Visit all key-value pairs fn each<'a>(&'a self, blk: &fn(&K, &'a V) -> bool) -> bool { - for uint::range(0, self.buckets.len()) |i| { - for self.buckets[i].each |bucket| { - if !blk(&bucket.key, &bucket.value) { + for self.buckets.each |bucket| { + for bucket.each |pair| { + if !blk(&pair.key, &pair.value) { return false; } } From 19dc72809daa0f53120f88b155459f877e854945 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Steinbrink?= Date: Mon, 20 May 2013 18:41:20 +0200 Subject: [PATCH 122/248] Optimize the lookup of traits containing a given method Currently, trait_info is a hashmap that allows a quick lookup of all methods contained in a given trait, but we actually only use it to lookup traits that contain a given method. Adjusting the map to support the lookup we actually need gives a nice speed boost, reducing the time required for the resolution step for librustc from ~2.6s to ~1.0s on my box. --- src/librustc/middle/resolve.rs | 185 +++++++++++++++++---------------- 1 file changed, 97 insertions(+), 88 deletions(-) diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 1568c3e55352f..db1f51c19ea67 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -734,7 +734,7 @@ pub fn Resolver(session: Session, graph_root: graph_root, - trait_info: HashMap::new(), + method_map: @mut HashMap::new(), structs: HashSet::new(), unresolved_imports: 0, @@ -776,7 +776,7 @@ pub struct Resolver { graph_root: @mut NameBindings, - trait_info: HashMap>, + method_map: @mut HashMap>, structs: HashSet, // The number of imports that are currently unresolved. @@ -1292,7 +1292,15 @@ pub impl Resolver { } let def_id = local_def(item.id); - self.trait_info.insert(def_id, method_names); + for method_names.each |name| { + if !self.method_map.contains_key(name) { + self.method_map.insert(*name, HashSet::new()); + } + match self.method_map.find_mut(name) { + Some(s) => { s.insert(def_id); }, + _ => fail!("Can't happen"), + } + } name_bindings.define_type(privacy, def_trait(def_id), sp); visit_item(item, new_parent, visitor); @@ -1589,7 +1597,15 @@ pub impl Resolver { interned_method_names.insert(method_name); } } - self.trait_info.insert(def_id, interned_method_names); + for interned_method_names.each |name| { + if !self.method_map.contains_key(name) { + self.method_map.insert(*name, HashSet::new()); + } + match self.method_map.find_mut(name) { + Some(s) => { s.insert(def_id); }, + _ => fail!("Can't happen"), + } + } child_name_bindings.define_type(Public, def, dummy_sp()); } @@ -4935,118 +4951,111 @@ pub impl Resolver { debug!("(searching for traits containing method) looking for '%s'", *self.session.str_of(name)); + let mut found_traits = ~[]; let mut search_module = self.current_module; - loop { - // Look for the current trait. - match /*bad*/copy self.current_trait_refs { - Some(trait_def_ids) => { - for trait_def_ids.each |trait_def_id| { - self.add_trait_info_if_containing_method( - &mut found_traits, *trait_def_id, name); - } - } - None => { - // Nothing to do. - } - } - - // Look for trait children. - for search_module.children.each_value |&child_name_bindings| { - match child_name_bindings.def_for_namespace(TypeNS) { - Some(def) => { - match def { - def_trait(trait_def_id) => { - self.add_trait_info_if_containing_method( - &mut found_traits, trait_def_id, name); - } - _ => { - // Continue. + match self.method_map.find(&name) { + Some(candidate_traits) => loop { + // Look for the current trait. + match /*bad*/copy self.current_trait_refs { + Some(trait_def_ids) => { + for trait_def_ids.each |trait_def_id| { + if candidate_traits.contains(trait_def_id) { + self.add_trait_info( + &mut found_traits, + *trait_def_id, name); } } } None => { - // Continue. + // Nothing to do. } } - } - // Look for imports. - for search_module.import_resolutions.each_value - |&import_resolution| { - - match import_resolution.target_for_namespace(TypeNS) { - None => { - // Continue. - } - Some(target) => { - match target.bindings.def_for_namespace(TypeNS) { - Some(def) => { - match def { - def_trait(trait_def_id) => { - let added = self. - add_trait_info_if_containing_method( + // Look for trait children. + for search_module.children.each_value |&child_name_bindings| { + match child_name_bindings.def_for_namespace(TypeNS) { + Some(def) => { + match def { + def_trait(trait_def_id) => { + if candidate_traits.contains(&trait_def_id) { + self.add_trait_info( &mut found_traits, trait_def_id, name); - if added { - self.used_imports.insert( - import_resolution.id); - } - } - _ => { - // Continue. } } - } - None => { - // Continue. + _ => { + // Continue. + } } } + None => { + // Continue. + } } } - } - // Move to the next parent. - match search_module.parent_link { - NoParentLink => { - // Done. - break; + // Look for imports. + for search_module.import_resolutions.each_value + |&import_resolution| { + + match import_resolution.target_for_namespace(TypeNS) { + None => { + // Continue. + } + Some(target) => { + match target.bindings.def_for_namespace(TypeNS) { + Some(def) => { + match def { + def_trait(trait_def_id) => { + if candidate_traits.contains(&trait_def_id) { + self.add_trait_info( + &mut found_traits, + trait_def_id, name); + self.used_imports.insert( + import_resolution.id); + } + } + _ => { + // Continue. + } + } + } + None => { + // Continue. + } + } + } + } } - ModuleParentLink(parent_module, _) | - BlockParentLink(parent_module, _) => { - search_module = parent_module; + + // Move to the next parent. + match search_module.parent_link { + NoParentLink => { + // Done. + break; + } + ModuleParentLink(parent_module, _) | + BlockParentLink(parent_module, _) => { + search_module = parent_module; + } } - } + }, + _ => () } return found_traits; } - fn add_trait_info_if_containing_method(&self, - found_traits: &mut ~[def_id], - trait_def_id: def_id, - name: ident) - -> bool { - debug!("(adding trait info if containing method) trying trait %d:%d \ - for method '%s'", + fn add_trait_info(&self, + found_traits: &mut ~[def_id], + trait_def_id: def_id, + name: ident) { + debug!("(adding trait info) found trait %d:%d for method '%s'", trait_def_id.crate, trait_def_id.node, *self.session.str_of(name)); - - match self.trait_info.find(&trait_def_id) { - Some(trait_info) if trait_info.contains(&name) => { - debug!("(adding trait info if containing method) found trait \ - %d:%d for method '%s'", - trait_def_id.crate, - trait_def_id.node, - *self.session.str_of(name)); - found_traits.push(trait_def_id); - true - } - Some(_) | None => { - false - } - } + found_traits.push(trait_def_id); } fn add_fixed_trait_for_expr(@mut self, From 15f97acdc87087e7747900be83d038757b86fb25 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 20 May 2013 13:02:08 -0500 Subject: [PATCH 123/248] Correctly track the source of imports with the same name --- src/libcore/vec.rs | 2 +- src/librustc/middle/resolve.rs | 4 +++ .../lint-unused-import-tricky-names.rs | 29 +++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 src/test/compile-fail/lint-unused-import-tricky-names.rs diff --git a/src/libcore/vec.rs b/src/libcore/vec.rs index 14dcde2381bf3..65f8dab25a5aa 100644 --- a/src/libcore/vec.rs +++ b/src/libcore/vec.rs @@ -22,7 +22,7 @@ use old_iter; use iterator::Iterator; use kinds::Copy; use libc; -use old_iter::{BaseIter, CopyableIter}; +use old_iter::CopyableIter; use option::{None, Option, Some}; use ptr::to_unsafe_ptr; use ptr; diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 1568c3e55352f..ef0bf6ad0e05d 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -1818,6 +1818,10 @@ pub impl Resolver { debug!("(building import directive) bumping \ reference"); resolution.outstanding_references += 1; + + // the source of this name is different now + resolution.privacy = privacy; + resolution.id = id; } None => { debug!("(building import directive) creating new"); diff --git a/src/test/compile-fail/lint-unused-import-tricky-names.rs b/src/test/compile-fail/lint-unused-import-tricky-names.rs new file mode 100644 index 0000000000000..e36b5572909d8 --- /dev/null +++ b/src/test/compile-fail/lint-unused-import-tricky-names.rs @@ -0,0 +1,29 @@ +// 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. + +#[deny(unused_imports)]; + +// Regression test for issue #6633 + +use foo::name::name; //~ ERROR: unused import +use foo::name; + +pub mod foo { + pub mod name { + pub type a = int; + pub mod name { + pub type a = float; + } + } +} + +fn bar() -> name::a { 1 } + +fn main(){} From 975f2649839c945660339b8929a04432b1562635 Mon Sep 17 00:00:00 2001 From: John Clements Date: Thu, 16 May 2013 17:41:47 -0700 Subject: [PATCH 124/248] refactoring test functions --- src/libsyntax/parse/mod.rs | 77 ++-------------------- src/libsyntax/syntax.rc | 2 + src/libsyntax/util/parser_testing.rs | 96 ++++++++++++++++++++++++++++ 3 files changed, 105 insertions(+), 70 deletions(-) create mode 100644 src/libsyntax/util/parser_testing.rs diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index fa52f3dde3d54..f9cf421429cfd 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -357,65 +357,18 @@ mod test { use abi; use ast_util::mk_ident; use parse::parser::Parser; - use parse::token::{ident_interner, mk_fresh_ident_interner}; - use diagnostic::{mk_span_handler, mk_handler}; - - // add known names to interner for testing - fn mk_testing_interner() -> @ident_interner { - let i = mk_fresh_ident_interner(); - // baby hack; in order to put the identifiers - // 'a' and 'b' at known locations, we're going - // to fill up the interner to length 100. If - // the # of preloaded items on the interner - // ever gets larger than 100, we'll have to - // adjust this number (say, to 200) and - // change the numbers in the identifier - // test cases below. - - assert!(i.len() < 100); - for int::range(0,100-((i.len()).to_int())) |_dc| { - i.gensym("dontcare"); - } - i.intern("a"); - i.intern("b"); - i.intern("c"); - i.intern("d"); - i.intern("return"); - assert_eq!(i.get(ast::ident{repr:101,ctxt:0}), @~"b"); - i - } - - // make a parse_sess that's closed over a - // testing interner (where a -> 100, b -> 101) - fn mk_testing_parse_sess() -> @mut ParseSess { - let interner = mk_testing_interner(); - let cm = @CodeMap::new(); - @mut ParseSess { - cm: cm, - next_id: 1, - span_diagnostic: mk_span_handler(mk_handler(None), cm), - interner: interner, - } - } - - // map a string to tts, using a made-up filename: return both the token_trees - // and the ParseSess - fn string_to_tts_t (source_str : @~str) -> (~[ast::token_tree],@mut ParseSess) { - let ps = mk_testing_parse_sess(); - (filemap_to_tts(ps,string_to_filemap(ps,source_str,~"bogofile")),ps) - } + use parse::token::{ident_interner, mk_ident_interner, mk_fresh_ident_interner}; + use diagnostic::{span_handler, mk_span_handler, mk_handler, Emitter}; + use util::parser_testing::{string_to_tts_and_sess,string_to_parser}; + use util::parser_testing::{string_to_crate, string_to_expr, string_to_item}; + use util::parser_testing::{string_to_stmt}; // map a string to tts, return the tt without its parsesess fn string_to_tts_only(source_str : @~str) -> ~[ast::token_tree] { - let (tts,_ps) = string_to_tts_t(source_str); + let (tts,_ps) = string_to_tts_and_sess(source_str); tts } - // map string to parser (via tts) - fn string_to_parser(source_str: @~str) -> Parser { - let ps = mk_testing_parse_sess(); - new_parser_from_source_str(ps,~[],~"bogofile",source_str) - } #[cfg(test)] fn to_json_str>(val: @E) -> ~str { do io::with_str_writer |writer| { @@ -424,22 +377,6 @@ mod test { } } - fn string_to_crate (source_str : @~str) -> @ast::crate { - string_to_parser(source_str).parse_crate_mod() - } - - fn string_to_expr (source_str : @~str) -> @ast::expr { - string_to_parser(source_str).parse_expr() - } - - fn string_to_item (source_str : @~str) -> Option<@ast::item> { - string_to_parser(source_str).parse_item(~[]) - } - - fn string_to_stmt (source_str : @~str) -> @ast::stmt { - string_to_parser(source_str).parse_stmt(~[]) - } - // produce a codemap::span fn sp (a: uint, b: uint) -> span { span{lo:BytePos(a),hi:BytePos(b),expn_info:None} @@ -482,7 +419,7 @@ mod test { }*/ #[test] fn string_to_tts_1 () { - let (tts,_ps) = string_to_tts_t(@~"fn a (b : int) { b; }"); + let (tts,_ps) = string_to_tts_and_sess(@~"fn a (b : int) { b; }"); assert_eq!(to_json_str(@tts), ~"[\ [\"tt_tok\",null,[\"IDENT\",\"fn\",false]],\ diff --git a/src/libsyntax/syntax.rc b/src/libsyntax/syntax.rc index 0d9b7ca429eae..7ac8c08b25d8a 100644 --- a/src/libsyntax/syntax.rc +++ b/src/libsyntax/syntax.rc @@ -30,6 +30,8 @@ extern mod std; #[macro_escape] pub mod util { pub mod interner; + #[cfg(test)] + pub mod parser_testing; } pub mod syntax { diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs new file mode 100644 index 0000000000000..9ab77803576e0 --- /dev/null +++ b/src/libsyntax/util/parser_testing.rs @@ -0,0 +1,96 @@ +// 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. + +use std::serialize::Encodable; +use std; +use core::io; +use core::option::{Option,None}; +use core::int; +use core::num::NumCast; +use codemap::{dummy_sp, CodeMap, BytePos, spanned}; +use opt_vec; +use ast; +use abi; +use ast_util::mk_ident; +use parse::parser::Parser; +use parse::token::{ident_interner, mk_ident_interner, mk_fresh_ident_interner}; +use diagnostic::{span_handler, mk_span_handler, mk_handler, Emitter}; + +use syntax::parse::{ParseSess,new_parse_sess,string_to_filemap,filemap_to_tts}; +use syntax::parse::{new_parser_from_source_str}; + +// add known names to interner for testing +fn mk_testing_interner() -> @ident_interner { + let i = mk_fresh_ident_interner(); + // baby hack; in order to put the identifiers + // 'a' and 'b' at known locations, we're going + // to fill up the interner to length 100. If + // the # of preloaded items on the interner + // ever gets larger than 100, we'll have to + // adjust this number (say, to 200) and + // change the numbers in the identifier + // test cases below. + + assert!(i.len() < 100); + for int::range(0,100-((i.len()).to_int())) |_dc| { + i.gensym(~"dontcare"); + } + i.intern("a"); + i.intern("b"); + i.intern("c"); + i.intern("d"); + i.intern("return"); + assert!(i.get(ast::ident{repr:101,ctxt:0}) == @~"b"); + i +} + +// make a parse_sess that's closed over a +// testing interner (where a -> 100, b -> 101) +fn mk_testing_parse_sess() -> @mut ParseSess { + let interner = mk_testing_interner(); + let cm = @CodeMap::new(); + @mut ParseSess { + cm: cm, + next_id: 1, + span_diagnostic: mk_span_handler(mk_handler(None), cm), + interner: interner, + } +} + +// map a string to tts, using a made-up filename: return both the token_trees +// and the ParseSess +pub fn string_to_tts_and_sess (source_str : @~str) -> (~[ast::token_tree],@mut ParseSess) { + let ps = mk_testing_parse_sess(); + (filemap_to_tts(ps,string_to_filemap(ps,source_str,~"bogofile")),ps) +} + +// map string to parser (via tts) +pub fn string_to_parser(source_str: @~str) -> Parser { + let ps = mk_testing_parse_sess(); + new_parser_from_source_str(ps,~[],~"bogofile",source_str) +} + +pub fn string_to_crate (source_str : @~str) -> @ast::crate { + string_to_parser(source_str).parse_crate_mod() +} + +// parse a string, return an expr +pub fn string_to_expr (source_str : @~str) -> @ast::expr { + string_to_parser(source_str).parse_expr() +} + +pub fn string_to_item (source_str : @~str) -> Option<@ast::item> { + string_to_parser(source_str).parse_item(~[]) +} + +pub fn string_to_stmt (source_str : @~str) -> @ast::stmt { + string_to_parser(source_str).parse_stmt(~[]) +} + From 05ab83eea80413ef4d7714cae93a30f24e2fff5c Mon Sep 17 00:00:00 2001 From: John Clements Date: Mon, 29 Apr 2013 13:16:02 -0700 Subject: [PATCH 125/248] parser comment --- src/libsyntax/parse/parser.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index cfef9c4987958..a7ba67901e89b 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -2496,6 +2496,7 @@ pub impl Parser { @ast::pat { id: self.get_id(), node: pat, span: mk_sp(lo, hi) } } + // parse ident or ident @ pat // used by the copy foo and ref foo patterns to give a good // error message when parsing mistakes like ref foo(a,b) fn parse_pat_ident(&self, From b621820dc4727677f14bee0ac5e2fa5e424ed22e Mon Sep 17 00:00:00 2001 From: John Clements Date: Tue, 30 Apr 2013 12:02:56 -0700 Subject: [PATCH 126/248] detect unused attrs in one more place, allow parsing to continue for all changed a bunch of fatal()'s into err()'s, to allow parsing to proceed. --- src/libsyntax/parse/mod.rs | 16 +++++++ src/libsyntax/parse/parser.rs | 61 ++++++++++++++---------- src/test/compile-fail/attr-before-ext.rs | 4 +- src/test/compile-fail/attr-before-let.rs | 4 +- 4 files changed, 57 insertions(+), 28 deletions(-) diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index f9cf421429cfd..7aff9f6745cbf 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -612,4 +612,20 @@ mod test { string_to_expr(@~"3 + 4"); string_to_expr(@~"a::z.froob(b,@(987+3))"); } + + #[test] fn attrs_fix_bug () { + string_to_item(@~"pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) + -> Result<@Writer, ~str> { + #[cfg(windows)] + fn wb() -> c_int { + (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int + } + + #[cfg(unix)] + fn wb() -> c_int { O_WRONLY as c_int } + + let mut fflags: c_int = wb(); +}"); + } + } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index a7ba67901e89b..fddeea9302414 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -2588,20 +2588,22 @@ pub impl Parser { }) } - // parse a statement. may include decl - fn parse_stmt(&self, first_item_attrs: ~[attribute]) -> @stmt { + // parse a statement. may include decl. + // precondition: any attributes are parsed already + fn parse_stmt(&self, item_attrs: ~[attribute]) -> @stmt { maybe_whole!(self, nt_stmt); fn check_expected_item(p: &Parser, current_attrs: &[attribute]) { // If we have attributes then we should have an item if !current_attrs.is_empty() { - p.fatal(~"expected item after attrs"); + p.span_err(*p.last_span, + ~"expected item after attributes"); } } let lo = self.span.lo; if self.is_keyword("let") { - check_expected_item(self, first_item_attrs); + check_expected_item(self, item_attrs); self.expect_keyword("let"); let decl = self.parse_let(); return @spanned(lo, decl.span.hi, stmt_decl(decl, self.get_id())); @@ -2614,7 +2616,7 @@ pub impl Parser { // to the macro clause of parse_item_or_view_item. This // could use some cleanup, it appears to me. - check_expected_item(self, first_item_attrs); + check_expected_item(self, item_attrs); // Potential trouble: if we allow macros with paths instead of // idents, we'd need to look ahead past the whole path here... @@ -2650,9 +2652,6 @@ pub impl Parser { } } else { - let item_attrs = vec::append(first_item_attrs, - self.parse_outer_attributes()); - match self.parse_item_or_view_item(/*bad*/ copy item_attrs, false) { iovi_item(i) => { @@ -2727,6 +2726,7 @@ pub impl Parser { let mut stmts = ~[]; let mut expr = None; + // wouldn't it be more uniform to parse view items only, here? let ParsedItemsAndViewItems { attrs_remaining: attrs_remaining, view_items: view_items, @@ -2741,23 +2741,29 @@ pub impl Parser { stmt_decl(decl, self.get_id()))); } - let mut initial_attrs = attrs_remaining; - - if *self.token == token::RBRACE && !vec::is_empty(initial_attrs) { - self.fatal(~"expected item"); - } + let mut attributes_box = attrs_remaining; - while *self.token != token::RBRACE { + while (*self.token != token::RBRACE) { + // parsing items even when they're not allowed lets us give + // better error messages and recover more gracefully. + attributes_box.push_all(self.parse_outer_attributes()); match *self.token { token::SEMI => { + if !vec::is_empty(attributes_box) { + self.span_err(*self.last_span,~"expected item after attributes"); + attributes_box = ~[]; + } self.bump(); // empty } + token::RBRACE => { + // fall through and out. + } _ => { - let stmt = self.parse_stmt(initial_attrs); - initial_attrs = ~[]; + let stmt = self.parse_stmt(attributes_box); + attributes_box = ~[]; match stmt.node { stmt_expr(e, stmt_id) => { - // Expression without semicolon + // expression without semicolon match *self.token { token::SEMI => { self.bump(); @@ -2773,7 +2779,7 @@ pub impl Parser { self.fatal( fmt!( "expected `;` or `}` after \ - expression but found `%s`", + expression but found `%s`", self.token_to_str(&t) ) ); @@ -2782,9 +2788,8 @@ pub impl Parser { } } } - stmt_mac(ref m, _) => { - // Statement macro; might be an expr + // statement macro; might be an expr match *self.token { token::SEMI => { self.bump(); @@ -2803,8 +2808,7 @@ pub impl Parser { _ => { stmts.push(stmt); } } } - - _ => { // All other kinds of statements: + _ => { // all other kinds of statements: stmts.push(stmt); if classify::stmt_ends_with_semi(stmt) { @@ -2815,6 +2819,11 @@ pub impl Parser { } } } + + if !vec::is_empty(attributes_box) { + self.span_err(*self.last_span,~"expected item after attributes"); + } + let hi = self.span.hi; self.bump(); let bloc = ast::blk_ { @@ -3519,7 +3528,7 @@ pub impl Parser { if first && attrs_remaining_len > 0u { // We parsed attributes for the first item but didn't find it - self.fatal(~"expected item"); + self.span_err(*self.last_span,~"expected item after attributes"); } ast::_mod { view_items: view_items, items: items } @@ -3724,11 +3733,15 @@ pub impl Parser { first_item_attrs: ~[attribute]) -> foreign_mod { let ParsedItemsAndViewItems { - attrs_remaining: _, + attrs_remaining: attrs_remaining, view_items: view_items, items: _, foreign_items: foreign_items } = self.parse_foreign_items(first_item_attrs, true); + if (! attrs_remaining.is_empty()) { + self.span_err(*self.last_span, + ~"expected item after attributes"); + } assert!(*self.token == token::RBRACE); ast::foreign_mod { sort: sort, diff --git a/src/test/compile-fail/attr-before-ext.rs b/src/test/compile-fail/attr-before-ext.rs index 2675b865e9017..cf0f4a6240e2b 100644 --- a/src/test/compile-fail/attr-before-ext.rs +++ b/src/test/compile-fail/attr-before-ext.rs @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - #[attr] - debug!("hi"); //~ ERROR expected item after attrs + #[attr] //~ ERROR expected item after attributes + debug!("hi"); } diff --git a/src/test/compile-fail/attr-before-let.rs b/src/test/compile-fail/attr-before-let.rs index 51ee903b1b1db..acc9aa8a9a13e 100644 --- a/src/test/compile-fail/attr-before-let.rs +++ b/src/test/compile-fail/attr-before-let.rs @@ -9,6 +9,6 @@ // except according to those terms. fn main() { - #[attr] - let _i = 0; //~ ERROR expected item + #[attr] //~ ERROR expected item + let _i = 0; } From fc4f304ef9916d691166592b3e49998594535c57 Mon Sep 17 00:00:00 2001 From: John Clements Date: Thu, 16 May 2013 17:42:08 -0700 Subject: [PATCH 127/248] hygiene infrastructure. - added a hash table to memoize rename and mark operations. - added rename, mark, and resolve fold fns --- src/libsyntax/ast.rs | 14 ++- src/libsyntax/ast_util.rs | 134 +++++++++++++++++++-------- src/libsyntax/ext/expand.rs | 93 ++++++++++++------- src/libsyntax/parse/mod.rs | 33 +++---- src/libsyntax/util/parser_testing.rs | 30 +++--- 5 files changed, 194 insertions(+), 110 deletions(-) diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 241450e7130a2..2b98803364c11 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -19,6 +19,7 @@ use core::option::{None, Option, Some}; use core::to_bytes; use core::to_bytes::IterBytes; use core::to_str::ToStr; +use core::hashmap::HashMap; use std::serialize::{Encodable, Decodable, Encoder, Decoder}; @@ -38,14 +39,20 @@ pub struct ident { repr: Name, ctxt: SyntaxContext } // that's causing unreleased memory to cause core dumps // and also perhaps to save some work in destructor checks. // the special uint '0' will be used to indicate an empty -// syntax context +// syntax context. // this uint is a reference to a table stored in thread-local // storage. pub type SyntaxContext = uint; -pub type SCTable = ~[SyntaxContext_]; +pub struct SCTable { + table : ~[SyntaxContext_], + mark_memo : HashMap<(SyntaxContext,Mrk),SyntaxContext>, + rename_memo : HashMap<(SyntaxContext,ident,Name),SyntaxContext> +} +// NB: these must be placed in any SCTable... pub static empty_ctxt : uint = 0; +pub static illegal_ctxt : uint = 1; #[deriving(Eq, Encodable, Decodable)] pub enum SyntaxContext_ { @@ -59,7 +66,8 @@ pub enum SyntaxContext_ { // "to" slot must have the same name and context // in the "from" slot. In essence, they're all // pointers to a single "rename" event node. - Rename (ident,Name,SyntaxContext) + Rename (ident,Name,SyntaxContext), + IllegalCtxt() } // a name represents an identifier diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index bb6d13b283118..eaacb054ca1ae 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -15,6 +15,7 @@ use codemap::{span, spanned}; use parse::token; use visit; use opt_vec; +use core::hashmap::HashMap; use core::to_bytes; @@ -577,22 +578,61 @@ pub enum Privacy { // HYGIENE FUNCTIONS /// Construct an identifier with the given repr and an empty context: -pub fn mk_ident(repr: uint) -> ident { ident {repr: repr, ctxt: 0}} +pub fn new_ident(repr: uint) -> ident { ident {repr: repr, ctxt: 0}} /// Extend a syntax context with a given mark -pub fn mk_mark (m:Mrk,ctxt:SyntaxContext,table:&mut SCTable) +pub fn new_mark (m:Mrk, tail:SyntaxContext,table:&mut SCTable) -> SyntaxContext { - idx_push(table,Mark(m,ctxt)) + let key = (tail,m); + // FIXME #5074 : can't use more natural style because we're missing + // flow-sensitivity. Results in two lookups on a hash table hit. + // also applies to new_rename, below. + // let try_lookup = table.mark_memo.find(&key); + match table.mark_memo.contains_key(&key) { + false => { + let new_idx = idx_push(&mut table.table,Mark(m,tail)); + table.mark_memo.insert(key,new_idx); + new_idx + } + true => { + match table.mark_memo.find(&key) { + None => fail!(~"internal error: key disappeared 2013042901"), + Some(idxptr) => {*idxptr} + } + } + } } /// Extend a syntax context with a given rename -pub fn mk_rename (id:ident, to:Name, tail:SyntaxContext, table: &mut SCTable) +pub fn new_rename (id:ident, to:Name, tail:SyntaxContext, table: &mut SCTable) -> SyntaxContext { - idx_push(table,Rename(id,to,tail)) + let key = (tail,id,to); + // FIXME #5074 + //let try_lookup = table.rename_memo.find(&key); + match table.rename_memo.contains_key(&key) { + false => { + let new_idx = idx_push(&mut table.table,Rename(id,to,tail)); + table.rename_memo.insert(key,new_idx); + new_idx + } + true => { + match table.rename_memo.find(&key) { + None => fail!(~"internal error: key disappeared 2013042902"), + Some(idxptr) => {*idxptr} + } + } + } } /// Make a fresh syntax context table with EmptyCtxt in slot zero -pub fn mk_sctable() -> SCTable { ~[EmptyCtxt] } +/// and IllegalCtxt in slot one. +pub fn new_sctable() -> SCTable { + SCTable { + table: ~[EmptyCtxt,IllegalCtxt], + mark_memo: HashMap::new(), + rename_memo: HashMap::new() + } +} /// Add a value to the end of a vec, return its index fn idx_push(vec: &mut ~[T], val: T) -> uint { @@ -601,8 +641,8 @@ fn idx_push(vec: &mut ~[T], val: T) -> uint { } /// Resolve a syntax object to a name, per MTWT. -pub fn resolve (id : ident, table : &SCTable) -> Name { - match table[id.ctxt] { +pub fn resolve (id : ident, table : &mut SCTable) -> Name { + match table.table[id.ctxt] { EmptyCtxt => id.repr, // ignore marks here: Mark(_,subctxt) => resolve (ident{repr:id.repr, ctxt: subctxt},table), @@ -619,6 +659,7 @@ pub fn resolve (id : ident, table : &SCTable) -> Name { resolvedthis } } + IllegalCtxt() => fail!(~"expected resolvable context, got IllegalCtxt") } } @@ -629,7 +670,7 @@ pub fn marksof(ctxt: SyntaxContext, stopname: Name, table: &SCTable) -> ~[Mrk] { let mut result = ~[]; let mut loopvar = ctxt; loop { - match table[loopvar] { + match table.table[loopvar] { EmptyCtxt => {return result;}, Mark(mark,tl) => { xorPush(&mut result,mark); @@ -644,6 +685,7 @@ pub fn marksof(ctxt: SyntaxContext, stopname: Name, table: &SCTable) -> ~[Mrk] { loopvar = tl; } } + IllegalCtxt => fail!(~"expected resolvable context, got IllegalCtxt") } } } @@ -713,15 +755,15 @@ mod test { -> SyntaxContext { tscs.foldr(tail, |tsc : &TestSC,tail : SyntaxContext| {match *tsc { - M(mrk) => mk_mark(mrk,tail,table), - R(ident,name) => mk_rename(ident,name,tail,table)}}) + M(mrk) => new_mark(mrk,tail,table), + R(ident,name) => new_rename(ident,name,tail,table)}}) } // gather a SyntaxContext back into a vector of TestSCs fn refold_test_sc(mut sc: SyntaxContext, table : &SCTable) -> ~[TestSC] { let mut result = ~[]; loop { - match table[sc] { + match table.table[sc] { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); @@ -733,40 +775,41 @@ mod test { sc = tail; loop; } + IllegalCtxt => fail!("expected resolvable context, got IllegalCtxt") } } } #[test] fn test_unfold_refold(){ - let mut t = mk_sctable(); + let mut t = new_sctable(); let test_sc = ~[M(3),R(id(101,0),14),M(9)]; - assert_eq!(unfold_test_sc(copy test_sc,empty_ctxt,&mut t),3); - assert_eq!(t[1],Mark(9,0)); - assert_eq!(t[2],Rename(id(101,0),14,1)); - assert_eq!(t[3],Mark(3,2)); - assert_eq!(refold_test_sc(3,&t),test_sc); + assert_eq!(unfold_test_sc(copy test_sc,empty_ctxt,&mut t),4); + assert_eq!(t.table[2],Mark(9,0)); + assert_eq!(t.table[3],Rename(id(101,0),14,2)); + assert_eq!(t.table[4],Mark(3,3)); + assert_eq!(refold_test_sc(4,&t),test_sc); } // extend a syntax context with a sequence of marks given // in a vector. v[0] will be the outermost mark. fn unfold_marks(mrks:~[Mrk],tail:SyntaxContext,table: &mut SCTable) -> SyntaxContext { mrks.foldr(tail, |mrk:&Mrk,tail:SyntaxContext| - {mk_mark(*mrk,tail,table)}) + {new_mark(*mrk,tail,table)}) } #[test] fn unfold_marks_test() { - let mut t = ~[EmptyCtxt]; + let mut t = new_sctable(); - assert_eq!(unfold_marks(~[3,7],empty_ctxt,&mut t),2); - assert_eq!(t[1],Mark(7,0)); - assert_eq!(t[2],Mark(3,1)); + assert_eq!(unfold_marks(~[3,7],empty_ctxt,&mut t),3); + assert_eq!(t.table[2],Mark(7,0)); + assert_eq!(t.table[3],Mark(3,2)); } #[test] fn test_marksof () { let stopname = 242; let name1 = 243; - let mut t = mk_sctable(); + let mut t = new_sctable(); assert_eq!(marksof (empty_ctxt,stopname,&t),~[]); // FIXME #5074: ANF'd to dodge nested calls { let ans = unfold_marks(~[4,98],empty_ctxt,&mut t); @@ -780,13 +823,13 @@ mod test { // rename where stop doesn't match: { let chain = ~[M(9), R(id(name1, - mk_mark (4, empty_ctxt,&mut t)), + new_mark (4, empty_ctxt,&mut t)), 100101102), M(14)]; let ans = unfold_test_sc(chain,empty_ctxt,&mut t); assert_eq! (marksof (ans, stopname, &t), ~[9,14]);} // rename where stop does match - { let name1sc = mk_mark(4, empty_ctxt, &mut t); + { let name1sc = new_mark(4, empty_ctxt, &mut t); let chain = ~[M(9), R(id(name1, name1sc), stopname), @@ -798,30 +841,30 @@ mod test { #[test] fn resolve_tests () { let a = 40; - let mut t = mk_sctable(); + let mut t = new_sctable(); // - ctxt is MT - assert_eq!(resolve(id(a,empty_ctxt),&t),a); + assert_eq!(resolve(id(a,empty_ctxt),&mut t),a); // - simple ignored marks { let sc = unfold_marks(~[1,2,3],empty_ctxt,&mut t); - assert_eq!(resolve(id(a,sc),&t),a);} + assert_eq!(resolve(id(a,sc),&mut t),a);} // - orthogonal rename where names don't match { let sc = unfold_test_sc(~[R(id(50,empty_ctxt),51),M(12)],empty_ctxt,&mut t); - assert_eq!(resolve(id(a,sc),&t),a);} + assert_eq!(resolve(id(a,sc),&mut t),a);} // - rename where names do match, but marks don't - { let sc1 = mk_mark(1,empty_ctxt,&mut t); + { let sc1 = new_mark(1,empty_ctxt,&mut t); let sc = unfold_test_sc(~[R(id(a,sc1),50), M(1), M(2)], empty_ctxt,&mut t); - assert_eq!(resolve(id(a,sc),&t), a);} + assert_eq!(resolve(id(a,sc),&mut t), a);} // - rename where names and marks match { let sc1 = unfold_test_sc(~[M(1),M(2)],empty_ctxt,&mut t); let sc = unfold_test_sc(~[R(id(a,sc1),50),M(1),M(2)],empty_ctxt,&mut t); - assert_eq!(resolve(id(a,sc),&t), 50); } + assert_eq!(resolve(id(a,sc),&mut t), 50); } // - rename where names and marks match by literal sharing { let sc1 = unfold_test_sc(~[M(1),M(2)],empty_ctxt,&mut t); let sc = unfold_test_sc(~[R(id(a,sc1),50)],sc1,&mut t); - assert_eq!(resolve(id(a,sc),&t), 50); } + assert_eq!(resolve(id(a,sc),&mut t), 50); } // - two renames of the same var.. can only happen if you use // local-expand to prevent the inner binding from being renamed // during the rename-pass caused by the first: @@ -829,20 +872,29 @@ mod test { { let sc = unfold_test_sc(~[R(id(a,empty_ctxt),50), R(id(a,empty_ctxt),51)], empty_ctxt,&mut t); - assert_eq!(resolve(id(a,sc),&t), 51); } + assert_eq!(resolve(id(a,sc),&mut t), 51); } // the simplest double-rename: - { let a_to_a50 = mk_rename(id(a,empty_ctxt),50,empty_ctxt,&mut t); - let a50_to_a51 = mk_rename(id(a,a_to_a50),51,a_to_a50,&mut t); - assert_eq!(resolve(id(a,a50_to_a51),&t),51); + { let a_to_a50 = new_rename(id(a,empty_ctxt),50,empty_ctxt,&mut t); + let a50_to_a51 = new_rename(id(a,a_to_a50),51,a_to_a50,&mut t); + assert_eq!(resolve(id(a,a50_to_a51),&mut t),51); // mark on the outside doesn't stop rename: - let sc = mk_mark(9,a50_to_a51,&mut t); - assert_eq!(resolve(id(a,sc),&t),51); + let sc = new_mark(9,a50_to_a51,&mut t); + assert_eq!(resolve(id(a,sc),&mut t),51); // but mark on the inside does: let a50_to_a51_b = unfold_test_sc(~[R(id(a,a_to_a50),51), M(9)], a_to_a50, &mut t); - assert_eq!(resolve(id(a,a50_to_a51_b),&t),50);} + assert_eq!(resolve(id(a,a50_to_a51_b),&mut t),50);} + } + + #[test] fn hashing_tests () { + let mut t = new_sctable(); + assert_eq!(new_mark(12,empty_ctxt,&mut t),2); + assert_eq!(new_mark(13,empty_ctxt,&mut t),3); + // using the same one again should result in the same index: + assert_eq!(new_mark(12,empty_ctxt,&mut t),2); + // I'm assuming that the rename table will behave the same.... } } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index f9ca84473fb3c..7a323b364706d 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -11,7 +11,9 @@ use ast::{blk_, attribute_, attr_outer, meta_word}; use ast::{crate, expr_, expr_mac, mac_invoc_tt}; use ast::{item_mac, stmt_, stmt_mac, stmt_expr, stmt_semi}; +use ast::{SCTable, illegal_ctxt}; use ast; +use ast_util::{new_rename, new_mark, resolve}; use attr; use codemap; use codemap::{span, CallInfo, ExpandedFrom, NameAndSpan, spanned}; @@ -635,62 +637,65 @@ pub fn expand_crate(parse_sess: @mut parse::ParseSess, @f.fold_crate(&*c) } -// given a function from paths to paths, produce +// given a function from idents to idents, produce // an ast_fold that applies that function: -fn fun_to_path_folder(f: @fn(&ast::Path)->ast::Path) -> @ast_fold{ +pub fn fun_to_ident_folder(f: @fn(ast::ident)->ast::ident) -> @ast_fold{ let afp = default_ast_fold(); let f_pre = @AstFoldFns{ - fold_path : |p, _| f(p), + fold_ident : |id, _| f(id), .. *afp }; make_fold(f_pre) } -/* going to have to figure out whether the table is passed in or -extracted from TLS... + // update the ctxts in a path to get a rename node -fn ctxt_update_rename(from: ast::Name, - fromctx: ast::SyntaxContext, to: ast::Name) -> - @fn(&ast::Path,@ast_fold)->ast::Path { - return |p:&ast::Path,_| - ast::Path {span: p.span, - global: p.global, - idents: p.idents.map(|id| - ast::ident{ - repr: id.repr, - // this needs to be cached.... - ctxt: Some(@ast::Rename(from,fromctx, - to,id.ctxt)) - }), - rp: p.rp, - types: p.types}; +pub fn new_ident_renamer(from: ast::ident, + to: ast::Name, + table: @mut SCTable) -> + @fn(ast::ident)->ast::ident { + |id : ast::ident| + ast::ident{ + repr: id.repr, + ctxt: new_rename(from,to,id.ctxt,table) + } } + // update the ctxts in a path to get a mark node -fn ctxt_update_mark(mark: uint) -> - @fn(&ast::Path,@ast_fold)->ast::Path { - return |p:&ast::Path,_| - ast::Path {span: p.span, - global: p.global, - idents: p.idents.map(|id| - ast::ident{ - repr: id.repr, - // this needs to be cached.... - ctxt: Some(@ast::Mark(mark,id.ctxt)) - }), - rp: p.rp, - types: p.types}; +pub fn new_ident_marker(mark: uint, + table: @mut SCTable) -> + @fn(ast::ident)->ast::ident { + |id : ast::ident| + ast::ident{ + repr: id.repr, + ctxt: new_mark(mark,id.ctxt,table) + } } -*/ + +// perform resolution (in the MTWT sense) on all of the +// idents in the tree. This is the final step in expansion. +pub fn new_ident_resolver(table: @mut SCTable) -> + @fn(ast::ident)->ast::ident { + |id : ast::ident| + ast::ident { + repr : resolve(id,table), + ctxt : illegal_ctxt + } +} + #[cfg(test)] mod test { use super::*; use ast; - use ast::{attribute_, attr_outer, meta_word}; + use ast::{attribute_, attr_outer, meta_word, empty_ctxt}; + use ast_util::{new_sctable}; use codemap; use codemap::spanned; use parse; + use core::io; use core::option::{None, Some}; + use util::parser_testing::{string_to_item_and_sess}; // make sure that fail! is present #[test] fn fail_exists_test () { @@ -792,4 +797,22 @@ mod test { } } + #[test] + fn renaming () { + let (maybe_item_ast,sess) = string_to_item_and_sess(@~"fn a() -> int { let b = 13; b} "); + let item_ast = match maybe_item_ast { + Some(x) => x, + None => fail!("test case fail") + }; + let table = @mut new_sctable(); + let a_name = 100; // enforced by testing_interner + let a2_name = sess.interner.gensym(@~"a2").repr; + let renamer = new_ident_renamer(ast::ident{repr:a_name,ctxt:empty_ctxt}, + a2_name,table); + let renamed_ast = fun_to_ident_folder(renamer).fold_item(item_ast).get(); + let resolver = new_ident_resolver(table); + let resolved_ast = fun_to_ident_folder(resolver).fold_item(renamed_ast).get(); + io::print(fmt!("ast: %?\n",resolved_ast)) + } + } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 7aff9f6745cbf..0a9e16f8f7cf6 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -346,21 +346,16 @@ mod test { use std::serialize::Encodable; use std; use core::io; - use core::option::Option; use core::option::Some; use core::option::None; - use core::int; - use core::num::NumCast; - use codemap::{CodeMap, span, BytePos, spanned}; + use codemap::{span, BytePos, spanned}; use opt_vec; use ast; use abi; - use ast_util::mk_ident; + use ast_util::new_ident; use parse::parser::Parser; - use parse::token::{ident_interner, mk_ident_interner, mk_fresh_ident_interner}; - use diagnostic::{span_handler, mk_span_handler, mk_handler, Emitter}; use util::parser_testing::{string_to_tts_and_sess,string_to_parser}; - use util::parser_testing::{string_to_crate, string_to_expr, string_to_item}; + use util::parser_testing::{string_to_expr, string_to_item}; use util::parser_testing::{string_to_stmt}; // map a string to tts, return the tt without its parsesess @@ -384,7 +379,7 @@ mod test { // convert a vector of uints to a vector of ast::idents fn ints_to_idents(ids: ~[uint]) -> ~[ast::ident] { - ids.map(|u| mk_ident(*u)) + ids.map(|u| new_ident(*u)) } #[test] fn path_exprs_1 () { @@ -393,7 +388,7 @@ mod test { callee_id:2, node:ast::expr_path(@ast::Path {span:sp(0,1), global:false, - idents:~[mk_ident(100)], + idents:~[new_ident(100)], rp:None, types:~[]}), span:sp(0,1)}) @@ -456,7 +451,7 @@ mod test { node:ast::expr_path( @ast::Path{span:sp(7,8), global:false, - idents:~[mk_ident(103)], + idents:~[new_ident(103)], rp:None, types:~[] }), @@ -474,7 +469,7 @@ mod test { @ast::Path{ span:sp(0,1), global:false, - idents:~[mk_ident(101)], + idents:~[new_ident(101)], rp:None, types: ~[]}), span: sp(0,1)}, @@ -495,7 +490,7 @@ mod test { @ast::Path{ span:sp(0,1), global:false, - idents:~[mk_ident(101)], + idents:~[new_ident(101)], rp: None, types: ~[]}, None // no idea @@ -514,7 +509,7 @@ mod test { span:sp(4,4), // this is bizarre... // check this in the original parser? global:false, - idents:~[mk_ident(105)], + idents:~[new_ident(105)], rp: None, types: ~[]}, 2), @@ -524,7 +519,7 @@ mod test { @ast::Path{ span:sp(0,1), global:false, - idents:~[mk_ident(101)], + idents:~[new_ident(101)], rp: None, types: ~[]}, None // no idea @@ -540,7 +535,7 @@ mod test { // assignment order of the node_ids. assert_eq!(string_to_item(@~"fn a (b : int) { b; }"), Some( - @ast::item{ident:mk_ident(100), + @ast::item{ident:new_ident(100), attrs:~[], id: 10, // fixme node: ast::item_fn(ast::fn_decl{ @@ -550,7 +545,7 @@ mod test { node: ast::ty_path(@ast::Path{ span:sp(10,13), global:false, - idents:~[mk_ident(106)], + idents:~[new_ident(106)], rp: None, types: ~[]}, 2), @@ -561,7 +556,7 @@ mod test { @ast::Path{ span:sp(6,7), global:false, - idents:~[mk_ident(101)], + idents:~[new_ident(101)], rp: None, types: ~[]}, None // no idea @@ -592,7 +587,7 @@ mod test { @ast::Path{ span:sp(17,18), global:false, - idents:~[mk_ident(101)], + idents:~[new_ident(101)], rp:None, types: ~[]}), span: sp(17,18)}, diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs index 9ab77803576e0..12c28f096f683 100644 --- a/src/libsyntax/util/parser_testing.rs +++ b/src/libsyntax/util/parser_testing.rs @@ -8,22 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::serialize::Encodable; -use std; -use core::io; use core::option::{Option,None}; use core::int; use core::num::NumCast; -use codemap::{dummy_sp, CodeMap, BytePos, spanned}; -use opt_vec; +use codemap::CodeMap; use ast; -use abi; -use ast_util::mk_ident; use parse::parser::Parser; -use parse::token::{ident_interner, mk_ident_interner, mk_fresh_ident_interner}; -use diagnostic::{span_handler, mk_span_handler, mk_handler, Emitter}; +use parse::token::{ident_interner, mk_fresh_ident_interner}; +use diagnostic::{mk_handler, mk_span_handler}; -use syntax::parse::{ParseSess,new_parse_sess,string_to_filemap,filemap_to_tts}; +use syntax::parse::{ParseSess,string_to_filemap,filemap_to_tts}; use syntax::parse::{new_parser_from_source_str}; // add known names to interner for testing @@ -71,10 +65,15 @@ pub fn string_to_tts_and_sess (source_str : @~str) -> (~[ast::token_tree],@mut P (filemap_to_tts(ps,string_to_filemap(ps,source_str,~"bogofile")),ps) } +pub fn string_to_parser_and_sess(source_str: @~str) -> (Parser,@mut ParseSess) { + let ps = mk_testing_parse_sess(); + (new_parser_from_source_str(ps,~[],~"bogofile",source_str),ps) +} + // map string to parser (via tts) pub fn string_to_parser(source_str: @~str) -> Parser { - let ps = mk_testing_parse_sess(); - new_parser_from_source_str(ps,~[],~"bogofile",source_str) + let (p,_) = string_to_parser_and_sess(source_str); + p } pub fn string_to_crate (source_str : @~str) -> @ast::crate { @@ -86,10 +85,17 @@ pub fn string_to_expr (source_str : @~str) -> @ast::expr { string_to_parser(source_str).parse_expr() } +// parse a string, return an item pub fn string_to_item (source_str : @~str) -> Option<@ast::item> { string_to_parser(source_str).parse_item(~[]) } +// parse a string, return an item and the ParseSess +pub fn string_to_item_and_sess (source_str : @~str) -> (Option<@ast::item>,@mut ParseSess) { + let (p,ps) = string_to_parser_and_sess(source_str); + (p.parse_item(~[]),ps) +} + pub fn string_to_stmt (source_str : @~str) -> @ast::stmt { string_to_parser(source_str).parse_stmt(~[]) } From 999f6926459294136b623b101c8a033ec8ec29db Mon Sep 17 00:00:00 2001 From: John Clements Date: Tue, 7 May 2013 12:34:52 -0700 Subject: [PATCH 128/248] getting rid of interner_key! macro --- src/librustdoc/extract.rs | 18 ++++------- src/libsyntax/ast.rs | 24 ++++---------- src/libsyntax/ext/expand.rs | 2 +- src/libsyntax/parse/lexer.rs | 2 +- src/libsyntax/parse/mod.rs | 43 +++++++++++++------------ src/libsyntax/parse/token.rs | 29 +++++++++++------ src/libsyntax/syntax.rc | 3 -- src/libsyntax/util/interner.rs | 16 ++-------- src/libsyntax/util/parser_testing.rs | 48 ++-------------------------- 9 files changed, 60 insertions(+), 125 deletions(-) diff --git a/src/librustdoc/extract.rs b/src/librustdoc/extract.rs index 0c49d457ad809..e3da6e6844e52 100644 --- a/src/librustdoc/extract.rs +++ b/src/librustdoc/extract.rs @@ -17,24 +17,18 @@ use doc; use core::local_data::local_data_get; use syntax::ast; use syntax; - -/* can't import macros yet, so this is copied from token.rs. See its comment - * there. */ -macro_rules! interner_key ( - () => (cast::transmute::<(uint, uint), - &fn(v: @@syntax::parse::token::ident_interner)>((-3 as uint, 0u))) -) +use syntax::parse::token::{ident_interner}; +use syntax::parse::token; // Hack; rather than thread an interner through everywhere, rely on // thread-local data pub fn to_str(id: ast::ident) -> ~str { - let intr = unsafe{ local_data_get(interner_key!()) }; - - return copy *(*intr.get()).get(id); + let intr = token::get_ident_interner(); + return copy *(*intr).get(id); } -pub fn interner() -> @syntax::parse::token::ident_interner { - return *(unsafe{ local_data_get(interner_key!()) }).get(); +pub fn interner() -> @ident_interner { + return token::get_ident_interner(); } pub fn from_srv( diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 2b98803364c11..a8ff8dab54c19 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -13,9 +13,10 @@ use codemap::{span, spanned}; use abi::AbiSet; use opt_vec::OptVec; +use parse::token::get_ident_interner; use core::cast; -use core::option::{None, Option, Some}; +use core::option::{Option}; use core::to_bytes; use core::to_bytes::IterBytes; use core::to_str::ToStr; @@ -67,7 +68,7 @@ pub enum SyntaxContext_ { // in the "from" slot. In essence, they're all // pointers to a single "rename" event node. Rename (ident,Name,SyntaxContext), - IllegalCtxt() + IllegalCtxt() } // a name represents an identifier @@ -78,27 +79,14 @@ pub type Mrk = uint; impl Encodable for ident { fn encode(&self, s: &mut S) { - unsafe { - let intr = - match local_data::local_data_get(interner_key!()) { - None => fail!("encode: TLS interner not set up"), - Some(intr) => intr - }; - - s.emit_str(*(*intr).get(*self)); - } + let intr = get_ident_interner(); + s.emit_str(*(*intr).get(*self)); } } impl Decodable for ident { fn decode(d: &mut D) -> ident { - let intr = match unsafe { - local_data::local_data_get(interner_key!()) - } { - None => fail!("decode: TLS interner not set up"), - Some(intr) => intr - }; - + let intr = get_ident_interner(); (*intr).intern(d.read_str()) } } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 7a323b364706d..db95cb65b7660 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -806,7 +806,7 @@ mod test { }; let table = @mut new_sctable(); let a_name = 100; // enforced by testing_interner - let a2_name = sess.interner.gensym(@~"a2").repr; + let a2_name = sess.interner.gensym("a2").repr; let renamer = new_ident_renamer(ast::ident{repr:a_name,ctxt:empty_ctxt}, a2_name,table); let renamed_ast = fun_to_ident_folder(renamer).fold_item(item_ast).get(); diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index 764dec0eeb391..5340293bb0249 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -786,7 +786,7 @@ mod test { fn setup(teststr: ~str) -> Env { let cm = CodeMap::new(); let fm = cm.new_filemap(~"zebra.rs", @teststr); - let ident_interner = token::mk_ident_interner(); // interner::mk(); + let ident_interner = token::get_ident_interner(); let span_handler = diagnostic::mk_span_handler(diagnostic::mk_handler(None),@cm); Env { diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 0a9e16f8f7cf6..8eb7ca2923c25 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -19,7 +19,7 @@ use diagnostic::{span_handler, mk_span_handler, mk_handler, Emitter}; use parse::attr::parser_attr; use parse::lexer::reader; use parse::parser::Parser; -use parse::token::{ident_interner, mk_ident_interner}; +use parse::token::{ident_interner, get_ident_interner}; use core::io; use core::option::{None, Option, Some}; @@ -59,7 +59,7 @@ pub fn new_parse_sess(demitter: Option) -> @mut ParseSess { cm: cm, next_id: 1, span_diagnostic: mk_span_handler(mk_handler(demitter), cm), - interner: mk_ident_interner(), + interner: get_ident_interner(), } } @@ -70,7 +70,7 @@ pub fn new_parse_sess_special_handler(sh: @span_handler, cm: cm, next_id: 1, span_diagnostic: sh, - interner: mk_ident_interner(), + interner: get_ident_interner(), } } @@ -352,8 +352,8 @@ mod test { use opt_vec; use ast; use abi; - use ast_util::new_ident; use parse::parser::Parser; + use parse::token::intern; use util::parser_testing::{string_to_tts_and_sess,string_to_parser}; use util::parser_testing::{string_to_expr, string_to_item}; use util::parser_testing::{string_to_stmt}; @@ -378,8 +378,8 @@ mod test { } // convert a vector of uints to a vector of ast::idents - fn ints_to_idents(ids: ~[uint]) -> ~[ast::ident] { - ids.map(|u| new_ident(*u)) + fn ints_to_idents(ids: ~[~str]) -> ~[ast::ident] { + ids.map(|u| intern(*u)) } #[test] fn path_exprs_1 () { @@ -388,7 +388,7 @@ mod test { callee_id:2, node:ast::expr_path(@ast::Path {span:sp(0,1), global:false, - idents:~[new_ident(100)], + idents:~[intern("a")], rp:None, types:~[]}), span:sp(0,1)}) @@ -398,11 +398,12 @@ mod test { assert_eq!(string_to_expr(@~"::a::b"), @ast::expr{id:1, callee_id:2, - node:ast::expr_path(@ast::Path {span:sp(0,6), - global:true, - idents:ints_to_idents(~[100,101]), - rp:None, - types:~[]}), + node:ast::expr_path( + @ast::Path {span:sp(0,6), + global:true, + idents:ints_to_idents(~[~"a",~"b"]), + rp:None, + types:~[]}), span:sp(0,6)}) } @@ -451,7 +452,7 @@ mod test { node:ast::expr_path( @ast::Path{span:sp(7,8), global:false, - idents:~[new_ident(103)], + idents:~[intern("d")], rp:None, types:~[] }), @@ -469,7 +470,7 @@ mod test { @ast::Path{ span:sp(0,1), global:false, - idents:~[new_ident(101)], + idents:~[intern("b")], rp:None, types: ~[]}), span: sp(0,1)}, @@ -490,7 +491,7 @@ mod test { @ast::Path{ span:sp(0,1), global:false, - idents:~[new_ident(101)], + idents:~[intern("b")], rp: None, types: ~[]}, None // no idea @@ -509,7 +510,7 @@ mod test { span:sp(4,4), // this is bizarre... // check this in the original parser? global:false, - idents:~[new_ident(105)], + idents:~[intern("int")], rp: None, types: ~[]}, 2), @@ -519,7 +520,7 @@ mod test { @ast::Path{ span:sp(0,1), global:false, - idents:~[new_ident(101)], + idents:~[intern("b")], rp: None, types: ~[]}, None // no idea @@ -535,7 +536,7 @@ mod test { // assignment order of the node_ids. assert_eq!(string_to_item(@~"fn a (b : int) { b; }"), Some( - @ast::item{ident:new_ident(100), + @ast::item{ident:intern("a"), attrs:~[], id: 10, // fixme node: ast::item_fn(ast::fn_decl{ @@ -545,7 +546,7 @@ mod test { node: ast::ty_path(@ast::Path{ span:sp(10,13), global:false, - idents:~[new_ident(106)], + idents:~[intern("int")], rp: None, types: ~[]}, 2), @@ -556,7 +557,7 @@ mod test { @ast::Path{ span:sp(6,7), global:false, - idents:~[new_ident(101)], + idents:~[intern("b")], rp: None, types: ~[]}, None // no idea @@ -587,7 +588,7 @@ mod test { @ast::Path{ span:sp(17,18), global:false, - idents:~[new_ident(101)], + idents:~[intern("b")], rp:None, types: ~[]}), span: sp(17,18)}, diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 88fa538908923..b4bad5abbf936 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -411,8 +411,7 @@ pub impl ident_interner { } // return a fresh interner, preloaded with special identifiers. -// EFFECT: stores this interner in TLS -pub fn mk_fresh_ident_interner() -> @ident_interner { +fn mk_fresh_ident_interner() -> @ident_interner { // the indices here must correspond to the numbers in // special_idents. let init_vec = ~[ @@ -453,23 +452,27 @@ pub fn mk_fresh_ident_interner() -> @ident_interner { "Self", // 34 ]; - let rv = @ident_interner { + @ident_interner { interner: interner::StrInterner::prefill(init_vec) - }; - unsafe { - local_data::local_data_set(interner_key!(), @rv); } - rv } // if an interner exists in TLS, return it. Otherwise, prepare a // fresh one. -pub fn mk_ident_interner() -> @ident_interner { +pub fn get_ident_interner() -> @ident_interner { unsafe { - match local_data::local_data_get(interner_key!()) { + let key = + (cast::transmute::<(uint, uint), + &fn(v: @@::parse::token::ident_interner)>( + (-3 as uint, 0u))); + match local_data::local_data_get(key) { Some(interner) => *interner, None => { - mk_fresh_ident_interner() + let interner = mk_fresh_ident_interner(); + unsafe { + local_data::local_data_set(key, @interner); + } + interner } } } @@ -481,6 +484,12 @@ pub fn mk_fake_ident_interner() -> @ident_interner { @ident_interner { interner: interner::StrInterner::new() } } +// maps a string to its interned representation +pub fn intern(str : &str) -> ast::ident { + let interner = get_ident_interner(); + interner.intern(str) +} + /** * All the valid words that have meaning in the Rust language. * diff --git a/src/libsyntax/syntax.rc b/src/libsyntax/syntax.rc index 7ac8c08b25d8a..0650df576031b 100644 --- a/src/libsyntax/syntax.rc +++ b/src/libsyntax/syntax.rc @@ -25,9 +25,6 @@ extern mod std; -// allow the interner_key macro -// to escape this module: -#[macro_escape] pub mod util { pub mod interner; #[cfg(test)] diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index cca2ec89fd421..5d49c8cd75d86 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -12,9 +12,6 @@ // allows bidirectional lookup; i.e. given a value, one can easily find the // type, and vice versa. -// allow the interner_key macro to escape this module: -#[macro_escape]; - use core::cmp::Equiv; use core::hashmap::HashMap; use syntax::parse::token::StringRef; @@ -78,6 +75,8 @@ pub impl Interner { } } +// A StrInterner differs from Interner in that it accepts +// borrowed pointers rather than @ ones, resulting in less allocation. pub struct StrInterner { priv map: @mut HashMap<@~str, uint>, priv vect: @mut ~[@~str], @@ -133,17 +132,6 @@ pub impl StrInterner { } } -/* Key for thread-local data for sneaking interner information to the -* encoder/decoder. It sounds like a hack because it is one. -* Bonus ultra-hack: functions as keys don't work across crates, -* so we have to use a unique number. See taskgroup_key! in task.rs -* for another case of this. */ -macro_rules! interner_key ( - () => (cast::transmute::<(uint, uint), - &fn(v: @@::parse::token::ident_interner)>( - (-3 as uint, 0u))) -) - #[cfg(test)] mod tests { use super::*; diff --git a/src/libsyntax/util/parser_testing.rs b/src/libsyntax/util/parser_testing.rs index 12c28f096f683..1c2210c96b6c2 100644 --- a/src/libsyntax/util/parser_testing.rs +++ b/src/libsyntax/util/parser_testing.rs @@ -9,64 +9,22 @@ // except according to those terms. use core::option::{Option,None}; -use core::int; -use core::num::NumCast; -use codemap::CodeMap; use ast; use parse::parser::Parser; -use parse::token::{ident_interner, mk_fresh_ident_interner}; -use diagnostic::{mk_handler, mk_span_handler}; +use parse::{new_parse_sess}; use syntax::parse::{ParseSess,string_to_filemap,filemap_to_tts}; use syntax::parse::{new_parser_from_source_str}; -// add known names to interner for testing -fn mk_testing_interner() -> @ident_interner { - let i = mk_fresh_ident_interner(); - // baby hack; in order to put the identifiers - // 'a' and 'b' at known locations, we're going - // to fill up the interner to length 100. If - // the # of preloaded items on the interner - // ever gets larger than 100, we'll have to - // adjust this number (say, to 200) and - // change the numbers in the identifier - // test cases below. - - assert!(i.len() < 100); - for int::range(0,100-((i.len()).to_int())) |_dc| { - i.gensym(~"dontcare"); - } - i.intern("a"); - i.intern("b"); - i.intern("c"); - i.intern("d"); - i.intern("return"); - assert!(i.get(ast::ident{repr:101,ctxt:0}) == @~"b"); - i -} - -// make a parse_sess that's closed over a -// testing interner (where a -> 100, b -> 101) -fn mk_testing_parse_sess() -> @mut ParseSess { - let interner = mk_testing_interner(); - let cm = @CodeMap::new(); - @mut ParseSess { - cm: cm, - next_id: 1, - span_diagnostic: mk_span_handler(mk_handler(None), cm), - interner: interner, - } -} - // map a string to tts, using a made-up filename: return both the token_trees // and the ParseSess pub fn string_to_tts_and_sess (source_str : @~str) -> (~[ast::token_tree],@mut ParseSess) { - let ps = mk_testing_parse_sess(); + let ps = new_parse_sess(None); (filemap_to_tts(ps,string_to_filemap(ps,source_str,~"bogofile")),ps) } pub fn string_to_parser_and_sess(source_str: @~str) -> (Parser,@mut ParseSess) { - let ps = mk_testing_parse_sess(); + let ps = new_parse_sess(None); (new_parser_from_source_str(ps,~[],~"bogofile",source_str),ps) } From b71a1ecea2de87cff3089f9f261be71cd314aac9 Mon Sep 17 00:00:00 2001 From: John Clements Date: Fri, 3 May 2013 10:29:08 -0700 Subject: [PATCH 129/248] added and rewrote text for 'do' and 'for' loops --- doc/rust.md | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/doc/rust.md b/doc/rust.md index 9839e9e8afd74..a115f41ae864b 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -2250,6 +2250,14 @@ do_expr : "do" expr [ '|' ident_list '|' ] ? '{' block '}' ; A _do expression_ provides a more-familiar block-syntax for a [lambda expression](#lambda-expressions), including a special translation of [return expressions](#return-expressions) inside the supplied block. +Any occurrence of a [return expression](#return-expressions) +inside this `block` expression is rewritten +as a reference to an (anonymous) flag set in the caller's environment, +which is checked on return from the `expr` and, if set, +causes a corresponding return from the caller. +In this way, the meaning of `return` statements in language built-in control blocks is preserved, +if they are rewritten using lambda functions and `do` expressions as abstractions. + The optional `ident_list` and `block` provided in a `do` expression are parsed as though they constitute a lambda expression; if the `ident_list` is missing, an empty `ident_list` is implied. @@ -2296,19 +2304,15 @@ A _for expression_ is similar to a [`do` expression](#do-expressions), in that it provides a special block-form of lambda expression, suited to passing the `block` function to a higher-order function implementing a loop. -Like a `do` expression, a `return` expression inside a `for` expresison is rewritten, -to access a local flag that causes an early return in the caller. - -Additionally, any occurrence of a [return expression](#return-expressions) -inside the `block` of a `for` expression is rewritten -as a reference to an (anonymous) flag set in the caller's environment, -which is checked on return from the `expr` and, if set, -causes a corresponding return from the caller. -In this way, the meaning of `return` statements in language built-in control blocks is preserved, -if they are rewritten using lambda functions and `do` expressions as abstractions. +In contrast to a `do` expression, a `for` expression is designed to work +with methods such as `each` and `times`, that require the body block to +return a boolean. The `for` expression accommodates this by implicitly +returning `true` at the end of each block, unless a `break` expression +is evaluated. -Like `return` expressions, any [`break`](#break-expressions) and [`loop`](#loop-expressions) expressions -are rewritten inside `for` expressions, with a combination of local flag variables, +In addition, [`break`](#break-expressions) and [`loop`](#loop-expressions) expressions +are rewritten inside `for` expressions in the same way that `return` expressions are, +with a combination of local flag variables, and early boolean-valued returns from the `block` function, such that the meaning of `break` and `loop` is preserved in a primitive loop when rewritten as a `for` loop controlled by a higher order function. From 074799b4c586c521ba678a4dc3809cad1a872dfe Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sat, 18 May 2013 03:07:28 -0400 Subject: [PATCH 130/248] Implement a lint mode to detect unnecessary allocations --- src/librustc/middle/lint.rs | 70 +++++++++++++++++++++++++++++++++++++ src/libsyntax/ext/env.rs | 6 ++-- 2 files changed, 73 insertions(+), 3 deletions(-) diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 079fb21a4fef9..6a1a8940a05c1 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -79,6 +79,7 @@ pub enum lint { unused_variable, dead_assignment, unused_mut, + unnecessary_allocation, } pub fn level_to_str(lv: level) -> &'static str { @@ -242,6 +243,13 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[ desc: "detect mut variables which don't need to be mutable", default: warn }), + + ("unnecessary_allocation", + LintSpec { + lint: unnecessary_allocation, + desc: "detects unnecessary allocations that can be eliminated", + default: warn + }), ]; /* @@ -881,6 +889,67 @@ fn lint_session(cx: @mut Context) -> visit::vt<()> { }) } +fn lint_unnecessary_allocations(cx: @mut Context) -> visit::vt<()> { + // If the expression `e` has an allocated type, but `t` dictates that it's + // something like a slice (doesn't need allocation), emit a warning with the + // specified span. + // + // Currently, this only applies to string and vector literals with sigils in + // front. Those can have the sigil removed to get a borrowed pointer + // automatically. + fn check(cx: @mut Context, e: @ast::expr, t: ty::t) { + match e.node { + ast::expr_vstore(e2, ast::expr_vstore_uniq) | + ast::expr_vstore(e2, ast::expr_vstore_box) => { + match e2.node { + ast::expr_lit(@codemap::spanned{ + node: ast::lit_str(*), _}) | + ast::expr_vec(*) => {} + _ => return + } + } + + _ => return + } + + match ty::get(t).sty { + ty::ty_estr(ty::vstore_slice(*)) | + ty::ty_evec(_, ty::vstore_slice(*)) => { + cx.span_lint(unnecessary_allocation, + e.span, "unnecessary allocation, the sigil can be \ + removed"); + } + + _ => () + } + } + + let visit_expr: @fn(@ast::expr) = |e| { + match e.node { + ast::expr_call(c, ref args, _) => { + let t = ty::node_id_to_type(cx.tcx, c.id); + let s = ty::ty_fn_sig(t); + for vec::each2(*args, s.inputs) |e, t| { + check(cx, *e, *t); + } + } + ast::expr_method_call(_, _, _, ref args, _) => { + let t = ty::node_id_to_type(cx.tcx, e.callee_id); + let s = ty::ty_fn_sig(t); + for vec::each2(*args, s.inputs) |e, t| { + check(cx, *e, *t); + } + } + _ => {} + } + }; + + visit::mk_simple_visitor(@visit::SimpleVisitor { + visit_expr: visit_expr, + .. *visit::default_simple_visitor() + }) +} + pub fn check_crate(tcx: ty::ctxt, crate: @ast::crate) { let cx = @mut Context { dict: @get_lint_dict(), @@ -908,6 +977,7 @@ pub fn check_crate(tcx: ty::ctxt, crate: @ast::crate) { cx.add_lint(lint_unused_unsafe(cx)); cx.add_lint(lint_unused_mut(cx)); cx.add_lint(lint_session(cx)); + cx.add_lint(lint_unnecessary_allocations(cx)); // type inference doesn't like this being declared below, we need to tell it // what the type of this first function is... diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 5b1e3737b236b..4be75d9ee5b57 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -18,7 +18,7 @@ use ast; use codemap::span; use ext::base::*; use ext::base; -use ext::build::mk_uniq_str; +use ext::build::mk_base_str; pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { @@ -29,8 +29,8 @@ pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) // Option rather than just an maybe-empty string. let e = match os::getenv(var) { - None => mk_uniq_str(cx, sp, ~""), - Some(ref s) => mk_uniq_str(cx, sp, copy *s) + None => mk_base_str(cx, sp, ~""), + Some(ref s) => mk_base_str(cx, sp, copy *s) }; MRExpr(e) } From 82fa0018c80c8f64cb1b446a7e59492d9ad97b1d Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 19 May 2013 01:07:44 -0400 Subject: [PATCH 131/248] Remove all unnecessary allocations (as flagged by lint) --- src/libcore/os.rs | 2 +- src/libcore/str.rs | 2 +- src/libcore/unstable/extfmt.rs | 4 +- src/librustc/back/link.rs | 43 +- src/librustc/back/rpath.rs | 6 +- src/librustc/driver/driver.rs | 109 +++-- src/librustc/driver/session.rs | 2 +- src/librustc/front/config.rs | 2 +- src/librustc/front/core_inject.rs | 2 +- src/librustc/front/intrinsic_inject.rs | 2 +- src/librustc/front/test.rs | 16 +- src/librustc/metadata/creader.rs | 8 +- src/librustc/metadata/decoder.rs | 14 +- src/librustc/metadata/encoder.rs | 8 +- src/librustc/metadata/filesearch.rs | 4 +- src/librustc/metadata/loader.rs | 4 +- src/librustc/metadata/tyencode.rs | 10 +- src/librustc/middle/astencode.rs | 14 +- src/librustc/middle/borrowck/check_loans.rs | 4 +- src/librustc/middle/borrowck/mod.rs | 18 +- src/librustc/middle/check_match.rs | 2 +- src/librustc/middle/dataflow.rs | 4 +- src/librustc/middle/entry.rs | 22 +- src/librustc/middle/kind.rs | 4 +- src/librustc/middle/lint.rs | 4 +- src/librustc/middle/liveness.rs | 20 +- src/librustc/middle/privacy.rs | 2 +- src/librustc/middle/region.rs | 2 +- src/librustc/middle/resolve.rs | 52 +-- src/librustc/middle/trans/_match.rs | 33 +- src/librustc/middle/trans/adt.rs | 13 +- src/librustc/middle/trans/base.rs | 328 +++++++------- src/librustc/middle/trans/build.rs | 18 +- src/librustc/middle/trans/cabi.rs | 2 +- src/librustc/middle/trans/callee.rs | 5 +- src/librustc/middle/trans/closure.rs | 6 +- src/librustc/middle/trans/common.rs | 40 +- src/librustc/middle/trans/consts.rs | 14 +- src/librustc/middle/trans/controlflow.rs | 6 +- src/librustc/middle/trans/debuginfo.rs | 54 +-- src/librustc/middle/trans/expr.rs | 26 +- src/librustc/middle/trans/foreign.rs | 118 ++--- src/librustc/middle/trans/glue.rs | 38 +- src/librustc/middle/trans/inline.rs | 8 +- src/librustc/middle/trans/machine.rs | 2 +- src/librustc/middle/trans/meth.rs | 14 +- src/librustc/middle/trans/monomorphize.rs | 25 +- src/librustc/middle/trans/reachable.rs | 4 +- src/librustc/middle/trans/shape.rs | 4 +- src/librustc/middle/trans/tvec.rs | 12 +- src/librustc/middle/trans/type_of.rs | 31 +- src/librustc/middle/trans/write_guard.rs | 12 +- src/librustc/middle/ty.rs | 61 ++- src/librustc/middle/typeck/check/mod.rs | 12 +- .../middle/typeck/infer/region_inference.rs | 8 +- src/librustc/middle/typeck/mod.rs | 4 +- src/librustc/rustc.rc | 30 +- src/librustc/util/ppaux.rs | 10 +- src/libstd/dlist.rs | 8 +- src/libstd/getopts.rs | 8 +- src/libstd/json.rs | 6 +- src/libstd/md4.rs | 2 +- src/libstd/net_url.rs | 10 +- src/libstd/rope.rs | 4 +- src/libstd/sha1.rs | 2 +- src/libstd/term.rs | 10 +- src/libstd/test.rs | 44 +- src/libstd/time.rs | 26 +- src/libsyntax/ast_map.rs | 2 +- src/libsyntax/ast_util.rs | 2 +- src/libsyntax/attr.rs | 6 +- src/libsyntax/diagnostic.rs | 4 +- src/libsyntax/ext/base.rs | 4 +- src/libsyntax/ext/concat_idents.rs | 6 +- src/libsyntax/ext/deriving/decodable.rs | 2 +- src/libsyntax/ext/deriving/encodable.rs | 2 +- src/libsyntax/ext/deriving/generic.rs | 12 +- src/libsyntax/ext/deriving/mod.rs | 4 +- src/libsyntax/ext/deriving/to_str.rs | 2 +- src/libsyntax/ext/deriving/ty.rs | 4 +- src/libsyntax/ext/expand.rs | 7 +- src/libsyntax/ext/fmt.rs | 2 +- src/libsyntax/ext/pipes/liveness.rs | 2 +- src/libsyntax/ext/pipes/parse_proto.rs | 2 +- src/libsyntax/ext/pipes/pipec.rs | 4 +- src/libsyntax/ext/quote.rs | 6 +- src/libsyntax/ext/source_util.rs | 2 +- src/libsyntax/ext/trace_macros.rs | 2 +- src/libsyntax/ext/tt/macro_parser.rs | 4 +- src/libsyntax/ext/tt/macro_rules.rs | 10 +- src/libsyntax/ext/tt/transcribe.rs | 10 +- src/libsyntax/parse/attr.rs | 2 +- src/libsyntax/parse/comments.rs | 16 +- src/libsyntax/parse/common.rs | 4 +- src/libsyntax/parse/parser.rs | 50 +-- src/libsyntax/parse/token.rs | 4 +- src/libsyntax/print/pp.rs | 2 +- src/libsyntax/print/pprust.rs | 422 +++++++++--------- src/test/compile-fail/lint-unused-imports.rs | 4 +- 99 files changed, 1022 insertions(+), 1027 deletions(-) diff --git a/src/libcore/os.rs b/src/libcore/os.rs index b6943462f068b..b2a30e50992c8 100644 --- a/src/libcore/os.rs +++ b/src/libcore/os.rs @@ -509,7 +509,7 @@ pub fn self_exe_path() -> Option { * Otherwise, homedir returns option::none. */ pub fn homedir() -> Option { - return match getenv(~"HOME") { + return match getenv("HOME") { Some(ref p) => if !str::is_empty(*p) { Some(Path(*p)) } else { diff --git a/src/libcore/str.rs b/src/libcore/str.rs index a760ff8f26277..53169554ec5e7 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -1808,7 +1808,7 @@ pub fn to_utf16(s: &str) -> ~[u16] { ch -= 0x1_0000_u32; let w1 = 0xD800_u16 | ((ch >> 10) as u16); let w2 = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16); - u.push_all(~[w1, w2]) + u.push_all([w1, w2]) } } u diff --git a/src/libcore/unstable/extfmt.rs b/src/libcore/unstable/extfmt.rs index 1a1a89a413fcc..8da378fdc97ce 100644 --- a/src/libcore/unstable/extfmt.rs +++ b/src/libcore/unstable/extfmt.rs @@ -178,7 +178,7 @@ pub mod ct { i += 1; if i >= lim { - err(~"unterminated conversion at end of string"); + err("unterminated conversion at end of string"); } else if s[i] == '%' as u8 { push_slice(&mut pieces, s, h, i); i += 1; @@ -309,7 +309,7 @@ pub mod ct { pub fn parse_type(s: &str, i: uint, lim: uint, err: ErrorFn) -> Parsed { - if i >= lim { err(~"missing type in conversion"); } + if i >= lim { err("missing type in conversion"); } // FIXME (#2249): Do we really want two signed types here? // How important is it to be printf compatible? diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index 92d3a451559f3..f999c20a7d0ec 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -387,8 +387,8 @@ pub mod write { fmt!("%s/bin/arm-linux-androideabi-gcc", path) } &None => { - sess.fatal(~"need Android NDK path for building \ - (--android-cross-path)") + sess.fatal("need Android NDK path for building \ + (--android-cross-path)") } }; let mut cc_args = ~[]; @@ -403,7 +403,7 @@ pub mod write { sess.err(fmt!("building with `%s` failed with code %d", cc_prog, prog.status)); sess.note(fmt!("%s arguments: %s", - cc_prog, str::connect(cc_args, ~" "))); + cc_prog, str::connect(cc_args, " "))); sess.note(prog.err + prog.out); sess.abort_if_errors(); } @@ -566,7 +566,7 @@ pub fn build_link_meta(sess: Session, || fmt!("output file name `%s` doesn't\ appear to have a stem", output.to_str())).to_managed(); - warn_missing(sess, ~"name", name); + warn_missing(sess, "name", name); name } }; @@ -577,7 +577,7 @@ pub fn build_link_meta(sess: Session, Some(v) => v, None => { let vers = @"0.0"; - warn_missing(sess, ~"vers", vers); + warn_missing(sess, "vers", vers); vers } }; @@ -618,9 +618,9 @@ pub fn symbol_hash(tcx: ty::ctxt, symbol_hasher.reset(); write_string(symbol_hasher, link_meta.name); - write_string(symbol_hasher, ~"-"); + write_string(symbol_hasher, "-"); write_string(symbol_hasher, link_meta.extras_hash); - write_string(symbol_hasher, ~"-"); + write_string(symbol_hasher, "-"); write_string(symbol_hasher, encoder::encoded_ty(tcx, t)); let mut hash = truncated_hash_result(symbol_hasher); // Prefix with _ so that it never blends into adjacent digits @@ -770,8 +770,8 @@ pub fn link_binary(sess: Session, fmt!("%s/bin/arm-linux-androideabi-gcc", path) } &None => { - sess.fatal(~"need Android NDK path for linking \ - (--android-cross-path)") + sess.fatal("need Android NDK path for linking \ + (--android-cross-path)") } } } else if sess.targ_cfg.os == session::os_win32 { @@ -798,21 +798,21 @@ pub fn link_binary(sess: Session, debug!("output: %s", output.to_str()); let cc_args = link_args(sess, obj_filename, out_filename, lm); - debug!("%s link args: %s", cc_prog, str::connect(cc_args, ~" ")); + debug!("%s link args: %s", cc_prog, str::connect(cc_args, " ")); // We run 'cc' here let prog = run::program_output(cc_prog, cc_args); if 0 != prog.status { sess.err(fmt!("linking with `%s` failed with code %d", cc_prog, prog.status)); sess.note(fmt!("%s arguments: %s", - cc_prog, str::connect(cc_args, ~" "))); + cc_prog, str::connect(cc_args, " "))); sess.note(prog.err + prog.out); sess.abort_if_errors(); } // Clean up on Darwin if sess.targ_cfg.os == session::os_macos { - run::run_program(~"dsymutil", ~[output.to_str()]); + run::run_program("dsymutil", [output.to_str()]); } // Remove the temporary object file if we aren't saving temps @@ -920,7 +920,7 @@ pub fn link_args(sess: Session, // On linux librt and libdl are an indirect dependencies via rustrt, // and binutils 2.22+ won't add them automatically if sess.targ_cfg.os == session::os_linux { - args.push_all(~[~"-lrt", ~"-ldl"]); + args.push_all([~"-lrt", ~"-ldl"]); // LLVM implements the `frem` instruction as a call to `fmod`, // which lives in libm. Similar to above, on some linuxes we @@ -928,19 +928,18 @@ pub fn link_args(sess: Session, args.push(~"-lm"); } else if sess.targ_cfg.os == session::os_android { - args.push_all(~[~"-ldl", ~"-llog", ~"-lsupc++", - ~"-lgnustl_shared"]); + args.push_all([~"-ldl", ~"-llog", ~"-lsupc++", ~"-lgnustl_shared"]); args.push(~"-lm"); } if sess.targ_cfg.os == session::os_freebsd { - args.push_all(~[~"-pthread", ~"-lrt", - ~"-L/usr/local/lib", ~"-lexecinfo", - ~"-L/usr/local/lib/gcc46", - ~"-L/usr/local/lib/gcc44", ~"-lstdc++", - ~"-Wl,-z,origin", - ~"-Wl,-rpath,/usr/local/lib/gcc46", - ~"-Wl,-rpath,/usr/local/lib/gcc44"]); + args.push_all([~"-pthread", ~"-lrt", + ~"-L/usr/local/lib", ~"-lexecinfo", + ~"-L/usr/local/lib/gcc46", + ~"-L/usr/local/lib/gcc44", ~"-lstdc++", + ~"-Wl,-z,origin", + ~"-Wl,-rpath,/usr/local/lib/gcc46", + ~"-Wl,-rpath,/usr/local/lib/gcc44"]); } // OS X 10.6 introduced 'compact unwind info', which is produced by the diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 4b3ed4c70f596..0dd37f0b9070a 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -86,9 +86,9 @@ fn get_rpaths(os: session::os, } } - log_rpaths(~"relative", rel_rpaths); - log_rpaths(~"absolute", abs_rpaths); - log_rpaths(~"fallback", fallback_rpaths); + log_rpaths("relative", rel_rpaths); + log_rpaths("absolute", abs_rpaths); + log_rpaths("fallback", fallback_rpaths); let mut rpaths = rel_rpaths; rpaths.push_all(abs_rpaths); diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 00621573b886a..33c70a3d4259f 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -376,7 +376,7 @@ pub fn pretty_print_input(sess: Session, cfg: ast::crate_cfg, input: &input, match node { pprust::node_expr(s, expr) => { pp::space(s.s); - pp::word(s.s, ~"as"); + pp::word(s.s, "as"); pp::space(s.s); pp::word(s.s, ppaux::ty_to_str(tcx, ty::expr_ty(tcx, expr))); pprust::pclose(s); @@ -442,33 +442,33 @@ pub fn pretty_print_input(sess: Session, cfg: ast::crate_cfg, input: &input, } pub fn get_os(triple: &str) -> Option { - if str::contains(triple, ~"win32") || - str::contains(triple, ~"mingw32") { + if str::contains(triple, "win32") || + str::contains(triple, "mingw32") { Some(session::os_win32) - } else if str::contains(triple, ~"darwin") { + } else if str::contains(triple, "darwin") { Some(session::os_macos) - } else if str::contains(triple, ~"android") { + } else if str::contains(triple, "android") { Some(session::os_android) - } else if str::contains(triple, ~"linux") { + } else if str::contains(triple, "linux") { Some(session::os_linux) - } else if str::contains(triple, ~"freebsd") { + } else if str::contains(triple, "freebsd") { Some(session::os_freebsd) } else { None } } pub fn get_arch(triple: &str) -> Option { - if str::contains(triple, ~"i386") || - str::contains(triple, ~"i486") || - str::contains(triple, ~"i586") || - str::contains(triple, ~"i686") || - str::contains(triple, ~"i786") { + if str::contains(triple, "i386") || + str::contains(triple, "i486") || + str::contains(triple, "i586") || + str::contains(triple, "i686") || + str::contains(triple, "i786") { Some(abi::X86) - } else if str::contains(triple, ~"x86_64") { + } else if str::contains(triple, "x86_64") { Some(abi::X86_64) - } else if str::contains(triple, ~"arm") || - str::contains(triple, ~"xscale") { + } else if str::contains(triple, "arm") || + str::contains(triple, "xscale") { Some(abi::Arm) - } else if str::contains(triple, ~"mips") { + } else if str::contains(triple, "mips") { Some(abi::Mips) } else { None } } @@ -508,6 +508,7 @@ pub fn build_target_config(sopts: @session::options, return target_cfg; } +#[cfg(stage0)] pub fn host_triple() -> ~str { // Get the host triple out of the build environment. This ensures that our // idea of the host triple is the same as for the set of libraries we've @@ -525,19 +526,37 @@ pub fn host_triple() -> ~str { }; } +#[cfg(not(stage0))] +pub fn host_triple() -> ~str { + // Get the host triple out of the build environment. This ensures that our + // idea of the host triple is the same as for the set of libraries we've + // actually built. We can't just take LLVM's host triple because they + // normalize all ix86 architectures to i386. + + // FIXME (#2400): Instead of grabbing the host triple we really should + // be grabbing (at compile time) the target triple that this rustc is + // built with and calling that (at runtime) the host triple. + let ht = env!("CFG_BUILD_TRIPLE"); + return if ht != "" { + ht.to_owned() + } else { + fail!("rustc built without CFG_BUILD_TRIPLE") + }; +} + pub fn build_session_options(binary: @~str, matches: &getopts::Matches, demitter: diagnostic::Emitter) -> @session::options { - let crate_type = if opt_present(matches, ~"lib") { + let crate_type = if opt_present(matches, "lib") { session::lib_crate - } else if opt_present(matches, ~"bin") { + } else if opt_present(matches, "bin") { session::bin_crate } else { session::unknown_crate }; - let parse_only = opt_present(matches, ~"parse-only"); - let no_trans = opt_present(matches, ~"no-trans"); + let parse_only = opt_present(matches, "parse-only"); + let no_trans = opt_present(matches, "no-trans"); let lint_levels = [lint::allow, lint::warn, lint::deny, lint::forbid]; @@ -553,7 +572,7 @@ pub fn build_session_options(binary: @~str, let flags = vec::append(getopts::opt_strs(matches, level_short), getopts::opt_strs(matches, level_name)); for flags.each |lint_name| { - let lint_name = str::replace(*lint_name, ~"-", ~"_"); + let lint_name = str::replace(*lint_name, "-", "_"); match lint_dict.find(&lint_name) { None => { early_error(demitter, fmt!("unknown %s flag: %s", @@ -567,7 +586,7 @@ pub fn build_session_options(binary: @~str, } let mut debugging_opts = 0u; - let debug_flags = getopts::opt_strs(matches, ~"Z"); + let debug_flags = getopts::opt_strs(matches, "Z"); let debug_map = session::debugging_opts_map(); for debug_flags.each |debug_flag| { let mut this_bit = 0u; @@ -589,31 +608,31 @@ pub fn build_session_options(binary: @~str, let output_type = if parse_only || no_trans { link::output_type_none - } else if opt_present(matches, ~"S") && - opt_present(matches, ~"emit-llvm") { + } else if opt_present(matches, "S") && + opt_present(matches, "emit-llvm") { link::output_type_llvm_assembly - } else if opt_present(matches, ~"S") { + } else if opt_present(matches, "S") { link::output_type_assembly - } else if opt_present(matches, ~"c") { + } else if opt_present(matches, "c") { link::output_type_object - } else if opt_present(matches, ~"emit-llvm") { + } else if opt_present(matches, "emit-llvm") { link::output_type_bitcode } else { link::output_type_exe }; - let sysroot_opt = getopts::opt_maybe_str(matches, ~"sysroot"); + let sysroot_opt = getopts::opt_maybe_str(matches, "sysroot"); let sysroot_opt = sysroot_opt.map(|m| @Path(*m)); - let target_opt = getopts::opt_maybe_str(matches, ~"target"); - let target_feature_opt = getopts::opt_maybe_str(matches, ~"target-feature"); - let save_temps = getopts::opt_present(matches, ~"save-temps"); + let target_opt = getopts::opt_maybe_str(matches, "target"); + let target_feature_opt = getopts::opt_maybe_str(matches, "target-feature"); + let save_temps = getopts::opt_present(matches, "save-temps"); let opt_level = { if (debugging_opts & session::no_opt) != 0 { No - } else if opt_present(matches, ~"O") { - if opt_present(matches, ~"opt-level") { + } else if opt_present(matches, "O") { + if opt_present(matches, "opt-level") { early_error(demitter, ~"-O and --opt-level both provided"); } Default - } else if opt_present(matches, ~"opt-level") { - match getopts::opt_str(matches, ~"opt-level") { + } else if opt_present(matches, "opt-level") { + match getopts::opt_str(matches, "opt-level") { ~"0" => No, ~"1" => Less, ~"2" => Default, @@ -641,9 +660,9 @@ pub fn build_session_options(binary: @~str, Some(s) => s }; - let addl_lib_search_paths = getopts::opt_strs(matches, ~"L").map(|s| Path(*s)); - let linker = getopts::opt_maybe_str(matches, ~"linker"); - let linker_args = getopts::opt_strs(matches, ~"link-args").flat_map( |a| { + let addl_lib_search_paths = getopts::opt_strs(matches, "L").map(|s| Path(*s)); + let linker = getopts::opt_maybe_str(matches, "linker"); + let linker_args = getopts::opt_strs(matches, "link-args").flat_map( |a| { let mut args = ~[]; for str::each_split_char(*a, ' ') |arg| { args.push(str::to_owned(arg)); @@ -651,10 +670,10 @@ pub fn build_session_options(binary: @~str, args }); - let cfg = parse_cfgspecs(getopts::opt_strs(matches, ~"cfg"), demitter); - let test = opt_present(matches, ~"test"); + let cfg = parse_cfgspecs(getopts::opt_strs(matches, "cfg"), demitter); + let test = opt_present(matches, "test"); let android_cross_path = getopts::opt_maybe_str( - matches, ~"android-cross-path"); + matches, "android-cross-path"); let sopts = @session::options { crate_type: crate_type, @@ -732,9 +751,9 @@ pub fn parse_pretty(sess: Session, name: &str) -> pp_mode { &"expanded,identified" => ppm_expanded_identified, &"identified" => ppm_identified, _ => { - sess.fatal(~"argument to `pretty` must be one of `normal`, \ - `expanded`, `typed`, `identified`, \ - or `expanded,identified`"); + sess.fatal("argument to `pretty` must be one of `normal`, \ + `expanded`, `typed`, `identified`, \ + or `expanded,identified`"); } } } @@ -875,7 +894,7 @@ pub fn build_output_filenames(input: &input, } if *odir != None { - sess.warn(~"ignoring --out-dir flag due to -o flag."); + sess.warn("ignoring --out-dir flag due to -o flag."); } } } diff --git a/src/librustc/driver/session.rs b/src/librustc/driver/session.rs index 6fba5ec8d3a82..e2cc285fb7afc 100644 --- a/src/librustc/driver/session.rs +++ b/src/librustc/driver/session.rs @@ -332,7 +332,7 @@ pub fn building_library(req_crate_type: crate_type, } else { match syntax::attr::first_attr_value_str_by_name( crate.node.attrs, - ~"crate_type") { + "crate_type") { Some(@~"lib") => true, _ => false } diff --git a/src/librustc/front/config.rs b/src/librustc/front/config.rs index 2246dd9d2f0aa..6341b1c155cca 100644 --- a/src/librustc/front/config.rs +++ b/src/librustc/front/config.rs @@ -175,7 +175,7 @@ fn in_cfg(cfg: ast::crate_cfg, attrs: ~[ast::attribute]) -> bool { pub fn metas_in_cfg(cfg: ast::crate_cfg, metas: ~[@ast::meta_item]) -> bool { // The "cfg" attributes on the item - let cfg_metas = attr::find_meta_items_by_name(metas, ~"cfg"); + let cfg_metas = attr::find_meta_items_by_name(metas, "cfg"); // Pull the inner meta_items from the #[cfg(meta_item, ...)] attributes, // so we can match against them. This is the list of configurations for diff --git a/src/librustc/front/core_inject.rs b/src/librustc/front/core_inject.rs index 5862dd00b3ce5..b3e045d8af9a8 100644 --- a/src/librustc/front/core_inject.rs +++ b/src/librustc/front/core_inject.rs @@ -28,7 +28,7 @@ pub fn maybe_inject_libcore_ref(sess: Session, } fn use_core(crate: @ast::crate) -> bool { - !attr::attrs_contains_name(crate.node.attrs, ~"no_core") + !attr::attrs_contains_name(crate.node.attrs, "no_core") } fn inject_libcore_ref(sess: Session, diff --git a/src/librustc/front/intrinsic_inject.rs b/src/librustc/front/intrinsic_inject.rs index 54dbea27bacc9..fd26971629580 100644 --- a/src/librustc/front/intrinsic_inject.rs +++ b/src/librustc/front/intrinsic_inject.rs @@ -25,7 +25,7 @@ pub fn inject_intrinsic(sess: Session, crate: @ast::crate) -> @ast::crate { match item { Some(i) => i, None => { - sess.fatal(~"no item found in intrinsic module"); + sess.fatal("no item found in intrinsic module"); } }; diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index be03ed99ad77b..eb199f6e10834 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -93,8 +93,8 @@ fn strip_test_functions(crate: @ast::crate) -> @ast::crate { // When not compiling with --test we should not compile the // #[test] functions do config::strip_items(crate) |attrs| { - !attr::contains_name(attr::attr_metas(attrs), ~"test") && - !attr::contains_name(attr::attr_metas(attrs), ~"bench") + !attr::contains_name(attr::attr_metas(attrs), "test") && + !attr::contains_name(attr::attr_metas(attrs), "bench") } } @@ -148,7 +148,7 @@ fn fold_item(cx: @mut TestCtxt, i: @ast::item, fld: @fold::ast_fold) let sess = cx.sess; sess.span_fatal( i.span, - ~"unsafe functions cannot be used for tests"); + "unsafe functions cannot be used for tests"); } _ => { debug!("this is a test function"); @@ -172,7 +172,7 @@ fn fold_item(cx: @mut TestCtxt, i: @ast::item, fld: @fold::ast_fold) fn is_test_fn(cx: @mut TestCtxt, i: @ast::item) -> bool { let has_test_attr = !attr::find_attrs_by_name(i.attrs, - ~"test").is_empty(); + "test").is_empty(); fn has_test_signature(i: @ast::item) -> bool { match &i.node { @@ -193,7 +193,7 @@ fn is_test_fn(cx: @mut TestCtxt, i: @ast::item) -> bool { let sess = cx.sess; sess.span_err( i.span, - ~"functions used as tests must have signature fn() -> ()." + "functions used as tests must have signature fn() -> ()." ); } return has_test_attr && has_test_signature(i); @@ -201,7 +201,7 @@ fn is_test_fn(cx: @mut TestCtxt, i: @ast::item) -> bool { fn is_bench_fn(i: @ast::item) -> bool { let has_bench_attr = - vec::len(attr::find_attrs_by_name(i.attrs, ~"bench")) > 0u; + vec::len(attr::find_attrs_by_name(i.attrs, "bench")) > 0u; fn has_test_signature(i: @ast::item) -> bool { match i.node { @@ -239,7 +239,7 @@ fn is_ignored(cx: @mut TestCtxt, i: @ast::item) -> bool { } fn should_fail(i: @ast::item) -> bool { - vec::len(attr::find_attrs_by_name(i.attrs, ~"should_fail")) > 0u + vec::len(attr::find_attrs_by_name(i.attrs, "should_fail")) > 0u } fn add_test_module(cx: &TestCtxt, m: &ast::_mod) -> ast::_mod { @@ -373,7 +373,7 @@ fn mk_tests(cx: &TestCtxt) -> @ast::item { fn is_std(cx: &TestCtxt) -> bool { let is_std = { let items = attr::find_linkage_metas(cx.crate.node.attrs); - match attr::last_meta_item_value_str_by_name(items, ~"name") { + match attr::last_meta_item_value_str_by_name(items, "name") { Some(@~"std") => true, _ => false } diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index da7a2c15f30be..d40257879d0ec 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -99,7 +99,7 @@ fn warn_if_multiple_versions(e: @mut Env, diag.handler().warn( fmt!("using multiple versions of crate `%s`", *name)); for matches.each |match_| { - diag.span_note(match_.span, ~"used here"); + diag.span_note(match_.span, "used here"); let attrs = ~[ attr::mk_attr(attr::mk_list_item( @~"link", /*bad*/copy *match_.metas)) @@ -164,7 +164,7 @@ fn visit_item(e: @mut Env, i: @ast::item) { ast::named => { let foreign_name = match attr::first_attr_value_str_by_name(i.attrs, - ~"link_name") { + "link_name") { Some(nn) => { if *nn == ~"" { e.diag.span_fatal( @@ -176,7 +176,7 @@ fn visit_item(e: @mut Env, i: @ast::item) { } None => e.intr.get(i.ident) }; - if attr::find_attrs_by_name(i.attrs, ~"nolink").is_empty() { + if attr::find_attrs_by_name(i.attrs, "nolink").is_empty() { already_added = !cstore::add_used_library(cstore, foreign_name); } @@ -272,7 +272,7 @@ fn resolve_crate(e: @mut Env, let cname = match attr::last_meta_item_value_str_by_name(load_ctxt.metas, - ~"name") { + "name") { Some(v) => v, None => e.intr.get(ident), }; diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index a7131e51ef7e8..de440632b1fdb 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -186,7 +186,7 @@ fn translated_parent_item_opt(cnum: ast::crate_num, d: ebml::Doc) -> fn item_reqd_and_translated_parent_item(cnum: ast::crate_num, d: ebml::Doc) -> ast::def_id { - let trait_did = item_parent_item(d).expect(~"item without parent"); + let trait_did = item_parent_item(d).expect("item without parent"); ast::def_id { crate: cnum, node: trait_did.node } } @@ -785,8 +785,8 @@ pub fn get_provided_trait_methods(intr: @ident_interner, cdata: cmd, let fty = match ty::get(ty).sty { ty::ty_bare_fn(ref f) => copy *f, _ => { - tcx.diag.handler().bug(~"get_provided_trait_methods(): id \ - has non-function type"); + tcx.diag.handler().bug("get_provided_trait_methods(): id \ + has non-function type"); } }; @@ -1064,7 +1064,7 @@ fn list_crate_attributes(intr: @ident_interner, md: ebml::Doc, hash: &str, out.write_str(fmt!("%s\n", pprust::attribute_to_str(*attr, intr))); } - out.write_str(~"\n\n"); + out.write_str("\n\n"); } pub fn get_crate_attributes(data: @~[u8]) -> ~[ast::attribute] { @@ -1097,7 +1097,7 @@ pub fn get_crate_deps(intr: @ident_interner, data: @~[u8]) -> ~[crate_dep] { } fn list_crate_deps(intr: @ident_interner, data: @~[u8], out: @io::Writer) { - out.write_str(~"=External Dependencies=\n"); + out.write_str("=External Dependencies=\n"); for get_crate_deps(intr, data).each |dep| { out.write_str( @@ -1105,7 +1105,7 @@ fn list_crate_deps(intr: @ident_interner, data: @~[u8], out: @io::Writer) { dep.cnum, *intr.get(dep.name), *dep.hash, *dep.vers)); } - out.write_str(~"\n"); + out.write_str("\n"); } pub fn get_crate_hash(data: @~[u8]) -> @~str { @@ -1118,7 +1118,7 @@ pub fn get_crate_vers(data: @~[u8]) -> @~str { let attrs = decoder::get_crate_attributes(data); let linkage_attrs = attr::find_linkage_metas(attrs); - match attr::last_meta_item_value_str_by_name(linkage_attrs, ~"vers") { + match attr::last_meta_item_value_str_by_name(linkage_attrs, "vers") { Some(ver) => ver, None => @~"0.0" } diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 460da5d60b33f..5fc05fe79209c 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -846,7 +846,7 @@ fn encode_info_for_item(ecx: @EncodeContext, struct_def.fields[0].node.kind == ast::unnamed_field { let ctor_id = match struct_def.ctor_id { Some(ctor_id) => ctor_id, - None => ecx.tcx.sess.bug(~"struct def didn't have ctor id"), + None => ecx.tcx.sess.bug("struct def didn't have ctor id"), }; encode_info_for_struct_ctor(ecx, @@ -1067,7 +1067,7 @@ fn encode_info_for_items(ecx: @EncodeContext, ebml_w.start_tag(tag_items_data); index.push(entry { val: crate_node_id, pos: ebml_w.writer.tell() }); encode_info_for_mod(ecx, ebml_w, &crate.node.module, - crate_node_id, ~[], + crate_node_id, [], syntax::parse::token::special_idents::invalid); visit::visit_crate(crate, (), visit::mk_vt(@visit::Visitor { visit_expr: |_e, _cx, _v| { }, @@ -1235,8 +1235,8 @@ fn synthesize_crate_attrs(ecx: @EncodeContext, let other_items = { - let tmp = attr::remove_meta_items_by_name(items, ~"name"); - attr::remove_meta_items_by_name(tmp, ~"vers") + let tmp = attr::remove_meta_items_by_name(items, "name"); + attr::remove_meta_items_by_name(tmp, "vers") }; let meta_items = vec::append(~[name_item, vers_item], other_items); diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 3bf8237df944c..7a7ee03b705fd 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -127,7 +127,7 @@ pub fn get_rustpkg_sysroot() -> Result { } pub fn get_rustpkg_root() -> Result { - match os::getenv(~"RUSTPKG_ROOT") { + match os::getenv("RUSTPKG_ROOT") { Some(ref _p) => result::Ok(Path((*_p))), None => match os::homedir() { Some(ref _q) => result::Ok((*_q).push(".rustpkg")), @@ -181,5 +181,5 @@ pub fn libdir() -> ~str { if str::is_empty(libdir) { fail!("rustc compiled without CFG_LIBDIR environment variable"); } - libdir + libdir.to_owned() } diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index cfb2bd4b837fa..75639e8c689e1 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -120,7 +120,7 @@ fn find_library_crate_aux( } else { cx.diag.span_err( cx.span, fmt!("multiple matching crates for `%s`", *crate_name)); - cx.diag.handler().note(~"candidates:"); + cx.diag.handler().note("candidates:"); for matches.each |&(ident, data)| { cx.diag.handler().note(fmt!("path: %s", ident)); let attrs = decoder::get_crate_attributes(data); @@ -132,7 +132,7 @@ fn find_library_crate_aux( } pub fn crate_name_from_metas(metas: &[@ast::meta_item]) -> @~str { - let name_items = attr::find_meta_items_by_name(metas, ~"name"); + let name_items = attr::find_meta_items_by_name(metas, "name"); match name_items.last_opt() { Some(i) => { match attr::get_meta_item_value_str(*i) { diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index 5f799f4994677..b1be0fb599eea 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -155,7 +155,7 @@ fn enc_region(w: @io::Writer, cx: @ctxt, r: ty::Region) { } ty::re_infer(_) => { // these should not crop up after typeck - cx.diag.handler().bug(~"Cannot encode region variables"); + cx.diag.handler().bug("Cannot encode region variables"); } } } @@ -301,7 +301,7 @@ fn enc_sty(w: @io::Writer, cx: @ctxt, st: ty::sty) { enc_bare_fn_ty(w, cx, f); } ty::ty_infer(_) => { - cx.diag.handler().bug(~"Cannot encode inference variable types"); + cx.diag.handler().bug("Cannot encode inference variable types"); } ty::ty_param(param_ty {idx: id, def_id: did}) => { w.write_char('p'); @@ -321,15 +321,15 @@ fn enc_sty(w: @io::Writer, cx: @ctxt, st: ty::sty) { } ty::ty_opaque_box => w.write_char('B'), ty::ty_struct(def, ref substs) => { - debug!("~~~~ %s", ~"a["); + debug!("~~~~ %s", "a["); w.write_str(&"a["); let s = (cx.ds)(def); debug!("~~~~ %s", s); w.write_str(s); - debug!("~~~~ %s", ~"|"); + debug!("~~~~ %s", "|"); w.write_char('|'); enc_substs(w, cx, substs); - debug!("~~~~ %s", ~"]"); + debug!("~~~~ %s", "]"); w.write_char(']'); } ty::ty_err => fail!("Shouldn't encode error type") diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 0235ab47967d7..5188f464504a6 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -614,10 +614,10 @@ fn encode_vtable_res(ecx: @e::EncodeContext, fn encode_vtable_origin(ecx: @e::EncodeContext, ebml_w: &mut writer::Encoder, vtable_origin: &typeck::vtable_origin) { - do ebml_w.emit_enum(~"vtable_origin") |ebml_w| { + do ebml_w.emit_enum("vtable_origin") |ebml_w| { match *vtable_origin { typeck::vtable_static(def_id, ref tys, vtable_res) => { - do ebml_w.emit_enum_variant(~"vtable_static", 0u, 3u) |ebml_w| { + do ebml_w.emit_enum_variant("vtable_static", 0u, 3u) |ebml_w| { do ebml_w.emit_enum_variant_arg(0u) |ebml_w| { ebml_w.emit_def_id(def_id) } @@ -630,7 +630,7 @@ fn encode_vtable_origin(ecx: @e::EncodeContext, } } typeck::vtable_param(pn, bn) => { - do ebml_w.emit_enum_variant(~"vtable_param", 1u, 2u) |ebml_w| { + do ebml_w.emit_enum_variant("vtable_param", 1u, 2u) |ebml_w| { do ebml_w.emit_enum_variant_arg(0u) |ebml_w| { ebml_w.emit_uint(pn); } @@ -756,20 +756,20 @@ impl ebml_writer_helpers for writer::Encoder { ecx: @e::EncodeContext, tpbt: ty::ty_param_bounds_and_ty) { do self.emit_struct("ty_param_bounds_and_ty", 2) |this| { - do this.emit_struct_field(~"generics", 0) |this| { + do this.emit_struct_field("generics", 0) |this| { do this.emit_struct("Generics", 2) |this| { - do this.emit_struct_field(~"type_param_defs", 0) |this| { + do this.emit_struct_field("type_param_defs", 0) |this| { do this.emit_from_vec(*tpbt.generics.type_param_defs) |this, type_param_def| { this.emit_type_param_def(ecx, type_param_def); } } - do this.emit_struct_field(~"region_param", 1) |this| { + do this.emit_struct_field("region_param", 1) |this| { tpbt.generics.region_param.encode(this); } } } - do this.emit_struct_field(~"ty", 1) |this| { + do this.emit_struct_field("ty", 1) |this| { this.emit_ty(ecx, tpbt.ty); } } diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index 8c66037e8385f..f8afc95a08b90 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -718,7 +718,7 @@ fn check_loans_in_expr<'a>(expr: @ast::expr, None, expr.callee_id, expr.span, - ~[rval]); + [rval]); } ast::expr_unary(*) | ast::expr_index(*) if this.bccx.method_map.contains_key(&expr.id) => { @@ -726,7 +726,7 @@ fn check_loans_in_expr<'a>(expr: @ast::expr, None, expr.callee_id, expr.span, - ~[]); + []); } _ => { } } diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 12321cf048ee4..b0978ae9e12a7 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -79,7 +79,7 @@ pub fn check_crate( visit::visit_crate(crate, bccx, v); if tcx.sess.borrowck_stats() { - io::println(~"--- borrowck stats ---"); + io::println("--- borrowck stats ---"); io::println(fmt!("paths requiring guarantees: %u", bccx.stats.guaranteed_paths)); io::println(fmt!("paths requiring loans : %s", @@ -556,27 +556,27 @@ pub impl BorrowckCtxt { err_out_of_root_scope(super_scope, sub_scope) => { note_and_explain_region( self.tcx, - ~"managed value would have to be rooted for ", + "managed value would have to be rooted for ", sub_scope, - ~"..."); + "..."); note_and_explain_region( self.tcx, - ~"...but can only be rooted for ", + "...but can only be rooted for ", super_scope, - ~""); + ""); } err_out_of_scope(super_scope, sub_scope) => { note_and_explain_region( self.tcx, - ~"borrowed pointer must be valid for ", + "borrowed pointer must be valid for ", sub_scope, - ~"..."); + "..."); note_and_explain_region( self.tcx, - ~"...but borrowed value is only valid for ", + "...but borrowed value is only valid for ", super_scope, - ~""); + ""); } } } diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index d859e03811f7f..7a81568117313 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -129,7 +129,7 @@ pub fn raw_pat(p: @pat) -> @pat { pub fn check_exhaustive(cx: @MatchCheckCtxt, sp: span, pats: ~[@pat]) { assert!((!pats.is_empty())); - let ext = match is_useful(cx, &pats.map(|p| ~[*p]), ~[wild()]) { + let ext = match is_useful(cx, &pats.map(|p| ~[*p]), [wild()]) { not_useful => { // This is good, wildcard pattern isn't reachable return; diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 593d4b13a3f50..9c9f72adc4df2 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -357,7 +357,7 @@ impl<'self, O:DataFlowOperator> PropagationContext<'self, O> { } ast::stmt_mac(*) => { - self.tcx().sess.span_bug(stmt.span, ~"unexpanded macro"); + self.tcx().sess.span_bug(stmt.span, "unexpanded macro"); } } } @@ -724,7 +724,7 @@ impl<'self, O:DataFlowOperator> PropagationContext<'self, O> { } ast::expr_mac(*) => { - self.tcx().sess.span_bug(expr.span, ~"unexpanded macro"); + self.tcx().sess.span_bug(expr.span, "unexpanded macro"); } } diff --git a/src/librustc/middle/entry.rs b/src/librustc/middle/entry.rs index f4b9e4b62fc4b..e478f29adf90a 100644 --- a/src/librustc/middle/entry.rs +++ b/src/librustc/middle/entry.rs @@ -78,7 +78,7 @@ fn find_item(item: @item, ctxt: @mut EntryContext, visitor: EntryVisitor) { } else { ctxt.session.span_err( item.span, - ~"multiple 'main' functions"); + "multiple 'main' functions"); } } else { // This isn't main @@ -89,23 +89,23 @@ fn find_item(item: @item, ctxt: @mut EntryContext, visitor: EntryVisitor) { } } - if attrs_contains_name(item.attrs, ~"main") { + if attrs_contains_name(item.attrs, "main") { if ctxt.attr_main_fn.is_none() { ctxt.attr_main_fn = Some((item.id, item.span)); } else { ctxt.session.span_err( item.span, - ~"multiple 'main' functions"); + "multiple 'main' functions"); } } - if attrs_contains_name(item.attrs, ~"start") { + if attrs_contains_name(item.attrs, "start") { if ctxt.start_fn.is_none() { ctxt.start_fn = Some((item.id, item.span)); } else { ctxt.session.span_err( item.span, - ~"multiple 'start' functions"); + "multiple 'start' functions"); } } } @@ -129,15 +129,15 @@ fn configure_main(ctxt: @mut EntryContext) { } else { if !*this.session.building_library { // No main function - this.session.err(~"main function not found"); + this.session.err("main function not found"); if !this.non_main_fns.is_empty() { // There were some functions named 'main' though. Try to give the user a hint. - this.session.note(~"the main function must be defined at the crate level \ - but you have one or more functions named 'main' that are not \ - defined at the crate level. Either move the definition or \ - attach the `#[main]` attribute to override this behavior."); + this.session.note("the main function must be defined at the crate level \ + but you have one or more functions named 'main' that are not \ + defined at the crate level. Either move the definition or \ + attach the `#[main]` attribute to override this behavior."); for this.non_main_fns.each |&(_, span)| { - this.session.span_note(span, ~"here is a function named 'main'"); + this.session.span_note(span, "here is a function named 'main'"); } } this.session.abort_if_errors(); diff --git a/src/librustc/middle/kind.rs b/src/librustc/middle/kind.rs index a891e8d3b7f83..bade18e1787a1 100644 --- a/src/librustc/middle/kind.rs +++ b/src/librustc/middle/kind.rs @@ -122,7 +122,7 @@ fn check_item(item: @item, cx: Context, visitor: visit::vt) { match item.node { item_impl(_, Some(trait_ref), self_type, _) => { match cx.tcx.def_map.find(&trait_ref.ref_id) { - None => cx.tcx.sess.bug(~"trait ref not in def map!"), + None => cx.tcx.sess.bug("trait ref not in def map!"), Some(&trait_def) => { let trait_def_id = ast_util::def_id_of_def(trait_def); if cx.tcx.lang_items.drop_trait() == trait_def_id { @@ -270,7 +270,7 @@ pub fn check_expr(e: @expr, cx: Context, v: visit::vt) { // Even though the callee_id may have been the id with // node_type_substs, e.id is correct here. ty::method_call_type_param_defs(cx.tcx, cx.method_map, e.id).expect( - ~"non path/method call expr has type substs??") + "non path/method call expr has type substs??") } }; if ts.len() != type_param_defs.len() { diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 6a1a8940a05c1..b14197649379b 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -439,7 +439,7 @@ pub fn each_lint(sess: session::Session, let metas = match meta.node { ast::meta_list(_, ref metas) => metas, _ => { - sess.span_err(meta.span, ~"malformed lint attribute"); + sess.span_err(meta.span, "malformed lint attribute"); loop; } }; @@ -451,7 +451,7 @@ pub fn each_lint(sess: session::Session, } } _ => { - sess.span_err(meta.span, ~"malformed lint attribute"); + sess.span_err(meta.span, "malformed lint attribute"); } } } diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 711e391527755..4608f773a1c26 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -726,7 +726,7 @@ pub impl Liveness { for uint::range(0, self.ir.num_vars) |var_idx| { let idx = node_base_idx + var_idx; if test(idx).is_valid() { - wr.write_str(~" "); + wr.write_str(" "); wr.write_str(Variable(var_idx).to_str()); } } @@ -750,7 +750,7 @@ pub impl Liveness { loop_scope.len() }; if len == 0 { - self.tcx.sess.span_bug(sp, ~"break outside loop"); + self.tcx.sess.span_bug(sp, "break outside loop"); } else { // FIXME(#5275): this shouldn't have to be a method... self.last_loop_scope() @@ -766,18 +766,18 @@ pub impl Liveness { fn ln_str(&self, ln: LiveNode) -> ~str { do io::with_str_writer |wr| { - wr.write_str(~"[ln("); + wr.write_str("[ln("); wr.write_uint(*ln); - wr.write_str(~") of kind "); + wr.write_str(") of kind "); wr.write_str(fmt!("%?", copy self.ir.lnks[*ln])); - wr.write_str(~" reads"); + wr.write_str(" reads"); self.write_vars(wr, ln, |idx| self.users[idx].reader ); - wr.write_str(~" writes"); + wr.write_str(" writes"); self.write_vars(wr, ln, |idx| self.users[idx].writer ); - wr.write_str(~" "); - wr.write_str(~" precedes "); + wr.write_str(" "); + wr.write_str(" precedes "); wr.write_str((copy self.successors[*ln]).to_str()); - wr.write_str(~"]"); + wr.write_str("]"); } } @@ -1195,7 +1195,7 @@ pub impl Liveness { expr_log(l, r) | expr_index(l, r) | expr_binary(_, l, r) => { - self.propagate_through_exprs(~[l, r], succ) + self.propagate_through_exprs([l, r], succ) } expr_addr_of(_, e) | diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index ce0f124da74c9..6ce074b526492 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -400,7 +400,7 @@ pub fn check_crate(tcx: ty::ctxt, // Do not check privacy inside items with the resolve_unexported // attribute. This is used for the test runner. if !attr::contains_name(attr::attr_metas(/*bad*/copy item.attrs), - ~"!resolve_unexported") { + "!resolve_unexported") { visit::visit_item(item, method_map, visitor); } }, diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index fce078a708f1a..cbe9e908da4f9 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -381,7 +381,7 @@ pub fn resolve_stmt(stmt: @ast::stmt, cx: Context, visitor: visit::vt) let expr_cx = Context {parent: Some(stmt_id), ..cx}; visit::visit_stmt(stmt, expr_cx, visitor); } - ast::stmt_mac(*) => cx.sess.bug(~"unexpanded macro") + ast::stmt_mac(*) => cx.sess.bug("unexpanded macro") } } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 1568c3e55352f..0365d849ae6cf 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -2584,7 +2584,7 @@ pub impl Resolver { match result { Failed => { self.session.span_err(span, - ~"unresolved name"); + "unresolved name"); return Failed; } Indeterminate => { @@ -2966,7 +2966,7 @@ pub impl Resolver { if index != import_count { let sn = self.session.codemap.span_to_snippet(imports[index].span); if str::contains(sn, "::") { - self.session.span_err(imports[index].span, ~"unresolved import"); + self.session.span_err(imports[index].span, "unresolved import"); } else { let err = fmt!("unresolved import (maybe you meant `%s::*`?)", sn.slice(0, sn.len() - 1)); // -1 to adjust for semicolon @@ -3249,14 +3249,14 @@ pub impl Resolver { self.session.span_err( span, - ~"attempted dynamic environment-capture"); + "attempted dynamic environment-capture"); } else { // This was an attempt to use a type parameter outside // its scope. self.session.span_err(span, - ~"attempt to use a type \ - argument out of scope"); + "attempt to use a type \ + argument out of scope"); } return None; @@ -3271,14 +3271,14 @@ pub impl Resolver { self.session.span_err( span, - ~"attempted dynamic environment-capture"); + "attempted dynamic environment-capture"); } else { // This was an attempt to use a type parameter outside // its scope. self.session.span_err(span, - ~"attempt to use a type \ - argument out of scope"); + "attempt to use a type \ + argument out of scope"); } return None; @@ -3286,8 +3286,8 @@ pub impl Resolver { ConstantItemRibKind => { // Still doesn't deal with upvars self.session.span_err(span, - ~"attempt to use a non-constant \ - value in a constant"); + "attempt to use a non-constant \ + value in a constant"); } } @@ -3352,7 +3352,7 @@ pub impl Resolver { // This is used to allow the test runner to run unexported tests. let orig_xray_flag = self.xray_context; if contains_name(attr_metas(item.attrs), - ~"!resolve_unexported") { + "!resolve_unexported") { self.xray_context = Xray; } @@ -3424,8 +3424,8 @@ pub impl Resolver { visitor) { None => self.session.span_err(trt.path.span, - ~"attempt to derive a \ - nonexistent trait"), + "attempt to derive a \ + nonexistent trait"), Some(def) => { // Write a mapping from the trait ID to the // definition of the trait into the definition @@ -3699,8 +3699,8 @@ pub impl Resolver { match self.resolve_path(trait_reference.path, TypeNS, true, visitor) { None => { self.session.span_err(trait_reference.path.span, - ~"attempt to implement an \ - unknown trait"); + "attempt to implement an \ + unknown trait"); } Some(def) => { self.record_def(trait_reference.ref_id, def); @@ -4094,8 +4094,8 @@ pub impl Resolver { } FoundConst(_) => { self.session.span_err(pattern.span, - ~"only refutable patterns \ - allowed here"); + "only refutable patterns \ + allowed here"); } BareIdentifierPatternUnresolved => { debug!("(resolving pattern) binding `%s`", @@ -4195,7 +4195,7 @@ pub impl Resolver { } None => { self.session.span_err(path.span, - ~"unresolved enum variant"); + "unresolved enum variant"); } } @@ -4223,8 +4223,8 @@ pub impl Resolver { } None => { self.session.span_err(path.span, - ~"unresolved enum variant, \ - struct or const"); + "unresolved enum variant, \ + struct or const"); } } @@ -4598,8 +4598,8 @@ pub impl Resolver { Some(dl_def(def)) => return Some(def), _ => { self.session.span_bug(span, - ~"self wasn't mapped to a \ - def?!") + "self wasn't mapped to a \ + def?!") } } } @@ -4829,8 +4829,8 @@ pub impl Resolver { } Some(_) => { self.session.span_bug(expr.span, - ~"label wasn't mapped to a \ - label def!") + "label wasn't mapped to a \ + label def!") } } } @@ -4839,8 +4839,8 @@ pub impl Resolver { match self.resolve_self_value_in_local_ribs(expr.span) { None => { self.session.span_err(expr.span, - ~"`self` is not allowed in \ - this context") + "`self` is not allowed in \ + this context") } Some(def) => self.record_def(expr.id, def), } diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index d2834a095aa9c..fa545f033a584 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -296,7 +296,7 @@ pub fn variant_opt(bcx: block, pat_id: ast::node_id) return lit(UnitLikeStructLit(pat_id)); } _ => { - ccx.sess.bug(~"non-variant or struct in variant_opt()"); + ccx.sess.bug("non-variant or struct in variant_opt()"); } } } @@ -891,10 +891,10 @@ pub fn extract_vec_elems(bcx: block, let mut elems = do vec::from_fn(elem_count) |i| { match slice { - None => GEPi(bcx, base, ~[i]), - Some(n) if i < n => GEPi(bcx, base, ~[i]), + None => GEPi(bcx, base, [i]), + Some(n) if i < n => GEPi(bcx, base, [i]), Some(n) if i > n => { - InBoundsGEP(bcx, base, ~[ + InBoundsGEP(bcx, base, [ Sub(bcx, count, C_int(bcx.ccx(), (elem_count - i) as int))]) } @@ -1089,11 +1089,8 @@ pub fn compare_values(cx: block, let scratch_rhs = alloca(cx, val_ty(rhs)); Store(cx, rhs, scratch_rhs); let did = cx.tcx().lang_items.uniq_str_eq_fn(); - let bcx = callee::trans_lang_call(cx, did, - ~[scratch_lhs, - scratch_rhs], - expr::SaveIn( - scratch_result.val)); + let bcx = callee::trans_lang_call(cx, did, [scratch_lhs, scratch_rhs], + expr::SaveIn(scratch_result.val)); let result = scratch_result.to_result(bcx); Result { bcx: result.bcx, @@ -1103,10 +1100,8 @@ pub fn compare_values(cx: block, ty::ty_estr(_) => { let scratch_result = scratch_datum(cx, ty::mk_bool(), false); let did = cx.tcx().lang_items.str_eq_fn(); - let bcx = callee::trans_lang_call(cx, did, - ~[lhs, rhs], - expr::SaveIn( - scratch_result.val)); + let bcx = callee::trans_lang_call(cx, did, [lhs, rhs], + expr::SaveIn(scratch_result.val)); let result = scratch_result.to_result(bcx); Result { bcx: result.bcx, @@ -1114,7 +1109,7 @@ pub fn compare_values(cx: block, } } _ => { - cx.tcx().sess.bug(~"only scalars and strings supported in \ + cx.tcx().sess.bug("only scalars and strings supported in \ compare_values"); } } @@ -1343,7 +1338,7 @@ pub fn compile_submatch(bcx: block, let tup_repr = adt::represent_type(bcx.ccx(), tup_ty); let n_tup_elts = match ty::get(tup_ty).sty { ty::ty_tup(ref elts) => elts.len(), - _ => ccx.sess.bug(~"non-tuple type in tuple pattern") + _ => ccx.sess.bug("non-tuple type in tuple pattern") }; let tup_vals = do vec::from_fn(n_tup_elts) |i| { adt::trans_field_ptr(bcx, tup_repr, val, 0, i) @@ -1362,7 +1357,7 @@ pub fn compile_submatch(bcx: block, ty::lookup_struct_fields(tcx, struct_id).len(); } _ => { - ccx.sess.bug(~"non-struct type in tuple struct pattern"); + ccx.sess.bug("non-struct type in tuple struct pattern"); } } @@ -1478,8 +1473,8 @@ pub fn compile_submatch(bcx: block, } _ => { bcx.sess().bug( - ~"in compile_submatch, expected \ - trans_opt to return a single_result") + "in compile_submatch, expected \ + trans_opt to return a single_result") } } } @@ -1689,7 +1684,7 @@ pub fn trans_match_inner(scope_cx: block, } }; let lldiscr = discr_datum.to_ref_llval(bcx); - compile_submatch(bcx, matches, ~[lldiscr], chk); + compile_submatch(bcx, matches, [lldiscr], chk); let mut arm_cxs = ~[]; for arm_datas.each |arm_data| { diff --git a/src/librustc/middle/trans/adt.rs b/src/librustc/middle/trans/adt.rs index 25e97b0c8a82c..4d1c4851e1f6b 100644 --- a/src/librustc/middle/trans/adt.rs +++ b/src/librustc/middle/trans/adt.rs @@ -158,7 +158,7 @@ fn represent_type_uncached(cx: @CrateContext, t: ty::t) -> Repr { if cases.len() == 0 { // Uninhabitable; represent as unit - return Univariant(mk_struct(cx, ~[], false), false); + return Univariant(mk_struct(cx, [], false), false); } if cases.all(|c| c.tys.len() == 0) { @@ -206,7 +206,7 @@ fn represent_type_uncached(cx: @CrateContext, t: ty::t) -> Repr { let discr = ~[ty::mk_int()]; return General(cases.map(|c| mk_struct(cx, discr + c.tys, false))) } - _ => cx.sess.bug(~"adt::represent_type called on non-ADT type") + _ => cx.sess.bug("adt::represent_type called on non-ADT type") } } @@ -353,7 +353,7 @@ pub fn trans_case(bcx: block, r: &Repr, discr: int) -> _match::opt_result { _match::single_result(rslt(bcx, C_int(bcx.ccx(), discr))) } Univariant(*) => { - bcx.ccx().sess.bug(~"no cases for univariants or structs") + bcx.ccx().sess.bug("no cases for univariants or structs") } General(*) => { _match::single_result(rslt(bcx, C_int(bcx.ccx(), discr))) @@ -423,7 +423,7 @@ pub fn trans_field_ptr(bcx: block, r: &Repr, val: ValueRef, discr: int, // someday), it will need to return a possibly-new bcx as well. match *r { CEnum(*) => { - bcx.ccx().sess.bug(~"element access in C-like enum") + bcx.ccx().sess.bug("element access in C-like enum") } Univariant(ref st, _dtor) => { assert_eq!(discr, 0); @@ -468,8 +468,7 @@ fn struct_field_ptr(bcx: block, st: &Struct, val: ValueRef, ix: uint, pub fn trans_drop_flag_ptr(bcx: block, r: &Repr, val: ValueRef) -> ValueRef { match *r { Univariant(ref st, true) => GEPi(bcx, val, [0, st.fields.len() - 1]), - _ => bcx.ccx().sess.bug(~"tried to get drop flag of non-droppable \ - type") + _ => bcx.ccx().sess.bug("tried to get drop flag of non-droppable type") } } @@ -600,7 +599,7 @@ pub fn const_get_discrim(ccx: @CrateContext, r: &Repr, val: ValueRef) pub fn const_get_field(ccx: @CrateContext, r: &Repr, val: ValueRef, _discr: int, ix: uint) -> ValueRef { match *r { - CEnum(*) => ccx.sess.bug(~"element access in C-like enum const"), + CEnum(*) => ccx.sess.bug("element access in C-like enum const"), Univariant(*) => const_struct_field(ccx, val, ix), General(*) => const_struct_field(ccx, val, ix + 1), NullablePointer{ _ } => const_struct_field(ccx, val, ix) diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 66cca74214a41..94ca02b22554b 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -235,7 +235,7 @@ pub fn umin(cx: block, a: ValueRef, b: ValueRef) -> ValueRef { pub fn ptr_offs(bcx: block, base: ValueRef, sz: ValueRef) -> ValueRef { let _icx = bcx.insn_ctxt("ptr_offs"); let raw = PointerCast(bcx, base, T_ptr(T_i8())); - InBoundsGEP(bcx, raw, ~[sz]) + InBoundsGEP(bcx, raw, [sz]) } // Increment a pointer by a given amount and then cast it to be a pointer @@ -296,7 +296,7 @@ pub fn malloc_raw_dyn(bcx: block, let bcx = callee::trans_lang_call( bcx, langcall, - ~[tydesc, size], + [tydesc, size], expr::SaveIn(rval)); let r = rslt(bcx, PointerCast(bcx, Load(bcx, rval), llty)); maybe_set_managed_unique_rc(r.bcx, r.val, heap); @@ -314,7 +314,7 @@ pub fn malloc_raw_dyn(bcx: block, pub fn non_gc_box_cast(bcx: block, val: ValueRef) -> ValueRef { unsafe { debug!("non_gc_box_cast"); - add_comment(bcx, ~"non_gc_box_cast"); + add_comment(bcx, "non_gc_box_cast"); assert!(llvm::LLVMGetPointerAddressSpace(val_ty(val)) == gc_box_addrspace || bcx.unreachable); let non_gc_t = T_ptr(llvm::LLVMGetElementType(val_ty(val))); @@ -563,8 +563,8 @@ pub fn compare_scalar_types(cx: block, } _ => { // Should never get here, because t is scalar. - cx.sess().bug(~"non-scalar type passed to \ - compare_scalar_types") + cx.sess().bug("non-scalar type passed to \ + compare_scalar_types") } } } @@ -579,8 +579,8 @@ pub fn compare_scalar_values(cx: block, -> ValueRef { let _icx = cx.insn_ctxt("compare_scalar_values"); fn die(cx: block) -> ! { - cx.tcx().sess.bug(~"compare_scalar_values: must be a\ - comparison operator"); + cx.tcx().sess.bug("compare_scalar_values: must be a\ + comparison operator"); } match nt { nil_type => { @@ -720,18 +720,18 @@ pub fn iter_structural_ty(cx: block, av: ValueRef, t: ty::t, _match::single_result(r) => { AddCase(llswitch, r.val, variant_cx.llbb) } - _ => ccx.sess.unimpl(~"value from adt::trans_case \ - in iter_structural_ty") + _ => ccx.sess.unimpl("value from adt::trans_case \ + in iter_structural_ty") } Br(variant_cx, next_cx.llbb); } cx = next_cx; } - _ => ccx.sess.unimpl(~"value from adt::trans_switch \ - in iter_structural_ty") + _ => ccx.sess.unimpl("value from adt::trans_switch \ + in iter_structural_ty") } } - _ => cx.sess().unimpl(~"type in iter_structural_ty") + _ => cx.sess().unimpl("type in iter_structural_ty") } return cx; } @@ -959,7 +959,7 @@ pub fn get_landing_pad(bcx: block) -> BasicBlockRef { // The landing pad return type (the type being propagated). Not sure what // this represents but it's determined by the personality function and // this is what the EH proposal example uses. - let llretty = T_struct(~[T_ptr(T_i8()), T_i32()], false); + let llretty = T_struct([T_ptr(T_i8()), T_i32()], false); // The exception handling personality function. This is the C++ // personality function __gxx_personality_v0, wrapped in our naming // convention. @@ -972,7 +972,7 @@ pub fn get_landing_pad(bcx: block) -> BasicBlockRef { // Because we may have unwound across a stack boundary, we must call into // the runtime to figure out which stack segment we are on and place the // stack limit back into the TLS. - Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, ~[]); + Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []); // We store the retval in a function-central alloca, so that calls to // Resume can find it. @@ -1159,7 +1159,7 @@ pub fn trans_stmt(cx: block, s: &ast::stmt) -> block { ast::decl_item(i) => trans_item(*cx.fcx.ccx, i) } } - ast::stmt_mac(*) => cx.tcx().sess.bug(~"unexpanded macro") + ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro") } return bcx; @@ -1462,7 +1462,7 @@ pub fn call_memcpy(cx: block, dst: ValueRef, src: ValueRef, let size = IntCast(cx, n_bytes, ccx.int_type); let align = C_i32(1i32); let volatile = C_i1(false); - Call(cx, memcpy, ~[dst_ptr, src_ptr, size, align, volatile]); + Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]); } pub fn memcpy_ty(bcx: block, dst: ValueRef, src: ValueRef, t: ty::t) { @@ -1509,7 +1509,7 @@ pub fn memzero(cx: block, llptr: ValueRef, llty: TypeRef) { let size = IntCast(cx, machine::llsize_of(ccx, llty), ccx.int_type); let align = C_i32(1i32); let volatile = C_i1(false); - Call(cx, llintrinsicfn, ~[llptr, llzeroval, size, align, volatile]); + Call(cx, llintrinsicfn, [llptr, llzeroval, size, align, volatile]); } pub fn alloc_ty(bcx: block, t: ty::t) -> ValueRef { @@ -1559,9 +1559,9 @@ pub struct BasicBlocks { pub fn mk_standard_basic_blocks(llfn: ValueRef) -> BasicBlocks { unsafe { BasicBlocks { - sa: str::as_c_str(~"static_allocas", + sa: str::as_c_str("static_allocas", |buf| llvm::LLVMAppendBasicBlock(llfn, buf)), - rt: str::as_c_str(~"return", + rt: str::as_c_str("return", |buf| llvm::LLVMAppendBasicBlock(llfn, buf)) } } @@ -2057,8 +2057,7 @@ pub fn trans_tuple_struct(ccx: @CrateContext, let llarg = match fcx.llargs.get_copy(&field.node.id) { local_mem(x) => x, _ => { - ccx.tcx.sess.bug(~"trans_tuple_struct: llarg wasn't \ - local_mem") + ccx.tcx.sess.bug("trans_tuple_struct: llarg wasn't local_mem") } }; let arg_ty = arg_tys[i]; @@ -2105,7 +2104,7 @@ pub fn trans_item(ccx: @CrateContext, item: &ast::item) { let llfndecl = get_item_val(ccx, item.id); foreign::trans_foreign_fn(ccx, vec::append(/*bad*/copy *path, - ~[path_name(item.ident)]), + [path_name(item.ident)]), decl, body, llfndecl, @@ -2113,7 +2112,7 @@ pub fn trans_item(ccx: @CrateContext, item: &ast::item) { } else if !generics.is_type_parameterized() { let llfndecl = get_item_val(ccx, item.id); trans_fn(ccx, - vec::append(/*bad*/copy *path, ~[path_name(item.ident)]), + vec::append(/*bad*/copy *path, [path_name(item.ident)]), decl, body, llfndecl, @@ -2263,8 +2262,8 @@ pub fn create_entry_wrapper(ccx: @CrateContext, fn create_main(ccx: @CrateContext, main_llfn: ValueRef) -> ValueRef { let nt = ty::mk_nil(); - let llfty = type_of_fn(ccx, ~[], nt); - let llfdecl = decl_fn(ccx.llmod, ~"_rust_main", + let llfty = type_of_fn(ccx, [], nt); + let llfdecl = decl_fn(ccx.llmod, "_rust_main", lib::llvm::CCallConv, llfty); let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None); @@ -2287,11 +2286,11 @@ pub fn create_entry_wrapper(ccx: @CrateContext, fn create_entry_fn(ccx: @CrateContext, rust_main: ValueRef, use_start_lang_item: bool) { - let llfty = T_fn(~[ccx.int_type, T_ptr(T_ptr(T_i8()))], ccx.int_type); + let llfty = T_fn([ccx.int_type, T_ptr(T_ptr(T_i8()))], ccx.int_type); // FIXME #4404 android JNI hacks let llfn = if *ccx.sess.building_library { - decl_cdecl_fn(ccx.llmod, ~"amain", llfty) + decl_cdecl_fn(ccx.llmod, "amain", llfty) } else { let main_name = match ccx.sess.targ_cfg.os { session::os_win32 => ~"WinMain@16", @@ -2299,7 +2298,7 @@ pub fn create_entry_wrapper(ccx: @CrateContext, }; decl_cdecl_fn(ccx.llmod, main_name, llfty) }; - let llbb = str::as_c_str(~"top", |buf| { + let llbb = str::as_c_str("top", |buf| { unsafe { llvm::LLVMAppendBasicBlock(llfn, buf) } @@ -2310,7 +2309,7 @@ pub fn create_entry_wrapper(ccx: @CrateContext, let start_def_id = ccx.tcx.lang_items.start_fn(); if start_def_id.crate == ast::local_crate { - ccx.sess.bug(~"start lang item is never in the local crate") + ccx.sess.bug("start lang item is never in the local crate") } else { let start_fn_type = csearch::get_type(ccx.tcx, start_def_id).ty; @@ -2328,8 +2327,8 @@ pub fn create_entry_wrapper(ccx: @CrateContext, let (start_fn, args) = if use_start_lang_item { let start_def_id = ccx.tcx.lang_items.start_fn(); let start_fn = if start_def_id.crate == ast::local_crate { - ccx.sess.bug(~"start lang item is never in the local \ - crate") + ccx.sess.bug("start lang item is never in the local \ + crate") } else { let start_fn_type = csearch::get_type(ccx.tcx, start_def_id).ty; @@ -2391,7 +2390,7 @@ pub fn item_path(ccx: @CrateContext, i: @ast::item) -> path { // separate map for paths? _ => fail!("item_path") }; - vec::append(/*bad*/copy *base, ~[path_name(i.ident)]) + vec::append(/*bad*/copy *base, [path_name(i.ident)]) } pub fn get_item_val(ccx: @CrateContext, id: ast::node_id) -> ValueRef { @@ -2404,7 +2403,7 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::node_id) -> ValueRef { let val = match tcx.items.get_copy(&id) { ast_map::node_item(i, pth) => { let my_path = vec::append(/*bad*/copy *pth, - ~[path_name(i.ident)]); + [path_name(i.ident)]); match i.node { ast::item_const(_, expr) => { let typ = ty::node_id_to_type(tcx, i.id); @@ -2442,8 +2441,8 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::node_id) -> ValueRef { debug!("get_item_val(): processing a node_trait_method"); match *trait_method { ast::required(_) => { - ccx.sess.bug(~"unexpected variant: required trait method in \ - get_item_val()"); + ccx.sess.bug("unexpected variant: required trait method in \ + get_item_val()"); } ast::provided(m) => { exprt = true; @@ -2461,7 +2460,7 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::node_id) -> ValueRef { ast::foreign_item_fn(*) => { register_fn(ccx, ni.span, vec::append(/*bad*/copy *pth, - ~[path_name(ni.ident)]), + [path_name(ni.ident)]), ni.id, ni.attrs) } @@ -2486,8 +2485,8 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::node_id) -> ValueRef { ast::tuple_variant_kind(ref args) => { assert!(args.len() != 0u); let pth = vec::append(/*bad*/copy *pth, - ~[path_name(enm.ident), - path_name((*v).node.name)]); + [path_name(enm.ident), + path_name((*v).node.name)]); llfn = match enm.node { ast::item_enum(_, _) => { register_fn(ccx, (*v).span, pth, id, enm.attrs) @@ -2507,8 +2506,8 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::node_id) -> ValueRef { // Only register the constructor if this is a tuple-like struct. match struct_def.ctor_id { None => { - tcx.sess.bug(~"attempt to register a constructor of \ - a non-tuple-like struct") + tcx.sess.bug("attempt to register a constructor of \ + a non-tuple-like struct") } Some(ctor_id) => { let llfn = register_fn(ccx, @@ -2541,7 +2540,7 @@ pub fn register_method(ccx: @CrateContext, pth: @ast_map::path, m: @ast::method) -> ValueRef { let mty = ty::node_id_to_type(ccx.tcx, id); - let pth = vec::append(/*bad*/copy *pth, ~[path_name((ccx.names)("meth")), + let pth = vec::append(/*bad*/copy *pth, [path_name((ccx.names)("meth")), path_name(m.ident)]); let llfn = register_fn_full(ccx, m.span, pth, id, m.attrs, mty); set_inline_hint_if_appr(m.attrs, llfn); @@ -2559,7 +2558,7 @@ pub fn trans_constant(ccx: @CrateContext, it: @ast::item) { let mut i = 0; let path = item_path(ccx, it); for (*enum_definition).variants.each |variant| { - let p = vec::append(/*bad*/copy path, ~[ + let p = vec::append(/*bad*/copy path, [ path_name(variant.node.name), path_name(special_idents::descrim) ]); @@ -2617,126 +2616,126 @@ pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<~str, ValueRef> { let T_trap_args: ~[TypeRef] = ~[]; let T_frameaddress_args: ~[TypeRef] = ~[T_i32()]; let gcroot = - decl_cdecl_fn(llmod, ~"llvm.gcroot", - T_fn(~[T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], + decl_cdecl_fn(llmod, "llvm.gcroot", + T_fn([T_ptr(T_ptr(T_i8())), T_ptr(T_i8())], T_void())); let gcread = - decl_cdecl_fn(llmod, ~"llvm.gcread", - T_fn(~[T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], + decl_cdecl_fn(llmod, "llvm.gcread", + T_fn([T_ptr(T_i8()), T_ptr(T_ptr(T_i8()))], T_void())); let memcpy32 = - decl_cdecl_fn(llmod, ~"llvm.memcpy.p0i8.p0i8.i32", + decl_cdecl_fn(llmod, "llvm.memcpy.p0i8.p0i8.i32", T_fn(copy T_memcpy32_args, T_void())); let memcpy64 = - decl_cdecl_fn(llmod, ~"llvm.memcpy.p0i8.p0i8.i64", + decl_cdecl_fn(llmod, "llvm.memcpy.p0i8.p0i8.i64", T_fn(copy T_memcpy64_args, T_void())); let memmove32 = - decl_cdecl_fn(llmod, ~"llvm.memmove.p0i8.p0i8.i32", + decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i32", T_fn(T_memcpy32_args, T_void())); let memmove64 = - decl_cdecl_fn(llmod, ~"llvm.memmove.p0i8.p0i8.i64", + decl_cdecl_fn(llmod, "llvm.memmove.p0i8.p0i8.i64", T_fn(T_memcpy64_args, T_void())); let memset32 = - decl_cdecl_fn(llmod, ~"llvm.memset.p0i8.i32", + decl_cdecl_fn(llmod, "llvm.memset.p0i8.i32", T_fn(T_memset32_args, T_void())); let memset64 = - decl_cdecl_fn(llmod, ~"llvm.memset.p0i8.i64", + decl_cdecl_fn(llmod, "llvm.memset.p0i8.i64", T_fn(T_memset64_args, T_void())); - let trap = decl_cdecl_fn(llmod, ~"llvm.trap", T_fn(T_trap_args, + let trap = decl_cdecl_fn(llmod, "llvm.trap", T_fn(T_trap_args, T_void())); - let frameaddress = decl_cdecl_fn(llmod, ~"llvm.frameaddress", + let frameaddress = decl_cdecl_fn(llmod, "llvm.frameaddress", T_fn(T_frameaddress_args, T_ptr(T_i8()))); - let sqrtf32 = decl_cdecl_fn(llmod, ~"llvm.sqrt.f32", - T_fn(~[T_f32()], T_f32())); - let sqrtf64 = decl_cdecl_fn(llmod, ~"llvm.sqrt.f64", - T_fn(~[T_f64()], T_f64())); - let powif32 = decl_cdecl_fn(llmod, ~"llvm.powi.f32", - T_fn(~[T_f32(), T_i32()], T_f32())); - let powif64 = decl_cdecl_fn(llmod, ~"llvm.powi.f64", - T_fn(~[T_f64(), T_i32()], T_f64())); - let sinf32 = decl_cdecl_fn(llmod, ~"llvm.sin.f32", - T_fn(~[T_f32()], T_f32())); - let sinf64 = decl_cdecl_fn(llmod, ~"llvm.sin.f64", - T_fn(~[T_f64()], T_f64())); - let cosf32 = decl_cdecl_fn(llmod, ~"llvm.cos.f32", - T_fn(~[T_f32()], T_f32())); - let cosf64 = decl_cdecl_fn(llmod, ~"llvm.cos.f64", - T_fn(~[T_f64()], T_f64())); - let powf32 = decl_cdecl_fn(llmod, ~"llvm.pow.f32", - T_fn(~[T_f32(), T_f32()], T_f32())); - let powf64 = decl_cdecl_fn(llmod, ~"llvm.pow.f64", - T_fn(~[T_f64(), T_f64()], T_f64())); - let expf32 = decl_cdecl_fn(llmod, ~"llvm.exp.f32", - T_fn(~[T_f32()], T_f32())); - let expf64 = decl_cdecl_fn(llmod, ~"llvm.exp.f64", - T_fn(~[T_f64()], T_f64())); - let exp2f32 = decl_cdecl_fn(llmod, ~"llvm.exp2.f32", - T_fn(~[T_f32()], T_f32())); - let exp2f64 = decl_cdecl_fn(llmod, ~"llvm.exp2.f64", - T_fn(~[T_f64()], T_f64())); - let logf32 = decl_cdecl_fn(llmod, ~"llvm.log.f32", - T_fn(~[T_f32()], T_f32())); - let logf64 = decl_cdecl_fn(llmod, ~"llvm.log.f64", - T_fn(~[T_f64()], T_f64())); - let log10f32 = decl_cdecl_fn(llmod, ~"llvm.log10.f32", - T_fn(~[T_f32()], T_f32())); - let log10f64 = decl_cdecl_fn(llmod, ~"llvm.log10.f64", - T_fn(~[T_f64()], T_f64())); - let log2f32 = decl_cdecl_fn(llmod, ~"llvm.log2.f32", - T_fn(~[T_f32()], T_f32())); - let log2f64 = decl_cdecl_fn(llmod, ~"llvm.log2.f64", - T_fn(~[T_f64()], T_f64())); - let fmaf32 = decl_cdecl_fn(llmod, ~"llvm.fma.f32", - T_fn(~[T_f32(), T_f32(), T_f32()], T_f32())); - let fmaf64 = decl_cdecl_fn(llmod, ~"llvm.fma.f64", - T_fn(~[T_f64(), T_f64(), T_f64()], T_f64())); - let fabsf32 = decl_cdecl_fn(llmod, ~"llvm.fabs.f32", - T_fn(~[T_f32()], T_f32())); - let fabsf64 = decl_cdecl_fn(llmod, ~"llvm.fabs.f64", - T_fn(~[T_f64()], T_f64())); - let floorf32 = decl_cdecl_fn(llmod, ~"llvm.floor.f32", - T_fn(~[T_f32()], T_f32())); - let floorf64 = decl_cdecl_fn(llmod, ~"llvm.floor.f64", - T_fn(~[T_f64()], T_f64())); - let ceilf32 = decl_cdecl_fn(llmod, ~"llvm.ceil.f32", - T_fn(~[T_f32()], T_f32())); - let ceilf64 = decl_cdecl_fn(llmod, ~"llvm.ceil.f64", - T_fn(~[T_f64()], T_f64())); - let truncf32 = decl_cdecl_fn(llmod, ~"llvm.trunc.f32", - T_fn(~[T_f32()], T_f32())); - let truncf64 = decl_cdecl_fn(llmod, ~"llvm.trunc.f64", - T_fn(~[T_f64()], T_f64())); - let ctpop8 = decl_cdecl_fn(llmod, ~"llvm.ctpop.i8", - T_fn(~[T_i8()], T_i8())); - let ctpop16 = decl_cdecl_fn(llmod, ~"llvm.ctpop.i16", - T_fn(~[T_i16()], T_i16())); - let ctpop32 = decl_cdecl_fn(llmod, ~"llvm.ctpop.i32", - T_fn(~[T_i32()], T_i32())); - let ctpop64 = decl_cdecl_fn(llmod, ~"llvm.ctpop.i64", - T_fn(~[T_i64()], T_i64())); - let ctlz8 = decl_cdecl_fn(llmod, ~"llvm.ctlz.i8", - T_fn(~[T_i8(), T_i1()], T_i8())); - let ctlz16 = decl_cdecl_fn(llmod, ~"llvm.ctlz.i16", - T_fn(~[T_i16(), T_i1()], T_i16())); - let ctlz32 = decl_cdecl_fn(llmod, ~"llvm.ctlz.i32", - T_fn(~[T_i32(), T_i1()], T_i32())); - let ctlz64 = decl_cdecl_fn(llmod, ~"llvm.ctlz.i64", - T_fn(~[T_i64(), T_i1()], T_i64())); - let cttz8 = decl_cdecl_fn(llmod, ~"llvm.cttz.i8", - T_fn(~[T_i8(), T_i1()], T_i8())); - let cttz16 = decl_cdecl_fn(llmod, ~"llvm.cttz.i16", - T_fn(~[T_i16(), T_i1()], T_i16())); - let cttz32 = decl_cdecl_fn(llmod, ~"llvm.cttz.i32", - T_fn(~[T_i32(), T_i1()], T_i32())); - let cttz64 = decl_cdecl_fn(llmod, ~"llvm.cttz.i64", - T_fn(~[T_i64(), T_i1()], T_i64())); - let bswap16 = decl_cdecl_fn(llmod, ~"llvm.bswap.i16", - T_fn(~[T_i16()], T_i16())); - let bswap32 = decl_cdecl_fn(llmod, ~"llvm.bswap.i32", - T_fn(~[T_i32()], T_i32())); - let bswap64 = decl_cdecl_fn(llmod, ~"llvm.bswap.i64", - T_fn(~[T_i64()], T_i64())); + let sqrtf32 = decl_cdecl_fn(llmod, "llvm.sqrt.f32", + T_fn([T_f32()], T_f32())); + let sqrtf64 = decl_cdecl_fn(llmod, "llvm.sqrt.f64", + T_fn([T_f64()], T_f64())); + let powif32 = decl_cdecl_fn(llmod, "llvm.powi.f32", + T_fn([T_f32(), T_i32()], T_f32())); + let powif64 = decl_cdecl_fn(llmod, "llvm.powi.f64", + T_fn([T_f64(), T_i32()], T_f64())); + let sinf32 = decl_cdecl_fn(llmod, "llvm.sin.f32", + T_fn([T_f32()], T_f32())); + let sinf64 = decl_cdecl_fn(llmod, "llvm.sin.f64", + T_fn([T_f64()], T_f64())); + let cosf32 = decl_cdecl_fn(llmod, "llvm.cos.f32", + T_fn([T_f32()], T_f32())); + let cosf64 = decl_cdecl_fn(llmod, "llvm.cos.f64", + T_fn([T_f64()], T_f64())); + let powf32 = decl_cdecl_fn(llmod, "llvm.pow.f32", + T_fn([T_f32(), T_f32()], T_f32())); + let powf64 = decl_cdecl_fn(llmod, "llvm.pow.f64", + T_fn([T_f64(), T_f64()], T_f64())); + let expf32 = decl_cdecl_fn(llmod, "llvm.exp.f32", + T_fn([T_f32()], T_f32())); + let expf64 = decl_cdecl_fn(llmod, "llvm.exp.f64", + T_fn([T_f64()], T_f64())); + let exp2f32 = decl_cdecl_fn(llmod, "llvm.exp2.f32", + T_fn([T_f32()], T_f32())); + let exp2f64 = decl_cdecl_fn(llmod, "llvm.exp2.f64", + T_fn([T_f64()], T_f64())); + let logf32 = decl_cdecl_fn(llmod, "llvm.log.f32", + T_fn([T_f32()], T_f32())); + let logf64 = decl_cdecl_fn(llmod, "llvm.log.f64", + T_fn([T_f64()], T_f64())); + let log10f32 = decl_cdecl_fn(llmod, "llvm.log10.f32", + T_fn([T_f32()], T_f32())); + let log10f64 = decl_cdecl_fn(llmod, "llvm.log10.f64", + T_fn([T_f64()], T_f64())); + let log2f32 = decl_cdecl_fn(llmod, "llvm.log2.f32", + T_fn([T_f32()], T_f32())); + let log2f64 = decl_cdecl_fn(llmod, "llvm.log2.f64", + T_fn([T_f64()], T_f64())); + let fmaf32 = decl_cdecl_fn(llmod, "llvm.fma.f32", + T_fn([T_f32(), T_f32(), T_f32()], T_f32())); + let fmaf64 = decl_cdecl_fn(llmod, "llvm.fma.f64", + T_fn([T_f64(), T_f64(), T_f64()], T_f64())); + let fabsf32 = decl_cdecl_fn(llmod, "llvm.fabs.f32", + T_fn([T_f32()], T_f32())); + let fabsf64 = decl_cdecl_fn(llmod, "llvm.fabs.f64", + T_fn([T_f64()], T_f64())); + let floorf32 = decl_cdecl_fn(llmod, "llvm.floor.f32", + T_fn([T_f32()], T_f32())); + let floorf64 = decl_cdecl_fn(llmod, "llvm.floor.f64", + T_fn([T_f64()], T_f64())); + let ceilf32 = decl_cdecl_fn(llmod, "llvm.ceil.f32", + T_fn([T_f32()], T_f32())); + let ceilf64 = decl_cdecl_fn(llmod, "llvm.ceil.f64", + T_fn([T_f64()], T_f64())); + let truncf32 = decl_cdecl_fn(llmod, "llvm.trunc.f32", + T_fn([T_f32()], T_f32())); + let truncf64 = decl_cdecl_fn(llmod, "llvm.trunc.f64", + T_fn([T_f64()], T_f64())); + let ctpop8 = decl_cdecl_fn(llmod, "llvm.ctpop.i8", + T_fn([T_i8()], T_i8())); + let ctpop16 = decl_cdecl_fn(llmod, "llvm.ctpop.i16", + T_fn([T_i16()], T_i16())); + let ctpop32 = decl_cdecl_fn(llmod, "llvm.ctpop.i32", + T_fn([T_i32()], T_i32())); + let ctpop64 = decl_cdecl_fn(llmod, "llvm.ctpop.i64", + T_fn([T_i64()], T_i64())); + let ctlz8 = decl_cdecl_fn(llmod, "llvm.ctlz.i8", + T_fn([T_i8(), T_i1()], T_i8())); + let ctlz16 = decl_cdecl_fn(llmod, "llvm.ctlz.i16", + T_fn([T_i16(), T_i1()], T_i16())); + let ctlz32 = decl_cdecl_fn(llmod, "llvm.ctlz.i32", + T_fn([T_i32(), T_i1()], T_i32())); + let ctlz64 = decl_cdecl_fn(llmod, "llvm.ctlz.i64", + T_fn([T_i64(), T_i1()], T_i64())); + let cttz8 = decl_cdecl_fn(llmod, "llvm.cttz.i8", + T_fn([T_i8(), T_i1()], T_i8())); + let cttz16 = decl_cdecl_fn(llmod, "llvm.cttz.i16", + T_fn([T_i16(), T_i1()], T_i16())); + let cttz32 = decl_cdecl_fn(llmod, "llvm.cttz.i32", + T_fn([T_i32(), T_i1()], T_i32())); + let cttz64 = decl_cdecl_fn(llmod, "llvm.cttz.i64", + T_fn([T_i64(), T_i1()], T_i64())); + let bswap16 = decl_cdecl_fn(llmod, "llvm.bswap.i16", + T_fn([T_i16()], T_i16())); + let bswap32 = decl_cdecl_fn(llmod, "llvm.bswap.i32", + T_fn([T_i32()], T_i32())); + let bswap64 = decl_cdecl_fn(llmod, "llvm.bswap.i64", + T_fn([T_i64()], T_i64())); let mut intrinsics = HashMap::new(); intrinsics.insert(~"llvm.gcroot", gcroot); @@ -2801,12 +2800,11 @@ pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<~str, ValueRef> { pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<~str, ValueRef>) { let declare = - decl_cdecl_fn(llmod, ~"llvm.dbg.declare", - T_fn(~[T_metadata(), T_metadata()], T_void())); + decl_cdecl_fn(llmod, "llvm.dbg.declare", + T_fn([T_metadata(), T_metadata()], T_void())); let value = - decl_cdecl_fn(llmod, ~"llvm.dbg.value", - T_fn(~[T_metadata(), T_i64(), T_metadata()], - T_void())); + decl_cdecl_fn(llmod, "llvm.dbg.value", + T_fn([T_metadata(), T_i64(), T_metadata()], T_void())); intrinsics.insert(~"llvm.dbg.declare", declare); intrinsics.insert(~"llvm.dbg.value", value); } @@ -2815,7 +2813,7 @@ pub fn trap(bcx: block) { let v: ~[ValueRef] = ~[]; match bcx.ccx().intrinsics.find(&~"llvm.trap") { Some(&x) => { Call(bcx, x, v); }, - _ => bcx.sess().bug(~"unbound llvm.trap in trap") + _ => bcx.sess().bug("unbound llvm.trap in trap") } } @@ -2838,9 +2836,9 @@ pub fn decl_gc_metadata(ccx: @CrateContext, llmod_id: &str) { } pub fn create_module_map(ccx: @CrateContext) -> ValueRef { - let elttype = T_struct(~[ccx.int_type, ccx.int_type], false); + let elttype = T_struct([ccx.int_type, ccx.int_type], false); let maptype = T_array(elttype, ccx.module_data.len() + 1); - let map = str::as_c_str(~"_rust_mod_map", |buf| { + let map = str::as_c_str("_rust_mod_map", |buf| { unsafe { llvm::LLVMAddGlobal(ccx.llmod, maptype, buf) } @@ -2848,11 +2846,11 @@ pub fn create_module_map(ccx: @CrateContext) -> ValueRef { lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage); let mut elts: ~[ValueRef] = ~[]; for ccx.module_data.each |key, &val| { - let elt = C_struct(~[p2i(ccx, C_cstr(ccx, @/*bad*/ copy *key)), + let elt = C_struct([p2i(ccx, C_cstr(ccx, @/*bad*/ copy *key)), p2i(ccx, val)]); elts.push(elt); } - let term = C_struct(~[C_int(ccx, 0), C_int(ccx, 0)]); + let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]); elts.push(term); unsafe { llvm::LLVMSetInitializer(map, C_array(elttype, elts)); @@ -2876,7 +2874,7 @@ pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta, }; let sym_name = ~"_rust_crate_map_" + mapname; let arrtype = T_array(int_type, n_subcrates as uint); - let maptype = T_struct(~[T_i32(), T_ptr(T_i8()), int_type, arrtype], false); + let maptype = T_struct([T_i32(), T_ptr(T_i8()), int_type, arrtype], false); let map = str::as_c_str(sym_name, |buf| { unsafe { llvm::LLVMAddGlobal(llmod, maptype, buf) @@ -2919,11 +2917,11 @@ pub fn fill_crate_map(ccx: @CrateContext, map: ValueRef) { unsafe { llvm::LLVMSetInitializer(map, C_struct( - ~[C_i32(1), - lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, - T_ptr(T_i8())), - p2i(ccx, create_module_map(ccx)), - C_array(ccx.int_type, subcrates)])); + [C_i32(1), + lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, + T_ptr(T_i8())), + p2i(ccx, create_module_map(ccx)), + C_array(ccx.int_type, subcrates)])); } } @@ -2950,8 +2948,8 @@ pub fn write_metadata(cx: @CrateContext, crate: &ast::crate) { if !*cx.sess.building_library { return; } let encode_parms = crate_ctxt_to_encode_parms(cx); let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate)); - let llconst = C_struct(~[llmeta]); - let mut llglobal = str::as_c_str(~"rust_metadata", |buf| { + let llconst = C_struct([llmeta]); + let mut llglobal = str::as_c_str("rust_metadata", |buf| { unsafe { llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst), buf) } @@ -2965,11 +2963,11 @@ pub fn write_metadata(cx: @CrateContext, crate: &ast::crate) { let t_ptr_i8 = T_ptr(T_i8()); llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8); - let llvm_used = str::as_c_str(~"llvm.used", |buf| { + let llvm_used = str::as_c_str("llvm.used", |buf| { llvm::LLVMAddGlobal(cx.llmod, T_array(t_ptr_i8, 1u), buf) }); lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage); - llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, ~[llglobal])); + llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal])); } } @@ -3122,7 +3120,7 @@ pub fn trans_crate(sess: session::Session, // Translate the metadata. write_metadata(ccx, crate); if ccx.sess.trans_stats() { - io::println(~"--- trans stats ---"); + io::println("--- trans stats ---"); io::println(fmt!("n_static_tydescs: %u", ccx.stats.n_static_tydescs)); io::println(fmt!("n_glues_created: %u", diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index 362bcd483b41f..5793732abbf91 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -189,7 +189,7 @@ pub fn Invoke(cx: block, val_str(cx.ccx().tn, Fn), str::connect(vec::map(Args, |a| val_str(cx.ccx().tn, *a).to_owned()), - ~", ")); + ", ")); unsafe { count_insn(cx, "invoke"); llvm::LLVMBuildInvoke(B(cx), @@ -862,7 +862,7 @@ pub fn _UndefReturn(cx: block, Fn: ValueRef) -> ValueRef { let ty = val_ty(Fn); let retty = if llvm::LLVMGetTypeKind(ty) == lib::llvm::Integer { llvm::LLVMGetReturnType(ty) } else { ccx.int_type }; - count_insn(cx, ~""); + count_insn(cx, ""); return llvm::LLVMGetUndef(retty); } } @@ -880,17 +880,17 @@ pub fn add_comment(bcx: block, text: &str) { unsafe { let ccx = bcx.ccx(); if ccx.sess.asm_comments() { - let sanitized = str::replace(text, ~"$", ~""); + let sanitized = str::replace(text, "$", ""); let comment_text = ~"# " + - str::replace(sanitized, ~"\n", ~"\n\t# "); + str::replace(sanitized, "\n", "\n\t# "); let asm = str::as_c_str(comment_text, |c| { - str::as_c_str(~"", |e| { - count_insn(bcx, ~"inlineasm"); - llvm::LLVMConstInlineAsm(T_fn(~[], T_void()), c, e, + str::as_c_str("", |e| { + count_insn(bcx, "inlineasm"); + llvm::LLVMConstInlineAsm(T_fn([], T_void()), c, e, False, False) }) }); - Call(bcx, asm, ~[]); + Call(bcx, asm, []); } } } @@ -1062,7 +1062,7 @@ pub fn Trap(cx: block) { let BB: BasicBlockRef = llvm::LLVMGetInsertBlock(b); let FN: ValueRef = llvm::LLVMGetBasicBlockParent(BB); let M: ModuleRef = llvm::LLVMGetGlobalParent(FN); - let T: ValueRef = str::as_c_str(~"llvm.trap", |buf| { + let T: ValueRef = str::as_c_str("llvm.trap", |buf| { llvm::LLVMGetNamedFunction(M, buf) }); assert!((T as int != 0)); diff --git a/src/librustc/middle/trans/cabi.rs b/src/librustc/middle/trans/cabi.rs index e103bbc5de7a8..c6f4d23041973 100644 --- a/src/librustc/middle/trans/cabi.rs +++ b/src/librustc/middle/trans/cabi.rs @@ -177,7 +177,7 @@ pub impl FnType { } } - let llretval = load_inbounds(bcx, llargbundle, ~[ 0, arg_tys.len() ]); + let llretval = load_inbounds(bcx, llargbundle, [ 0, arg_tys.len() ]); let llretval = if self.ret_ty.cast { let retptr = BitCast(bcx, llretval, T_ptr(self.ret_ty.ty)); Load(bcx, retptr) diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index 382e80148ec01..6fbefb1d8aeda 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -379,7 +379,7 @@ pub fn trans_lang_call(bcx: block, trans_fn_ref_with_vtables_to_callee(bcx, did, 0, - ~[], + [], None) }, ArgVals(args), @@ -717,8 +717,7 @@ pub fn trans_arg_expr(bcx: block, } _ => { bcx.sess().impossible_case( - arg_expr.span, ~"ret_flag with non-loop-\ - body expr"); + arg_expr.span, "ret_flag with non-loop-body expr"); } } } diff --git a/src/librustc/middle/trans/closure.rs b/src/librustc/middle/trans/closure.rs index d9cf1a3b4bc54..3a14d72e9bfdb 100644 --- a/src/librustc/middle/trans/closure.rs +++ b/src/librustc/middle/trans/closure.rs @@ -317,7 +317,7 @@ pub fn load_environment(fcx: fn_ctxt, Some(ll) => ll, None => { let ll = - str::as_c_str(~"load_env", + str::as_c_str("load_env", |buf| unsafe { llvm::LLVMAppendBasicBlock(fcx.llfn, buf) @@ -516,7 +516,7 @@ pub fn make_opaque_cbox_take_glue( let bcx = callee::trans_lang_call( bcx, bcx.tcx().lang_items.exchange_malloc_fn(), - ~[opaque_tydesc, sz], + [opaque_tydesc, sz], expr::SaveIn(rval)); let cbox_out = PointerCast(bcx, Load(bcx, rval), llopaquecboxty); call_memcpy(bcx, cbox_out, cbox_in, sz); @@ -589,7 +589,7 @@ pub fn make_opaque_cbox_free_glue( ast::ManagedSigil => glue::trans_free(bcx, cbox), ast::OwnedSigil => glue::trans_exchange_free(bcx, cbox), ast::BorrowedSigil => { - bcx.sess().bug(~"impossible") + bcx.sess().bug("impossible") } } } diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 0274ecbfd1dd4..115cf52056f40 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -781,7 +781,7 @@ pub fn T_void() -> TypeRef { } pub fn T_nil() -> TypeRef { - return T_struct(~[], false) + return T_struct([], false) } pub fn T_metadata() -> TypeRef { unsafe { return llvm::LLVMMetadataType(); } } @@ -864,7 +864,7 @@ pub fn T_fn(inputs: &[TypeRef], output: TypeRef) -> TypeRef { } pub fn T_fn_pair(cx: @CrateContext, tfn: TypeRef) -> TypeRef { - return T_struct(~[T_ptr(tfn), T_opaque_cbox_ptr(cx)], false); + return T_struct([T_ptr(tfn), T_opaque_cbox_ptr(cx)], false); } pub fn T_ptr(t: TypeRef) -> TypeRef { @@ -903,7 +903,7 @@ pub fn set_struct_body(t: TypeRef, elts: &[TypeRef], packed: bool) { } } -pub fn T_empty_struct() -> TypeRef { return T_struct(~[], false); } +pub fn T_empty_struct() -> TypeRef { return T_struct([], false); } // A vtable is, in reality, a vtable pointer followed by zero or more pointers // to tydescs and other vtables that it closes over. But the types and number @@ -912,7 +912,7 @@ pub fn T_empty_struct() -> TypeRef { return T_struct(~[], false); } pub fn T_vtable() -> TypeRef { T_array(T_ptr(T_i8()), 1u) } pub fn T_task(targ_cfg: @session::config) -> TypeRef { - let t = T_named_struct(~"task"); + let t = T_named_struct("task"); // Refcount // Delegate pointer @@ -960,11 +960,11 @@ pub fn T_generic_glue_fn(cx: @CrateContext) -> TypeRef { } pub fn T_tydesc(targ_cfg: @session::config) -> TypeRef { - let tydesc = T_named_struct(~"tydesc"); + let tydesc = T_named_struct("tydesc"); let tydescpp = T_ptr(T_ptr(tydesc)); let pvoid = T_ptr(T_i8()); let glue_fn_ty = - T_ptr(T_fn(~[T_ptr(T_nil()), T_ptr(T_nil()), tydescpp, + T_ptr(T_fn([T_ptr(T_nil()), T_ptr(T_nil()), tydescpp, pvoid], T_void())); let int_type = T_int(targ_cfg); @@ -990,9 +990,9 @@ pub fn T_vector(t: TypeRef, n: uint) -> TypeRef { // Interior vector. pub fn T_vec2(targ_cfg: @session::config, t: TypeRef) -> TypeRef { - return T_struct(~[T_int(targ_cfg), // fill - T_int(targ_cfg), // alloc - T_array(t, 0u)], // elements + return T_struct([T_int(targ_cfg), // fill + T_int(targ_cfg), // alloc + T_array(t, 0u)], // elements false); } @@ -1028,7 +1028,7 @@ pub fn T_box_header(cx: @CrateContext) -> TypeRef { } pub fn T_box(cx: @CrateContext, t: TypeRef) -> TypeRef { - return T_struct(vec::append(T_box_header_fields(cx), ~[t]), false); + return T_struct(vec::append(T_box_header_fields(cx), [t]), false); } pub fn T_box_ptr(t: TypeRef) -> TypeRef { @@ -1046,7 +1046,7 @@ pub fn T_opaque_box_ptr(cx: @CrateContext) -> TypeRef { } pub fn T_unique(cx: @CrateContext, t: TypeRef) -> TypeRef { - return T_struct(vec::append(T_box_header_fields(cx), ~[t]), false); + return T_struct(vec::append(T_box_header_fields(cx), [t]), false); } pub fn T_unique_ptr(t: TypeRef) -> TypeRef { @@ -1056,12 +1056,12 @@ pub fn T_unique_ptr(t: TypeRef) -> TypeRef { } pub fn T_port(cx: @CrateContext, _t: TypeRef) -> TypeRef { - return T_struct(~[cx.int_type], false); // Refcount + return T_struct([cx.int_type], false); // Refcount } pub fn T_chan(cx: @CrateContext, _t: TypeRef) -> TypeRef { - return T_struct(~[cx.int_type], false); // Refcount + return T_struct([cx.int_type], false); // Refcount } @@ -1085,16 +1085,16 @@ pub fn T_captured_tydescs(cx: @CrateContext, n: uint) -> TypeRef { pub fn T_opaque_trait(cx: @CrateContext, store: ty::TraitStore) -> TypeRef { match store { ty::BoxTraitStore => { - T_struct(~[T_ptr(cx.tydesc_type), T_opaque_box_ptr(cx)], false) + T_struct([T_ptr(cx.tydesc_type), T_opaque_box_ptr(cx)], false) } ty::UniqTraitStore => { - T_struct(~[T_ptr(cx.tydesc_type), - T_unique_ptr(T_unique(cx, T_i8())), - T_ptr(cx.tydesc_type)], + T_struct([T_ptr(cx.tydesc_type), + T_unique_ptr(T_unique(cx, T_i8())), + T_ptr(cx.tydesc_type)], false) } ty::RegionTraitStore(_) => { - T_struct(~[T_ptr(cx.tydesc_type), T_ptr(T_i8())], false) + T_struct([T_ptr(cx.tydesc_type), T_ptr(T_i8())], false) } } } @@ -1130,7 +1130,7 @@ pub fn C_floating(s: &str, t: TypeRef) -> ValueRef { } pub fn C_nil() -> ValueRef { - return C_struct(~[]); + return C_struct([]); } pub fn C_bool(b: bool) -> ValueRef { @@ -1193,7 +1193,7 @@ pub fn C_estr_slice(cx: @CrateContext, s: @~str) -> ValueRef { unsafe { let len = s.len(); let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), T_ptr(T_i8())); - C_struct(~[cs, C_uint(cx, len + 1u /* +1 for null */)]) + C_struct([cs, C_uint(cx, len + 1u /* +1 for null */)]) } } diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 1348ea6801edb..ac85a9f5eaca9 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -165,7 +165,7 @@ pub fn get_const_val(cx: @CrateContext, def_id: ast::def_id) -> ValueRef { }, _) => { trans_const(cx, subexpr, def_id.node); } - _ => cx.tcx.sess.bug(~"expected a const to be an item") + _ => cx.tcx.sess.bug("expected a const to be an item") } } cx.const_values.get_copy(&def_id.node) @@ -177,7 +177,7 @@ pub fn const_expr(cx: @CrateContext, e: @ast::expr) -> ValueRef { match cx.tcx.adjustments.find(&e.id) { None => { } Some(&@ty::AutoAddEnv(ty::re_static, ast::BorrowedSigil)) => { - llconst = C_struct(~[llconst, C_null(T_opaque_box_ptr(cx))]) + llconst = C_struct([llconst, C_null(T_opaque_box_ptr(cx))]) } Some(&@ty::AutoAddEnv(ref r, ref s)) => { cx.sess.span_bug(e.span, fmt!("unexpected static function: \ @@ -213,7 +213,7 @@ pub fn const_expr(cx: @CrateContext, e: @ast::expr) -> ValueRef { val_ty(llconst)); assert_eq!(abi::slice_elt_base, 0); assert_eq!(abi::slice_elt_len, 1); - llconst = C_struct(~[llptr, size]); + llconst = C_struct([llptr, size]); } _ => { cx.sess.span_bug(e.span, @@ -450,8 +450,8 @@ fn const_expr_unadjusted(cx: @CrateContext, e: @ast::expr) -> ValueRef { llvm::LLVMConstIntCast(iv, llty, s) } expr::cast_float => llvm::LLVMConstUIToFP(iv, llty), - _ => cx.sess.bug(~"enum cast destination is not \ - integral or float") + _ => cx.sess.bug("enum cast destination is not \ + integral or float") } } (expr::cast_pointer, expr::cast_pointer) => { @@ -462,7 +462,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: @ast::expr) -> ValueRef { } _ => { cx.sess.impossible_case(e.span, - ~"bad combination of types for cast") + "bad combination of types for cast") } } } @@ -512,7 +512,7 @@ fn const_expr_unadjusted(cx: @CrateContext, e: @ast::expr) -> ValueRef { llvm::LLVMSetGlobalConstant(gv, True); SetLinkage(gv, PrivateLinkage); let p = const_ptrcast(cx, gv, llunitty); - C_struct(~[p, sz]) + C_struct([p, sz]) } _ => cx.sess.span_bug(e.span, "bad const-slice expr") } diff --git a/src/librustc/middle/trans/controlflow.rs b/src/librustc/middle/trans/controlflow.rs index ac512bc4bf95d..a1b673be66785 100644 --- a/src/librustc/middle/trans/controlflow.rs +++ b/src/librustc/middle/trans/controlflow.rs @@ -93,14 +93,14 @@ pub fn trans_if(bcx: block, trans_block(else_bcx_in, blk, dest) } // would be nice to have a constraint on ifs - _ => bcx.tcx().sess.bug(~"strange alternative in if") + _ => bcx.tcx().sess.bug("strange alternative in if") } } _ => else_bcx_in }; let else_bcx_out = trans_block_cleanups(else_bcx_out, block_cleanups(else_bcx_in)); - return join_blocks(bcx, ~[then_bcx_out, else_bcx_out]); + return join_blocks(bcx, [then_bcx_out, else_bcx_out]); } @@ -228,7 +228,7 @@ pub fn trans_log(log_ex: @ast::expr, let val = val_datum.to_ref_llval(bcx); let did = bcx.tcx().lang_items.log_type_fn(); let bcx = callee::trans_lang_call_with_type_params( - bcx, did, ~[level, val], ~[val_datum.ty], expr::Ignore); + bcx, did, [level, val], [val_datum.ty], expr::Ignore); bcx } } diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index d8252a449ba0d..0582853d9e1a7 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -217,7 +217,7 @@ fn create_compile_unit(cx: @CrateContext) -> @Metadata { llstr(env!("CFG_VERSION")), lli1(true), // deprecated: main compile unit lli1(cx.sess.opts.optimize != session::No), - llstr(~""), // flags (???) + llstr(""), // flags (???) lli32(0) // runtime version (???) ]; let unit_node = llmdnode(unit_metadata); @@ -368,7 +368,7 @@ fn create_basic_type(cx: @CrateContext, t: ty::t, span: span) ast::ty_f32 => (~"f32", DW_ATE_float), ast::ty_f64 => (~"f64", DW_ATE_float) }, - _ => cx.sess.bug(~"debuginfo::create_basic_type - t is invalid type") + _ => cx.sess.bug("debuginfo::create_basic_type - t is invalid type") }; let fname = filename_from_span(cx, span); @@ -522,7 +522,7 @@ fn create_tuple(cx: @CrateContext, t: ty::t, elements: &[ty::t], span: span) for elements.each |element| { let ty_md = create_ty(cx, *element, span); let (size, align) = size_and_align_of(cx, *element); - add_member(scx, ~"", line_from_span(cx.sess.codemap, span) as int, + add_member(scx, "", line_from_span(cx.sess.codemap, span) as int, size as int, align as int, ty_md.node); } let mdval = @Metadata { @@ -539,7 +539,7 @@ fn voidptr() -> (ValueRef, int, int) { let null = ptr::null(); let size = sys::size_of::() as int; let align = sys::min_align_of::() as int; - let vp = create_derived_type(PointerTypeTag, null, ~"", 0, + let vp = create_derived_type(PointerTypeTag, null, "", 0, size, align, 0, null); return (vp, size, align); } @@ -561,16 +561,16 @@ fn create_boxed_type(cx: @CrateContext, contents: ty::t, let refcount_type = create_basic_type(cx, int_t, span); let name = ty_to_str(cx.tcx, contents); let scx = create_structure(file_node, @fmt!("box<%s>", name), 0); - add_member(scx, ~"refcnt", 0, sys::size_of::() as int, + add_member(scx, "refcnt", 0, sys::size_of::() as int, sys::min_align_of::() as int, refcount_type.node); // the tydesc and other pointers should be irrelevant to the // debugger, so treat them as void* types let (vp, vpsize, vpalign) = voidptr(); - add_member(scx, ~"tydesc", 0, vpsize, vpalign, vp); - add_member(scx, ~"prev", 0, vpsize, vpalign, vp); - add_member(scx, ~"next", 0, vpsize, vpalign, vp); + add_member(scx, "tydesc", 0, vpsize, vpalign, vp); + add_member(scx, "prev", 0, vpsize, vpalign, vp); + add_member(scx, "next", 0, vpsize, vpalign, vp); let (size, align) = size_and_align_of(cx, contents); - add_member(scx, ~"boxed", 0, size, align, boxed.node); + add_member(scx, "boxed", 0, size, align, boxed.node); let llnode = finish_structure(scx); let mdval = @Metadata { node: llnode, @@ -619,7 +619,7 @@ fn create_fixed_vec(cx: @CrateContext, vec_t: ty::t, elem_t: ty::t, let fname = filename_from_span(cx, span); let file_node = create_file(cx, fname); let (size, align) = size_and_align_of(cx, elem_t); - let subrange = llmdnode(~[lltag(SubrangeTag), lli64(0), lli64(len - 1)]); + let subrange = llmdnode([lltag(SubrangeTag), lli64(0), lli64(len - 1)]); let name = fmt!("[%s]", ty_to_str(cx.tcx, elem_t)); let array = create_composite_type(ArrayTypeTag, name, file_node.node, 0, size * len, align, 0, Some(t_md.node), @@ -641,18 +641,18 @@ fn create_boxed_vec(cx: @CrateContext, vec_t: ty::t, elem_t: ty::t, let vec_scx = create_structure(file_node, @/*bad*/ copy ty_to_str(cx.tcx, vec_t), 0); let size_t_type = create_basic_type(cx, ty::mk_uint(), vec_ty_span); - add_member(vec_scx, ~"fill", 0, sys::size_of::() as int, + add_member(vec_scx, "fill", 0, sys::size_of::() as int, sys::min_align_of::() as int, size_t_type.node); - add_member(vec_scx, ~"alloc", 0, sys::size_of::() as int, + add_member(vec_scx, "alloc", 0, sys::size_of::() as int, sys::min_align_of::() as int, size_t_type.node); - let subrange = llmdnode(~[lltag(SubrangeTag), lli64(0), lli64(0)]); + let subrange = llmdnode([lltag(SubrangeTag), lli64(0), lli64(0)]); let (arr_size, arr_align) = size_and_align_of(cx, elem_t); let name = fmt!("[%s]", ty_to_str(cx.tcx, elem_t)); let data_ptr = create_composite_type(ArrayTypeTag, name, file_node.node, 0, arr_size, arr_align, 0, Some(elem_ty_md.node), Some(~[subrange])); - add_member(vec_scx, ~"data", 0, 0, // clang says the size should be 0 + add_member(vec_scx, "data", 0, 0, // clang says the size should be 0 sys::min_align_of::() as int, data_ptr); let llnode = finish_structure(vec_scx); let vec_md = @Metadata { @@ -665,15 +665,15 @@ fn create_boxed_vec(cx: @CrateContext, vec_t: ty::t, elem_t: ty::t, let box_scx = create_structure(file_node, @fmt!("box<%s>", name), 0); let int_t = ty::mk_int(); let refcount_type = create_basic_type(cx, int_t, vec_ty_span); - add_member(box_scx, ~"refcnt", 0, sys::size_of::() as int, + add_member(box_scx, "refcnt", 0, sys::size_of::() as int, sys::min_align_of::() as int, refcount_type.node); let (vp, vpsize, vpalign) = voidptr(); - add_member(box_scx, ~"tydesc", 0, vpsize, vpalign, vp); - add_member(box_scx, ~"prev", 0, vpsize, vpalign, vp); - add_member(box_scx, ~"next", 0, vpsize, vpalign, vp); + add_member(box_scx, "tydesc", 0, vpsize, vpalign, vp); + add_member(box_scx, "prev", 0, vpsize, vpalign, vp); + add_member(box_scx, "next", 0, vpsize, vpalign, vp); let size = 2 * sys::size_of::() as int; let align = sys::min_align_of::() as int; - add_member(box_scx, ~"boxed", 0, size, align, vec_md.node); + add_member(box_scx, "boxed", 0, size, align, vec_md.node); let llnode = finish_structure(box_scx); let mdval = @Metadata { node: llnode, @@ -693,8 +693,8 @@ fn create_vec_slice(cx: @CrateContext, vec_t: ty::t, elem_t: ty::t, span: span) let elem_ptr = create_pointer_type(cx, elem_t, span, elem_ty_md); let scx = create_structure(file_node, @ty_to_str(cx.tcx, vec_t), 0); let (_, ptr_size, ptr_align) = voidptr(); - add_member(scx, ~"vec", 0, ptr_size, ptr_align, elem_ptr.node); - add_member(scx, ~"length", 0, sys::size_of::() as int, + add_member(scx, "vec", 0, ptr_size, ptr_align, elem_ptr.node); + add_member(scx, "length", 0, sys::size_of::() as int, sys::min_align_of::() as int, uint_type.node); let llnode = finish_structure(scx); let mdval = @Metadata { @@ -715,7 +715,7 @@ fn create_fn_ty(cx: @CrateContext, fn_ty: ty::t, inputs: ~[ty::t], output: ty::t let output_ptr_md = create_pointer_type(cx, output, span, output_md); let inputs_vals = do inputs.map |arg| { create_ty(cx, *arg, span).node }; let members = ~[output_ptr_md.node, vp] + inputs_vals; - let llnode = create_composite_type(SubroutineTag, ~"", file_node.node, + let llnode = create_composite_type(SubroutineTag, "", file_node.node, 0, 0, 0, 0, None, Some(members)); let mdval = @Metadata { node: llnode, @@ -802,7 +802,7 @@ fn create_ty(cx: @CrateContext, t: ty::t, span: span) ty::ty_tup(ref elements) => { create_tuple(cx, t, *elements, span) }, - _ => cx.sess.bug(~"debuginfo: unexpected type in create_ty") + _ => cx.sess.bug("debuginfo: unexpected type in create_ty") } } @@ -869,7 +869,7 @@ pub fn create_local_var(bcx: block, local: @ast::local) } } }; - let declargs = ~[llmdnode(~[llptr]), mdnode]; + let declargs = ~[llmdnode([llptr]), mdnode]; trans::build::Call(bcx, *cx.intrinsics.get(&~"llvm.dbg.declare"), declargs); return mdval; @@ -918,7 +918,7 @@ pub fn create_arg(bcx: block, arg: ast::arg, sp: span) let llptr = match fcx.llargs.get_copy(&arg.id) { local_mem(v) | local_imm(v) => v, }; - let declargs = ~[llmdnode(~[llptr]), mdnode]; + let declargs = ~[llmdnode([llptr]), mdnode]; trans::build::Call(bcx, *cx.intrinsics.get(&~"llvm.dbg.declare"), declargs); @@ -1003,7 +1003,7 @@ pub fn create_function(fcx: fn_ctxt) -> @Metadata { } else { llnull() }; - let sub_node = create_composite_type(SubroutineTag, ~"", file_node, 0, 0, + let sub_node = create_composite_type(SubroutineTag, "", file_node, 0, 0, 0, 0, option::None, option::Some(~[ty_node])); @@ -1013,7 +1013,7 @@ pub fn create_function(fcx: fn_ctxt) -> @Metadata { llstr(*cx.sess.str_of(ident)), //XXX fully-qualified C++ name: llstr(*cx.sess.str_of(ident)), - llstr(~""), //XXX MIPS name????? + llstr(""), //XXX MIPS name????? file_node, lli32(loc.line as int), sub_node, diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 8883cc44d1213..f457cc80da898 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -885,9 +885,9 @@ fn trans_lvalue_unadjusted(bcx: block, expr: @ast::expr) -> DatumBlock { }; let vt = tvec::vec_types(bcx, base_datum.ty); - base::maybe_name_value(bcx.ccx(), vt.llunit_size, ~"unit_sz"); + base::maybe_name_value(bcx.ccx(), vt.llunit_size, "unit_sz"); let scaled_ix = Mul(bcx, ix_val, vt.llunit_size); - base::maybe_name_value(bcx.ccx(), scaled_ix, ~"scaled_ix"); + base::maybe_name_value(bcx.ccx(), scaled_ix, "scaled_ix"); let mut (bcx, base, len) = base_datum.get_vec_base_and_len(bcx, index_expr.span, @@ -907,7 +907,7 @@ fn trans_lvalue_unadjusted(bcx: block, expr: @ast::expr) -> DatumBlock { controlflow::trans_fail_bounds_check(bcx, index_expr.span, ix_val, unscaled_len) }; - let elt = InBoundsGEP(bcx, base, ~[ix_val]); + let elt = InBoundsGEP(bcx, base, [ix_val]); let elt = PointerCast(bcx, elt, T_ptr(vt.llunit_ty)); return DatumBlock { bcx: bcx, @@ -1110,8 +1110,8 @@ pub fn with_field_tys(tcx: ty::ctxt, struct_fields(tcx, variant_id, substs)) } _ => { - tcx.sess.bug(~"resolve didn't map this expr to a \ - variant ID") + tcx.sess.bug("resolve didn't map this expr to a \ + variant ID") } } } @@ -1168,7 +1168,7 @@ fn trans_rec_or_struct(bcx: block, } None => { if need_base.any(|b| *b) { - tcx.sess.span_bug(expr_span, ~"missing fields and no base expr") + tcx.sess.span_bug(expr_span, "missing fields and no base expr") } None } @@ -1313,9 +1313,9 @@ fn trans_unary_datum(bcx: block, trans_boxed_expr(bcx, un_ty, sub_expr, sub_ty, heap) } ast::deref => { - bcx.sess().bug(~"deref expressions should have been \ - translated using trans_lvalue(), not \ - trans_unary_datum()") + bcx.sess().bug("deref expressions should have been \ + translated using trans_lvalue(), not \ + trans_unary_datum()") } }; @@ -1482,8 +1482,8 @@ fn trans_lazy_binop(bcx: block, } Br(past_rhs, join.llbb); - let phi = Phi(join, T_bool(), ~[lhs, rhs], ~[past_lhs.llbb, - past_rhs.llbb]); + let phi = Phi(join, T_bool(), [lhs, rhs], [past_lhs.llbb, + past_rhs.llbb]); return immediate_rvalue_bcx(join, phi, binop_ty); } @@ -1644,10 +1644,10 @@ fn trans_imm_cast(bcx: block, expr: @ast::expr, val_ty(lldiscrim_a), lldiscrim_a, true), cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out), - _ => ccx.sess.bug(~"translating unsupported cast.") + _ => ccx.sess.bug("translating unsupported cast.") } } - _ => ccx.sess.bug(~"translating unsupported cast.") + _ => ccx.sess.bug("translating unsupported cast.") }; return immediate_rvalue_bcx(bcx, newval, t_out); } diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index 13d8f854fb20f..0ed0eb31c0b27 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -51,7 +51,7 @@ fn abi_info(ccx: @CrateContext) -> @cabi::ABIInfo { } pub fn link_name(ccx: @CrateContext, i: @ast::foreign_item) -> @~str { - match attr::first_attr_value_str_by_name(i.attrs, ~"link_name") { + match attr::first_attr_value_str_by_name(i.attrs, "link_name") { None => ccx.sess.str_of(i.ident), Some(ln) => ln, } @@ -106,7 +106,7 @@ fn foreign_signature(ccx: @CrateContext, fn_sig: &ty::FnSig) fn shim_types(ccx: @CrateContext, id: ast::node_id) -> ShimTypes { let fn_sig = match ty::get(ty::node_id_to_type(ccx.tcx, id)).sty { ty::ty_bare_fn(ref fn_ty) => copy fn_ty.sig, - _ => ccx.sess.bug(~"c_arg_and_ret_lltys called on non-function type") + _ => ccx.sess.bug("c_arg_and_ret_lltys called on non-function type") }; let llsig = foreign_signature(ccx, &fn_sig); let bundle_ty = T_struct(vec::append_one(copy llsig.llarg_tys, @@ -122,7 +122,7 @@ fn shim_types(ccx: @CrateContext, id: ast::node_id) -> ShimTypes { llsig: llsig, ret_def: ret_def, bundle_ty: bundle_ty, - shim_fn_ty: T_fn(~[T_ptr(bundle_ty)], T_nil()), + shim_fn_ty: T_fn([T_ptr(bundle_ty)], T_nil()), fn_ty: fn_ty } } @@ -207,7 +207,7 @@ fn build_wrap_fn_(ccx: @CrateContext, // Create call itself. let llshimfnptr = PointerCast(bcx, llshimfn, T_ptr(T_i8())); let llrawargbundle = PointerCast(bcx, llargbundle, T_ptr(T_i8())); - Call(bcx, shim_upcall, ~[llrawargbundle, llshimfnptr]); + Call(bcx, shim_upcall, [llrawargbundle, llshimfnptr]); ret_builder(bcx, tys, llargbundle); // Perform a custom version of `finish_fn`. First, tie up the header @@ -521,10 +521,10 @@ pub fn trans_foreign_mod(ccx: @CrateContext, llargval = Load(bcx, llargval); } - store_inbounds(bcx, llargval, llargbundle, ~[0u, i]); + store_inbounds(bcx, llargval, llargbundle, [0u, i]); } let llretptr = bcx.fcx.llretptr.get(); - store_inbounds(bcx, llretptr, llargbundle, ~[0u, n]); + store_inbounds(bcx, llretptr, llargbundle, [0u, n]); } fn build_ret(bcx: block, @@ -532,7 +532,7 @@ pub fn trans_foreign_mod(ccx: @CrateContext, llargbundle: ValueRef) { let _icx = bcx.insn_ctxt("foreign::wrap::build_ret"); let arg_count = shim_types.fn_sig.inputs.len(); - let llretptr = load_inbounds(bcx, llargbundle, ~[0, arg_count]); + let llretptr = load_inbounds(bcx, llargbundle, [0, arg_count]); Store(bcx, Load(bcx, llretptr), bcx.fcx.llretptr.get()); build_return(bcx); } @@ -808,7 +808,7 @@ pub fn trans_intrinsic(ccx: @CrateContext, } ~"frame_address" => { let frameaddress = *ccx.intrinsics.get(&~"llvm.frameaddress"); - let frameaddress_val = Call(bcx, frameaddress, ~[C_i32(0i32)]); + let frameaddress_val = Call(bcx, frameaddress, [C_i32(0i32)]); let star_u8 = ty::mk_imm_ptr( bcx.tcx(), ty::mk_mach_uint(ast::ty_u8)); @@ -836,9 +836,9 @@ pub fn trans_intrinsic(ccx: @CrateContext, // XXX This is a hack to grab the address of this particular // native function. There should be a general in-language // way to do this - let llfty = type_of_fn(bcx.ccx(), ~[], ty::mk_nil()); + let llfty = type_of_fn(bcx.ccx(), [], ty::mk_nil()); let morestack_addr = decl_cdecl_fn( - bcx.ccx().llmod, ~"__morestack", llfty); + bcx.ccx().llmod, "__morestack", llfty); let morestack_addr = PointerCast(bcx, morestack_addr, T_ptr(T_nil())); Store(bcx, morestack_addr, fcx.llretptr.get()); @@ -851,7 +851,7 @@ pub fn trans_intrinsic(ccx: @CrateContext, let volatile = C_i1(false); let llfn = *bcx.ccx().intrinsics.get( &~"llvm.memmove.p0i8.p0i8.i32"); - Call(bcx, llfn, ~[dst_ptr, src_ptr, size, align, volatile]); + Call(bcx, llfn, [dst_ptr, src_ptr, size, align, volatile]); } ~"memmove64" => { let dst_ptr = get_param(decl, first_real_arg); @@ -861,248 +861,248 @@ pub fn trans_intrinsic(ccx: @CrateContext, let volatile = C_i1(false); let llfn = *bcx.ccx().intrinsics.get( &~"llvm.memmove.p0i8.p0i8.i64"); - Call(bcx, llfn, ~[dst_ptr, src_ptr, size, align, volatile]); + Call(bcx, llfn, [dst_ptr, src_ptr, size, align, volatile]); } ~"sqrtf32" => { let x = get_param(decl, first_real_arg); let sqrtf = *ccx.intrinsics.get(&~"llvm.sqrt.f32"); - Store(bcx, Call(bcx, sqrtf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, sqrtf, [x]), fcx.llretptr.get()); } ~"sqrtf64" => { let x = get_param(decl, first_real_arg); let sqrtf = *ccx.intrinsics.get(&~"llvm.sqrt.f64"); - Store(bcx, Call(bcx, sqrtf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, sqrtf, [x]), fcx.llretptr.get()); } ~"powif32" => { let a = get_param(decl, first_real_arg); let x = get_param(decl, first_real_arg + 1u); let powif = *ccx.intrinsics.get(&~"llvm.powi.f32"); - Store(bcx, Call(bcx, powif, ~[a, x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, powif, [a, x]), fcx.llretptr.get()); } ~"powif64" => { let a = get_param(decl, first_real_arg); let x = get_param(decl, first_real_arg + 1u); let powif = *ccx.intrinsics.get(&~"llvm.powi.f64"); - Store(bcx, Call(bcx, powif, ~[a, x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, powif, [a, x]), fcx.llretptr.get()); } ~"sinf32" => { let x = get_param(decl, first_real_arg); let sinf = *ccx.intrinsics.get(&~"llvm.sin.f32"); - Store(bcx, Call(bcx, sinf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, sinf, [x]), fcx.llretptr.get()); } ~"sinf64" => { let x = get_param(decl, first_real_arg); let sinf = *ccx.intrinsics.get(&~"llvm.sin.f64"); - Store(bcx, Call(bcx, sinf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, sinf, [x]), fcx.llretptr.get()); } ~"cosf32" => { let x = get_param(decl, first_real_arg); let cosf = *ccx.intrinsics.get(&~"llvm.cos.f32"); - Store(bcx, Call(bcx, cosf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, cosf, [x]), fcx.llretptr.get()); } ~"cosf64" => { let x = get_param(decl, first_real_arg); let cosf = *ccx.intrinsics.get(&~"llvm.cos.f64"); - Store(bcx, Call(bcx, cosf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, cosf, [x]), fcx.llretptr.get()); } ~"powf32" => { let a = get_param(decl, first_real_arg); let x = get_param(decl, first_real_arg + 1u); let powf = *ccx.intrinsics.get(&~"llvm.pow.f32"); - Store(bcx, Call(bcx, powf, ~[a, x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, powf, [a, x]), fcx.llretptr.get()); } ~"powf64" => { let a = get_param(decl, first_real_arg); let x = get_param(decl, first_real_arg + 1u); let powf = *ccx.intrinsics.get(&~"llvm.pow.f64"); - Store(bcx, Call(bcx, powf, ~[a, x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, powf, [a, x]), fcx.llretptr.get()); } ~"expf32" => { let x = get_param(decl, first_real_arg); let expf = *ccx.intrinsics.get(&~"llvm.exp.f32"); - Store(bcx, Call(bcx, expf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, expf, [x]), fcx.llretptr.get()); } ~"expf64" => { let x = get_param(decl, first_real_arg); let expf = *ccx.intrinsics.get(&~"llvm.exp.f64"); - Store(bcx, Call(bcx, expf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, expf, [x]), fcx.llretptr.get()); } ~"exp2f32" => { let x = get_param(decl, first_real_arg); let exp2f = *ccx.intrinsics.get(&~"llvm.exp2.f32"); - Store(bcx, Call(bcx, exp2f, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, exp2f, [x]), fcx.llretptr.get()); } ~"exp2f64" => { let x = get_param(decl, first_real_arg); let exp2f = *ccx.intrinsics.get(&~"llvm.exp2.f64"); - Store(bcx, Call(bcx, exp2f, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, exp2f, [x]), fcx.llretptr.get()); } ~"logf32" => { let x = get_param(decl, first_real_arg); let logf = *ccx.intrinsics.get(&~"llvm.log.f32"); - Store(bcx, Call(bcx, logf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, logf, [x]), fcx.llretptr.get()); } ~"logf64" => { let x = get_param(decl, first_real_arg); let logf = *ccx.intrinsics.get(&~"llvm.log.f64"); - Store(bcx, Call(bcx, logf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, logf, [x]), fcx.llretptr.get()); } ~"log10f32" => { let x = get_param(decl, first_real_arg); let log10f = *ccx.intrinsics.get(&~"llvm.log10.f32"); - Store(bcx, Call(bcx, log10f, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, log10f, [x]), fcx.llretptr.get()); } ~"log10f64" => { let x = get_param(decl, first_real_arg); let log10f = *ccx.intrinsics.get(&~"llvm.log10.f64"); - Store(bcx, Call(bcx, log10f, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, log10f, [x]), fcx.llretptr.get()); } ~"log2f32" => { let x = get_param(decl, first_real_arg); let log2f = *ccx.intrinsics.get(&~"llvm.log2.f32"); - Store(bcx, Call(bcx, log2f, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, log2f, [x]), fcx.llretptr.get()); } ~"log2f64" => { let x = get_param(decl, first_real_arg); let log2f = *ccx.intrinsics.get(&~"llvm.log2.f64"); - Store(bcx, Call(bcx, log2f, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, log2f, [x]), fcx.llretptr.get()); } ~"fmaf32" => { let a = get_param(decl, first_real_arg); let b = get_param(decl, first_real_arg + 1u); let c = get_param(decl, first_real_arg + 2u); let fmaf = *ccx.intrinsics.get(&~"llvm.fma.f32"); - Store(bcx, Call(bcx, fmaf, ~[a, b, c]), fcx.llretptr.get()); + Store(bcx, Call(bcx, fmaf, [a, b, c]), fcx.llretptr.get()); } ~"fmaf64" => { let a = get_param(decl, first_real_arg); let b = get_param(decl, first_real_arg + 1u); let c = get_param(decl, first_real_arg + 2u); let fmaf = *ccx.intrinsics.get(&~"llvm.fma.f64"); - Store(bcx, Call(bcx, fmaf, ~[a, b, c]), fcx.llretptr.get()); + Store(bcx, Call(bcx, fmaf, [a, b, c]), fcx.llretptr.get()); } ~"fabsf32" => { let x = get_param(decl, first_real_arg); let fabsf = *ccx.intrinsics.get(&~"llvm.fabs.f32"); - Store(bcx, Call(bcx, fabsf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, fabsf, [x]), fcx.llretptr.get()); } ~"fabsf64" => { let x = get_param(decl, first_real_arg); let fabsf = *ccx.intrinsics.get(&~"llvm.fabs.f64"); - Store(bcx, Call(bcx, fabsf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, fabsf, [x]), fcx.llretptr.get()); } ~"floorf32" => { let x = get_param(decl, first_real_arg); let floorf = *ccx.intrinsics.get(&~"llvm.floor.f32"); - Store(bcx, Call(bcx, floorf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, floorf, [x]), fcx.llretptr.get()); } ~"floorf64" => { let x = get_param(decl, first_real_arg); let floorf = *ccx.intrinsics.get(&~"llvm.floor.f64"); - Store(bcx, Call(bcx, floorf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, floorf, [x]), fcx.llretptr.get()); } ~"ceilf32" => { let x = get_param(decl, first_real_arg); let ceilf = *ccx.intrinsics.get(&~"llvm.ceil.f32"); - Store(bcx, Call(bcx, ceilf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, ceilf, [x]), fcx.llretptr.get()); } ~"ceilf64" => { let x = get_param(decl, first_real_arg); let ceilf = *ccx.intrinsics.get(&~"llvm.ceil.f64"); - Store(bcx, Call(bcx, ceilf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, ceilf, [x]), fcx.llretptr.get()); } ~"truncf32" => { let x = get_param(decl, first_real_arg); let truncf = *ccx.intrinsics.get(&~"llvm.trunc.f32"); - Store(bcx, Call(bcx, truncf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, truncf, [x]), fcx.llretptr.get()); } ~"truncf64" => { let x = get_param(decl, first_real_arg); let truncf = *ccx.intrinsics.get(&~"llvm.trunc.f64"); - Store(bcx, Call(bcx, truncf, ~[x]), fcx.llretptr.get()); + Store(bcx, Call(bcx, truncf, [x]), fcx.llretptr.get()); } ~"ctpop8" => { let x = get_param(decl, first_real_arg); let ctpop = *ccx.intrinsics.get(&~"llvm.ctpop.i8"); - Store(bcx, Call(bcx, ctpop, ~[x]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctpop, [x]), fcx.llretptr.get()) } ~"ctpop16" => { let x = get_param(decl, first_real_arg); let ctpop = *ccx.intrinsics.get(&~"llvm.ctpop.i16"); - Store(bcx, Call(bcx, ctpop, ~[x]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctpop, [x]), fcx.llretptr.get()) } ~"ctpop32" => { let x = get_param(decl, first_real_arg); let ctpop = *ccx.intrinsics.get(&~"llvm.ctpop.i32"); - Store(bcx, Call(bcx, ctpop, ~[x]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctpop, [x]), fcx.llretptr.get()) } ~"ctpop64" => { let x = get_param(decl, first_real_arg); let ctpop = *ccx.intrinsics.get(&~"llvm.ctpop.i64"); - Store(bcx, Call(bcx, ctpop, ~[x]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctpop, [x]), fcx.llretptr.get()) } ~"ctlz8" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let ctlz = *ccx.intrinsics.get(&~"llvm.ctlz.i8"); - Store(bcx, Call(bcx, ctlz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctlz, [x, y]), fcx.llretptr.get()) } ~"ctlz16" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let ctlz = *ccx.intrinsics.get(&~"llvm.ctlz.i16"); - Store(bcx, Call(bcx, ctlz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctlz, [x, y]), fcx.llretptr.get()) } ~"ctlz32" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let ctlz = *ccx.intrinsics.get(&~"llvm.ctlz.i32"); - Store(bcx, Call(bcx, ctlz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctlz, [x, y]), fcx.llretptr.get()) } ~"ctlz64" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let ctlz = *ccx.intrinsics.get(&~"llvm.ctlz.i64"); - Store(bcx, Call(bcx, ctlz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, ctlz, [x, y]), fcx.llretptr.get()) } ~"cttz8" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let cttz = *ccx.intrinsics.get(&~"llvm.cttz.i8"); - Store(bcx, Call(bcx, cttz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, cttz, [x, y]), fcx.llretptr.get()) } ~"cttz16" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let cttz = *ccx.intrinsics.get(&~"llvm.cttz.i16"); - Store(bcx, Call(bcx, cttz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, cttz, [x, y]), fcx.llretptr.get()) } ~"cttz32" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let cttz = *ccx.intrinsics.get(&~"llvm.cttz.i32"); - Store(bcx, Call(bcx, cttz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, cttz, [x, y]), fcx.llretptr.get()) } ~"cttz64" => { let x = get_param(decl, first_real_arg); let y = C_i1(false); let cttz = *ccx.intrinsics.get(&~"llvm.cttz.i64"); - Store(bcx, Call(bcx, cttz, ~[x, y]), fcx.llretptr.get()) + Store(bcx, Call(bcx, cttz, [x, y]), fcx.llretptr.get()) } ~"bswap16" => { let x = get_param(decl, first_real_arg); let cttz = *ccx.intrinsics.get(&~"llvm.bswap.i16"); - Store(bcx, Call(bcx, cttz, ~[x]), fcx.llretptr.get()) + Store(bcx, Call(bcx, cttz, [x]), fcx.llretptr.get()) } ~"bswap32" => { let x = get_param(decl, first_real_arg); let cttz = *ccx.intrinsics.get(&~"llvm.bswap.i32"); - Store(bcx, Call(bcx, cttz, ~[x]), fcx.llretptr.get()) + Store(bcx, Call(bcx, cttz, [x]), fcx.llretptr.get()) } ~"bswap64" => { let x = get_param(decl, first_real_arg); let cttz = *ccx.intrinsics.get(&~"llvm.bswap.i64"); - Store(bcx, Call(bcx, cttz, ~[x]), fcx.llretptr.get()) + Store(bcx, Call(bcx, cttz, [x]), fcx.llretptr.get()) } _ => { // Could we make this an enum rather than a string? does it get @@ -1207,7 +1207,7 @@ pub fn trans_foreign_fn(ccx: @CrateContext, let n = tys.fn_sig.inputs.len(); if !ty::type_is_immediate(tys.fn_sig.output) { - let llretptr = load_inbounds(bcx, llargbundle, ~[0u, n]); + let llretptr = load_inbounds(bcx, llargbundle, [0u, n]); llargvals.push(llretptr); } else { llargvals.push(C_null(T_ptr(T_i8()))); @@ -1239,7 +1239,7 @@ pub fn trans_foreign_fn(ccx: @CrateContext, let arg_count = shim_types.fn_sig.inputs.len(); let llretptr = load_inbounds(bcx, llargbundle, - ~[0, arg_count]); + [0, arg_count]); Store(bcx, llretval, llretptr); } else { // NB: The return pointer in the Rust ABI function is wired diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index f77e2e0d52aa2..048acdc07a120 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -42,7 +42,7 @@ pub fn trans_free(cx: block, v: ValueRef) -> block { callee::trans_lang_call( cx, cx.tcx().lang_items.free_fn(), - ~[PointerCast(cx, v, T_ptr(T_i8()))], + [PointerCast(cx, v, T_ptr(T_i8()))], expr::Ignore) } @@ -51,7 +51,7 @@ pub fn trans_exchange_free(cx: block, v: ValueRef) -> block { callee::trans_lang_call( cx, cx.tcx().lang_items.exchange_free_fn(), - ~[PointerCast(cx, v, T_ptr(T_i8()))], + [PointerCast(cx, v, T_ptr(T_i8()))], expr::Ignore) } @@ -100,7 +100,7 @@ pub fn drop_ty_immediate(bcx: block, v: ValueRef, t: ty::t) -> block { ty::ty_estr(ty::vstore_box) => { decr_refcnt_maybe_free(bcx, v, t) } - _ => bcx.tcx().sess.bug(~"drop_ty_immediate: non-box ty") + _ => bcx.tcx().sess.bug("drop_ty_immediate: non-box ty") } } @@ -147,7 +147,7 @@ pub fn free_ty_immediate(bcx: block, v: ValueRef, t: ty::t) -> block { Store(bcx, v, vp); free_ty(bcx, vp, t) } - _ => bcx.tcx().sess.bug(~"free_ty_immediate: non-box ty") + _ => bcx.tcx().sess.bug("free_ty_immediate: non-box ty") } } @@ -269,7 +269,7 @@ pub fn lazily_emit_tydesc_glue(ccx: @CrateContext, ppaux::ty_to_str(ccx.tcx, ti.ty)); let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"take"); ti.take_glue = Some(glue_fn); - make_generic_glue(ccx, ti.ty, glue_fn, make_take_glue, ~"take"); + make_generic_glue(ccx, ti.ty, glue_fn, make_take_glue, "take"); debug!("--- lazily_emit_tydesc_glue TAKE %s", ppaux::ty_to_str(ccx.tcx, ti.ty)); } @@ -282,7 +282,7 @@ pub fn lazily_emit_tydesc_glue(ccx: @CrateContext, ppaux::ty_to_str(ccx.tcx, ti.ty)); let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"drop"); ti.drop_glue = Some(glue_fn); - make_generic_glue(ccx, ti.ty, glue_fn, make_drop_glue, ~"drop"); + make_generic_glue(ccx, ti.ty, glue_fn, make_drop_glue, "drop"); debug!("--- lazily_emit_tydesc_glue DROP %s", ppaux::ty_to_str(ccx.tcx, ti.ty)); } @@ -295,7 +295,7 @@ pub fn lazily_emit_tydesc_glue(ccx: @CrateContext, ppaux::ty_to_str(ccx.tcx, ti.ty)); let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"free"); ti.free_glue = Some(glue_fn); - make_generic_glue(ccx, ti.ty, glue_fn, make_free_glue, ~"free"); + make_generic_glue(ccx, ti.ty, glue_fn, make_free_glue, "free"); debug!("--- lazily_emit_tydesc_glue FREE %s", ppaux::ty_to_str(ccx.tcx, ti.ty)); } @@ -308,7 +308,7 @@ pub fn lazily_emit_tydesc_glue(ccx: @CrateContext, ppaux::ty_to_str(ccx.tcx, ti.ty)); let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, ~"visit"); ti.visit_glue = Some(glue_fn); - make_generic_glue(ccx, ti.ty, glue_fn, make_visit_glue, ~"visit"); + make_generic_glue(ccx, ti.ty, glue_fn, make_visit_glue, "visit"); debug!("--- lazily_emit_tydesc_glue VISIT %s", ppaux::ty_to_str(ccx.tcx, ti.ty)); } @@ -379,8 +379,8 @@ pub fn call_tydesc_glue_full(bcx: block, } }; - Call(bcx, llfn, ~[C_null(T_ptr(T_nil())), C_null(T_ptr(T_nil())), - C_null(T_ptr(T_ptr(bcx.ccx().tydesc_type))), llrawptr]); + Call(bcx, llfn, [C_null(T_ptr(T_nil())), C_null(T_ptr(T_nil())), + C_null(T_ptr(T_ptr(bcx.ccx().tydesc_type))), llrawptr]); } // See [Note-arg-mode] @@ -394,7 +394,7 @@ pub fn call_tydesc_glue(cx: block, v: ValueRef, t: ty::t, field: uint) pub fn make_visit_glue(bcx: block, v: ValueRef, t: ty::t) { let _icx = bcx.insn_ctxt("make_visit_glue"); - let bcx = do with_scope(bcx, None, ~"visitor cleanup") |bcx| { + let bcx = do with_scope(bcx, None, "visitor cleanup") |bcx| { let mut bcx = bcx; let (visitor_trait, object_ty) = ty::visitor_object_ty(bcx.tcx()); let v = PointerCast(bcx, v, T_ptr(type_of::type_of(bcx.ccx(), object_ty))); @@ -820,14 +820,14 @@ pub fn emit_tydescs(ccx: @CrateContext) { let tydesc = C_named_struct(ccx.tydesc_type, - ~[ti.size, // size - ti.align, // align - take_glue, // take_glue - drop_glue, // drop_glue - free_glue, // free_glue - visit_glue, // visit_glue - shape, // shape - shape_tables]); // shape_tables + [ti.size, // size + ti.align, // align + take_glue, // take_glue + drop_glue, // drop_glue + free_glue, // free_glue + visit_glue, // visit_glue + shape, // shape + shape_tables]); // shape_tables unsafe { let gvar = ti.tydesc; diff --git a/src/librustc/middle/trans/inline.rs b/src/librustc/middle/trans/inline.rs index 10e019b2a376c..8c88119107f78 100644 --- a/src/librustc/middle/trans/inline.rs +++ b/src/librustc/middle/trans/inline.rs @@ -77,14 +77,14 @@ pub fn maybe_instantiate_inline(ccx: @CrateContext, fn_id: ast::def_id, ccx.external.insert(there.id, Some(here.id.node)); } } - _ => ccx.sess.bug(~"maybe_instantiate_inline: item has a \ - non-enum parent") + _ => ccx.sess.bug("maybe_instantiate_inline: item has a \ + non-enum parent") } if translate { trans_item(ccx, item); } local_def(my_id) } csearch::found_parent(_, _) => { - ccx.sess.bug(~"maybe_get_item_ast returned a found_parent \ + ccx.sess.bug("maybe_get_item_ast returned a found_parent \ with a non-item parent"); } csearch::found(ast::ii_method(impl_did, mth)) => { @@ -98,7 +98,7 @@ pub fn maybe_instantiate_inline(ccx: @CrateContext, fn_id: ast::def_id, let llfn = get_item_val(ccx, mth.id); let path = vec::append( ty::item_path(ccx.tcx, impl_did), - ~[path_name(mth.ident)]); + [path_name(mth.ident)]); let self_kind = match mth.explicit_self.node { ast::sty_static => no_self, _ => { diff --git a/src/librustc/middle/trans/machine.rs b/src/librustc/middle/trans/machine.rs index 038c5e0369b8c..bd3c630fbb7b0 100644 --- a/src/librustc/middle/trans/machine.rs +++ b/src/librustc/middle/trans/machine.rs @@ -150,6 +150,6 @@ pub fn static_size_of_enum(cx: @CrateContext, t: ty::t) -> uint { cx.enum_sizes.insert(t, max_size); return max_size; } - _ => cx.sess.bug(~"static_size_of_enum called on non-enum") + _ => cx.sess.bug("static_size_of_enum called on non-enum") } } diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index 337e2a13b1fde..c6af3178d503d 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -213,8 +213,8 @@ pub fn trans_method_callee(bcx: block, // Make sure to fail with a readable error message if // there's some internal error here if !(method_index < supertrait_method_def_ids.len()) { - tcx.sess.bug(~"trans_method_callee: supertrait method \ - index is out of bounds"); + tcx.sess.bug("trans_method_callee: supertrait method \ + index is out of bounds"); } // Get the method name using the method index in the origin let method_name = @@ -657,11 +657,11 @@ pub fn trans_trait_callee_from_llval(bcx: block, let self_mode; match explicit_self { ast::sty_static => { - bcx.tcx().sess.bug(~"shouldn't see static method here"); + bcx.tcx().sess.bug("shouldn't see static method here"); } ast::sty_value => { - bcx.tcx().sess.bug(~"methods with by-value self should not be \ - called on objects"); + bcx.tcx().sess.bug("methods with by-value self should not be \ + called on objects"); } ast::sty_region(*) => { // As before, we need to pass a pointer to a pointer to the @@ -691,7 +691,7 @@ pub fn trans_trait_callee_from_llval(bcx: block, // Pass a pointer to the box. match store { ty::BoxTraitStore => llself = llbox, - _ => bcx.tcx().sess.bug(~"@self receiver with non-@Trait") + _ => bcx.tcx().sess.bug("@self receiver with non-@Trait") } let llscratch = alloca(bcx, val_ty(llself)); @@ -704,7 +704,7 @@ pub fn trans_trait_callee_from_llval(bcx: block, // Pass the unique pointer. match store { ty::UniqTraitStore => llself = llbox, - _ => bcx.tcx().sess.bug(~"~self receiver with non-~Trait") + _ => bcx.tcx().sess.bug("~self receiver with non-~Trait") } let llscratch = alloca(bcx, val_ty(llself)); diff --git a/src/librustc/middle/trans/monomorphize.rs b/src/librustc/middle/trans/monomorphize.rs index 40b92d336536c..f07cf58c6e9b6 100644 --- a/src/librustc/middle/trans/monomorphize.rs +++ b/src/librustc/middle/trans/monomorphize.rs @@ -120,23 +120,23 @@ pub fn monomorphic_fn(ccx: @CrateContext, (pt, m.ident, m.span) } ast_map::node_trait_method(@ast::required(_), _, _) => { - ccx.tcx.sess.bug(~"Can't monomorphize a required trait method") + ccx.tcx.sess.bug("Can't monomorphize a required trait method") } ast_map::node_expr(*) => { - ccx.tcx.sess.bug(~"Can't monomorphize an expr") + ccx.tcx.sess.bug("Can't monomorphize an expr") } ast_map::node_stmt(*) => { - ccx.tcx.sess.bug(~"Can't monomorphize a stmt") + ccx.tcx.sess.bug("Can't monomorphize a stmt") } - ast_map::node_arg(*) => ccx.tcx.sess.bug(~"Can't monomorphize an arg"), + ast_map::node_arg(*) => ccx.tcx.sess.bug("Can't monomorphize an arg"), ast_map::node_block(*) => { - ccx.tcx.sess.bug(~"Can't monomorphize a block") + ccx.tcx.sess.bug("Can't monomorphize a block") } ast_map::node_local(*) => { - ccx.tcx.sess.bug(~"Can't monomorphize a local") + ccx.tcx.sess.bug("Can't monomorphize a local") } ast_map::node_callee_scope(*) => { - ccx.tcx.sess.bug(~"Can't monomorphize a callee-scope") + ccx.tcx.sess.bug("Can't monomorphize a callee-scope") } ast_map::node_struct_ctor(_, i, pt) => (pt, i.ident, i.span) }; @@ -169,8 +169,7 @@ pub fn monomorphic_fn(ccx: @CrateContext, ccx.monomorphizing.insert(fn_id, depth + 1); let pt = vec::append(/*bad*/copy *pt, - ~[path_name((ccx.names)( - *ccx.sess.str_of(name)))]); + [path_name((ccx.names)(*ccx.sess.str_of(name)))]); let s = mangle_exported_name(ccx, /*bad*/copy pt, mono_ty); let mk_lldecl = || { @@ -206,7 +205,7 @@ pub fn monomorphic_fn(ccx: @CrateContext, d } ast_map::node_item(*) => { - ccx.tcx.sess.bug(~"Can't monomorphize this kind of item") + ccx.tcx.sess.bug("Can't monomorphize this kind of item") } ast_map::node_foreign_item(i, _, _, _) => { let d = mk_lldecl(); @@ -225,7 +224,7 @@ pub fn monomorphic_fn(ccx: @CrateContext, this_tv.disr_val, psubsts, d); } ast::struct_variant_kind(_) => - ccx.tcx.sess.bug(~"can't monomorphize struct variants"), + ccx.tcx.sess.bug("can't monomorphize struct variants"), } d } @@ -257,8 +256,8 @@ pub fn monomorphic_fn(ccx: @CrateContext, set_inline_hint(d); base::trans_tuple_struct(ccx, /*bad*/copy struct_def.fields, - struct_def.ctor_id.expect(~"ast-mapped tuple struct \ - didn't have a ctor id"), + struct_def.ctor_id.expect("ast-mapped tuple struct \ + didn't have a ctor id"), psubsts, d); d diff --git a/src/librustc/middle/trans/reachable.rs b/src/librustc/middle/trans/reachable.rs index dfae7ca0e889b..471d8218ec4e7 100644 --- a/src/librustc/middle/trans/reachable.rs +++ b/src/librustc/middle/trans/reachable.rs @@ -212,8 +212,8 @@ fn traverse_inline_body(cx: @mut ctx, body: &blk) { } Some(_) => {} None => { - cx.tcx.sess.span_bug(e.span, ~"expr_method_call not in \ - method map"); + cx.tcx.sess.span_bug(e.span, "expr_method_call not in \ + method map"); } } } diff --git a/src/librustc/middle/trans/shape.rs b/src/librustc/middle/trans/shape.rs index 31de128074110..ab40d41dfe939 100644 --- a/src/librustc/middle/trans/shape.rs +++ b/src/librustc/middle/trans/shape.rs @@ -48,8 +48,8 @@ pub fn mk_global(ccx: @CrateContext, pub fn mk_ctxt(llmod: ModuleRef) -> Ctxt { unsafe { - let llshapetablesty = trans::common::T_named_struct(~"shapes"); - let _llshapetables = str::as_c_str(~"shapes", |buf| { + let llshapetablesty = trans::common::T_named_struct("shapes"); + let _llshapetables = str::as_c_str("shapes", |buf| { llvm::LLVMAddGlobal(llmod, llshapetablesty, buf) }); diff --git a/src/librustc/middle/trans/tvec.rs b/src/librustc/middle/trans/tvec.rs index 7a85e93584e25..29e026189db7c 100644 --- a/src/librustc/middle/trans/tvec.rs +++ b/src/librustc/middle/trans/tvec.rs @@ -45,8 +45,8 @@ pub fn expand_boxed_vec_ty(tcx: ty::ctxt, t: ty::t) -> ty::t { ty::ty_estr(ty::vstore_box) | ty::ty_evec(_, ty::vstore_box) => { ty::mk_imm_box(tcx, unboxed_vec_ty) } - _ => tcx.sess.bug(~"non boxed-vec type \ - in tvec::expand_boxed_vec_ty") + _ => tcx.sess.bug("non boxed-vec type \ + in tvec::expand_boxed_vec_ty") } } @@ -74,7 +74,7 @@ pub fn pointer_add(bcx: block, ptr: ValueRef, bytes: ValueRef) -> ValueRef { let _icx = bcx.insn_ctxt("tvec::pointer_add"); let old_ty = val_ty(ptr); let bptr = PointerCast(bcx, ptr, T_ptr(T_i8())); - return PointerCast(bcx, InBoundsGEP(bcx, bptr, ~[bytes]), old_ty); + return PointerCast(bcx, InBoundsGEP(bcx, bptr, [bytes]), old_ty); } pub fn alloc_raw(bcx: block, unit_ty: ty::t, @@ -313,7 +313,7 @@ pub fn trans_uniq_or_managed_vstore(bcx: block, let bcx = callee::trans_lang_call( bcx, bcx.tcx().lang_items.strdup_uniq_fn(), - ~[ llptrval, llsizeval ], + [ llptrval, llsizeval ], expr::SaveIn(lldestval.to_ref_llval(bcx))); return DatumBlock { bcx: bcx, @@ -564,7 +564,7 @@ pub fn iter_vec_raw(bcx: block, data_ptr: ValueRef, vec_ty: ty::t, let header_bcx = base::sub_block(bcx, "iter_vec_loop_header"); Br(bcx, header_bcx.llbb); let data_ptr = - Phi(header_bcx, val_ty(data_ptr), ~[data_ptr], ~[bcx.llbb]); + Phi(header_bcx, val_ty(data_ptr), [data_ptr], [bcx.llbb]); let not_yet_at_end = ICmp(header_bcx, lib::llvm::IntULT, data_ptr, data_end_ptr); let body_bcx = base::sub_block(header_bcx, "iter_vec_loop_body"); @@ -572,7 +572,7 @@ pub fn iter_vec_raw(bcx: block, data_ptr: ValueRef, vec_ty: ty::t, CondBr(header_bcx, not_yet_at_end, body_bcx.llbb, next_bcx.llbb); let body_bcx = f(body_bcx, data_ptr, unit_ty); AddIncomingToPhi(data_ptr, InBoundsGEP(body_bcx, data_ptr, - ~[C_int(bcx.ccx(), 1)]), + [C_int(bcx.ccx(), 1)]), body_bcx.llbb); Br(body_bcx, header_bcx.llbb); return next_bcx; diff --git a/src/librustc/middle/trans/type_of.rs b/src/librustc/middle/trans/type_of.rs index 8d5721aeb6512..10c2a21e288bf 100644 --- a/src/librustc/middle/trans/type_of.rs +++ b/src/librustc/middle/trans/type_of.rs @@ -70,7 +70,7 @@ pub fn type_of_fn_from_ty(cx: @CrateContext, fty: ty::t) -> TypeRef { ty::ty_closure(ref f) => type_of_fn(cx, f.sig.inputs, f.sig.output), ty::ty_bare_fn(ref f) => type_of_fn(cx, f.sig.inputs, f.sig.output), _ => { - cx.sess.bug(~"type_of_fn_from_ty given non-closure, non-bare-fn") + cx.sess.bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } @@ -90,7 +90,7 @@ pub fn type_of_non_gc_box(cx: @CrateContext, t: ty::t) -> TypeRef { T_ptr(T_unique(cx, type_of(cx, mt.ty))) } _ => { - cx.sess.bug(~"non-box in type_of_non_gc_box"); + cx.sess.bug("non-box in type_of_non_gc_box"); } } } @@ -135,11 +135,11 @@ pub fn sizing_type_of(cx: @CrateContext, t: ty::t) -> TypeRef { ty::ty_estr(ty::vstore_slice(*)) | ty::ty_evec(_, ty::vstore_slice(*)) => { - T_struct(~[T_ptr(T_i8()), T_ptr(T_i8())], false) + T_struct([T_ptr(T_i8()), T_ptr(T_i8())], false) } ty::ty_bare_fn(*) => T_ptr(T_i8()), - ty::ty_closure(*) => T_struct(~[T_ptr(T_i8()), T_ptr(T_i8())], false), + ty::ty_closure(*) => T_struct([T_ptr(T_i8()), T_ptr(T_i8())], false), ty::ty_trait(_, _, store, _) => T_opaque_trait(cx, store), ty::ty_estr(ty::vstore_fixed(size)) => T_array(T_i8(), size), @@ -239,15 +239,11 @@ pub fn type_of(cx: @CrateContext, t: ty::t) -> TypeRef { ty::ty_rptr(_, ref mt) => T_ptr(type_of(cx, mt.ty)), ty::ty_evec(ref mt, ty::vstore_slice(_)) => { - T_struct(~[T_ptr(type_of(cx, mt.ty)), - T_uint_ty(cx, ast::ty_u)], - false) + T_struct([T_ptr(type_of(cx, mt.ty)), T_uint_ty(cx, ast::ty_u)], false) } ty::ty_estr(ty::vstore_slice(_)) => { - T_struct(~[T_ptr(T_i8()), - T_uint_ty(cx, ast::ty_u)], - false) + T_struct([T_ptr(T_i8()), T_uint_ty(cx, ast::ty_u)], false) } ty::ty_estr(ty::vstore_fixed(n)) => { @@ -282,10 +278,10 @@ pub fn type_of(cx: @CrateContext, t: ty::t) -> TypeRef { substs.tps)) } } - ty::ty_self(*) => cx.tcx.sess.unimpl(~"type_of: ty_self"), - ty::ty_infer(*) => cx.tcx.sess.bug(~"type_of with ty_infer"), - ty::ty_param(*) => cx.tcx.sess.bug(~"type_of with ty_param"), - ty::ty_err(*) => cx.tcx.sess.bug(~"type_of with ty_err") + ty::ty_self(*) => cx.tcx.sess.unimpl("type_of: ty_self"), + ty::ty_infer(*) => cx.tcx.sess.bug("type_of with ty_infer"), + ty::ty_param(*) => cx.tcx.sess.bug("type_of with ty_param"), + ty::ty_err(*) => cx.tcx.sess.bug("type_of with ty_err") }; cx.lltypes.insert(t, llty); @@ -336,8 +332,8 @@ pub fn llvm_type_name(cx: @CrateContext, } pub fn type_of_dtor(ccx: @CrateContext, self_ty: ty::t) -> TypeRef { - T_fn(~[T_ptr(T_i8()), // output pointer - T_ptr(type_of(ccx, self_ty))], // self arg + T_fn([T_ptr(T_i8()), // output pointer + T_ptr(type_of(ccx, self_ty))], // self arg T_nil()) } @@ -351,6 +347,5 @@ pub fn type_of_rooted(ccx: @CrateContext, t: ty::t) -> TypeRef { pub fn type_of_glue_fn(ccx: @CrateContext, t: ty::t) -> TypeRef { let tydescpp = T_ptr(T_ptr(ccx.tydesc_type)); let llty = T_ptr(type_of(ccx, t)); - return T_fn(~[T_ptr(T_nil()), T_ptr(T_nil()), tydescpp, llty], - T_nil()); + return T_fn([T_ptr(T_nil()), T_ptr(T_nil()), tydescpp, llty], T_nil()); } diff --git a/src/librustc/middle/trans/write_guard.rs b/src/librustc/middle/trans/write_guard.rs index 8a6b4acac8eab..9fd6204311253 100644 --- a/src/librustc/middle/trans/write_guard.rs +++ b/src/librustc/middle/trans/write_guard.rs @@ -78,7 +78,7 @@ pub fn return_to_mut(mut bcx: block, bcx = callee::trans_lang_call( bcx, bcx.tcx().lang_items.unrecord_borrow_fn(), - ~[ + [ box_ptr, bits_val, filename_val, @@ -90,7 +90,7 @@ pub fn return_to_mut(mut bcx: block, callee::trans_lang_call( bcx, bcx.tcx().lang_items.return_to_mut_fn(), - ~[ + [ box_ptr, bits_val, filename_val, @@ -153,7 +153,7 @@ fn root(datum: &Datum, bcx = callee::trans_lang_call( bcx, freeze_did, - ~[ + [ box_ptr, filename, line @@ -164,7 +164,7 @@ fn root(datum: &Datum, bcx = callee::trans_lang_call( bcx, bcx.tcx().lang_items.record_borrow_fn(), - ~[ + [ box_ptr, Load(bcx, scratch_bits.val), filename, @@ -193,8 +193,6 @@ fn perform_write_guard(datum: &Datum, callee::trans_lang_call( bcx, bcx.tcx().lang_items.check_not_borrowed_fn(), - ~[PointerCast(bcx, llval, T_ptr(T_i8())), - filename, - line], + [PointerCast(bcx, llval, T_ptr(T_i8())), filename, line], expr::Ignore) } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 1a2a84ceae856..2067431a9ef47 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -1481,7 +1481,7 @@ pub fn subst_tps(cx: ctxt, tps: &[t], self_ty_opt: Option, typ: t) -> t { ty_param(p) => tps[p.idx], ty_self(_) => { match self_ty_opt { - None => cx.sess.bug(~"ty_self unexpected here"), + None => cx.sess.bug("ty_self unexpected here"), Some(self_ty) => { subst_tps(cx, tps, self_ty_opt, self_ty) } @@ -1582,8 +1582,7 @@ pub fn sequence_element_type(cx: ctxt, ty: t) -> t { match get(ty).sty { ty_estr(_) => return mk_mach_uint(ast::ty_u8), ty_evec(mt, _) | ty_unboxed_vec(mt) => return mt.ty, - _ => cx.sess.bug( - ~"sequence_element_type called on non-sequence value"), + _ => cx.sess.bug("sequence_element_type called on non-sequence value"), } } @@ -2133,7 +2132,7 @@ pub fn type_contents(cx: ctxt, ty: t) -> TypeContents { ty_type => TC_NONE, ty_err => { - cx.sess.bug(~"Asked to compute contents of fictitious type"); + cx.sess.bug("Asked to compute contents of fictitious type"); } }; @@ -2471,7 +2470,7 @@ pub fn type_is_pod(cx: ctxt, ty: t) -> bool { } ty_infer(*) | ty_self(*) | ty_err => { - cx.sess.bug(~"non concrete type in type_is_pod"); + cx.sess.bug("non concrete type in type_is_pod"); } } @@ -3519,29 +3518,29 @@ pub fn type_err_to_str(cx: ctxt, err: &type_err) -> ~str { pub fn note_and_explain_type_err(cx: ctxt, err: &type_err) { match *err { terr_regions_does_not_outlive(subregion, superregion) => { - note_and_explain_region(cx, ~"", subregion, ~"..."); - note_and_explain_region(cx, ~"...does not necessarily outlive ", - superregion, ~""); + note_and_explain_region(cx, "", subregion, "..."); + note_and_explain_region(cx, "...does not necessarily outlive ", + superregion, ""); } terr_regions_not_same(region1, region2) => { - note_and_explain_region(cx, ~"", region1, ~"..."); - note_and_explain_region(cx, ~"...is not the same lifetime as ", - region2, ~""); + note_and_explain_region(cx, "", region1, "..."); + note_and_explain_region(cx, "...is not the same lifetime as ", + region2, ""); } terr_regions_no_overlap(region1, region2) => { - note_and_explain_region(cx, ~"", region1, ~"..."); - note_and_explain_region(cx, ~"...does not overlap ", - region2, ~""); + note_and_explain_region(cx, "", region1, "..."); + note_and_explain_region(cx, "...does not overlap ", + region2, ""); } terr_regions_insufficiently_polymorphic(_, conc_region) => { note_and_explain_region(cx, - ~"concrete lifetime that was found is ", - conc_region, ~""); + "concrete lifetime that was found is ", + conc_region, ""); } terr_regions_overly_polymorphic(_, conc_region) => { note_and_explain_region(cx, - ~"expected concrete lifetime is ", - conc_region, ~""); + "expected concrete lifetime is ", + conc_region, ""); } _ => {} } @@ -3691,7 +3690,7 @@ pub fn ty_to_def_id(ty: t) -> Option { fn struct_ctor_id(cx: ctxt, struct_did: ast::def_id) -> Option { if struct_did.crate != ast::local_crate { // XXX: Cross-crate functionality. - cx.sess.unimpl(~"constructor ID of cross-crate tuple structs"); + cx.sess.unimpl("constructor ID of cross-crate tuple structs"); } match cx.items.find(&struct_did.node) { @@ -3701,10 +3700,10 @@ fn struct_ctor_id(cx: ctxt, struct_did: ast::def_id) -> Option { struct_def.ctor_id.map(|ctor_id| ast_util::local_def(*ctor_id)) } - _ => cx.sess.bug(~"called struct_ctor_id on non-struct") + _ => cx.sess.bug("called struct_ctor_id on non-struct") } } - _ => cx.sess.bug(~"called struct_ctor_id on non-struct") + _ => cx.sess.bug("called struct_ctor_id on non-struct") } } @@ -3869,7 +3868,7 @@ pub fn enum_variants(cx: ctxt, id: ast::def_id) -> @~[VariantInfo] { disr_val = match const_eval::eval_const_expr(cx, ex) { const_eval::const_int(val) => val as int, - _ => cx.sess.bug(~"tag_variants: bad disr expr") + _ => cx.sess.bug("tag_variants: bad disr expr") } } _ => disr_val += 1 @@ -3888,7 +3887,7 @@ pub fn enum_variants(cx: ctxt, id: ast::def_id) -> @~[VariantInfo] { } }) } - _ => cx.sess.bug(~"tag_variants: id not bound to an enum") + _ => cx.sess.bug("tag_variants: id not bound to an enum") } }; cx.enum_var_cache.insert(id, result); @@ -3908,7 +3907,7 @@ pub fn enum_variant_with_id(cx: ctxt, if variant.id == variant_id { return variant; } i += 1; } - cx.sess.bug(~"enum_variant_with_id(): no variant exists with that ID"); + cx.sess.bug("enum_variant_with_id(): no variant exists with that ID"); } @@ -4003,7 +4002,7 @@ pub fn lookup_struct_fields(cx: ctxt, did: ast::def_id) -> ~[field_ty] { ast::item_struct(struct_def, _) => { struct_field_tys(struct_def.fields) } - _ => cx.sess.bug(~"struct ID bound to non-struct") + _ => cx.sess.bug("struct ID bound to non-struct") } } Some(&ast_map::node_variant(ref variant, _, _)) => { @@ -4012,8 +4011,8 @@ pub fn lookup_struct_fields(cx: ctxt, did: ast::def_id) -> ~[field_ty] { struct_field_tys(struct_def.fields) } _ => { - cx.sess.bug(~"struct ID bound to enum variant that isn't \ - struct-like") + cx.sess.bug("struct ID bound to enum variant that isn't \ + struct-like") } } } @@ -4037,7 +4036,7 @@ pub fn lookup_struct_field(cx: ctxt, match vec::find(lookup_struct_fields(cx, parent), |f| f.id.node == field_id.node) { Some(t) => t, - None => cx.sess.bug(~"struct ID not found in parent's fields") + None => cx.sess.bug("struct ID not found in parent's fields") } } @@ -4338,11 +4337,11 @@ pub fn get_impl_id(tcx: ctxt, trait_id: def_id, self_ty: t) -> def_id { None => // try autoderef! match deref(tcx, self_ty, false) { Some(some_ty) => get_impl_id(tcx, trait_id, some_ty.ty), - None => tcx.sess.bug(~"get_impl_id: no impl of trait for \ - this type") + None => tcx.sess.bug("get_impl_id: no impl of trait for \ + this type") } }, - None => tcx.sess.bug(~"get_impl_id: trait isn't in trait_impls") + None => tcx.sess.bug("get_impl_id: trait isn't in trait_impls") } } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 54537397c6263..d45882cc17b05 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -1462,7 +1462,7 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt, ) -> ty::t { match method::lookup(fcx, op_ex, self_ex, - op_ex.callee_id, opname, self_t, ~[], + op_ex.callee_id, opname, self_t, [], deref_args, CheckTraitsOnly, autoderef_receiver) { Some(ref origin) => { let method_ty = fcx.node_ty(op_ex.callee_id); @@ -1876,7 +1876,7 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt, } else { "s" }, - str::connect(missing_fields, ~", "))); + str::connect(missing_fields, ", "))); } } @@ -2111,7 +2111,7 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt, } None => fcx.tcx().sess.impossible_case( expr.span, - ~"loop body must have an expected type") + "loop body must have an expected type") } } }; @@ -2397,7 +2397,7 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt, } fcx.write_nil(id); } - ast::expr_mac(_) => tcx.sess.bug(~"unexpanded macro"), + ast::expr_mac(_) => tcx.sess.bug("unexpanded macro"), ast::expr_break(_) => { fcx.write_bot(id); } ast::expr_again(_) => { fcx.write_bot(id); } ast::expr_ret(expr_opt) => { @@ -2551,7 +2551,7 @@ pub fn check_expr_with_unifier(fcx: @mut FnCtxt, None => { fcx.tcx().sess.impossible_case( expr.span, - ~"do body must have expected type") + "do body must have expected type") } } }; @@ -2911,7 +2911,7 @@ pub fn check_stmt(fcx: @mut FnCtxt, stmt: @ast::stmt) { saw_bot |= ty::type_is_bot(expr_ty); saw_err |= ty::type_is_error(expr_ty); } - ast::stmt_mac(*) => fcx.ccx.tcx.sess.bug(~"unexpanded macro") + ast::stmt_mac(*) => fcx.ccx.tcx.sess.bug("unexpanded macro") } if saw_bot { fcx.write_bot(node_id); diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index 89041bffd0941..0a38e021879cb 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -1642,9 +1642,9 @@ pub impl RegionVarBindings { note_and_explain_region( self.tcx, - ~"first, the lifetime must be contained by ", + "first, the lifetime must be contained by ", upper_bound_1.region, - ~"..."); + "..."); self.tcx.sess.span_note( upper_bound_1.span, @@ -1652,9 +1652,9 @@ pub impl RegionVarBindings { note_and_explain_region( self.tcx, - ~"but, the lifetime must also be contained by ", + "but, the lifetime must also be contained by ", upper_bound_2.region, - ~"..."); + "..."); self.tcx.sess.span_note( upper_bound_2.span, diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index dd313c54efb92..048a6588ba2c5 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -382,9 +382,9 @@ fn check_for_entry_fn(ccx: @mut CrateCtxt) { Some((id, sp)) => match *tcx.sess.entry_type { Some(session::EntryMain) => check_main_fn_ty(ccx, id, sp), Some(session::EntryStart) => check_start_fn_ty(ccx, id, sp), - None => tcx.sess.bug(~"entry function without a type") + None => tcx.sess.bug("entry function without a type") }, - None => tcx.sess.bug(~"type checking without entry function") + None => tcx.sess.bug("type checking without entry function") } } } diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index 72eef2ba4132c..310b0c964eee4 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -137,7 +137,7 @@ pub mod lib { pub fn version(argv0: &str) { let mut vers = ~"unknown version"; let env_vers = env!("CFG_VERSION"); - if env_vers.len() != 0 { vers = env_vers; } + if env_vers.len() != 0 { vers = env_vers.to_owned(); } io::println(fmt!("%s %s", argv0, vers)); io::println(fmt!("host: %s", host_triple())); } @@ -168,11 +168,11 @@ Available lint options: } io::println(fmt!("\nAvailable lint checks:\n")); io::println(fmt!(" %s %7.7s %s", - padded(max_key, ~"name"), ~"default", ~"meaning")); + padded(max_key, "name"), "default", "meaning")); io::println(fmt!(" %s %7.7s %s\n", - padded(max_key, ~"----"), ~"-------", ~"-------")); + padded(max_key, "----"), "-------", "-------")); for lint_dict.each |k, v| { - let k = str::replace(*k, ~"_", ~"-"); + let k = str::replace(*k, "_", "-"); io::println(fmt!(" %s %7.7s %s", padded(max_key, k), match v.default { @@ -183,7 +183,7 @@ Available lint options: }, v.desc)); } - io::println(~""); + io::println(""); } pub fn describe_debug_flags() { @@ -211,24 +211,24 @@ pub fn run_compiler(args: &~[~str], demitter: diagnostic::Emitter) { } }; - if opt_present(matches, ~"h") || opt_present(matches, ~"help") { + if opt_present(matches, "h") || opt_present(matches, "help") { usage(*binary); return; } - let lint_flags = vec::append(getopts::opt_strs(matches, ~"W"), - getopts::opt_strs(matches, ~"warn")); + let lint_flags = vec::append(getopts::opt_strs(matches, "W"), + getopts::opt_strs(matches, "warn")); if lint_flags.contains(&~"help") { describe_warnings(); return; } - if getopts::opt_strs(matches, ~"Z").contains(&~"help") { + if getopts::opt_strs(matches, "Z").contains(&~"help") { describe_debug_flags(); return; } - if opt_present(matches, ~"v") || opt_present(matches, ~"version") { + if opt_present(matches, "v") || opt_present(matches, "version") { version(*binary); return; } @@ -248,12 +248,12 @@ pub fn run_compiler(args: &~[~str], demitter: diagnostic::Emitter) { let sopts = build_session_options(binary, matches, demitter); let sess = build_session(sopts, demitter); - let odir = getopts::opt_maybe_str(matches, ~"out-dir"); + let odir = getopts::opt_maybe_str(matches, "out-dir"); let odir = odir.map(|o| Path(*o)); - let ofile = getopts::opt_maybe_str(matches, ~"o"); + let ofile = getopts::opt_maybe_str(matches, "o"); let ofile = ofile.map(|o| Path(*o)); let cfg = build_configuration(sess, binary, &input); - let pretty = getopts::opt_default(matches, ~"pretty", "normal").map( + let pretty = getopts::opt_default(matches, "pretty", "normal").map( |a| parse_pretty(sess, *a)); match pretty { Some::(ppm) => { @@ -262,7 +262,7 @@ pub fn run_compiler(args: &~[~str], demitter: diagnostic::Emitter) { } None:: => {/* continue */ } } - let ls = opt_present(matches, ~"ls"); + let ls = opt_present(matches, "ls"); if ls { match input { file_input(ref ifile) => { @@ -334,7 +334,7 @@ pub fn monitor(f: ~fn(diagnostic::Emitter)) { if p.recv() == done { diagnostic::emit( None, - diagnostic::ice_msg(~"unexpected failure"), + diagnostic::ice_msg("unexpected failure"), diagnostic::error); for [ diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 13a2f376c0694..06adb6cc364af 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -409,13 +409,13 @@ pub fn ty_to_str(cx: ctxt, typ: t) -> ~str { ty_uniq(ref tm) => ~"~" + mt_to_str(cx, tm), ty_ptr(ref tm) => ~"*" + mt_to_str(cx, tm), ty_rptr(r, ref tm) => { - region_to_str_space(cx, ~"&", r) + mt_to_str(cx, tm) + region_to_str_space(cx, "&", r) + mt_to_str(cx, tm) } ty_unboxed_vec(ref tm) => { ~"unboxed_vec<" + mt_to_str(cx, tm) + ~">" } ty_type => ~"type", ty_tup(ref elems) => { let strs = elems.map(|elem| ty_to_str(cx, *elem)); - ~"(" + str::connect(strs, ~",") + ~")" + ~"(" + str::connect(strs, ",") + ~")" } ty_closure(ref f) => { closure_to_str(cx, f) @@ -428,11 +428,11 @@ pub fn ty_to_str(cx: ctxt, typ: t) -> ~str { ty_param(param_ty {idx: id, def_id: did}) => { if cx.sess.verbose() { fmt!("'%s:%?", - str::from_bytes(~[('a' as u8) + (id as u8)]), + str::from_bytes([('a' as u8) + (id as u8)]), did) } else { fmt!("'%s", - str::from_bytes(~[('a' as u8) + (id as u8)])) + str::from_bytes([('a' as u8) + (id as u8)])) } } ty_self(*) => ~"Self", @@ -450,7 +450,7 @@ pub fn ty_to_str(cx: ctxt, typ: t) -> ~str { ty_evec(ref mt, vs) => { vstore_ty_to_str(cx, mt, vs) } - ty_estr(vs) => fmt!("%s%s", vstore_to_str(cx, vs), ~"str"), + ty_estr(vs) => fmt!("%s%s", vstore_to_str(cx, vs), "str"), ty_opaque_box => ~"@?", ty_opaque_closure_ptr(ast::BorrowedSigil) => ~"closure&", ty_opaque_closure_ptr(ast::ManagedSigil) => ~"closure@", diff --git a/src/libstd/dlist.rs b/src/libstd/dlist.rs index 100543d7d98c7..57cd03e16a097 100644 --- a/src/libstd/dlist.rs +++ b/src/libstd/dlist.rs @@ -136,10 +136,10 @@ priv impl DList { } if !nobe.linked { fail!("That node isn't linked to any dlist.") } if !((nobe.prev.is_some() - || managed::mut_ptr_eq(self.hd.expect(~"headless dlist?"), + || managed::mut_ptr_eq(self.hd.expect("headless dlist?"), nobe)) && (nobe.next.is_some() - || managed::mut_ptr_eq(self.tl.expect(~"tailless dlist?"), + || managed::mut_ptr_eq(self.tl.expect("tailless dlist?"), nobe))) { fail!("That node isn't on this dlist.") } @@ -514,10 +514,10 @@ impl BaseIter for @mut DList { } if !nobe.linked || (!((nobe.prev.is_some() - || managed::mut_ptr_eq(self.hd.expect(~"headless dlist?"), + || managed::mut_ptr_eq(self.hd.expect("headless dlist?"), nobe)) && (nobe.next.is_some() - || managed::mut_ptr_eq(self.tl.expect(~"tailless dlist?"), + || managed::mut_ptr_eq(self.tl.expect("tailless dlist?"), nobe)))) { fail!("Removing a dlist node during iteration is forbidden!") } diff --git a/src/libstd/getopts.rs b/src/libstd/getopts.rs index d0b298deb8984..6a9a60baae6a2 100644 --- a/src/libstd/getopts.rs +++ b/src/libstd/getopts.rs @@ -587,7 +587,7 @@ pub mod groups { */ pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str { - let desc_sep = ~"\n" + str::repeat(~" ", 24); + let desc_sep = ~"\n" + str::repeat(" ", 24); let rows = vec::map(opts, |optref| { let OptGroup{short_name: short_name, @@ -597,7 +597,7 @@ pub mod groups { hasarg: hasarg, _} = copy *optref; - let mut row = str::repeat(~" ", 4); + let mut row = str::repeat(" ", 4); // short option row += match short_name.len() { @@ -623,7 +623,7 @@ pub mod groups { // here we just need to indent the start of the description let rowlen = row.len(); row += if rowlen < 24 { - str::repeat(~" ", 24 - rowlen) + str::repeat(" ", 24 - rowlen) } else { copy desc_sep }; @@ -650,7 +650,7 @@ pub mod groups { return str::to_owned(brief) + ~"\n\nOptions:\n" + - str::connect(rows, ~"\n") + + str::connect(rows, "\n") + ~"\n\n"; } } // end groups module diff --git a/src/libstd/json.rs b/src/libstd/json.rs index 270cf675c878a..44e965b5c4320 100644 --- a/src/libstd/json.rs +++ b/src/libstd/json.rs @@ -524,9 +524,9 @@ priv impl Parser { if self.eof() { return self.error(~"EOF while parsing value"); } match self.ch { - 'n' => self.parse_ident(~"ull", Null), - 't' => self.parse_ident(~"rue", Boolean(true)), - 'f' => self.parse_ident(~"alse", Boolean(false)), + 'n' => self.parse_ident("ull", Null), + 't' => self.parse_ident("rue", Boolean(true)), + 'f' => self.parse_ident("alse", Boolean(false)), '0' .. '9' | '-' => self.parse_number(), '"' => match self.parse_str() { diff --git a/src/libstd/md4.rs b/src/libstd/md4.rs index 19cd418915e74..da81f730eda82 100644 --- a/src/libstd/md4.rs +++ b/src/libstd/md4.rs @@ -26,7 +26,7 @@ pub fn md4(msg: &[u8]) -> Quad { let orig_len: u64 = (msg.len() * 8u) as u64; // pad message - let mut msg = vec::append(vec::to_owned(msg), ~[0x80u8]); + let mut msg = vec::append(vec::to_owned(msg), [0x80u8]); let mut bitlen = orig_len + 8u64; while (bitlen + 64u64) % 512u64 > 0u64 { msg.push(0u8); diff --git a/src/libstd/net_url.rs b/src/libstd/net_url.rs index 19e0dc1441275..fb57c717be960 100644 --- a/src/libstd/net_url.rs +++ b/src/libstd/net_url.rs @@ -350,7 +350,7 @@ pub fn query_to_str(query: &Query) -> ~str { } } } - return str::connect(strvec, ~"&"); + return str::connect(strvec, "&"); } // returns the scheme and the rest of the url, or a parsing error @@ -390,7 +390,7 @@ enum Input { // returns userinfo, host, port, and unparsed part, or an error fn get_authority(rawurl: &str) -> Result<(Option, ~str, Option<~str>, ~str), ~str> { - if !str::starts_with(rawurl, ~"//") { + if !str::starts_with(rawurl, "//") { // there is no authority. return Ok((None, ~"", None, rawurl.to_str())); } @@ -575,7 +575,7 @@ fn get_path(rawurl: &str, authority: bool) -> } if authority { - if end != 0 && !str::starts_with(rawurl, ~"/") { + if end != 0 && !str::starts_with(rawurl, "/") { return Err(~"Non-empty path must begin with\ '/' in presence of authority."); } @@ -588,8 +588,8 @@ fn get_path(rawurl: &str, authority: bool) -> // returns the parsed query and the fragment, if present fn get_query_fragment(rawurl: &str) -> Result<(Query, Option<~str>), ~str> { - if !str::starts_with(rawurl, ~"?") { - if str::starts_with(rawurl, ~"#") { + if !str::starts_with(rawurl, "?") { + if str::starts_with(rawurl, "#") { let f = decode_component(str::slice(rawurl, 1, str::len(rawurl)).to_owned()); diff --git a/src/libstd/rope.rs b/src/libstd/rope.rs index 925f79b66c9b2..04444789f827a 100644 --- a/src/libstd/rope.rs +++ b/src/libstd/rope.rs @@ -106,7 +106,7 @@ Section: Adding things to a rope * * this function executes in near-constant time */ pub fn append_char(rope: Rope, char: char) -> Rope { - return append_str(rope, @str::from_chars(~[char])); + return append_str(rope, @str::from_chars([char])); } /** @@ -127,7 +127,7 @@ pub fn append_str(rope: Rope, str: @~str) -> Rope { * * this function executes in near-constant time */ pub fn prepend_char(rope: Rope, char: char) -> Rope { - return prepend_str(rope, @str::from_chars(~[char])); + return prepend_str(rope, @str::from_chars([char])); } /** diff --git a/src/libstd/sha1.rs b/src/libstd/sha1.rs index bb3be8a55ea3b..d7051d734698f 100644 --- a/src/libstd/sha1.rs +++ b/src/libstd/sha1.rs @@ -177,7 +177,7 @@ pub fn sha1() -> @Sha1 { let b = (hpart >> 16u32 & 0xFFu32) as u8; let c = (hpart >> 8u32 & 0xFFu32) as u8; let d = (hpart & 0xFFu32) as u8; - rs = vec::append(copy rs, ~[a, b, c, d]); + rs = vec::append(copy rs, [a, b, c, d]); } return rs; } diff --git a/src/libstd/term.rs b/src/libstd/term.rs index 236c7f668c2e0..fcac70622104d 100644 --- a/src/libstd/term.rs +++ b/src/libstd/term.rs @@ -35,19 +35,19 @@ pub static color_bright_magenta: u8 = 13u8; pub static color_bright_cyan: u8 = 14u8; pub static color_bright_white: u8 = 15u8; -pub fn esc(writer: @io::Writer) { writer.write(~[0x1bu8, '[' as u8]); } +pub fn esc(writer: @io::Writer) { writer.write([0x1bu8, '[' as u8]); } /// Reset the foreground and background colors to default pub fn reset(writer: @io::Writer) { esc(writer); - writer.write(~['0' as u8, 'm' as u8]); + writer.write(['0' as u8, 'm' as u8]); } /// Returns true if the terminal supports color pub fn color_supported() -> bool { let supported_terms = ~[~"xterm-color", ~"xterm", ~"screen-bce", ~"xterm-256color"]; - return match os::getenv(~"TERM") { + return match os::getenv("TERM") { option::Some(ref env) => { for supported_terms.each |term| { if *term == *env { return true; } @@ -62,8 +62,8 @@ pub fn set_color(writer: @io::Writer, first_char: u8, color: u8) { assert!((color < 16u8)); esc(writer); let mut color = color; - if color >= 8u8 { writer.write(~['1' as u8, ';' as u8]); color -= 8u8; } - writer.write(~[first_char, ('0' as u8) + color, 'm' as u8]); + if color >= 8u8 { writer.write(['1' as u8, ';' as u8]); color -= 8u8; } + writer.write([first_char, ('0' as u8) + color, 'm' as u8]); } /// Set the foreground color diff --git a/src/libstd/test.rs b/src/libstd/test.rs index e9fd4e9a2b837..4046ce83c9dcf 100644 --- a/src/libstd/test.rs +++ b/src/libstd/test.rs @@ -131,12 +131,12 @@ type OptRes = Either; // Parses command line arguments into test options pub fn parse_opts(args: &[~str]) -> OptRes { let args_ = vec::tail(args); - let opts = ~[getopts::optflag(~"ignored"), - getopts::optflag(~"test"), - getopts::optflag(~"bench"), - getopts::optopt(~"save"), - getopts::optopt(~"diff"), - getopts::optopt(~"logfile")]; + let opts = ~[getopts::optflag("ignored"), + getopts::optflag("test"), + getopts::optflag("bench"), + getopts::optopt("save"), + getopts::optopt("diff"), + getopts::optopt("logfile")]; let matches = match getopts::getopts(args_, opts) { Ok(m) => m, @@ -148,19 +148,19 @@ pub fn parse_opts(args: &[~str]) -> OptRes { option::Some(copy (matches).free[0]) } else { option::None }; - let run_ignored = getopts::opt_present(&matches, ~"ignored"); + let run_ignored = getopts::opt_present(&matches, "ignored"); - let logfile = getopts::opt_maybe_str(&matches, ~"logfile"); + let logfile = getopts::opt_maybe_str(&matches, "logfile"); let logfile = logfile.map(|s| Path(*s)); - let run_benchmarks = getopts::opt_present(&matches, ~"bench"); + let run_benchmarks = getopts::opt_present(&matches, "bench"); let run_tests = ! run_benchmarks || - getopts::opt_present(&matches, ~"test"); + getopts::opt_present(&matches, "test"); - let save_results = getopts::opt_maybe_str(&matches, ~"save"); + let save_results = getopts::opt_maybe_str(&matches, "save"); let save_results = save_results.map(|s| Path(*s)); - let compare_results = getopts::opt_maybe_str(&matches, ~"diff"); + let compare_results = getopts::opt_maybe_str(&matches, "diff"); let compare_results = compare_results.map(|s| Path(*s)); let test_opts = TestOpts { @@ -220,18 +220,18 @@ pub fn run_tests_console(opts: &TestOpts, TrOk => { st.passed += 1; write_ok(st.out, st.use_color); - st.out.write_line(~""); + st.out.write_line(""); } TrFailed => { st.failed += 1; write_failed(st.out, st.use_color); - st.out.write_line(~""); + st.out.write_line(""); st.failures.push(test); } TrIgnored => { st.ignored += 1; write_ignored(st.out, st.use_color); - st.out.write_line(~""); + st.out.write_line(""); } TrBench(bs) => { st.benchmarked += 1u; @@ -246,8 +246,8 @@ pub fn run_tests_console(opts: &TestOpts, let log_out = match opts.logfile { Some(ref path) => match io::file_writer(path, - ~[io::Create, - io::Truncate]) { + [io::Create, + io::Truncate]) { result::Ok(w) => Some(w), result::Err(ref s) => { fail!("can't open output file: %s", *s) @@ -318,19 +318,19 @@ pub fn run_tests_console(opts: &TestOpts, } fn write_ok(out: @io::Writer, use_color: bool) { - write_pretty(out, ~"ok", term::color_green, use_color); + write_pretty(out, "ok", term::color_green, use_color); } fn write_failed(out: @io::Writer, use_color: bool) { - write_pretty(out, ~"FAILED", term::color_red, use_color); + write_pretty(out, "FAILED", term::color_red, use_color); } fn write_ignored(out: @io::Writer, use_color: bool) { - write_pretty(out, ~"ignored", term::color_yellow, use_color); + write_pretty(out, "ignored", term::color_yellow, use_color); } fn write_bench(out: @io::Writer, use_color: bool) { - write_pretty(out, ~"bench", term::color_cyan, use_color); + write_pretty(out, "bench", term::color_cyan, use_color); } fn write_pretty(out: @io::Writer, @@ -348,7 +348,7 @@ pub fn run_tests_console(opts: &TestOpts, } fn print_failures(st: &ConsoleTestState) { - st.out.write_line(~"\nfailures:"); + st.out.write_line("\nfailures:"); let mut failures = ~[]; for uint::range(0, vec::uniq_len(&const st.failures)) |i| { let name = copy st.failures[i].name; diff --git a/src/libstd/time.rs b/src/libstd/time.rs index 9e6a45137a4a5..565ce2d0dd3b3 100644 --- a/src/libstd/time.rs +++ b/src/libstd/time.rs @@ -199,7 +199,7 @@ pub impl Tm { * Return a string of the current time in the form * "Thu Jan 1 00:00:00 1970". */ - fn ctime(&self) -> ~str { self.strftime(~"%c") } + fn ctime(&self) -> ~str { self.strftime("%c") } /// Formats the time according to the format string. fn strftime(&self, format: &str) -> ~str { @@ -214,9 +214,9 @@ pub impl Tm { */ fn rfc822(&self) -> ~str { if self.tm_gmtoff == 0_i32 { - self.strftime(~"%a, %d %b %Y %T GMT") + self.strftime("%a, %d %b %Y %T GMT") } else { - self.strftime(~"%a, %d %b %Y %T %Z") + self.strftime("%a, %d %b %Y %T %Z") } } @@ -227,7 +227,7 @@ pub impl Tm { * utc: "Thu, 22 Mar 2012 14:53:18 -0000" */ fn rfc822z(&self) -> ~str { - self.strftime(~"%a, %d %b %Y %T %z") + self.strftime("%a, %d %b %Y %T %z") } /** @@ -238,9 +238,9 @@ pub impl Tm { */ fn rfc3339(&self) -> ~str { if self.tm_gmtoff == 0_i32 { - self.strftime(~"%Y-%m-%dT%H:%M:%SZ") + self.strftime("%Y-%m-%dT%H:%M:%SZ") } else { - let s = self.strftime(~"%Y-%m-%dT%H:%M:%S"); + let s = self.strftime("%Y-%m-%dT%H:%M:%S"); let sign = if self.tm_gmtoff > 0_i32 { '+' } else { '-' }; let mut m = i32::abs(self.tm_gmtoff) / 60_i32; let h = m / 60_i32; @@ -326,7 +326,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result { fn parse_type(s: &str, pos: uint, ch: char, tm: &mut Tm) -> Result { match ch { - 'A' => match match_strs(s, pos, ~[ + 'A' => match match_strs(s, pos, [ (~"Sunday", 0_i32), (~"Monday", 1_i32), (~"Tuesday", 2_i32), @@ -338,7 +338,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result { Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) } None => Err(~"Invalid day") }, - 'a' => match match_strs(s, pos, ~[ + 'a' => match match_strs(s, pos, [ (~"Sun", 0_i32), (~"Mon", 1_i32), (~"Tue", 2_i32), @@ -350,7 +350,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result { Some(item) => { let (v, pos) = item; tm.tm_wday = v; Ok(pos) } None => Err(~"Invalid day") }, - 'B' => match match_strs(s, pos, ~[ + 'B' => match match_strs(s, pos, [ (~"January", 0_i32), (~"February", 1_i32), (~"March", 2_i32), @@ -367,7 +367,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result { Some(item) => { let (v, pos) = item; tm.tm_mon = v; Ok(pos) } None => Err(~"Invalid month") }, - 'b' | 'h' => match match_strs(s, pos, ~[ + 'b' | 'h' => match match_strs(s, pos, [ (~"Jan", 0_i32), (~"Feb", 1_i32), (~"Mar", 2_i32), @@ -488,13 +488,13 @@ priv fn do_strptime(s: &str, format: &str) -> Result { } 'n' => parse_char(s, pos, '\n'), 'P' => match match_strs(s, pos, - ~[(~"am", 0_i32), (~"pm", 12_i32)]) { + [(~"am", 0_i32), (~"pm", 12_i32)]) { Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) } None => Err(~"Invalid hour") }, 'p' => match match_strs(s, pos, - ~[(~"AM", 0_i32), (~"PM", 12_i32)]) { + [(~"AM", 0_i32), (~"PM", 12_i32)]) { Some(item) => { let (v, pos) = item; tm.tm_hour += v; Ok(pos) } None => Err(~"Invalid hour") @@ -579,7 +579,7 @@ priv fn do_strptime(s: &str, format: &str) -> Result { } } 'Z' => { - if match_str(s, pos, ~"UTC") || match_str(s, pos, ~"GMT") { + if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") { tm.tm_gmtoff = 0_i32; tm.tm_zone = ~"UTC"; Ok(pos + 3u) diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index e9f15c0a8f5ce..5b08f59b35c2e 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -107,7 +107,7 @@ pub struct Ctx { pub type vt = visit::vt<@mut Ctx>; pub fn extend(cx: @mut Ctx, elt: ident) -> @path { - @(vec::append(copy cx.path, ~[path_name(elt)])) + @(vec::append(copy cx.path, [path_name(elt)])) } pub fn mk_ast_map_visitor() -> vt { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index eaacb054ca1ae..e209fd14b5e02 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -21,7 +21,7 @@ use core::to_bytes; pub fn path_name_i(idents: &[ident], intr: @token::ident_interner) -> ~str { // FIXME: Bad copies (#2543 -- same for everything else that says "bad") - str::connect(idents.map(|i| copy *intr.get(*i)), ~"::") + str::connect(idents.map(|i| copy *intr.get(*i)), "::") } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index aebe5bbfc748a..981df1156df59 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -291,7 +291,7 @@ pub fn remove_meta_items_by_name(items: ~[@ast::meta_item], name: &str) -> * linkage */ pub fn find_linkage_metas(attrs: &[ast::attribute]) -> ~[@ast::meta_item] { - do find_attrs_by_name(attrs, ~"link").flat_map |attr| { + do find_attrs_by_name(attrs, "link").flat_map |attr| { match attr.node.value.node { ast::meta_list(_, ref items) => /* FIXME (#2543) */ copy *items, _ => ~[] @@ -314,9 +314,9 @@ pub fn find_inline_attr(attrs: &[ast::attribute]) -> inline_attr { match attr.node.value.node { ast::meta_word(@~"inline") => ia_hint, ast::meta_list(@~"inline", ref items) => { - if !find_meta_items_by_name(*items, ~"always").is_empty() { + if !find_meta_items_by_name(*items, "always").is_empty() { ia_always - } else if !find_meta_items_by_name(*items, ~"never").is_empty() { + } else if !find_meta_items_by_name(*items, "never").is_empty() { ia_never } else { ia_hint diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 993fa612a2709..21e2ad82b1493 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -218,7 +218,7 @@ pub fn emit(cmsp: Option<(@codemap::CodeMap, span)>, msg: &str, lvl: level) { print_macro_backtrace(cm, sp); } None => { - print_diagnostic(~"", lvl, msg); + print_diagnostic("", lvl, msg); } } } @@ -296,7 +296,7 @@ fn print_macro_backtrace(cm: @codemap::CodeMap, sp: span) { print_diagnostic(*ss, note, fmt!("in expansion of %s!", ei.callee.name)); let ss = cm.span_to_str(ei.call_site); - print_diagnostic(ss, note, ~"expansion site"); + print_diagnostic(ss, note, "expansion site"); print_macro_backtrace(cm, ei.call_site); } } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index a97c69ba4ffec..2a7f8c8865b81 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -250,7 +250,7 @@ pub fn mk_ctxt(parse_sess: @mut parse::ParseSess, cfg: ast::crate_cfg) fn call_site(&self) -> span { match *self.backtrace { Some(@ExpandedFrom(CallInfo {call_site: cs, _})) => cs, - None => self.bug(~"missing top span") + None => self.bug("missing top span") } } fn print_backtrace(&self) { } @@ -276,7 +276,7 @@ pub fn mk_ctxt(parse_sess: @mut parse::ParseSess, cfg: ast::crate_cfg) })) => { *self.backtrace = prev } - _ => self.bug(~"tried to pop without a push") + _ => self.bug("tried to pop without a push") } } fn span_fatal(&self, sp: span, msg: &str) -> ! { diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index 96e5e4143226c..da32cc1162513 100644 --- a/src/libsyntax/ext/concat_idents.rs +++ b/src/libsyntax/ext/concat_idents.rs @@ -21,15 +21,13 @@ pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) if i & 1 == 1 { match *e { ast::tt_tok(_, token::COMMA) => (), - _ => cx.span_fatal(sp, ~"concat_idents! \ - expecting comma.") + _ => cx.span_fatal(sp, "concat_idents! expecting comma.") } } else { match *e { ast::tt_tok(_, token::IDENT(ident,_)) => res_str += cx.str_of(ident), - _ => cx.span_fatal(sp, ~"concat_idents! \ - requires ident args.") + _ => cx.span_fatal(sp, "concat_idents! requires ident args.") } } } diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 2e2f382a7687b..fe20511204632 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -291,7 +291,7 @@ fn expand_deriving_decodable_struct_method( unnamed_field => { cx.span_unimpl( span, - ~"unnamed fields with `deriving(Decodable)`" + "unnamed fields with `deriving(Decodable)`" ); } } diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 8a1c3933f5127..b1df8405d7627 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -321,7 +321,7 @@ fn expand_deriving_encodable_struct_method( unnamed_field => { cx.span_unimpl( span, - ~"unnamed fields with `deriving(Encodable)`" + "unnamed fields with `deriving(Encodable)`" ); } } diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index fc14e3c3f732b..2fc9dadfe2c1b 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -539,8 +539,8 @@ impl<'self> MethodDef<'self> { (opt_id, field, other_fields) } } - [] => { cx.span_bug(span, ~"No self arguments to non-static \ - method in generic `deriving`") } + [] => { cx.span_bug(span, "No self arguments to non-static \ + method in generic `deriving`") } }; // body of the inner most destructuring match @@ -658,8 +658,8 @@ impl<'self> MethodDef<'self> { // we've matched against all arguments, so make the final // expression at the bottom of the match tree if matches_so_far.len() == 0 { - cx.span_bug(span, ~"no self match on an enum in generic \ - `deriving`"); + cx.span_bug(span, "no self match on an enum in generic \ + `deriving`"); } // we currently have a vec of vecs, where each // subvec is the fields of one of the arguments, @@ -718,8 +718,8 @@ impl<'self> MethodDef<'self> { // make a matching-variant match, and a _ match. let index = match matching { Some(i) => i, - None => cx.span_bug(span, ~"Non-matching variants when required to \ - be matching in generic `deriving`") + None => cx.span_bug(span, "Non-matching variants when required to \ + be matching in generic `deriving`") }; // matching-variant match diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 78cd5cdb423d9..6f4429af12d75 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -67,11 +67,11 @@ pub fn expand_meta_deriving(cx: @ext_ctxt, match mitem.node { meta_name_value(_, ref l) => { - cx.span_err(l.span, ~"unexpected value in `deriving`"); + cx.span_err(l.span, "unexpected value in `deriving`"); in_items } meta_word(_) | meta_list(_, []) => { - cx.span_warn(mitem.span, ~"empty trait list in `deriving`"); + cx.span_warn(mitem.span, "empty trait list in `deriving`"); in_items } meta_list(_, ref titems) => { diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs index 13cb09e970df6..f155cb3790faa 100644 --- a/src/libsyntax/ext/deriving/to_str.rs +++ b/src/libsyntax/ext/deriving/to_str.rs @@ -49,6 +49,6 @@ fn to_str_substructure(cx: @ext_ctxt, span: span, substr: &Substructure) -> @exp cx.ident_of("log_str")], ~[self_addr]) } - _ => cx.span_bug(span, ~"Invalid number of arguments in `deriving(ToStr)`") + _ => cx.span_bug(span, "Invalid number of arguments in `deriving(ToStr)`") } } diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index 8fd372e479286..5fc3aeb789c10 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -167,8 +167,8 @@ pub impl Ty { Literal(ref p) => { p.to_path(cx, span, self_ty, self_generics) } - Ptr(*) => { cx.span_bug(span, ~"Pointer in a path in generic `deriving`") } - Tuple(*) => { cx.span_bug(span, ~"Tuple in a path in generic `deriving`") } + Ptr(*) => { cx.span_bug(span, "Pointer in a path in generic `deriving`") } + Tuple(*) => { cx.span_bug(span, "Tuple in a path in generic `deriving`") } } } } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index db95cb65b7660..ff0cf6f28ad8f 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -234,7 +234,7 @@ pub fn expand_item_mac(extsbox: @mut SyntaxEnv, item_mac(codemap::spanned { node: mac_invoc_tt(pth, ref tts), _}) => { (pth, copy *tts) } - _ => cx.span_bug(it.span, ~"invalid item macro invocation") + _ => cx.span_bug(it.span, "invalid item macro invocation") }; let extname = cx.parse_sess().interner.get(pth.idents[0]); @@ -377,8 +377,7 @@ pub fn expand_block(extsbox: @mut SyntaxEnv, // see note below about treatment of exts table with_exts_frame!(extsbox,orig(blk,sp,fld)) }, - _ => cx.span_bug(sp, - ~"expected ScopeMacros binding for \" block\"") + _ => cx.span_bug(sp, "expected ScopeMacros binding for \" block\"") } } @@ -628,7 +627,7 @@ pub fn expand_crate(parse_sess: @mut parse::ParseSess, attrs, parse_sess) { Some(item) => item, - None => cx.bug(~"expected core macros to parse correctly") + None => cx.bug("expected core macros to parse correctly") }; // This is run for its side-effects on the expander env, // as it registers all the core macros as expanders. diff --git a/src/libsyntax/ext/fmt.rs b/src/libsyntax/ext/fmt.rs index 26b3178a91110..24046faa6849d 100644 --- a/src/libsyntax/ext/fmt.rs +++ b/src/libsyntax/ext/fmt.rs @@ -88,7 +88,7 @@ fn pieces_to_expr(cx: @ext_ctxt, sp: span, let count_is_args = ~[count_lit]; return mk_call_global(cx, sp, count_is_path, count_is_args); } - _ => cx.span_unimpl(sp, ~"unimplemented fmt! conversion") + _ => cx.span_unimpl(sp, "unimplemented fmt! conversion") } } fn make_ty(cx: @ext_ctxt, sp: span, t: Ty) -> @ast::expr { diff --git a/src/libsyntax/ext/pipes/liveness.rs b/src/libsyntax/ext/pipes/liveness.rs index 8799bd064f658..104e5f94d1770 100644 --- a/src/libsyntax/ext/pipes/liveness.rs +++ b/src/libsyntax/ext/pipes/liveness.rs @@ -85,7 +85,7 @@ pub fn analyze(proto: @mut protocol_, _cx: @ext_ctxt) { } if self_live.len() > 0 { - let states = str::connect(self_live.map(|s| copy s.name), ~" "); + let states = str::connect(self_live.map(|s| copy s.name), " "); debug!("protocol %s is unbounded due to loops involving: %s", copy proto.name, states); diff --git a/src/libsyntax/ext/pipes/parse_proto.rs b/src/libsyntax/ext/pipes/parse_proto.rs index 5c99ddc9040ab..28c8c9a704d90 100644 --- a/src/libsyntax/ext/pipes/parse_proto.rs +++ b/src/libsyntax/ext/pipes/parse_proto.rs @@ -114,7 +114,7 @@ impl proto_parser for parser::Parser { self.bump(); None } - _ => self.fatal(~"invalid next state") + _ => self.fatal("invalid next state") }; state.add_message(mname, *self.span, args, next); diff --git a/src/libsyntax/ext/pipes/pipec.rs b/src/libsyntax/ext/pipes/pipec.rs index b537ef87d543f..8a9c714e7e939 100644 --- a/src/libsyntax/ext/pipes/pipec.rs +++ b/src/libsyntax/ext/pipes/pipec.rs @@ -96,7 +96,7 @@ impl gen_send for message { name, str::connect(vec::append_one( arg_names.map(|x| cx.str_of(*x)), - ~"s"), ~", ")); + ~"s"), ", ")); if !try { body += fmt!("::core::pipes::send(pipe, message);\n"); @@ -148,7 +148,7 @@ impl gen_send for message { } else { ~"(" + str::connect(arg_names.map(|x| copy *x), - ~", ") + ~")" + ", ") + ~")" }; let mut body = ~"{ "; diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index fc673c4422f1d..2134c2ba19bff 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -86,7 +86,7 @@ pub mod rt { impl<'self> ToSource for &'self [@ast::item] { fn to_source(&self, cx: @ext_ctxt) -> ~str { - str::connect(self.map(|i| i.to_source(cx)), ~"\n\n") + str::connect(self.map(|i| i.to_source(cx)), "\n\n") } } @@ -98,7 +98,7 @@ pub mod rt { impl<'self> ToSource for &'self [@ast::Ty] { fn to_source(&self, cx: @ext_ctxt) -> ~str { - str::connect(self.map(|i| i.to_source(cx)), ~", ") + str::connect(self.map(|i| i.to_source(cx)), ", ") } } @@ -421,7 +421,7 @@ fn id_ext(cx: @ext_ctxt, str: &str) -> ast::ident { // Lift an ident to the expr that evaluates to that ident. fn mk_ident(cx: @ext_ctxt, sp: span, ident: ast::ident) -> @ast::expr { - let e_str = build::mk_uniq_str(cx, sp, cx.str_of(ident)); + let e_str = build::mk_base_str(cx, sp, cx.str_of(ident)); build::mk_method_call(cx, sp, build::mk_path(cx, sp, ids_ext(cx, ~[~"ext_cx"])), id_ext(cx, "ident_of"), diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index ab22b3152f477..c0d9b3f06af56 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -67,7 +67,7 @@ pub fn expand_mod(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) base::check_zero_tts(cx, sp, tts, "module_path!"); base::MRExpr(mk_base_str(cx, sp, str::connect(cx.mod_path().map( - |x| cx.str_of(*x)), ~"::"))) + |x| cx.str_of(*x)), "::"))) } // include! : parse the given file as an expr diff --git a/src/libsyntax/ext/trace_macros.rs b/src/libsyntax/ext/trace_macros.rs index 1bb4080814226..0ecb3b2a3f47f 100644 --- a/src/libsyntax/ext/trace_macros.rs +++ b/src/libsyntax/ext/trace_macros.rs @@ -39,7 +39,7 @@ pub fn expand_trace_macros(cx: @ext_ctxt, } else if rust_parser.is_keyword("false") { cx.set_trace_macros(false); } else { - cx.span_fatal(sp, ~"trace_macros! only accepts `true` or `false`") + cx.span_fatal(sp, "trace_macros! only accepts `true` or `false`") } rust_parser.bump(); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index aa211973f1c52..a34045a883eec 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -371,7 +371,7 @@ pub fn parse( *sess.interner.get(bind)) } _ => fail!() - } }), ~" or "); + } }), " or "); return error(sp, fmt!( "Local ambiguity: multiple parsing options: \ built-in NTs %s or %u other options.", @@ -413,7 +413,7 @@ pub fn parse_nt(p: &Parser, name: &str) -> nonterminal { match name { "item" => match p.parse_item(~[]) { Some(i) => token::nt_item(i), - None => p.fatal(~"expected an item keyword") + None => p.fatal("expected an item keyword") }, "block" => token::nt_block(p.parse_block()), "stmt" => token::nt_stmt(p.parse_stmt(~[])), diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index be6cc7a846ad3..d34eca342e93e 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -64,12 +64,12 @@ pub fn add_new_extension(cx: @ext_ctxt, // Extract the arguments: let lhses = match *argument_map.get(&lhs_nm) { @matched_seq(ref s, _) => /* FIXME (#2543) */ @copy *s, - _ => cx.span_bug(sp, ~"wrong-structured lhs") + _ => cx.span_bug(sp, "wrong-structured lhs") }; let rhses = match *argument_map.get(&rhs_nm) { @matched_seq(ref s, _) => /* FIXME (#2543) */ @copy *s, - _ => cx.span_bug(sp, ~"wrong-structured rhs") + _ => cx.span_bug(sp, "wrong-structured rhs") }; // Given `lhses` and `rhses`, this is the new macro we create @@ -114,10 +114,10 @@ pub fn add_new_extension(cx: @ext_ctxt, (*tts).slice(1u,(*tts).len()-1u).to_owned() } _ => cx.span_fatal( - sp, ~"macro rhs must be delimited") + sp, "macro rhs must be delimited") } }, - _ => cx.span_bug(sp, ~"bad thing in rhs") + _ => cx.span_bug(sp, "bad thing in rhs") }; // rhs has holes ( `$id` and `$(...)` that need filled) let trncbr = new_tt_reader(s_d, itr, Some(named_matches), @@ -139,7 +139,7 @@ pub fn add_new_extension(cx: @ext_ctxt, error(sp, ref msg) => cx.span_fatal(sp, (*msg)) } } - _ => cx.bug(~"non-matcher found in parsed lhses") + _ => cx.bug("non-matcher found in parsed lhses") } } cx.span_fatal(best_fail_spot, best_fail_msg); diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 438efb2326c7a..d806801b7d172 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -234,9 +234,9 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { lis_unconstrained => { r.sp_diag.span_fatal( sp, /* blame macro writer */ - ~"attempted to repeat an expression \ - containing no syntax \ - variables matched as repeating at this depth"); + "attempted to repeat an expression \ + containing no syntax \ + variables matched as repeating at this depth"); } lis_contradiction(ref msg) => { /* FIXME #2887 blame macro invoker instead*/ @@ -247,8 +247,8 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { if !zerok { r.sp_diag.span_fatal(sp, /* FIXME #2887 blame invoker */ - ~"this must repeat at least \ - once"); + "this must repeat at least \ + once"); } r.stack.idx += 1u; diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index 93584b00d39e6..d947fa43ca7e8 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -51,7 +51,7 @@ impl parser_attr for Parser { self.span.hi ); if attr.node.style != ast::attr_outer { - self.fatal(~"expected outer comment"); + self.fatal("expected outer comment"); } attrs += ~[attr]; self.bump(); diff --git a/src/libsyntax/parse/comments.rs b/src/libsyntax/parse/comments.rs index 89873b2793566..da7ad6ffeffcc 100644 --- a/src/libsyntax/parse/comments.rs +++ b/src/libsyntax/parse/comments.rs @@ -33,15 +33,15 @@ pub struct cmnt { } pub fn is_doc_comment(s: &str) -> bool { - (s.starts_with(~"///") && !is_line_non_doc_comment(s)) || - s.starts_with(~"//!") || - (s.starts_with(~"/**") && !is_block_non_doc_comment(s)) || - s.starts_with(~"/*!") + (s.starts_with("///") && !is_line_non_doc_comment(s)) || + s.starts_with("//!") || + (s.starts_with("/**") && !is_block_non_doc_comment(s)) || + s.starts_with("/*!") } pub fn doc_comment_style(comment: &str) -> ast::attr_style { assert!(is_doc_comment(comment)); - if comment.starts_with(~"//!") || comment.starts_with(~"/*!") { + if comment.starts_with("//!") || comment.starts_with("/*!") { ast::attr_inner } else { ast::attr_outer @@ -92,14 +92,14 @@ pub fn strip_doc_comment_decoration(comment: &str) -> ~str { }; } - if comment.starts_with(~"//") { + if comment.starts_with("//") { // FIXME #5475: // return comment.slice(3u, comment.len()).trim().to_owned(); let r = comment.slice(3u, comment.len()); return r.trim().to_owned(); } - if comment.starts_with(~"/*") { + if comment.starts_with("/*") { let mut lines = ~[]; for str::each_line_any(comment.slice(3u, comment.len() - 2u)) |line| { lines.push(line.to_owned()) @@ -108,7 +108,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> ~str { let lines = block_trim(lines, ~"\t ", None); let lines = block_trim(lines, ~"*", Some(1u)); let lines = block_trim(lines, ~"\t ", None); - return str::connect(lines, ~"\n"); + return str::connect(lines, "\n"); } fail!("not a doc-comment: %s", comment); diff --git a/src/libsyntax/parse/common.rs b/src/libsyntax/parse/common.rs index 6595343654f11..6e85b814b31e8 100644 --- a/src/libsyntax/parse/common.rs +++ b/src/libsyntax/parse/common.rs @@ -104,9 +104,7 @@ pub impl Parser { i } token::INTERPOLATED(token::nt_ident(*)) => { - self.bug( - ~"ident interpolation not converted to real token" - ); + self.bug("ident interpolation not converted to real token"); } _ => { self.fatal( diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index fddeea9302414..2de27285ce2b1 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -354,7 +354,7 @@ pub impl Parser { fn get_lifetime(&self, tok: &token::Token) -> ast::ident { match *tok { token::LIFETIME(ref ident) => copy *ident, - _ => self.bug(~"not a lifetime"), + _ => self.bug("not a lifetime"), } } @@ -434,7 +434,7 @@ pub impl Parser { }); fn parse_onceness(this: &Parser) -> Onceness { - if this.eat_keyword(~"once") { + if this.eat_keyword("once") { Once } else { Many @@ -1354,7 +1354,7 @@ pub impl Parser { self.bump(); match *self.token { token::LPAREN | token::LBRACE => {} - _ => self.fatal(~"expected open delimiter") + _ => self.fatal("expected open delimiter") }; let ket = token::flip_delimiter(&*self.token); @@ -1520,7 +1520,7 @@ pub impl Parser { self.bump(); (Some(sep), zerok) } else { - self.fatal(~"expected `*` or `+`"); + self.fatal("expected `*` or `+`"); } } } @@ -1587,7 +1587,7 @@ pub impl Parser { match *self.token { token::EOF => { - self.fatal(~"file ended with unbalanced delimiters"); + self.fatal("file ended with unbalanced delimiters"); } token::LPAREN | token::LBRACE | token::LBRACKET => { let close_delim = token::flip_delimiter(&*self.token); @@ -1602,7 +1602,7 @@ pub impl Parser { |p| p.parse_token_tree() ), // the close delimiter: - ~[parse_any_tt_tok(self)] + [parse_any_tt_tok(self)] ) ) ) @@ -1635,7 +1635,7 @@ pub impl Parser { token::flip_delimiter(self.token) ) } - _ => self.fatal(~"expected open delimiter") + _ => self.fatal("expected open delimiter") } } @@ -1678,7 +1678,7 @@ pub impl Parser { token::RPAREN ); if ms.len() == 0u { - self.fatal(~"repetition body must be nonempty"); + self.fatal("repetition body must be nonempty"); } let (sep, zerok) = self.parse_sep_and_zerok(); match_seq(ms, sep, zerok, name_idx_lo, *name_idx) @@ -1996,7 +1996,7 @@ pub impl Parser { let block = self.parse_lambda_block_expr(); let last_arg = self.mk_expr(block.span.lo, block.span.hi, ctor(block)); - let args = vec::append(args, ~[last_arg]); + let args = vec::append(args, [last_arg]); self.mk_expr(lo.lo, block.span.hi, expr_call(f, args, sugar)) } expr_method_call(f, i, /*bad*/ copy tps, @@ -2004,7 +2004,7 @@ pub impl Parser { let block = self.parse_lambda_block_expr(); let last_arg = self.mk_expr(block.span.lo, block.span.hi, ctor(block)); - let args = vec::append(args, ~[last_arg]); + let args = vec::append(args, [last_arg]); self.mk_expr(lo.lo, block.span.hi, expr_method_call(f, i, tps, args, sugar)) } @@ -2575,7 +2575,7 @@ pub impl Parser { // XXX: Remove after snapshot. } if !is_plain_ident(&*self.token) { - self.fatal(~"expected ident"); + self.fatal("expected ident"); } let name = self.parse_ident(); self.expect(&token::COLON); @@ -2597,7 +2597,7 @@ pub impl Parser { // If we have attributes then we should have an item if !current_attrs.is_empty() { p.span_err(*p.last_span, - ~"expected item after attributes"); + "expected item after attributes"); } } @@ -2664,7 +2664,7 @@ pub impl Parser { "view items must be declared at the top of the block"); } iovi_foreign_item(_) => { - self.fatal(~"foreign items are not allowed here"); + self.fatal("foreign items are not allowed here"); } iovi_none() => { /* fallthrough */ } } @@ -3528,7 +3528,7 @@ pub impl Parser { if first && attrs_remaining_len > 0u { // We parsed attributes for the first item but didn't find it - self.span_err(*self.last_span,~"expected item after attributes"); + self.span_err(*self.last_span, "expected item after attributes"); } ast::_mod { view_items: view_items, items: items } @@ -3583,7 +3583,7 @@ pub impl Parser { let (main_mod, new_mod) = match (main_mod_item, new_mod_item) { (item_mod(m), item_mod(n)) => (m, n), - _ => self.bug(~"parsed mod item should be mod") + _ => self.bug("parsed mod item should be mod") }; let merged_mod = ast::_mod { view_items: main_mod.view_items + new_mod.view_items, @@ -3600,7 +3600,7 @@ pub impl Parser { fn push_mod_path(&self, id: ident, attrs: ~[ast::attribute]) { let default_path = self.sess.interner.get(id); let file_path = match ::attr::first_attr_value_str_by_name( - attrs, ~"path") { + attrs, "path") { Some(d) => copy *d, None => copy *default_path @@ -3623,7 +3623,7 @@ pub impl Parser { let mod_path = Path(".").push_many(*mod_path_stack); let default_path = *self.sess.interner.get(id) + ~".rs"; let file_path = match ::attr::first_attr_value_str_by_name( - outer_attrs, ~"path") { + outer_attrs, "path") { Some(d) => { let path = Path(copy *d); if !path.is_absolute { @@ -3660,7 +3660,7 @@ pub impl Parser { return (ast::item_mod(m0), mod_attrs); fn cdir_path_opt(default: ~str, attrs: ~[ast::attribute]) -> ~str { - match ::attr::first_attr_value_str_by_name(attrs, ~"path") { + match ::attr::first_attr_value_str_by_name(attrs, "path") { Some(d) => copy *d, None => default } @@ -3915,7 +3915,7 @@ pub impl Parser { } self.expect(&token::RBRACE); if (have_disr && !all_nullary) { - self.fatal(~"discriminator values can only be used with a c-like \ + self.fatal("discriminator values can only be used with a c-like \ enum"); } @@ -4209,7 +4209,7 @@ pub impl Parser { || self.look_ahead(2) == token::LBRACE) { // MACRO INVOCATION ITEM if attrs.len() > 0 { - self.fatal(~"attrs on macros are not yet supported"); + self.fatal("attrs on macros are not yet supported"); } // item macro. @@ -4235,7 +4235,7 @@ pub impl Parser { |p| p.parse_token_tree() ) } - _ => self.fatal(~"expected open delimiter") + _ => self.fatal("expected open delimiter") }; // single-variant-enum... : let m = ast::mac_invoc_tt(pth, tts); @@ -4262,9 +4262,9 @@ pub impl Parser { iovi_none => None, iovi_view_item(_) => - self.fatal(~"view items are not allowed here"), + self.fatal("view items are not allowed here"), iovi_foreign_item(_) => - self.fatal(~"foreign items are not allowed here"), + self.fatal("foreign items are not allowed here"), iovi_item(item) => Some(item) } @@ -4404,7 +4404,7 @@ pub impl Parser { let metadata = self.parse_optional_meta(); view_item_extern_mod(ident, metadata, self.get_id()) } else { - self.bug(~"expected view item"); + self.bug("expected view item"); }; self.expect(&token::SEMI); @ast::view_item { node: node, @@ -4551,7 +4551,7 @@ pub impl Parser { self.bump(); self.id_to_str(s) } - _ => self.fatal(~"expected string literal") + _ => self.fatal("expected string literal") } } } diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index b4bad5abbf936..055336a6d9532 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -173,14 +173,14 @@ pub fn to_str(in: @ident_interner, t: &Token) -> ~str { LIT_INT_UNSUFFIXED(i) => { i.to_str() } LIT_FLOAT(s, t) => { let mut body = copy *in.get(s); - if body.ends_with(~".") { + if body.ends_with(".") { body = body + ~"0"; // `10.f` is not a float literal } body + ast_util::float_ty_to_str(t) } LIT_FLOAT_UNSUFFIXED(s) => { let mut body = copy *in.get(s); - if body.ends_with(~".") { + if body.ends_with(".") { body = body + ~"0"; // `10.f` is not a float literal } body diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 52495522613dd..6b2ee61545e6d 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -437,7 +437,7 @@ pub impl Printer { } fn print_newline(&mut self, amount: int) { debug!("NEWLINE %d", amount); - (*self.out).write_str(~"\n"); + (*self.out).write_str("\n"); self.pending_indentation = 0; self.indent(amount); } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index b2db752af1179..a535e5d195f2a 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -227,17 +227,17 @@ pub fn box(s: @ps, u: uint, b: pp::breaks) { pp::box(s.s, u, b); } -pub fn nbsp(s: @ps) { word(s.s, ~" "); } +pub fn nbsp(s: @ps) { word(s.s, " "); } pub fn word_nbsp(s: @ps, w: &str) { word(s.s, w); nbsp(s); } pub fn word_space(s: @ps, w: &str) { word(s.s, w); space(s.s); } -pub fn popen(s: @ps) { word(s.s, ~"("); } +pub fn popen(s: @ps) { word(s.s, "("); } -pub fn pclose(s: @ps) { word(s.s, ~")"); } +pub fn pclose(s: @ps) { word(s.s, ")"); } -pub fn head(s: @ps, w: ~str) { +pub fn head(s: @ps, w: &str) { // outer-box is consistent cbox(s, indent_unit); // head-box is inconsistent @@ -249,7 +249,7 @@ pub fn head(s: @ps, w: ~str) { } pub fn bopen(s: @ps) { - word(s.s, ~"{"); + word(s.s, "{"); end(s); // close the head-box } @@ -260,7 +260,7 @@ pub fn bclose_maybe_open (s: @ps, span: codemap::span, indented: uint, close_box: bool) { maybe_print_comment(s, span.hi); break_offset_if_not_bol(s, 1u, -(indented as int)); - word(s.s, ~"}"); + word(s.s, "}"); if close_box { end(s); // close the outer-box } @@ -304,18 +304,18 @@ pub fn break_offset_if_not_bol(s: @ps, n: uint, off: int) { // Synthesizes a comment that was not textually present in the original source // file. pub fn synth_comment(s: @ps, text: ~str) { - word(s.s, ~"/*"); + word(s.s, "/*"); space(s.s); word(s.s, text); space(s.s); - word(s.s, ~"*/"); + word(s.s, "*/"); } pub fn commasep(s: @ps, b: breaks, elts: &[IN], op: &fn(@ps, IN)) { box(s, 0u, b); let mut first = true; for elts.each |elt| { - if first { first = false; } else { word_space(s, ~","); } + if first { first = false; } else { word_space(s, ","); } op(s, *elt); } end(s); @@ -332,7 +332,7 @@ pub fn commasep_cmnt(s: @ps, b: breaks, elts: &[IN], op: &fn(@ps, IN), op(s, *elt); i += 1u; if i < len { - word(s.s, ~","); + word(s.s, ","); maybe_print_trailing_comment(s, get_span(*elt), Some(get_span(elts[i]).hi)); space_if_not_bol(s); @@ -374,23 +374,23 @@ pub fn print_type(s: @ps, ty: @ast::Ty) { maybe_print_comment(s, ty.span.lo); ibox(s, 0u); match ty.node { - ast::ty_nil => word(s.s, ~"()"), - ast::ty_bot => word(s.s, ~"!"), - ast::ty_box(ref mt) => { word(s.s, ~"@"); print_mt(s, mt); } - ast::ty_uniq(ref mt) => { word(s.s, ~"~"); print_mt(s, mt); } + ast::ty_nil => word(s.s, "()"), + ast::ty_bot => word(s.s, "!"), + ast::ty_box(ref mt) => { word(s.s, "@"); print_mt(s, mt); } + ast::ty_uniq(ref mt) => { word(s.s, "~"); print_mt(s, mt); } ast::ty_vec(ref mt) => { - word(s.s, ~"["); + word(s.s, "["); match mt.mutbl { - ast::m_mutbl => word_space(s, ~"mut"), - ast::m_const => word_space(s, ~"const"), + ast::m_mutbl => word_space(s, "mut"), + ast::m_const => word_space(s, "const"), ast::m_imm => () } print_type(s, mt.ty); - word(s.s, ~"]"); + word(s.s, "]"); } - ast::ty_ptr(ref mt) => { word(s.s, ~"*"); print_mt(s, mt); } + ast::ty_ptr(ref mt) => { word(s.s, "*"); print_mt(s, mt); } ast::ty_rptr(lifetime, ref mt) => { - word(s.s, ~"&"); + word(s.s, "&"); print_opt_lifetime(s, lifetime); print_mt(s, mt); } @@ -398,7 +398,7 @@ pub fn print_type(s: @ps, ty: @ast::Ty) { popen(s); commasep(s, inconsistent, *elts, print_type); if elts.len() == 1 { - word(s.s, ~","); + word(s.s, ","); } pclose(s); } @@ -418,16 +418,16 @@ pub fn print_type(s: @ps, ty: @ast::Ty) { } ast::ty_path(path, _) => print_path(s, path, false), ast::ty_fixed_length_vec(ref mt, v) => { - word(s.s, ~"["); + word(s.s, "["); match mt.mutbl { - ast::m_mutbl => word_space(s, ~"mut"), - ast::m_const => word_space(s, ~"const"), + ast::m_mutbl => word_space(s, "mut"), + ast::m_const => word_space(s, "const"), ast::m_imm => () } print_type(s, mt.ty); - word(s.s, ~", .."); + word(s.s, ", .."); print_expr(s, v); - word(s.s, ~"]"); + word(s.s, "]"); } ast::ty_mac(_) => { fail!("print_type doesn't know how to print a ty_mac"); @@ -449,15 +449,15 @@ pub fn print_foreign_item(s: @ps, item: @ast::foreign_item) { print_fn(s, decl, Some(purity), AbiSet::Rust(), item.ident, generics, None, ast::inherited); end(s); // end head-ibox - word(s.s, ~";"); + word(s.s, ";"); end(s); // end the outer fn box } ast::foreign_item_const(t) => { - head(s, ~"static"); + head(s, "static"); print_ident(s, item.ident); - word_space(s, ~":"); + word_space(s, ":"); print_type(s, t); - word(s.s, ~";"); + word(s.s, ";"); end(s); // end the head-ibox end(s); // end the outer cbox } @@ -474,14 +474,14 @@ pub fn print_item(s: @ps, item: @ast::item) { ast::item_const(ty, expr) => { head(s, visibility_qualified(item.vis, ~"static")); print_ident(s, item.ident); - word_space(s, ~":"); + word_space(s, ":"); print_type(s, ty); space(s.s); end(s); // end the head-ibox - word_space(s, ~"="); + word_space(s, "="); print_expr(s, expr); - word(s.s, ~";"); + word(s.s, ";"); end(s); // end the outer cbox } @@ -496,7 +496,7 @@ pub fn print_item(s: @ps, item: @ast::item) { None, item.vis ); - word(s.s, ~" "); + word(s.s, " "); print_block_with_attrs(s, body, item.attrs); } ast::item_mod(ref _mod) => { @@ -512,7 +512,7 @@ pub fn print_item(s: @ps, item: @ast::item) { word_nbsp(s, nmod.abis.to_str()); match nmod.sort { ast::named => { - word_nbsp(s, ~"mod"); + word_nbsp(s, "mod"); print_ident(s, item.ident); nbsp(s); } @@ -531,9 +531,9 @@ pub fn print_item(s: @ps, item: @ast::item) { end(s); // end the inner ibox space(s.s); - word_space(s, ~"="); + word_space(s, "="); print_type(s, ty); - word(s.s, ~";"); + word(s.s, ";"); end(s); // end the outer ibox } ast::item_enum(ref enum_definition, ref params) => { @@ -562,7 +562,7 @@ pub fn print_item(s: @ps, item: @ast::item) { Some(t) => { print_trait_ref(s, t); space(s.s); - word_space(s, ~"for"); + word_space(s, "for"); } None => () }; @@ -571,7 +571,7 @@ pub fn print_item(s: @ps, item: @ast::item) { space(s.s); if methods.len() == 0 { - word(s.s, ~";"); + word(s.s, ";"); } else { bopen(s); for methods.each |meth| { @@ -585,16 +585,16 @@ pub fn print_item(s: @ps, item: @ast::item) { print_ident(s, item.ident); print_generics(s, generics); if traits.len() != 0u { - word(s.s, ~":"); + word(s.s, ":"); for traits.eachi |i, trait_| { nbsp(s); if i != 0 { - word_space(s, ~"+"); + word_space(s, "+"); } print_path(s, trait_.path, false); } } - word(s.s, ~" "); + word(s.s, " "); bopen(s); for methods.each |meth| { print_trait_method(s, meth); @@ -605,7 +605,7 @@ pub fn print_item(s: @ps, item: @ast::item) { _}) => { print_visibility(s, item.vis); print_path(s, pth, false); - word(s.s, ~"! "); + word(s.s, "! "); print_ident(s, item.ident); cbox(s, indent_unit); popen(s); @@ -641,7 +641,7 @@ pub fn print_variants(s: @ps, print_outer_attributes(s, v.node.attrs); ibox(s, indent_unit); print_variant(s, v); - word(s.s, ~","); + word(s.s, ","); end(s); maybe_print_trailing_comment(s, v.span, None); } @@ -692,7 +692,7 @@ pub fn print_struct(s: @ps, } pclose(s); } - word(s.s, ~";"); + word(s.s, ";"); end(s); end(s); // close the outer-box } else { @@ -709,9 +709,9 @@ pub fn print_struct(s: @ps, print_outer_attributes(s, field.node.attrs); print_visibility(s, visibility); print_ident(s, ident); - word_nbsp(s, ~":"); + word_nbsp(s, ":"); print_type(s, field.node.ty); - word(s.s, ~","); + word(s.s, ","); } } } @@ -734,17 +734,17 @@ pub fn print_tt(s: @ps, tt: &ast::token_tree) { word(s.s, parse::token::to_str(s.intr, tk)); } ast::tt_seq(_, ref tts, ref sep, zerok) => { - word(s.s, ~"$("); + word(s.s, "$("); for (*tts).each() |tt_elt| { print_tt(s, tt_elt); } - word(s.s, ~")"); + word(s.s, ")"); match (*sep) { Some(ref tk) => word(s.s, parse::token::to_str(s.intr, tk)), None => () } - word(s.s, if zerok { ~"*" } else { ~"+" }); + word(s.s, if zerok { "*" } else { "+" }); } ast::tt_nonterminal(_, name) => { - word(s.s, ~"$"); + word(s.s, "$"); print_ident(s, name); } } @@ -776,7 +776,7 @@ pub fn print_variant(s: @ps, v: &ast::variant) { } } ast::struct_variant_kind(struct_def) => { - head(s, ~""); + head(s, ""); let generics = ast_util::empty_generics(); print_struct(s, struct_def, &generics, v.node.name, v.span); } @@ -784,7 +784,7 @@ pub fn print_variant(s: @ps, v: &ast::variant) { match v.node.disr_expr { Some(d) => { space(s.s); - word_space(s, ~"="); + word_space(s, "="); print_expr(s, d); } _ => () @@ -798,7 +798,7 @@ pub fn print_ty_method(s: @ps, m: &ast::ty_method) { print_ty_fn(s, None, None, None, m.purity, ast::Many, &m.decl, Some(m.ident), Some(&m.generics), Some(/*bad*/ copy m.explicit_self.node)); - word(s.s, ~";"); + word(s.s, ";"); } pub fn print_trait_method(s: @ps, m: &ast::trait_method) { @@ -815,7 +815,7 @@ pub fn print_method(s: @ps, meth: @ast::method) { print_fn(s, &meth.decl, Some(meth.purity), AbiSet::Rust(), meth.ident, &meth.generics, Some(meth.explicit_self.node), meth.vis); - word(s.s, ~" "); + word(s.s, " "); print_block_with_attrs(s, &meth.body, meth.attrs); } @@ -837,7 +837,7 @@ pub fn print_inner_attributes(s: @ps, attrs: &[ast::attribute]) { ast::attr_inner => { print_attribute(s, *attr); if !attr.node.is_sugared_doc { - word(s.s, ~";"); + word(s.s, ";"); } count += 1; } @@ -855,9 +855,9 @@ pub fn print_attribute(s: @ps, attr: ast::attribute) { let comment = attr::get_meta_item_value_str(meta).get(); word(s.s, *comment); } else { - word(s.s, ~"#["); + word(s.s, "#["); print_meta_item(s, attr.node.value); - word(s.s, ~"]"); + word(s.s, "]"); } } @@ -875,15 +875,15 @@ pub fn print_stmt(s: @ps, st: &ast::stmt) { ast::stmt_semi(expr, _) => { space_if_not_bol(s); print_expr(s, expr); - word(s.s, ~";"); + word(s.s, ";"); } ast::stmt_mac(ref mac, semi) => { space_if_not_bol(s); print_mac(s, mac); - if semi { word(s.s, ~";"); } + if semi { word(s.s, ";"); } } } - if parse::classify::stmt_ends_with_semi(st) { word(s.s, ~";"); } + if parse::classify::stmt_ends_with_semi(st) { word(s.s, ";"); } maybe_print_trailing_comment(s, st.span, None); } @@ -925,7 +925,7 @@ pub fn print_possibly_embedded_block_(s: @ps, attrs: &[ast::attribute], close_box: bool) { match blk.node.rules { - ast::unsafe_blk => word_space(s, ~"unsafe"), + ast::unsafe_blk => word_space(s, "unsafe"), ast::default_blk => () } maybe_print_comment(s, blk.span.lo); @@ -956,8 +956,8 @@ pub fn print_possibly_embedded_block_(s: @ps, pub fn print_if(s: @ps, test: @ast::expr, blk: &ast::blk, elseopt: Option<@ast::expr>, chk: bool) { - head(s, ~"if"); - if chk { word_nbsp(s, ~"check"); } + head(s, "if"); + if chk { word_nbsp(s, "check"); } print_expr(s, test); space(s.s); print_block(s, blk); @@ -969,7 +969,7 @@ pub fn print_if(s: @ps, test: @ast::expr, blk: &ast::blk, ast::expr_if(i, ref t, e) => { cbox(s, indent_unit - 1u); ibox(s, 0u); - word(s.s, ~" else if "); + word(s.s, " else if "); print_expr(s, i); space(s.s); print_block(s, t); @@ -979,7 +979,7 @@ pub fn print_if(s: @ps, test: @ast::expr, blk: &ast::blk, ast::expr_block(ref b) => { cbox(s, indent_unit - 1u); ibox(s, 0u); - word(s.s, ~" else "); + word(s.s, " else "); print_block(s, b); } // BLEAH, constraints would be great here @@ -998,7 +998,7 @@ pub fn print_mac(s: @ps, m: &ast::mac) { match m.node { ast::mac_invoc_tt(pth, ref tts) => { print_path(s, pth, false); - word(s.s, ~"!"); + word(s.s, "!"); popen(s); print_tts(s, *tts); pclose(s); @@ -1009,11 +1009,11 @@ pub fn print_mac(s: @ps, m: &ast::mac) { pub fn print_vstore(s: @ps, t: ast::vstore) { match t { ast::vstore_fixed(Some(i)) => word(s.s, fmt!("%u", i)), - ast::vstore_fixed(None) => word(s.s, ~"_"), - ast::vstore_uniq => word(s.s, ~"~"), - ast::vstore_box => word(s.s, ~"@"), + ast::vstore_fixed(None) => word(s.s, "_"), + ast::vstore_uniq => word(s.s, "~"), + ast::vstore_box => word(s.s, "@"), ast::vstore_slice(r) => { - word(s.s, ~"&"); + word(s.s, "&"); print_opt_lifetime(s, r); } } @@ -1021,16 +1021,16 @@ pub fn print_vstore(s: @ps, t: ast::vstore) { pub fn print_expr_vstore(s: @ps, t: ast::expr_vstore) { match t { - ast::expr_vstore_uniq => word(s.s, ~"~"), - ast::expr_vstore_box => word(s.s, ~"@"), + ast::expr_vstore_uniq => word(s.s, "~"), + ast::expr_vstore_box => word(s.s, "@"), ast::expr_vstore_mut_box => { - word(s.s, ~"@"); - word(s.s, ~"mut"); + word(s.s, "@"); + word(s.s, "mut"); } - ast::expr_vstore_slice => word(s.s, ~"&"), + ast::expr_vstore_slice => word(s.s, "&"), ast::expr_vstore_mut_slice => { - word(s.s, ~"&"); - word(s.s, ~"mut"); + word(s.s, "&"); + word(s.s, "mut"); } } } @@ -1041,11 +1041,11 @@ pub fn print_call_pre(s: @ps, -> Option<@ast::expr> { match sugar { ast::DoSugar => { - head(s, ~"do"); + head(s, "do"); Some(base_args.pop()) } ast::ForSugar => { - head(s, ~"for"); + head(s, "for"); Some(base_args.pop()) } ast::NoSugar => None @@ -1082,9 +1082,9 @@ pub fn print_call_post(s: @ps, pub fn print_expr(s: @ps, expr: @ast::expr) { fn print_field(s: @ps, field: ast::field) { ibox(s, indent_unit); - if field.node.mutbl == ast::m_mutbl { word_nbsp(s, ~"mut"); } + if field.node.mutbl == ast::m_mutbl { word_nbsp(s, "mut"); } print_ident(s, field.node.ident); - word_space(s, ~":"); + word_space(s, ":"); print_expr(s, field.node.expr); end(s); } @@ -1101,53 +1101,53 @@ pub fn print_expr(s: @ps, expr: @ast::expr) { }, ast::expr_vec(ref exprs, mutbl) => { ibox(s, indent_unit); - word(s.s, ~"["); + word(s.s, "["); if mutbl == ast::m_mutbl { - word(s.s, ~"mut"); + word(s.s, "mut"); if exprs.len() > 0u { nbsp(s); } } commasep_exprs(s, inconsistent, *exprs); - word(s.s, ~"]"); + word(s.s, "]"); end(s); } ast::expr_repeat(element, count, mutbl) => { ibox(s, indent_unit); - word(s.s, ~"["); + word(s.s, "["); if mutbl == ast::m_mutbl { - word(s.s, ~"mut"); + word(s.s, "mut"); nbsp(s); } print_expr(s, element); - word(s.s, ~","); - word(s.s, ~".."); + word(s.s, ","); + word(s.s, ".."); print_expr(s, count); - word(s.s, ~"]"); + word(s.s, "]"); end(s); } ast::expr_struct(path, ref fields, wth) => { print_path(s, path, true); - word(s.s, ~"{"); + word(s.s, "{"); commasep_cmnt(s, consistent, (*fields), print_field, get_span); match wth { Some(expr) => { ibox(s, indent_unit); - word(s.s, ~","); + word(s.s, ","); space(s.s); - word(s.s, ~".."); + word(s.s, ".."); print_expr(s, expr); end(s); } - _ => (word(s.s, ~",")) + _ => (word(s.s, ",")) } - word(s.s, ~"}"); + word(s.s, "}"); } ast::expr_tup(ref exprs) => { popen(s); commasep_exprs(s, inconsistent, *exprs); if exprs.len() == 1 { - word(s.s, ~","); + word(s.s, ","); } pclose(s); } @@ -1161,12 +1161,12 @@ pub fn print_expr(s: @ps, expr: @ast::expr) { let mut base_args = copy *args; let blk = print_call_pre(s, sugar, &mut base_args); print_expr(s, func); - word(s.s, ~"."); + word(s.s, "."); print_ident(s, ident); if tys.len() > 0u { - word(s.s, ~"::<"); + word(s.s, "::<"); commasep(s, inconsistent, *tys, print_type); - word(s.s, ~">"); + word(s.s, ">"); } print_call_post(s, sugar, &blk, &mut base_args); } @@ -1181,7 +1181,7 @@ pub fn print_expr(s: @ps, expr: @ast::expr) { print_expr(s, expr); } ast::expr_addr_of(m, expr) => { - word(s.s, ~"&"); + word(s.s, "&"); print_mutability(s, m); // Avoid `& &e` => `&&e`. match (m, &expr.node) { @@ -1194,32 +1194,32 @@ pub fn print_expr(s: @ps, expr: @ast::expr) { ast::expr_cast(expr, ty) => { print_expr(s, expr); space(s.s); - word_space(s, ~"as"); + word_space(s, "as"); print_type(s, ty); } ast::expr_if(test, ref blk, elseopt) => { print_if(s, test, blk, elseopt, false); } ast::expr_while(test, ref blk) => { - head(s, ~"while"); + head(s, "while"); print_expr(s, test); space(s.s); print_block(s, blk); } ast::expr_loop(ref blk, opt_ident) => { for opt_ident.each |ident| { - word(s.s, ~"'"); + word(s.s, "'"); print_ident(s, *ident); - word_space(s, ~":"); + word_space(s, ":"); } - head(s, ~"loop"); + head(s, "loop"); space(s.s); print_block(s, blk); } ast::expr_match(expr, ref arms) => { cbox(s, indent_unit); ibox(s, 4); - word_nbsp(s, ~"match"); + word_nbsp(s, "match"); print_expr(s, expr); space(s.s); bopen(s); @@ -1232,19 +1232,19 @@ pub fn print_expr(s: @ps, expr: @ast::expr) { for arm.pats.each |p| { if first { first = false; - } else { space(s.s); word_space(s, ~"|"); } + } else { space(s.s); word_space(s, "|"); } print_refutable_pat(s, *p); } space(s.s); match arm.guard { Some(e) => { - word_space(s, ~"if"); + word_space(s, "if"); print_expr(s, e); space(s.s); } None => () } - word_space(s, ~"=>"); + word_space(s, "=>"); // Extract the expression from the extra block the parser adds // in the case of foo => expr @@ -1268,7 +1268,7 @@ pub fn print_expr(s: @ps, expr: @ast::expr) { } if !expr_is_simple_block(expr) && i < len - 1 { - word(s.s, ~","); + word(s.s, ","); } end(s); // close enclosing cbox } @@ -1321,97 +1321,97 @@ pub fn print_expr(s: @ps, expr: @ast::expr) { ibox(s, 0u); print_block(s, blk); } - ast::expr_copy(e) => { word_space(s, ~"copy"); print_expr(s, e); } + ast::expr_copy(e) => { word_space(s, "copy"); print_expr(s, e); } ast::expr_assign(lhs, rhs) => { print_expr(s, lhs); space(s.s); - word_space(s, ~"="); + word_space(s, "="); print_expr(s, rhs); } ast::expr_assign_op(op, lhs, rhs) => { print_expr(s, lhs); space(s.s); word(s.s, ast_util::binop_to_str(op)); - word_space(s, ~"="); + word_space(s, "="); print_expr(s, rhs); } ast::expr_field(expr, id, ref tys) => { print_expr(s, expr); - word(s.s, ~"."); + word(s.s, "."); print_ident(s, id); if tys.len() > 0u { - word(s.s, ~"::<"); + word(s.s, "::<"); commasep(s, inconsistent, *tys, print_type); - word(s.s, ~">"); + word(s.s, ">"); } } ast::expr_index(expr, index) => { print_expr(s, expr); - word(s.s, ~"["); + word(s.s, "["); print_expr(s, index); - word(s.s, ~"]"); + word(s.s, "]"); } ast::expr_path(path) => print_path(s, path, true), - ast::expr_self => word(s.s, ~"self"), + ast::expr_self => word(s.s, "self"), ast::expr_break(opt_ident) => { - word(s.s, ~"break"); + word(s.s, "break"); space(s.s); for opt_ident.each |ident| { - word(s.s, ~"'"); + word(s.s, "'"); print_ident(s, *ident); space(s.s); } } ast::expr_again(opt_ident) => { - word(s.s, ~"loop"); + word(s.s, "loop"); space(s.s); for opt_ident.each |ident| { - word(s.s, ~"'"); + word(s.s, "'"); print_ident(s, *ident); space(s.s) } } ast::expr_ret(result) => { - word(s.s, ~"return"); + word(s.s, "return"); match result { - Some(expr) => { word(s.s, ~" "); print_expr(s, expr); } + Some(expr) => { word(s.s, " "); print_expr(s, expr); } _ => () } } ast::expr_log(lexp, expr) => { - word(s.s, ~"__log"); + word(s.s, "__log"); popen(s); print_expr(s, lexp); - word(s.s, ~","); + word(s.s, ","); space_if_not_bol(s); print_expr(s, expr); pclose(s); } ast::expr_inline_asm(ref a) => { if a.volatile { - word(s.s, ~"__volatile__ asm!"); + word(s.s, "__volatile__ asm!"); } else { - word(s.s, ~"asm!"); + word(s.s, "asm!"); } popen(s); print_string(s, *a.asm); - word_space(s, ~":"); + word_space(s, ":"); for a.outputs.each |&(co, o)| { print_string(s, *co); popen(s); print_expr(s, o); pclose(s); - word_space(s, ~","); + word_space(s, ","); } - word_space(s, ~":"); + word_space(s, ":"); for a.inputs.each |&(co, o)| { print_string(s, *co); popen(s); print_expr(s, o); pclose(s); - word_space(s, ~","); + word_space(s, ","); } - word_space(s, ~":"); + word_space(s, ":"); print_string(s, *a.clobbers); pclose(s); } @@ -1430,7 +1430,7 @@ pub fn print_local_decl(s: @ps, loc: @ast::local) { print_irrefutable_pat(s, loc.node.pat); match loc.node.ty.node { ast::ty_infer => (), - _ => { word_space(s, ~":"); print_type(s, loc.node.ty); } + _ => { word_space(s, ":"); print_type(s, loc.node.ty); } } } @@ -1440,12 +1440,12 @@ pub fn print_decl(s: @ps, decl: @ast::decl) { ast::decl_local(ref locs) => { space_if_not_bol(s); ibox(s, indent_unit); - word_nbsp(s, ~"let"); + word_nbsp(s, "let"); // if any are mut, all are mut if locs.any(|l| l.node.is_mutbl) { assert!(locs.all(|l| l.node.is_mutbl)); - word_nbsp(s, ~"mut"); + word_nbsp(s, "mut"); } fn print_local(s: @ps, loc: @ast::local) { @@ -1455,7 +1455,7 @@ pub fn print_decl(s: @ps, decl: @ast::decl) { match loc.node.init { Some(init) => { nbsp(s); - word_space(s, ~"="); + word_space(s, "="); print_expr(s, init); } _ => () @@ -1475,34 +1475,34 @@ pub fn print_ident(s: @ps, ident: ast::ident) { pub fn print_for_decl(s: @ps, loc: @ast::local, coll: @ast::expr) { print_local_decl(s, loc); space(s.s); - word_space(s, ~"in"); + word_space(s, "in"); print_expr(s, coll); } pub fn print_path(s: @ps, path: @ast::Path, colons_before_params: bool) { maybe_print_comment(s, path.span.lo); - if path.global { word(s.s, ~"::"); } + if path.global { word(s.s, "::"); } let mut first = true; for path.idents.each |id| { - if first { first = false; } else { word(s.s, ~"::"); } + if first { first = false; } else { word(s.s, "::"); } print_ident(s, *id); } if path.rp.is_some() || !path.types.is_empty() { - if colons_before_params { word(s.s, ~"::"); } + if colons_before_params { word(s.s, "::"); } if path.rp.is_some() || !path.types.is_empty() { - word(s.s, ~"<"); + word(s.s, "<"); for path.rp.each |r| { print_lifetime(s, *r); if !path.types.is_empty() { - word_space(s, ~","); + word_space(s, ","); } } commasep(s, inconsistent, path.types, print_type); - word(s.s, ~">"); + word(s.s, ">"); } } } @@ -1522,16 +1522,16 @@ pub fn print_pat(s: @ps, pat: @ast::pat, refutable: bool) { /* Pat isn't normalized, but the beauty of it is that it doesn't matter */ match pat.node { - ast::pat_wild => word(s.s, ~"_"), + ast::pat_wild => word(s.s, "_"), ast::pat_ident(binding_mode, path, sub) => { if refutable { match binding_mode { ast::bind_by_ref(mutbl) => { - word_nbsp(s, ~"ref"); + word_nbsp(s, "ref"); print_mutability(s, mutbl); } ast::bind_by_copy => { - word_nbsp(s, ~"copy"); + word_nbsp(s, "copy"); } ast::bind_infer => {} } @@ -1539,7 +1539,7 @@ pub fn print_pat(s: @ps, pat: @ast::pat, refutable: bool) { print_path(s, path, true); match sub { Some(p) => { - word(s.s, ~"@"); + word(s.s, "@"); print_pat(s, p, refutable); } None => () @@ -1548,7 +1548,7 @@ pub fn print_pat(s: @ps, pat: @ast::pat, refutable: bool) { ast::pat_enum(path, ref args_) => { print_path(s, path, true); match *args_ { - None => word(s.s, ~"(*)"), + None => word(s.s, "(*)"), Some(ref args) => { if !args.is_empty() { popen(s); @@ -1561,11 +1561,11 @@ pub fn print_pat(s: @ps, pat: @ast::pat, refutable: bool) { } ast::pat_struct(path, ref fields, etc) => { print_path(s, path, true); - word(s.s, ~"{"); + word(s.s, "{"); fn print_field(s: @ps, f: ast::field_pat, refutable: bool) { cbox(s, indent_unit); print_ident(s, f.ident); - word_space(s, ~":"); + word_space(s, ":"); print_pat(s, f.pat, refutable); end(s); } @@ -1574,53 +1574,53 @@ pub fn print_pat(s: @ps, pat: @ast::pat, refutable: bool) { |s, f| print_field(s,f,refutable), get_span); if etc { - if fields.len() != 0u { word_space(s, ~","); } - word(s.s, ~"_"); + if fields.len() != 0u { word_space(s, ","); } + word(s.s, "_"); } - word(s.s, ~"}"); + word(s.s, "}"); } ast::pat_tup(ref elts) => { popen(s); commasep(s, inconsistent, *elts, |s, p| print_pat(s, p, refutable)); if elts.len() == 1 { - word(s.s, ~","); + word(s.s, ","); } pclose(s); } ast::pat_box(inner) => { - word(s.s, ~"@"); + word(s.s, "@"); print_pat(s, inner, refutable); } ast::pat_uniq(inner) => { - word(s.s, ~"~"); + word(s.s, "~"); print_pat(s, inner, refutable); } ast::pat_region(inner) => { - word(s.s, ~"&"); + word(s.s, "&"); print_pat(s, inner, refutable); } ast::pat_lit(e) => print_expr(s, e), ast::pat_range(begin, end) => { print_expr(s, begin); space(s.s); - word(s.s, ~".."); + word(s.s, ".."); print_expr(s, end); } ast::pat_vec(ref before, slice, ref after) => { - word(s.s, ~"["); + word(s.s, "["); do commasep(s, inconsistent, *before) |s, p| { print_pat(s, p, refutable); } for slice.each |&p| { - if !before.is_empty() { word_space(s, ~","); } - word(s.s, ~".."); + if !before.is_empty() { word_space(s, ","); } + word(s.s, ".."); print_pat(s, p, refutable); - if !after.is_empty() { word_space(s, ~","); } + if !after.is_empty() { word_space(s, ","); } } do commasep(s, inconsistent, *after) |s, p| { print_pat(s, p, refutable); } - word(s.s, ~"]"); + word(s.s, "]"); } } (s.ann.post)(ann_node); @@ -1634,18 +1634,18 @@ pub fn explicit_self_to_str(explicit_self: ast::explicit_self_, intr: @ident_int pub fn print_explicit_self(s: @ps, explicit_self: ast::explicit_self_) -> bool { match explicit_self { ast::sty_static => { return false; } - ast::sty_value => { word(s.s, ~"self"); } + ast::sty_value => { word(s.s, "self"); } ast::sty_region(lt, m) => { - word(s.s, ~"&"); + word(s.s, "&"); print_opt_lifetime(s, lt); print_mutability(s, m); - word(s.s, ~"self"); + word(s.s, "self"); } ast::sty_box(m) => { - word(s.s, ~"@"); print_mutability(s, m); word(s.s, ~"self"); + word(s.s, "@"); print_mutability(s, m); word(s.s, "self"); } ast::sty_uniq(m) => { - word(s.s, ~"~"); print_mutability(s, m); word(s.s, ~"self"); + word(s.s, "~"); print_mutability(s, m); word(s.s, "self"); } } return true; @@ -1659,7 +1659,7 @@ pub fn print_fn(s: @ps, generics: &ast::Generics, opt_explicit_self: Option, vis: ast::visibility) { - head(s, ~""); + head(s, ""); print_fn_header_info(s, opt_explicit_self, purity, abis, ast::Many, None, vis); nbsp(s); print_ident(s, name); @@ -1678,7 +1678,7 @@ pub fn print_fn_args(s: @ps, decl: &ast::fn_decl, } for decl.inputs.each |arg| { - if first { first = false; } else { word_space(s, ~","); } + if first { first = false; } else { word_space(s, ","); } print_arg(s, *arg); } @@ -1696,22 +1696,22 @@ pub fn print_fn_args_and_ret(s: @ps, decl: &ast::fn_decl, ast::ty_nil => {} _ => { space_if_not_bol(s); - word_space(s, ~"->"); + word_space(s, "->"); print_type(s, decl.output); } } } pub fn print_fn_block_args(s: @ps, decl: &ast::fn_decl) { - word(s.s, ~"|"); + word(s.s, "|"); print_fn_args(s, decl, None); - word(s.s, ~"|"); + word(s.s, "|"); match decl.output.node { ast::ty_infer => {} _ => { space_if_not_bol(s); - word_space(s, ~"->"); + word_space(s, "->"); print_type(s, decl.output); } } @@ -1721,33 +1721,33 @@ pub fn print_fn_block_args(s: @ps, decl: &ast::fn_decl) { pub fn print_bounds(s: @ps, bounds: @OptVec) { if !bounds.is_empty() { - word(s.s, ~":"); + word(s.s, ":"); let mut first = true; for bounds.each |bound| { nbsp(s); if first { first = false; } else { - word_space(s, ~"+"); + word_space(s, "+"); } match *bound { TraitTyParamBound(tref) => print_trait_ref(s, tref), - RegionTyParamBound => word(s.s, ~"'static"), + RegionTyParamBound => word(s.s, "'static"), } } } } pub fn print_lifetime(s: @ps, lifetime: &ast::Lifetime) { - word(s.s, ~"'"); + word(s.s, "'"); print_ident(s, lifetime.ident); } pub fn print_generics(s: @ps, generics: &ast::Generics) { let total = generics.lifetimes.len() + generics.ty_params.len(); if total > 0 { - word(s.s, ~"<"); + word(s.s, "<"); fn print_item(s: @ps, generics: &ast::Generics, idx: uint) { if idx < generics.lifetimes.len() { let lifetime = generics.lifetimes.get(idx); @@ -1767,7 +1767,7 @@ pub fn print_generics(s: @ps, generics: &ast::Generics) { commasep(s, inconsistent, ints, |s, i| print_item(s, generics, i)); - word(s.s, ~">"); + word(s.s, ">"); } } @@ -1777,7 +1777,7 @@ pub fn print_meta_item(s: @ps, item: @ast::meta_item) { ast::meta_word(name) => word(s.s, *name), ast::meta_name_value(name, value) => { word_space(s, *name); - word_space(s, ~"="); + word_space(s, "="); print_literal(s, @value); } ast::meta_list(name, ref items) => { @@ -1801,23 +1801,23 @@ pub fn print_view_path(s: @ps, vp: @ast::view_path) { if path.idents[path.idents.len()-1u] != ident { print_ident(s, ident); space(s.s); - word_space(s, ~"="); + word_space(s, "="); } print_path(s, path, false); } ast::view_path_glob(path, _) => { print_path(s, path, false); - word(s.s, ~"::*"); + word(s.s, "::*"); } ast::view_path_list(path, ref idents, _) => { print_path(s, path, false); - word(s.s, ~"::{"); + word(s.s, "::{"); do commasep(s, inconsistent, (*idents)) |s, w| { print_ident(s, w.node.name); } - word(s.s, ~"}"); + word(s.s, "}"); } } } @@ -1833,7 +1833,7 @@ pub fn print_view_item(s: @ps, item: @ast::view_item) { print_visibility(s, item.vis); match item.node { ast::view_item_extern_mod(id, ref mta, _) => { - head(s, ~"extern mod"); + head(s, "extern mod"); print_ident(s, id); if !mta.is_empty() { popen(s); @@ -1843,19 +1843,19 @@ pub fn print_view_item(s: @ps, item: @ast::view_item) { } ast::view_item_use(ref vps) => { - head(s, ~"use"); + head(s, "use"); print_view_paths(s, *vps); } } - word(s.s, ~";"); + word(s.s, ";"); end(s); // end inner head-block end(s); // end outer head-block } pub fn print_mutability(s: @ps, mutbl: ast::mutability) { match mutbl { - ast::m_mutbl => word_nbsp(s, ~"mut"), - ast::m_const => word_nbsp(s, ~"const"), + ast::m_mutbl => word_nbsp(s, "mut"), + ast::m_const => word_nbsp(s, "const"), ast::m_imm => {/* nothing */ } } } @@ -1868,7 +1868,7 @@ pub fn print_mt(s: @ps, mt: &ast::mt) { pub fn print_arg(s: @ps, input: ast::arg) { ibox(s, indent_unit); if input.is_mutbl { - word_space(s, ~"mut"); + word_space(s, "mut"); } match input.ty.node { ast::ty_infer => print_irrefutable_pat(s, input.pat), @@ -1881,7 +1881,7 @@ pub fn print_arg(s: @ps, input: ast::arg) { } _ => { print_irrefutable_pat(s, input.pat); - word(s.s, ~":"); + word(s.s, ":"); space(s.s); } } @@ -1910,8 +1910,8 @@ pub fn print_ty_fn(s: @ps, print_opt_lifetime(s, opt_region); print_purity(s, purity); print_onceness(s, onceness); - word(s.s, ~"fn"); - match id { Some(id) => { word(s.s, ~" "); print_ident(s, id); } _ => () } + word(s.s, "fn"); + match id { Some(id) => { word(s.s, " "); print_ident(s, id); } _ => () } match generics { Some(g) => print_generics(s, g), _ => () } zerobreak(s.s); @@ -1924,7 +1924,7 @@ pub fn print_ty_fn(s: @ps, first = !print_explicit_self(s, *explicit_self); } for decl.inputs.each |arg| { - if first { first = false; } else { word_space(s, ~","); } + if first { first = false; } else { word_space(s, ","); } print_arg(s, *arg); } end(s); @@ -1937,8 +1937,8 @@ pub fn print_ty_fn(s: @ps, _ => { space_if_not_bol(s); ibox(s, indent_unit); - word_space(s, ~"->"); - if decl.cf == ast::noreturn { word_nbsp(s, ~"!"); } + word_space(s, "->"); + if decl.cf == ast::noreturn { word_nbsp(s, "!"); } else { print_type(s, decl.output); } end(s); } @@ -2024,9 +2024,9 @@ pub fn print_literal(s: @ps, lit: @ast::lit) { word(s.s, *f + ast_util::float_ty_to_str(t)); } ast::lit_float_unsuffixed(f) => word(s.s, *f), - ast::lit_nil => word(s.s, ~"()"), + ast::lit_nil => word(s.s, "()"), ast::lit_bool(val) => { - if val { word(s.s, ~"true"); } else { word(s.s, ~"false"); } + if val { word(s.s, "true"); } else { word(s.s, "false"); } } } } @@ -2082,7 +2082,7 @@ pub fn print_comment(s: @ps, cmnt: &comments::cmnt) { } } comments::trailing => { - word(s.s, ~" "); + word(s.s, " "); if cmnt.lines.len() == 1u { word(s.s, cmnt.lines[0]); hardbreak(s.s); @@ -2109,9 +2109,9 @@ pub fn print_comment(s: @ps, cmnt: &comments::cmnt) { } pub fn print_string(s: @ps, st: &str) { - word(s.s, ~"\""); + word(s.s, "\""); word(s.s, str::escape_default(st)); - word(s.s, ~"\""); + word(s.s, "\""); } pub fn to_str(t: T, f: @fn(@ps, T), intr: @ident_interner) -> ~str { @@ -2146,7 +2146,7 @@ pub fn print_opt_purity(s: @ps, opt_purity: Option) { pub fn print_extern_opt_abis(s: @ps, opt_abis: Option) { match opt_abis { Some(abis) => { - word_nbsp(s, ~"extern"); + word_nbsp(s, "extern"); word_nbsp(s, abis.to_str()); } None => {} @@ -2155,9 +2155,9 @@ pub fn print_extern_opt_abis(s: @ps, opt_abis: Option) { pub fn print_opt_sigil(s: @ps, opt_sigil: Option) { match opt_sigil { - Some(ast::BorrowedSigil) => { word(s.s, ~"&"); } - Some(ast::OwnedSigil) => { word(s.s, ~"~"); } - Some(ast::ManagedSigil) => { word(s.s, ~"@"); } + Some(ast::BorrowedSigil) => { word(s.s, "&"); } + Some(ast::OwnedSigil) => { word(s.s, "~"); } + Some(ast::ManagedSigil) => { word(s.s, "@"); } None => {} }; } @@ -2172,7 +2172,7 @@ pub fn print_fn_header_info(s: @ps, word(s.s, visibility_qualified(vis, ~"")); if abis != AbiSet::Rust() { - word_nbsp(s, ~"extern"); + word_nbsp(s, "extern"); word_nbsp(s, abis.to_str()); if opt_purity != Some(ast::extern_fn) { @@ -2183,7 +2183,7 @@ pub fn print_fn_header_info(s: @ps, } print_onceness(s, onceness); - word(s.s, ~"fn"); + word(s.s, "fn"); print_opt_sigil(s, opt_sigil); } @@ -2219,7 +2219,7 @@ pub fn print_purity(s: @ps, p: ast::purity) { pub fn print_onceness(s: @ps, o: ast::Onceness) { match o { - ast::Once => { word_nbsp(s, ~"once"); } + ast::Once => { word_nbsp(s, "once"); } ast::Many => {} } } diff --git a/src/test/compile-fail/lint-unused-imports.rs b/src/test/compile-fail/lint-unused-imports.rs index f3b0a1f73f933..dc5936777c9fe 100644 --- a/src/test/compile-fail/lint-unused-imports.rs +++ b/src/test/compile-fail/lint-unused-imports.rs @@ -55,8 +55,8 @@ fn main() { cal(foo::Point{x:3, y:9}); let a = 3; ignore(a); - io::stdout().write_str(~"a"); - let _a = do map(~[2]) |&x| { + io::stdout().write_str("a"); + let _a = do map([2]) |&x| { x + 2 }; } From 7bd421776681285bf4dfba09fe7a6dae4c8eecd5 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 9 May 2013 12:49:14 -0700 Subject: [PATCH 132/248] Replace all uses of rust-intrinsic ABI with calls to unstable::intrinsics --- src/libcore/cast.rs | 27 +++++++++------------------ src/libcore/stackwalk.rs | 10 ++-------- src/libcore/sys.rs | 19 +++++-------------- src/libcore/unstable/intrinsics.rs | 5 +++-- src/libstd/arena.rs | 15 ++++----------- src/libstd/priority_queue.rs | 3 ++- 6 files changed, 25 insertions(+), 54 deletions(-) diff --git a/src/libcore/cast.rs b/src/libcore/cast.rs index 4e71b62f10cd7..e3336e24a6e1a 100644 --- a/src/libcore/cast.rs +++ b/src/libcore/cast.rs @@ -12,26 +12,17 @@ use sys; use unstable; - -pub mod rusti { - #[abi = "rust-intrinsic"] - #[link_name = "rusti"] - pub extern "rust-intrinsic" { - fn forget(x: T); - - fn transmute(e: T) -> U; - } -} +use unstable::intrinsics; /// Casts the value at `src` to U. The two types must have the same length. pub unsafe fn transmute_copy(src: &T) -> U { - let mut dest: U = unstable::intrinsics::init(); + let mut dest: U = intrinsics::init(); { - let dest_ptr: *mut u8 = rusti::transmute(&mut dest); - let src_ptr: *u8 = rusti::transmute(src); - unstable::intrinsics::memmove64(dest_ptr, - src_ptr, - sys::size_of::() as u64); + let dest_ptr: *mut u8 = transmute(&mut dest); + let src_ptr: *u8 = transmute(src); + intrinsics::memmove64(dest_ptr, + src_ptr, + sys::size_of::() as u64); } dest } @@ -45,7 +36,7 @@ pub unsafe fn transmute_copy(src: &T) -> U { * reinterpret_cast on pointer types. */ #[inline(always)] -pub unsafe fn forget(thing: T) { rusti::forget(thing); } +pub unsafe fn forget(thing: T) { intrinsics::forget(thing); } /** * Force-increment the reference count on a shared box. If used @@ -65,7 +56,7 @@ pub unsafe fn bump_box_refcount(t: @T) { forget(t); } */ #[inline(always)] pub unsafe fn transmute(thing: L) -> G { - rusti::transmute(thing) + intrinsics::transmute(thing) } /// Coerce an immutable reference to be mutable. diff --git a/src/libcore/stackwalk.rs b/src/libcore/stackwalk.rs index fbb6753723293..784656718d0d2 100644 --- a/src/libcore/stackwalk.rs +++ b/src/libcore/stackwalk.rs @@ -11,6 +11,7 @@ #[doc(hidden)]; // FIXME #3538 use cast::transmute; +use unstable::intrinsics; pub type Word = uint; @@ -75,13 +76,6 @@ fn test_simple_deep() { fn frame_address(f: &fn(x: *u8)) { unsafe { - rusti::frame_address(f) - } -} - -pub mod rusti { - #[abi = "rust-intrinsic"] - pub extern "rust-intrinsic" { - pub fn frame_address(f: &once fn(x: *u8)); + intrinsics::frame_address(f) } } diff --git a/src/libcore/sys.rs b/src/libcore/sys.rs index fc57cf40d1e01..962295e0b8a4b 100644 --- a/src/libcore/sys.rs +++ b/src/libcore/sys.rs @@ -19,6 +19,7 @@ use libc; use libc::{c_void, c_char, size_t}; use repr; use str; +use unstable::intrinsics; pub type FreeGlue<'self> = &'self fn(*TypeDesc, *c_void); @@ -38,16 +39,6 @@ pub struct Closure { env: *(), } -pub mod rusti { - #[abi = "rust-intrinsic"] - pub extern "rust-intrinsic" { - fn get_tydesc() -> *(); - fn size_of() -> uint; - fn pref_align_of() -> uint; - fn min_align_of() -> uint; - } -} - pub mod rustrt { use libc::{c_char, size_t}; @@ -81,7 +72,7 @@ pub fn shape_le(x1: &T, x2: &T) -> bool { */ #[inline(always)] pub fn get_type_desc() -> *TypeDesc { - unsafe { rusti::get_tydesc::() as *TypeDesc } + unsafe { intrinsics::get_tydesc::() as *TypeDesc } } /// Returns a pointer to a type descriptor. @@ -93,7 +84,7 @@ pub fn get_type_desc_val(_val: &T) -> *TypeDesc { /// Returns the size of a type #[inline(always)] pub fn size_of() -> uint { - unsafe { rusti::size_of::() } + unsafe { intrinsics::size_of::() } } /// Returns the size of the type that `_val` points to @@ -128,7 +119,7 @@ pub fn nonzero_size_of_val(_val: &T) -> uint { */ #[inline(always)] pub fn min_align_of() -> uint { - unsafe { rusti::min_align_of::() } + unsafe { intrinsics::min_align_of::() } } /// Returns the ABI-required minimum alignment of the type of the value that @@ -141,7 +132,7 @@ pub fn min_align_of_val(_val: &T) -> uint { /// Returns the preferred alignment of a type #[inline(always)] pub fn pref_align_of() -> uint { - unsafe { rusti::pref_align_of::() } + unsafe { intrinsics::pref_align_of::() } } /// Returns the preferred alignment of the type of the value that diff --git a/src/libcore/unstable/intrinsics.rs b/src/libcore/unstable/intrinsics.rs index f332ecc63fc7e..d476822819eb9 100644 --- a/src/libcore/unstable/intrinsics.rs +++ b/src/libcore/unstable/intrinsics.rs @@ -114,6 +114,7 @@ pub extern "rust-intrinsic" { /// `forget` is unsafe because the caller is responsible for /// ensuring the argument is deallocated already. pub unsafe fn forget(_: T) -> (); + pub fn transmute(e: T) -> U; /// Returns `true` if a type requires drop glue. pub fn needs_drop() -> bool; @@ -121,8 +122,8 @@ pub extern "rust-intrinsic" { // XXX: intrinsic uses legacy modes and has reference to TyDesc // and TyVisitor which are in librustc //fn visit_tydesc(++td: *TyDesc, &&tv: TyVisitor) -> (); - // XXX: intrinsic uses legacy modes - //fn frame_address(f: &once fn(*u8)); + + pub fn frame_address(f: &once fn(*u8)); /// Get the address of the `__morestack` stack growth function. pub fn morestack_addr() -> *(); diff --git a/src/libstd/arena.rs b/src/libstd/arena.rs index fd9fba8c1d753..a087a16caa245 100644 --- a/src/libstd/arena.rs +++ b/src/libstd/arena.rs @@ -43,14 +43,7 @@ use core::sys::TypeDesc; use core::sys; use core::uint; use core::vec; - -pub mod rusti { - #[abi = "rust-intrinsic"] - pub extern "rust-intrinsic" { - fn move_val_init(dst: &mut T, src: T); - fn needs_drop() -> bool; - } -} +use core::unstable::intrinsics; pub mod rustrt { use core::libc::size_t; @@ -208,7 +201,7 @@ pub impl Arena { let tydesc = sys::get_type_desc::(); let ptr = self.alloc_pod_inner((*tydesc).size, (*tydesc).align); let ptr: *mut T = transmute(ptr); - rusti::move_val_init(&mut (*ptr), op()); + intrinsics::move_val_init(&mut (*ptr), op()); return transmute(ptr); } } @@ -261,7 +254,7 @@ pub impl Arena { // has *not* been initialized yet. *ty_ptr = transmute(tydesc); // Actually initialize it - rusti::move_val_init(&mut(*ptr), op()); + intrinsics::move_val_init(&mut(*ptr), op()); // Now that we are done, update the tydesc to indicate that // the object is there. *ty_ptr = bitpack_tydesc_ptr(tydesc, true); @@ -276,7 +269,7 @@ pub impl Arena { unsafe { // XXX: Borrow check let this = transmute_mut_region(self); - if !rusti::needs_drop::() { + if !intrinsics::needs_drop::() { return this.alloc_pod(op); } // XXX: Borrow check diff --git a/src/libstd/priority_queue.rs b/src/libstd/priority_queue.rs index 2f5d12d08073b..f1e0027146c9e 100644 --- a/src/libstd/priority_queue.rs +++ b/src/libstd/priority_queue.rs @@ -11,8 +11,9 @@ //! A priority queue implemented with a binary heap use core::old_iter::BaseIter; +use core::unstable::intrinsics::{move_val_init, init}; +use core::unstable::intrinsics::uninit; use core::util::{replace, swap}; -use core::unstable::intrinsics::{init, move_val_init}; pub struct PriorityQueue { priv data: ~[T], From 7ffd5233548b841b770b05a915ac6d103334c64f Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Wed, 15 May 2013 19:08:50 -0700 Subject: [PATCH 133/248] core: Update clone docs --- src/libcore/clone.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 2650b96c4083c..2965b31a8c390 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -25,8 +25,9 @@ by convention implementing the `Clone` trait and calling the use core::kinds::Const; pub trait Clone { - /// Return a deep copy of the owned object tree. Types with shared ownership like managed boxes - /// are cloned with a shallow copy. + /// Returns a copy of the value. The contents of owned pointers + /// are copied to maintain uniqueness, while the contents of + /// managed pointers are not copied. fn clone(&self) -> Self; } @@ -85,8 +86,9 @@ clone_impl!(bool) clone_impl!(char) pub trait DeepClone { - /// Return a deep copy of the object tree. Types with shared ownership are also copied via a - /// deep copy, unlike `Clone`. + /// Return a deep copy of the value. Unlike `Clone`, the contents of shared pointer types + /// *are* copied. Note that this is currently unimplemented for managed boxes, as + /// it would need to handle cycles, but it is implemented for other smart-pointer types. fn deep_clone(&self) -> Self; } From f03c9bd08cde6c83306d91bb07c4810b8b8f13ba Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 18 May 2013 00:44:47 -0700 Subject: [PATCH 134/248] core::rt: Rename WorkQueue methods, remove extra push method --- src/libcore/rt/sched.rs | 4 ++-- src/libcore/rt/work_queue.rs | 16 ++++++---------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 7fd40fb329f47..7099ae865e934 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -112,7 +112,7 @@ pub impl Scheduler { /// to run it later. Always use this instead of pushing to the work queue /// directly. fn enqueue_task(&mut self, task: ~Coroutine) { - self.work_queue.push_front(task); + self.work_queue.push(task); self.event_loop.callback(resume_task_from_queue); fn resume_task_from_queue() { @@ -129,7 +129,7 @@ pub impl Scheduler { rtdebug!("looking in work queue for task to schedule"); let mut this = self; - match this.work_queue.pop_front() { + match this.work_queue.pop() { Some(task) => { rtdebug!("resuming task from work queue"); this.resume_task_immediately(task); diff --git a/src/libcore/rt/work_queue.rs b/src/libcore/rt/work_queue.rs index f82b5847ef2b8..7011b4ebc1040 100644 --- a/src/libcore/rt/work_queue.rs +++ b/src/libcore/rt/work_queue.rs @@ -23,25 +23,21 @@ pub impl WorkQueue { } } - fn push_back(&mut self, value: T) { - self.queue.push(value) + fn push(&mut self, value: T) { + self.queue.unshift(value) } - fn pop_back(&mut self) -> Option { + fn pop(&mut self) -> Option { if !self.queue.is_empty() { - Some(self.queue.pop()) + Some(self.queue.shift()) } else { None } } - fn push_front(&mut self, value: T) { - self.queue.unshift(value) - } - - fn pop_front(&mut self) -> Option { + fn steal(&mut self) -> Option { if !self.queue.is_empty() { - Some(self.queue.shift()) + Some(self.queue.pop()) } else { None } From ee06ed2bfd233b57c5989696bb723bddf6569622 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 18 May 2013 01:07:16 -0700 Subject: [PATCH 135/248] core::rt: Put a lock on the work queue --- src/libcore/rt/work_queue.rs | 35 ++++++++++++++++++++++------------- 1 file changed, 22 insertions(+), 13 deletions(-) diff --git a/src/libcore/rt/work_queue.rs b/src/libcore/rt/work_queue.rs index 7011b4ebc1040..31f73cd09b54d 100644 --- a/src/libcore/rt/work_queue.rs +++ b/src/libcore/rt/work_queue.rs @@ -11,39 +11,48 @@ use container::Container; use option::*; use vec::OwnedVector; +use unstable::sync::{Exclusive, exclusive}; +use cell::Cell; +use kinds::Owned; pub struct WorkQueue { - priv queue: ~[T] + // XXX: Another mystery bug fixed by boxing this lock + priv queue: ~Exclusive<~[T]> } -pub impl WorkQueue { +pub impl WorkQueue { fn new() -> WorkQueue { WorkQueue { - queue: ~[] + queue: ~exclusive(~[]) } } fn push(&mut self, value: T) { - self.queue.unshift(value) + let value = Cell(value); + self.queue.with(|q| q.unshift(value.take()) ); } fn pop(&mut self) -> Option { - if !self.queue.is_empty() { - Some(self.queue.shift()) - } else { - None + do self.queue.with |q| { + if !q.is_empty() { + Some(q.shift()) + } else { + None + } } } fn steal(&mut self) -> Option { - if !self.queue.is_empty() { - Some(self.queue.pop()) - } else { - None + do self.queue.with |q| { + if !q.is_empty() { + Some(q.pop()) + } else { + None + } } } fn is_empty(&self) -> bool { - return self.queue.is_empty(); + self.queue.with_imm(|q| q.is_empty() ) } } From d2a1378ed8dd3693511836fdee656d8f79089a73 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 18 May 2013 01:38:44 -0700 Subject: [PATCH 136/248] core::rt: Add MessageQueue type This is the queue used to send messages to Schedulers --- src/libcore/rt/message_queue.rs | 44 +++++++++++++++++++++++++++++++++ src/libcore/rt/mod.rs | 5 +++- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/libcore/rt/message_queue.rs diff --git a/src/libcore/rt/message_queue.rs b/src/libcore/rt/message_queue.rs new file mode 100644 index 0000000000000..014e71d3de689 --- /dev/null +++ b/src/libcore/rt/message_queue.rs @@ -0,0 +1,44 @@ +// 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. + +use container::Container; +use kinds::Owned; +use vec::OwnedVector; +use cell::Cell; +use option::*; +use unstable::sync::{Exclusive, exclusive}; + +pub struct MessageQueue { + // XXX: Another mystery bug fixed by boxing this lock + priv queue: ~Exclusive<~[T]> +} + +impl MessageQueue { + pub fn new() -> MessageQueue { + MessageQueue { + queue: ~exclusive(~[]) + } + } + + pub fn push(&mut self, value: T) { + let value = Cell(value); + self.queue.with(|q| q.push(value.take()) ); + } + + pub fn pop(&mut self) -> Option { + do self.queue.with |q| { + if !q.is_empty() { + Some(q.shift()) + } else { + None + } + } + } +} \ No newline at end of file diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 4dce9da505b5f..3d51345336f3b 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -91,9 +91,12 @@ pub mod uv; /// Bindings to pthread/windows thread-local storage. pub mod thread_local_storage; -/// A parallel work-stealing dequeue. +/// A parallel work-stealing deque. mod work_queue; +/// A parallel queue. +mod message_queue; + /// Stack segments and caching. mod stack; From fa18a861fbd934c295990e59b20c7a0498b88f08 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sat, 18 May 2013 01:53:40 -0700 Subject: [PATCH 137/248] core::rt: Queues MessageQueue and WorkQueue are cloneable --- src/libcore/rt/message_queue.rs | 11 ++++++++++- src/libcore/rt/work_queue.rs | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/libcore/rt/message_queue.rs b/src/libcore/rt/message_queue.rs index 014e71d3de689..eaab9288ac8d0 100644 --- a/src/libcore/rt/message_queue.rs +++ b/src/libcore/rt/message_queue.rs @@ -14,6 +14,7 @@ use vec::OwnedVector; use cell::Cell; use option::*; use unstable::sync::{Exclusive, exclusive}; +use clone::Clone; pub struct MessageQueue { // XXX: Another mystery bug fixed by boxing this lock @@ -41,4 +42,12 @@ impl MessageQueue { } } } -} \ No newline at end of file +} + +impl Clone for MessageQueue { + fn clone(&self) -> MessageQueue { + MessageQueue { + queue: self.queue.clone() + } + } +} diff --git a/src/libcore/rt/work_queue.rs b/src/libcore/rt/work_queue.rs index 31f73cd09b54d..e9eb663392b24 100644 --- a/src/libcore/rt/work_queue.rs +++ b/src/libcore/rt/work_queue.rs @@ -14,6 +14,7 @@ use vec::OwnedVector; use unstable::sync::{Exclusive, exclusive}; use cell::Cell; use kinds::Owned; +use clone::Clone; pub struct WorkQueue { // XXX: Another mystery bug fixed by boxing this lock @@ -56,3 +57,11 @@ pub impl WorkQueue { self.queue.with_imm(|q| q.is_empty() ) } } + +impl Clone for WorkQueue { + fn clone(&self) -> WorkQueue { + WorkQueue { + queue: self.queue.clone() + } + } +} From b0722c55f8205a43a0b8124ca179dada766c23ed Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 01:04:01 -0700 Subject: [PATCH 138/248] core:rt:: Rename LocalServices to Task --- src/libcore/logging.rs | 2 +- src/libcore/rt/mod.rs | 16 ++----- src/libcore/rt/sched.rs | 14 +++--- src/libcore/rt/{local_services.rs => task.rs} | 47 +++++++++---------- src/libcore/rt/test.rs | 38 +++++++-------- src/libcore/sys.rs | 6 +-- src/libcore/task/local_data_priv.rs | 8 ++-- src/libcore/task/mod.rs | 4 +- src/libcore/unstable/lang.rs | 10 ++-- 9 files changed, 67 insertions(+), 78 deletions(-) rename src/libcore/rt/{local_services.rs => task.rs} (83%) diff --git a/src/libcore/logging.rs b/src/libcore/logging.rs index e137c5d3034d2..16a80866cf1ab 100644 --- a/src/libcore/logging.rs +++ b/src/libcore/logging.rs @@ -67,7 +67,7 @@ pub fn log_type(level: u32, object: &T) { fn newsched_log_str(msg: ~str) { unsafe { - match rt::local_services::unsafe_try_borrow_local_services() { + match rt::task::unsafe_try_borrow_local_task() { Some(local) => { // Use the available logger (*local).logger.log(Left(msg)); diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 3d51345336f3b..208a6de46e822 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -31,14 +31,8 @@ access to the global heap. Unlike most of `rt` the global heap is truly a global resource and generally operates independently of the rest of the runtime. -All other runtime features are 'local', either thread-local or -task-local. Those critical to the functioning of the language are -defined in the module `local_services`. Local services are those which -are expected to be available to Rust code generally but rely on -thread- or task-local state. These currently include the local heap, +All other runtime features are task-local, including the local heap, the garbage collector, local storage, logging and the stack unwinder. -Local services are primarily implemented for tasks, but may also -be implemented for use outside of tasks. The relationship between `rt` and the rest of the core library is not entirely clear yet and some modules will be moving into or @@ -67,7 +61,10 @@ use ptr::Ptr; /// The global (exchange) heap. pub mod global_heap; -/// The Scheduler and Coroutine types. +/// Implementations of language-critical runtime features like @. +pub mod task; + +/// The coroutine task scheduler, built on the `io` event loop. mod sched; /// Thread-local access to the current Scheduler. @@ -77,9 +74,6 @@ pub mod local_sched; #[path = "io/mod.rs"] pub mod io; -/// Thread-local implementations of language-critical runtime features like @. -pub mod local_services; - /// The EventLoop and internal synchronous I/O interface. mod rtio; diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 7099ae865e934..4b2165b4d2ae3 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -16,7 +16,7 @@ use super::work_queue::WorkQueue; use super::stack::{StackPool, StackSegment}; use super::rtio::{EventLoop, EventLoopObject}; use super::context::Context; -use super::local_services::LocalServices; +use super::task::Task; use cell::Cell; // A more convenient name for external callers, e.g. `local_sched::take()` @@ -350,16 +350,16 @@ pub struct Coroutine { /// the task is dead priv saved_context: Context, /// The heap, GC, unwinding, local storage, logging - local_services: LocalServices + task: Task } pub impl Coroutine { fn new(stack_pool: &mut StackPool, start: ~fn()) -> Coroutine { - Coroutine::with_local(stack_pool, LocalServices::new(), start) + Coroutine::with_task(stack_pool, Task::new(), start) } - fn with_local(stack_pool: &mut StackPool, - local_services: LocalServices, + fn with_task(stack_pool: &mut StackPool, + task: Task, start: ~fn()) -> Coroutine { let start = Coroutine::build_start_wrapper(start); let mut stack = stack_pool.take_segment(MIN_STACK_SIZE); @@ -368,7 +368,7 @@ pub impl Coroutine { return Coroutine { current_stack_segment: stack, saved_context: initial_context, - local_services: local_services + task: task }; } @@ -385,7 +385,7 @@ pub impl Coroutine { let sched = local_sched::unsafe_borrow(); let task = (*sched).current_task.get_mut_ref(); // FIXME #6141: shouldn't neet to put `start()` in another closure - task.local_services.run(||start()); + task.task.run(||start()); } let sched = local_sched::take(); diff --git a/src/libcore/rt/local_services.rs b/src/libcore/rt/task.rs similarity index 83% rename from src/libcore/rt/local_services.rs rename to src/libcore/rt/task.rs index 8d6873be8cd56..c3832d1338ad0 100644 --- a/src/libcore/rt/local_services.rs +++ b/src/libcore/rt/task.rs @@ -13,11 +13,6 @@ //! local storage, and logging. Even a 'freestanding' Rust would likely want //! to implement this. -//! Local services may exist in at least three different contexts: -//! when running as a task, when running in the scheduler's context, -//! or when running outside of a scheduler but with local services -//! (freestanding rust with local services?). - use prelude::*; use libc::{c_void, uintptr_t}; use cast::transmute; @@ -25,7 +20,7 @@ use super::sched::local_sched; use super::local_heap::LocalHeap; use rt::logging::StdErrLogger; -pub struct LocalServices { +pub struct Task { heap: LocalHeap, gc: GarbageCollector, storage: LocalStorage, @@ -41,9 +36,9 @@ pub struct Unwinder { unwinding: bool, } -impl LocalServices { - pub fn new() -> LocalServices { - LocalServices { +impl Task { + pub fn new() -> Task { + Task { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(ptr::null(), None), @@ -53,8 +48,8 @@ impl LocalServices { } } - pub fn without_unwinding() -> LocalServices { - LocalServices { + pub fn without_unwinding() -> Task { + Task { heap: LocalHeap::new(), gc: GarbageCollector, storage: LocalStorage(ptr::null(), None), @@ -66,9 +61,9 @@ impl LocalServices { pub fn run(&mut self, f: &fn()) { // This is just an assertion that `run` was called unsafely - // and this instance of LocalServices is still accessible. - do borrow_local_services |sched| { - assert!(ptr::ref_eq(sched, self)); + // and this instance of Task is still accessible. + do borrow_local_task |task| { + assert!(ptr::ref_eq(task, self)); } match self.unwinder { @@ -86,14 +81,14 @@ impl LocalServices { /// Must be called manually before finalization to clean up /// thread-local resources. Some of the routines here expect - /// LocalServices to be available recursively so this must be - /// called unsafely, without removing LocalServices from + /// Task to be available recursively so this must be + /// called unsafely, without removing Task from /// thread-local-storage. fn destroy(&mut self) { // This is just an assertion that `destroy` was called unsafely - // and this instance of LocalServices is still accessible. - do borrow_local_services |sched| { - assert!(ptr::ref_eq(sched, self)); + // and this instance of Task is still accessible. + do borrow_local_task |task| { + assert!(ptr::ref_eq(task, self)); } match self.storage { LocalStorage(ptr, Some(ref dtor)) => { @@ -105,7 +100,7 @@ impl LocalServices { } } -impl Drop for LocalServices { +impl Drop for Task { fn finalize(&self) { assert!(self.destroyed) } } @@ -156,11 +151,11 @@ impl Unwinder { /// Borrow a pointer to the installed local services. /// Fails (likely aborting the process) if local services are not available. -pub fn borrow_local_services(f: &fn(&mut LocalServices)) { +pub fn borrow_local_task(f: &fn(&mut Task)) { do local_sched::borrow |sched| { match sched.current_task { Some(~ref mut task) => { - f(&mut task.local_services) + f(&mut task.task) } None => { fail!("no local services for schedulers yet") @@ -169,10 +164,10 @@ pub fn borrow_local_services(f: &fn(&mut LocalServices)) { } } -pub unsafe fn unsafe_borrow_local_services() -> *mut LocalServices { +pub unsafe fn unsafe_borrow_local_task() -> *mut Task { match (*local_sched::unsafe_borrow()).current_task { Some(~ref mut task) => { - let s: *mut LocalServices = &mut task.local_services; + let s: *mut Task = &mut task.task; return s; } None => { @@ -182,9 +177,9 @@ pub unsafe fn unsafe_borrow_local_services() -> *mut LocalServices { } } -pub unsafe fn unsafe_try_borrow_local_services() -> Option<*mut LocalServices> { +pub unsafe fn unsafe_try_borrow_local_task() -> Option<*mut Task> { if local_sched::exists() { - Some(unsafe_borrow_local_services()) + Some(unsafe_borrow_local_task()) } else { None } diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index d739d0110ba35..c3e52594d6e77 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -13,7 +13,7 @@ use option::*; use cell::Cell; use result::{Result, Ok, Err}; use super::io::net::ip::{IpAddr, Ipv4}; -use rt::local_services::LocalServices; +use rt::task::Task; use rt::thread::Thread; /// Creates a new scheduler in a new thread and runs a task in it, @@ -28,9 +28,9 @@ pub fn run_in_newsched_task(f: ~fn()) { do run_in_bare_thread { let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~Coroutine::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f.take()); + let task = ~Coroutine::with_task(&mut sched.stack_pool, + Task::without_unwinding(), + f.take()); sched.enqueue_task(task); sched.run(); } @@ -41,9 +41,9 @@ pub fn spawntask(f: ~fn()) { use super::sched::*; let mut sched = local_sched::take(); - let task = ~Coroutine::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_task(&mut sched.stack_pool, + Task::without_unwinding(), + f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); let sched = local_sched::take(); @@ -56,9 +56,9 @@ pub fn spawntask_immediately(f: ~fn()) { use super::sched::*; let mut sched = local_sched::take(); - let task = ~Coroutine::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_task(&mut sched.stack_pool, + Task::without_unwinding(), + f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); do local_sched::borrow |sched| { @@ -72,9 +72,9 @@ pub fn spawntask_later(f: ~fn()) { use super::sched::*; let mut sched = local_sched::take(); - let task = ~Coroutine::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_task(&mut sched.stack_pool, + Task::without_unwinding(), + f); sched.enqueue_task(task); local_sched::put(sched); @@ -89,9 +89,9 @@ pub fn spawntask_random(f: ~fn()) { let run_now: bool = Rand::rand(&mut rng); let mut sched = local_sched::take(); - let task = ~Coroutine::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f); + let task = ~Coroutine::with_task(&mut sched.stack_pool, + Task::without_unwinding(), + f); if run_now { do sched.switch_running_tasks_and_then(task) |task| { @@ -155,9 +155,9 @@ pub fn spawntask_thread(f: ~fn()) -> Thread { let f = Cell(f); let thread = do Thread::start { let mut sched = ~UvEventLoop::new_scheduler(); - let task = ~Coroutine::with_local(&mut sched.stack_pool, - LocalServices::without_unwinding(), - f.take()); + let task = ~Coroutine::with_task(&mut sched.stack_pool, + Task::without_unwinding(), + f.take()); sched.enqueue_task(task); sched.run(); }; diff --git a/src/libcore/sys.rs b/src/libcore/sys.rs index fc57cf40d1e01..c21ce5213142b 100644 --- a/src/libcore/sys.rs +++ b/src/libcore/sys.rs @@ -204,7 +204,7 @@ impl FailWithCause for &'static str { pub fn begin_unwind_(msg: *c_char, file: *c_char, line: size_t) -> ! { use option::Option; use rt::{context, OldTaskContext, TaskContext}; - use rt::local_services::{unsafe_borrow_local_services, Unwinder}; + use rt::task::{unsafe_borrow_local_task, Unwinder}; let context = context(); match context { @@ -233,8 +233,8 @@ pub fn begin_unwind_(msg: *c_char, file: *c_char, line: size_t) -> ! { gc::cleanup_stack_for_failure(); - let local_services = unsafe_borrow_local_services(); - let unwinder: &mut Option = &mut (*local_services).unwinder; + let task = unsafe_borrow_local_task(); + let unwinder: &mut Option = &mut (*task).unwinder; match *unwinder { Some(ref mut unwinder) => unwinder.begin_unwind(), None => abort!("failure without unwinder. aborting process") diff --git a/src/libcore/task/local_data_priv.rs b/src/libcore/task/local_data_priv.rs index be4e639e94c32..6871dd3aecd88 100644 --- a/src/libcore/task/local_data_priv.rs +++ b/src/libcore/task/local_data_priv.rs @@ -18,7 +18,7 @@ use task::rt; use local_data::LocalDataKey; use super::rt::rust_task; -use rt::local_services::LocalStorage; +use rt::task::LocalStorage; pub enum Handle { OldHandle(*rust_task), @@ -28,15 +28,15 @@ pub enum Handle { impl Handle { pub fn new() -> Handle { use rt::{context, OldTaskContext}; - use rt::local_services::unsafe_borrow_local_services; + use rt::task::unsafe_borrow_local_task; unsafe { match context() { OldTaskContext => { OldHandle(rt::rust_get_task()) } _ => { - let local_services = unsafe_borrow_local_services(); - NewHandle(&mut (*local_services).storage) + let task = unsafe_borrow_local_task(); + NewHandle(&mut (*task).storage) } } } diff --git a/src/libcore/task/mod.rs b/src/libcore/task/mod.rs index f06b5abf04f01..372a9f6defaff 100644 --- a/src/libcore/task/mod.rs +++ b/src/libcore/task/mod.rs @@ -504,7 +504,7 @@ pub fn failing() -> bool { //! True if the running task has failed use rt::{context, OldTaskContext}; - use rt::local_services::borrow_local_services; + use rt::task::borrow_local_task; match context() { OldTaskContext => { @@ -514,7 +514,7 @@ pub fn failing() -> bool { } _ => { let mut unwinding = false; - do borrow_local_services |local| { + do borrow_local_task |local| { unwinding = match local.unwinder { Some(unwinder) => { unwinder.unwinding diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index 1ae657849c424..1efe5d0d1a41d 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -17,7 +17,7 @@ use managed::raw::BoxRepr; use str; use sys; use rt::{context, OldTaskContext}; -use rt::local_services::borrow_local_services; +use rt::task::borrow_local_task; use option::{Option, Some, None}; use io; use rt::global_heap; @@ -243,8 +243,8 @@ pub unsafe fn local_malloc(td: *c_char, size: uintptr_t) -> *c_char { } _ => { let mut alloc = ::ptr::null(); - do borrow_local_services |srv| { - alloc = srv.heap.alloc(td as *c_void, size as uint) as *c_char; + do borrow_local_task |task| { + alloc = task.heap.alloc(td as *c_void, size as uint) as *c_char; } return alloc; } @@ -261,8 +261,8 @@ pub unsafe fn local_free(ptr: *c_char) { rustrt::rust_upcall_free_noswitch(ptr); } _ => { - do borrow_local_services |srv| { - srv.heap.free(ptr as *c_void); + do borrow_local_task |task| { + task.heap.free(ptr as *c_void); } } } From 43c6f32ece85a7df86ee041771a54c097dae6a13 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 01:13:53 -0700 Subject: [PATCH 139/248] core::rt: Add Local trait --- src/libcore/rt/local.rs | 17 +++++++++++++++++ src/libcore/rt/mod.rs | 4 ++++ 2 files changed, 21 insertions(+) create mode 100644 src/libcore/rt/local.rs diff --git a/src/libcore/rt/local.rs b/src/libcore/rt/local.rs new file mode 100644 index 0000000000000..ec54bcb99dd7f --- /dev/null +++ b/src/libcore/rt/local.rs @@ -0,0 +1,17 @@ +// 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. + +pub trait Local { + fn put_local(value: ~Self); + fn take_local() -> ~Self; + fn exists() -> bool; + fn borrow(f: &fn(&mut Self)); + fn unsafe_borrow() -> *mut Self; +} diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 208a6de46e822..37ac6ad3365c3 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -81,6 +81,10 @@ mod rtio; #[path = "uv/mod.rs"] pub mod uv; +/// The Local trait for types that are accessible via thread-local +/// or task-local storage. +pub mod local; + // FIXME #5248: The import in `sched` doesn't resolve unless this is pub! /// Bindings to pthread/windows thread-local storage. pub mod thread_local_storage; From f59fcd5d5f7ba94f7c705eb2c081760dd2213067 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 14:05:20 -0700 Subject: [PATCH 140/248] core::rt: Store Task as a ~ pointer --- src/libcore/rt/sched.rs | 6 +++--- src/libcore/rt/task.rs | 4 ++-- src/libcore/rt/test.rs | 12 ++++++------ 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 4b2165b4d2ae3..3abbb1f79e596 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -350,16 +350,16 @@ pub struct Coroutine { /// the task is dead priv saved_context: Context, /// The heap, GC, unwinding, local storage, logging - task: Task + task: ~Task } pub impl Coroutine { fn new(stack_pool: &mut StackPool, start: ~fn()) -> Coroutine { - Coroutine::with_task(stack_pool, Task::new(), start) + Coroutine::with_task(stack_pool, ~Task::new(), start) } fn with_task(stack_pool: &mut StackPool, - task: Task, + task: ~Task, start: ~fn()) -> Coroutine { let start = Coroutine::build_start_wrapper(start); let mut stack = stack_pool.take_segment(MIN_STACK_SIZE); diff --git a/src/libcore/rt/task.rs b/src/libcore/rt/task.rs index c3832d1338ad0..65b7c885b5735 100644 --- a/src/libcore/rt/task.rs +++ b/src/libcore/rt/task.rs @@ -155,7 +155,7 @@ pub fn borrow_local_task(f: &fn(&mut Task)) { do local_sched::borrow |sched| { match sched.current_task { Some(~ref mut task) => { - f(&mut task.task) + f(&mut *task.task) } None => { fail!("no local services for schedulers yet") @@ -167,7 +167,7 @@ pub fn borrow_local_task(f: &fn(&mut Task)) { pub unsafe fn unsafe_borrow_local_task() -> *mut Task { match (*local_sched::unsafe_borrow()).current_task { Some(~ref mut task) => { - let s: *mut Task = &mut task.task; + let s: *mut Task = &mut *task.task; return s; } None => { diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index c3e52594d6e77..66993041752cf 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -29,7 +29,7 @@ pub fn run_in_newsched_task(f: ~fn()) { do run_in_bare_thread { let mut sched = ~UvEventLoop::new_scheduler(); let task = ~Coroutine::with_task(&mut sched.stack_pool, - Task::without_unwinding(), + ~Task::without_unwinding(), f.take()); sched.enqueue_task(task); sched.run(); @@ -42,7 +42,7 @@ pub fn spawntask(f: ~fn()) { let mut sched = local_sched::take(); let task = ~Coroutine::with_task(&mut sched.stack_pool, - Task::without_unwinding(), + ~Task::without_unwinding(), f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); @@ -57,7 +57,7 @@ pub fn spawntask_immediately(f: ~fn()) { let mut sched = local_sched::take(); let task = ~Coroutine::with_task(&mut sched.stack_pool, - Task::without_unwinding(), + ~Task::without_unwinding(), f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); @@ -73,7 +73,7 @@ pub fn spawntask_later(f: ~fn()) { let mut sched = local_sched::take(); let task = ~Coroutine::with_task(&mut sched.stack_pool, - Task::without_unwinding(), + ~Task::without_unwinding(), f); sched.enqueue_task(task); @@ -90,7 +90,7 @@ pub fn spawntask_random(f: ~fn()) { let mut sched = local_sched::take(); let task = ~Coroutine::with_task(&mut sched.stack_pool, - Task::without_unwinding(), + ~Task::without_unwinding(), f); if run_now { @@ -156,7 +156,7 @@ pub fn spawntask_thread(f: ~fn()) -> Thread { let thread = do Thread::start { let mut sched = ~UvEventLoop::new_scheduler(); let task = ~Coroutine::with_task(&mut sched.stack_pool, - Task::without_unwinding(), + ~Task::without_unwinding(), f.take()); sched.enqueue_task(task); sched.run(); From 86ba4573498ef251933fcc784d513c7586dfaae1 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 14:24:36 -0700 Subject: [PATCH 141/248] rt: Rename rust_initialize_global_state to rust_initialize_rt_tls_key --- src/libcore/rt/local_sched.rs | 10 ++++++++++ src/libcore/rt/sched.rs | 7 ++----- src/rt/rust_builtin.cpp | 4 ++-- src/rt/rustrt.def.in | 2 +- 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index 895354d2218e5..5f7f8509a7b22 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -23,6 +23,16 @@ use unstable::finally::Finally; #[cfg(test)] use rt::uv::uvio::UvEventLoop; +/// Initialize the TLS key. Other ops will fail if this isn't executed first. +pub fn init_tls_key() { + unsafe { + rust_initialize_rt_tls_key(); + extern { + fn rust_initialize_rt_tls_key(); + } + } +} + /// Give the Scheduler to thread-local storage pub fn put(sched: ~Scheduler) { unsafe { diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 3abbb1f79e596..0cdc4e9602bad 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -64,11 +64,8 @@ pub impl Scheduler { fn new(event_loop: ~EventLoopObject) -> Scheduler { - // Lazily initialize the global state, currently the scheduler TLS key - unsafe { rust_initialize_global_state(); } - extern { - fn rust_initialize_global_state(); - } + // Lazily initialize the scheduler TLS key + local_sched::init_tls_key(); Scheduler { event_loop: event_loop, diff --git a/src/rt/rust_builtin.cpp b/src/rt/rust_builtin.cpp index 1a64066b5a946..a2f253550af16 100644 --- a/src/rt/rust_builtin.cpp +++ b/src/rt/rust_builtin.cpp @@ -840,9 +840,9 @@ rust_get_rt_tls_key() { return &rt_key; } -// Initialize the global state required by the new scheduler +// Initialize the TLS key used by the new scheduler extern "C" CDECL void -rust_initialize_global_state() { +rust_initialize_rt_tls_key() { static lock_and_signal init_lock; static bool initialized = false; diff --git a/src/rt/rustrt.def.in b/src/rt/rustrt.def.in index cdc282440b830..e3e522aa7ceec 100644 --- a/src/rt/rustrt.def.in +++ b/src/rt/rustrt.def.in @@ -222,7 +222,7 @@ rust_uv_ip4_addrp rust_uv_ip6_addrp rust_uv_free_ip4_addr rust_uv_free_ip6_addr -rust_initialize_global_state +rust_initialize_rt_tls_key rust_dbg_next_port rust_new_memory_region rust_delete_memory_region From 97c2fd1a965b3af037fa22c911dfb618f818c172 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 14:39:46 -0700 Subject: [PATCH 142/248] core::rt: Move some TLS functions from local_sched to local_ptr --- src/libcore/rt/local_ptr.rs | 63 +++++++++++++++++++++++++++++++++++ src/libcore/rt/local_sched.rs | 58 ++++---------------------------- src/libcore/rt/mod.rs | 13 +++++--- src/libcore/rt/sched.rs | 7 ++-- 4 files changed, 82 insertions(+), 59 deletions(-) create mode 100644 src/libcore/rt/local_ptr.rs diff --git a/src/libcore/rt/local_ptr.rs b/src/libcore/rt/local_ptr.rs new file mode 100644 index 0000000000000..3d706fbbdae19 --- /dev/null +++ b/src/libcore/rt/local_ptr.rs @@ -0,0 +1,63 @@ +// 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. + +//! Access to a single thread-local pointer + +use libc::c_void; +use cast; +use option::{Option, Some, None}; +use tls = rt::thread_local_storage; + +/// Initialize the TLS key. Other ops will fail if this isn't executed first. +pub fn init_tls_key() { + unsafe { + rust_initialize_rt_tls_key(); + extern { + fn rust_initialize_rt_tls_key(); + } + } +} + +pub fn tls_key() -> tls::Key { + match maybe_tls_key() { + Some(key) => key, + None => abort!("runtime tls key not initialized") + } +} + +pub fn maybe_tls_key() -> Option { + unsafe { + let key: *mut c_void = rust_get_rt_tls_key(); + let key: &mut tls::Key = cast::transmute(key); + let key = *key; + // Check that the key has been initialized. + + // NB: This is a little racy because, while the key is + // initalized under a mutex and it's assumed to be initalized + // in the Scheduler ctor by any thread that needs to use it, + // we are not accessing the key under a mutex. Threads that + // are not using the new Scheduler but still *want to check* + // whether they are running under a new Scheduler may see a 0 + // value here that is in the process of being initialized in + // another thread. I think this is fine since the only action + // they could take if it was initialized would be to check the + // thread-local value and see that it's not set. + if key != -1 { + return Some(key); + } else { + return None; + } + } +} + +extern { + #[fast_ffi] + fn rust_get_rt_tls_key() -> *mut c_void; +} diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index 5f7f8509a7b22..6b3bc373d2210 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -18,25 +18,16 @@ use cell::Cell; use rt::sched::Scheduler; use rt::rtio::{EventLoop, IoFactoryObject}; -use tls = rt::thread_local_storage; use unstable::finally::Finally; +use rt::local_ptr; +use tls = rt::thread_local_storage; #[cfg(test)] use rt::uv::uvio::UvEventLoop; -/// Initialize the TLS key. Other ops will fail if this isn't executed first. -pub fn init_tls_key() { - unsafe { - rust_initialize_rt_tls_key(); - extern { - fn rust_initialize_rt_tls_key(); - } - } -} - /// Give the Scheduler to thread-local storage pub fn put(sched: ~Scheduler) { unsafe { - let key = tls_key(); + let key = local_ptr::tls_key(); let void_sched: *mut c_void = cast::transmute(sched); tls::set(key, void_sched); } @@ -45,7 +36,7 @@ pub fn put(sched: ~Scheduler) { /// Take ownership of the Scheduler from thread-local storage pub fn take() -> ~Scheduler { unsafe { - let key = tls_key(); + let key = local_ptr::tls_key(); let void_sched: *mut c_void = tls::get(key); rtassert!(void_sched.is_not_null()); let sched: ~Scheduler = cast::transmute(void_sched); @@ -57,7 +48,7 @@ pub fn take() -> ~Scheduler { /// Check whether there is a thread-local Scheduler attached to the running thread pub fn exists() -> bool { unsafe { - match maybe_tls_key() { + match local_ptr::maybe_tls_key() { Some(key) => tls::get(key).is_not_null(), None => false } @@ -89,7 +80,7 @@ pub fn borrow(f: &fn(&mut Scheduler)) { /// Because this leaves the Scheduler in thread-local storage it is possible /// For the Scheduler pointer to be aliased pub unsafe fn unsafe_borrow() -> *mut Scheduler { - let key = tls_key(); + let key = local_ptr::tls_key(); let mut void_sched: *mut c_void = tls::get(key); rtassert!(void_sched.is_not_null()); { @@ -106,43 +97,6 @@ pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { return io; } -fn tls_key() -> tls::Key { - match maybe_tls_key() { - Some(key) => key, - None => abort!("runtime tls key not initialized") - } -} - -fn maybe_tls_key() -> Option { - unsafe { - let key: *mut c_void = rust_get_rt_tls_key(); - let key: &mut tls::Key = cast::transmute(key); - let key = *key; - // Check that the key has been initialized. - - // NB: This is a little racy because, while the key is - // initalized under a mutex and it's assumed to be initalized - // in the Scheduler ctor by any thread that needs to use it, - // we are not accessing the key under a mutex. Threads that - // are not using the new Scheduler but still *want to check* - // whether they are running under a new Scheduler may see a 0 - // value here that is in the process of being initialized in - // another thread. I think this is fine since the only action - // they could take if it was initialized would be to check the - // thread-local value and see that it's not set. - if key != -1 { - return Some(key); - } else { - return None; - } - } -} - -extern { - #[fast_ffi] - fn rust_get_rt_tls_key() -> *mut c_void; -} - #[test] fn thread_local_scheduler_smoke_test() { let scheduler = ~UvEventLoop::new_scheduler(); diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index 37ac6ad3365c3..bda44b4c67f86 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -85,10 +85,6 @@ pub mod uv; /// or task-local storage. pub mod local; -// FIXME #5248: The import in `sched` doesn't resolve unless this is pub! -/// Bindings to pthread/windows thread-local storage. -pub mod thread_local_storage; - /// A parallel work-stealing deque. mod work_queue; @@ -126,6 +122,15 @@ pub mod tube; /// Simple reimplementation of core::comm pub mod comm; +// FIXME #5248 shouldn't be pub +/// The runtime needs to be able to put a pointer into thread-local storage. +pub mod local_ptr; + +// FIXME #5248: The import in `sched` doesn't resolve unless this is pub! +/// Bindings to pthread/windows thread-local storage. +pub mod thread_local_storage; + + /// Set up a default runtime configuration, given compiler-supplied arguments. /// /// This is invoked by the `start` _language item_ (unstable::lang) to diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 0cdc4e9602bad..8352993278cec 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -11,13 +11,14 @@ use option::*; use sys; use cast::transmute; +use cell::Cell; use super::work_queue::WorkQueue; use super::stack::{StackPool, StackSegment}; use super::rtio::{EventLoop, EventLoopObject}; use super::context::Context; use super::task::Task; -use cell::Cell; +use rt::local_ptr; // A more convenient name for external callers, e.g. `local_sched::take()` pub mod local_sched; @@ -64,8 +65,8 @@ pub impl Scheduler { fn new(event_loop: ~EventLoopObject) -> Scheduler { - // Lazily initialize the scheduler TLS key - local_sched::init_tls_key(); + // Lazily initialize the runtime TLS key + local_ptr::init_tls_key(); Scheduler { event_loop: event_loop, From 71aa6b6631547a7b2e6839931e73286e0bf6ce5d Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 14:57:47 -0700 Subject: [PATCH 143/248] core::rt: Move more TLS functionality into local_ptr --- src/libcore/rt/local_ptr.rs | 96 ++++++++++++++++++++++++++++++++--- src/libcore/rt/local_sched.rs | 56 ++------------------ 2 files changed, 94 insertions(+), 58 deletions(-) diff --git a/src/libcore/rt/local_ptr.rs b/src/libcore/rt/local_ptr.rs index 3d706fbbdae19..80d797e8c6543 100644 --- a/src/libcore/rt/local_ptr.rs +++ b/src/libcore/rt/local_ptr.rs @@ -8,11 +8,19 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Access to a single thread-local pointer +//! Access to a single thread-local pointer. +//! +//! The runtime will use this for storing ~Task. +//! +//! XXX: Add runtime checks for usage of inconsistent pointer types. +//! and for overwriting an existing pointer. use libc::c_void; use cast; +use ptr; +use cell::Cell; use option::{Option, Some, None}; +use unstable::finally::Finally; use tls = rt::thread_local_storage; /// Initialize the TLS key. Other ops will fail if this isn't executed first. @@ -25,14 +33,87 @@ pub fn init_tls_key() { } } -pub fn tls_key() -> tls::Key { +/// Give a pointer to thread-local storage. +/// +/// # Safety note +/// +/// Does not validate the pointer type. +pub unsafe fn put(sched: ~T) { + let key = tls_key(); + let void_ptr: *mut c_void = cast::transmute(sched); + tls::set(key, void_ptr); +} + +/// Take ownership of a pointer from thread-local storage. +/// +/// # Safety note +/// +/// Does not validate the pointer type. +pub unsafe fn take() -> ~T { + let key = tls_key(); + let void_ptr: *mut c_void = tls::get(key); + rtassert!(void_ptr.is_not_null()); + let ptr: ~T = cast::transmute(void_ptr); + tls::set(key, ptr::mut_null()); + return ptr; +} + +/// Check whether there is a thread-local pointer installed. +pub fn exists() -> bool { + unsafe { + match maybe_tls_key() { + Some(key) => tls::get(key).is_not_null(), + None => false + } + } +} + +/// Borrow the thread-local scheduler from thread-local storage. +/// While the scheduler is borrowed it is not available in TLS. +/// +/// # Safety note +/// +/// Does not validate the pointer type. +pub unsafe fn borrow(f: &fn(&mut T)) { + let mut value = take(); + + // XXX: Need a different abstraction from 'finally' here to avoid unsafety + let unsafe_ptr = cast::transmute_mut_region(&mut *value); + let value_cell = Cell(value); + + do (|| { + f(unsafe_ptr); + }).finally { + put(value_cell.take()); + } +} + +/// Borrow a mutable reference to the thread-local Scheduler +/// +/// # Safety Note +/// +/// Because this leaves the Scheduler in thread-local storage it is possible +/// For the Scheduler pointer to be aliased +pub unsafe fn unsafe_borrow() -> *mut T { + let key = tls_key(); + let mut void_sched: *mut c_void = tls::get(key); + rtassert!(void_sched.is_not_null()); + { + let sched: *mut *mut c_void = &mut void_sched; + let sched: *mut ~T = sched as *mut ~T; + let sched: *mut T = &mut **sched; + return sched; + } +} + +fn tls_key() -> tls::Key { match maybe_tls_key() { Some(key) => key, None => abort!("runtime tls key not initialized") } } -pub fn maybe_tls_key() -> Option { +fn maybe_tls_key() -> Option { unsafe { let key: *mut c_void = rust_get_rt_tls_key(); let key: &mut tls::Key = cast::transmute(key); @@ -55,9 +136,10 @@ pub fn maybe_tls_key() -> Option { return None; } } -} -extern { - #[fast_ffi] - fn rust_get_rt_tls_key() -> *mut c_void; + extern { + #[fast_ffi] + fn rust_get_rt_tls_key() -> *mut c_void; + } + } diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index 6b3bc373d2210..e3c0b4c4e8847 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -25,53 +25,17 @@ use tls = rt::thread_local_storage; #[cfg(test)] use rt::uv::uvio::UvEventLoop; /// Give the Scheduler to thread-local storage -pub fn put(sched: ~Scheduler) { - unsafe { - let key = local_ptr::tls_key(); - let void_sched: *mut c_void = cast::transmute(sched); - tls::set(key, void_sched); - } -} +pub fn put(sched: ~Scheduler) { unsafe { local_ptr::put(sched) } } /// Take ownership of the Scheduler from thread-local storage -pub fn take() -> ~Scheduler { - unsafe { - let key = local_ptr::tls_key(); - let void_sched: *mut c_void = tls::get(key); - rtassert!(void_sched.is_not_null()); - let sched: ~Scheduler = cast::transmute(void_sched); - tls::set(key, mut_null()); - return sched; - } -} +pub fn take() -> ~Scheduler { unsafe { local_ptr::take() } } /// Check whether there is a thread-local Scheduler attached to the running thread -pub fn exists() -> bool { - unsafe { - match local_ptr::maybe_tls_key() { - Some(key) => tls::get(key).is_not_null(), - None => false - } - } -} +pub fn exists() -> bool { local_ptr::exists() } /// Borrow the thread-local scheduler from thread-local storage. /// While the scheduler is borrowed it is not available in TLS. -pub fn borrow(f: &fn(&mut Scheduler)) { - let mut sched = take(); - - // XXX: Need a different abstraction from 'finally' here to avoid unsafety - unsafe { - let unsafe_sched = cast::transmute_mut_region(&mut *sched); - let sched = Cell(sched); - - do (|| { - f(unsafe_sched); - }).finally { - put(sched.take()); - } - } -} +pub fn borrow(f: &fn(&mut Scheduler)) { unsafe { local_ptr::borrow(f) } } /// Borrow a mutable reference to the thread-local Scheduler /// @@ -79,17 +43,7 @@ pub fn borrow(f: &fn(&mut Scheduler)) { /// /// Because this leaves the Scheduler in thread-local storage it is possible /// For the Scheduler pointer to be aliased -pub unsafe fn unsafe_borrow() -> *mut Scheduler { - let key = local_ptr::tls_key(); - let mut void_sched: *mut c_void = tls::get(key); - rtassert!(void_sched.is_not_null()); - { - let sched: *mut *mut c_void = &mut void_sched; - let sched: *mut ~Scheduler = sched as *mut ~Scheduler; - let sched: *mut Scheduler = &mut **sched; - return sched; - } -} +pub unsafe fn unsafe_borrow() -> *mut Scheduler { local_ptr::unsafe_borrow() } pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { let sched = unsafe_borrow(); From 18fab45aab8622b0bfbcd336d57652bfb2f4f4ac Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 15:25:35 -0700 Subject: [PATCH 144/248] core::rt: Make local_sched a wrapper around Local --- src/libcore/rt/local.rs | 17 ++++++++++++++--- src/libcore/rt/local_sched.rs | 11 ++++++----- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/libcore/rt/local.rs b/src/libcore/rt/local.rs index ec54bcb99dd7f..09e6ecda6a04a 100644 --- a/src/libcore/rt/local.rs +++ b/src/libcore/rt/local.rs @@ -8,10 +8,21 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use rt::sched::Scheduler; +use rt::local_ptr; + pub trait Local { fn put_local(value: ~Self); fn take_local() -> ~Self; - fn exists() -> bool; - fn borrow(f: &fn(&mut Self)); - fn unsafe_borrow() -> *mut Self; + fn exists_local() -> bool; + fn borrow_local(f: &fn(&mut Self)); + unsafe fn unsafe_borrow_local() -> *mut Self; } + +impl Local for Scheduler { + fn put_local(value: ~Scheduler) { unsafe { local_ptr::put(value) }} + fn take_local() -> ~Scheduler { unsafe { local_ptr::take() } } + fn exists_local() -> bool { local_ptr::exists() } + fn borrow_local(f: &fn(&mut Scheduler)) { unsafe { local_ptr::borrow(f) } } + unsafe fn unsafe_borrow_local() -> *mut Scheduler { local_ptr::unsafe_borrow() } +} \ No newline at end of file diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index e3c0b4c4e8847..8923bb45f58db 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -21,21 +21,22 @@ use rt::rtio::{EventLoop, IoFactoryObject}; use unstable::finally::Finally; use rt::local_ptr; use tls = rt::thread_local_storage; +use rt::local::Local; #[cfg(test)] use rt::uv::uvio::UvEventLoop; /// Give the Scheduler to thread-local storage -pub fn put(sched: ~Scheduler) { unsafe { local_ptr::put(sched) } } +pub fn put(sched: ~Scheduler) { Local::put_local(sched) } /// Take ownership of the Scheduler from thread-local storage -pub fn take() -> ~Scheduler { unsafe { local_ptr::take() } } +pub fn take() -> ~Scheduler { Local::take_local() } /// Check whether there is a thread-local Scheduler attached to the running thread -pub fn exists() -> bool { local_ptr::exists() } +pub fn exists() -> bool { Local::exists_local::() } /// Borrow the thread-local scheduler from thread-local storage. /// While the scheduler is borrowed it is not available in TLS. -pub fn borrow(f: &fn(&mut Scheduler)) { unsafe { local_ptr::borrow(f) } } +pub fn borrow(f: &fn(&mut Scheduler)) { Local::borrow_local(f) } /// Borrow a mutable reference to the thread-local Scheduler /// @@ -43,7 +44,7 @@ pub fn borrow(f: &fn(&mut Scheduler)) { unsafe { local_ptr::borrow(f) } } /// /// Because this leaves the Scheduler in thread-local storage it is possible /// For the Scheduler pointer to be aliased -pub unsafe fn unsafe_borrow() -> *mut Scheduler { local_ptr::unsafe_borrow() } +pub unsafe fn unsafe_borrow() -> *mut Scheduler { Local::unsafe_borrow_local() } pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { let sched = unsafe_borrow(); From 06f1a64bd6e417b73f1b812b860271e86bb42b47 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 15:45:39 -0700 Subject: [PATCH 145/248] core::rt: Convert users of local_sched to Local trait --- src/libcore/rt/comm.rs | 11 ++++--- src/libcore/rt/local.rs | 54 +++++++++++++++++++++++++------ src/libcore/rt/local_sched.rs | 50 +---------------------------- src/libcore/rt/mod.rs | 14 ++++---- src/libcore/rt/sched.rs | 60 ++++++++++++++++++----------------- src/libcore/rt/task.rs | 9 +++--- src/libcore/rt/test.rs | 27 ++++++++-------- src/libcore/rt/tube.rs | 25 ++++++++------- src/libcore/rt/uv/uvio.rs | 35 ++++++++++---------- src/libcore/task/spawn.rs | 3 +- 10 files changed, 143 insertions(+), 145 deletions(-) diff --git a/src/libcore/rt/comm.rs b/src/libcore/rt/comm.rs index 93afbea82786a..544d9817558c6 100644 --- a/src/libcore/rt/comm.rs +++ b/src/libcore/rt/comm.rs @@ -20,7 +20,8 @@ use cast; use util; use ops::Drop; use kinds::Owned; -use rt::sched::Coroutine; +use rt::sched::{Scheduler, Coroutine}; +use rt::local::Local; use rt::local_sched; use unstable::intrinsics::{atomic_xchg, atomic_load}; use util::Void; @@ -127,7 +128,7 @@ impl ChanOne { task_as_state => { // Port is blocked. Wake it up. let recvr: ~Coroutine = cast::transmute(task_as_state); - let sched = local_sched::take(); + let sched = Local::take::(); sched.schedule_task(recvr); } } @@ -157,7 +158,7 @@ impl PortOne { // XXX: Optimize this to not require the two context switches when data is available // Switch to the scheduler to put the ~Task into the Packet state. - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then |task| { unsafe { // Atomically swap the task pointer into the Packet state, issuing @@ -173,7 +174,7 @@ impl PortOne { STATE_ONE => { // Channel is closed. Switch back and check the data. let task: ~Coroutine = cast::transmute(task_as_state); - let sched = local_sched::take(); + let sched = Local::take::(); sched.resume_task_immediately(task); } _ => util::unreachable() @@ -239,7 +240,7 @@ impl Drop for ChanOneHack { // The port is blocked waiting for a message we will never send. Wake it. assert!((*this.packet()).payload.is_none()); let recvr: ~Coroutine = cast::transmute(task_as_state); - let sched = local_sched::take(); + let sched = Local::take::(); sched.schedule_task(recvr); } } diff --git a/src/libcore/rt/local.rs b/src/libcore/rt/local.rs index 09e6ecda6a04a..c054ba68d1082 100644 --- a/src/libcore/rt/local.rs +++ b/src/libcore/rt/local.rs @@ -12,17 +12,51 @@ use rt::sched::Scheduler; use rt::local_ptr; pub trait Local { - fn put_local(value: ~Self); - fn take_local() -> ~Self; - fn exists_local() -> bool; - fn borrow_local(f: &fn(&mut Self)); - unsafe fn unsafe_borrow_local() -> *mut Self; + fn put(value: ~Self); + fn take() -> ~Self; + fn exists() -> bool; + fn borrow(f: &fn(&mut Self)); + unsafe fn unsafe_borrow() -> *mut Self; } impl Local for Scheduler { - fn put_local(value: ~Scheduler) { unsafe { local_ptr::put(value) }} - fn take_local() -> ~Scheduler { unsafe { local_ptr::take() } } - fn exists_local() -> bool { local_ptr::exists() } - fn borrow_local(f: &fn(&mut Scheduler)) { unsafe { local_ptr::borrow(f) } } - unsafe fn unsafe_borrow_local() -> *mut Scheduler { local_ptr::unsafe_borrow() } + fn put(value: ~Scheduler) { unsafe { local_ptr::put(value) }} + fn take() -> ~Scheduler { unsafe { local_ptr::take() } } + fn exists() -> bool { local_ptr::exists() } + fn borrow(f: &fn(&mut Scheduler)) { unsafe { local_ptr::borrow(f) } } + unsafe fn unsafe_borrow() -> *mut Scheduler { local_ptr::unsafe_borrow() } +} + +#[cfg(test)] +mod test { + use rt::sched::Scheduler; + use rt::uv::uvio::UvEventLoop; + use super::*; + + #[test] + fn thread_local_scheduler_smoke_test() { + let scheduler = ~UvEventLoop::new_scheduler(); + Local::put(scheduler); + let _scheduler: ~Scheduler = Local::take(); + } + + #[test] + fn thread_local_scheduler_two_instances() { + let scheduler = ~UvEventLoop::new_scheduler(); + Local::put(scheduler); + let _scheduler: ~Scheduler = Local::take(); + let scheduler = ~UvEventLoop::new_scheduler(); + Local::put(scheduler); + let _scheduler: ~Scheduler = Local::take(); + } + + #[test] + fn borrow_smoke_test() { + let scheduler = ~UvEventLoop::new_scheduler(); + Local::put(scheduler); + unsafe { + let _scheduler: *mut Scheduler = Local::unsafe_borrow(); + } + let _scheduler: ~Scheduler = Local::take(); + } } \ No newline at end of file diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs index 8923bb45f58db..48e3351c44f28 100644 --- a/src/libcore/rt/local_sched.rs +++ b/src/libcore/rt/local_sched.rs @@ -25,56 +25,8 @@ use rt::local::Local; #[cfg(test)] use rt::uv::uvio::UvEventLoop; -/// Give the Scheduler to thread-local storage -pub fn put(sched: ~Scheduler) { Local::put_local(sched) } - -/// Take ownership of the Scheduler from thread-local storage -pub fn take() -> ~Scheduler { Local::take_local() } - -/// Check whether there is a thread-local Scheduler attached to the running thread -pub fn exists() -> bool { Local::exists_local::() } - -/// Borrow the thread-local scheduler from thread-local storage. -/// While the scheduler is borrowed it is not available in TLS. -pub fn borrow(f: &fn(&mut Scheduler)) { Local::borrow_local(f) } - -/// Borrow a mutable reference to the thread-local Scheduler -/// -/// # Safety Note -/// -/// Because this leaves the Scheduler in thread-local storage it is possible -/// For the Scheduler pointer to be aliased -pub unsafe fn unsafe_borrow() -> *mut Scheduler { Local::unsafe_borrow_local() } - pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { - let sched = unsafe_borrow(); + let sched = Local::unsafe_borrow::(); let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); return io; } - -#[test] -fn thread_local_scheduler_smoke_test() { - let scheduler = ~UvEventLoop::new_scheduler(); - put(scheduler); - let _scheduler = take(); -} - -#[test] -fn thread_local_scheduler_two_instances() { - let scheduler = ~UvEventLoop::new_scheduler(); - put(scheduler); - let _scheduler = take(); - let scheduler = ~UvEventLoop::new_scheduler(); - put(scheduler); - let _scheduler = take(); -} - -#[test] -fn borrow_smoke_test() { - let scheduler = ~UvEventLoop::new_scheduler(); - put(scheduler); - unsafe { - let _scheduler = unsafe_borrow(); - } - let _scheduler = take(); -} diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index bda44b4c67f86..c8532f6b94a3a 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -188,16 +188,17 @@ pub enum RuntimeContext { pub fn context() -> RuntimeContext { use task::rt::rust_task; - use self::sched::local_sched; + use self::local::Local; + use self::sched::{local_sched, Scheduler}; // XXX: Hitting TLS twice to check if the scheduler exists // then to check for the task is not good for perf if unsafe { rust_try_get_task().is_not_null() } { return OldTaskContext; } else { - if local_sched::exists() { + if Local::exists::() { let context = ::cell::empty_cell(); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { if sched.in_task_context() { context.put_back(TaskContext); } else { @@ -219,9 +220,10 @@ pub fn context() -> RuntimeContext { #[test] fn test_context() { use unstable::run_in_bare_thread; - use self::sched::{local_sched, Coroutine}; + use self::sched::{local_sched, Scheduler, Coroutine}; use rt::uv::uvio::UvEventLoop; use cell::Cell; + use rt::local::Local; assert_eq!(context(), OldTaskContext); do run_in_bare_thread { @@ -229,11 +231,11 @@ fn test_context() { let mut sched = ~UvEventLoop::new_scheduler(); let task = ~do Coroutine::new(&mut sched.stack_pool) { assert_eq!(context(), TaskContext); - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then() |task| { assert_eq!(context(), SchedulerContext); let task = Cell(task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { sched.enqueue_task(task.take()); } } diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 8352993278cec..0004ef29de02a 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -19,6 +19,7 @@ use super::rtio::{EventLoop, EventLoopObject}; use super::context::Context; use super::task::Task; use rt::local_ptr; +use rt::local::Local; // A more convenient name for external callers, e.g. `local_sched::take()` pub mod local_sched; @@ -94,12 +95,12 @@ pub impl Scheduler { }; // Give ownership of the scheduler (self) to the thread - local_sched::put(self_sched); + Local::put(self_sched); (*event_loop).run(); } - let sched = local_sched::take(); + let sched = Local::take::(); assert!(sched.work_queue.is_empty()); return sched; } @@ -114,7 +115,7 @@ pub impl Scheduler { self.event_loop.callback(resume_task_from_queue); fn resume_task_from_queue() { - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_from_queue(); } } @@ -134,7 +135,7 @@ pub impl Scheduler { } None => { rtdebug!("no tasks in queue"); - local_sched::put(this); + Local::put(this); } } } @@ -150,7 +151,7 @@ pub impl Scheduler { do self.deschedule_running_task_and_then |dead_task| { let dead_task = Cell(dead_task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { dead_task.take().recycle(&mut sched.stack_pool); } } @@ -163,7 +164,7 @@ pub impl Scheduler { do self.switch_running_tasks_and_then(task) |last_task| { let last_task = Cell(last_task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { sched.enqueue_task(last_task.take()); } } @@ -174,7 +175,7 @@ pub impl Scheduler { do self.switch_running_tasks_and_then(task) |last_task| { let last_task = Cell(last_task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { sched.enqueue_task(last_task.take()); } } @@ -192,18 +193,18 @@ pub impl Scheduler { this.current_task = Some(task); this.enqueue_cleanup_job(DoNothing); - local_sched::put(this); + Local::put(this); // Take pointers to both the task and scheduler's saved registers. unsafe { - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); let (sched_context, _, next_task_context) = (*sched).get_contexts(); let next_task_context = next_task_context.unwrap(); // Context switch to the task, restoring it's registers // and saving the scheduler's Context::swap(sched_context, next_task_context); - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); // The running task should have passed ownership elsewhere assert!((*sched).current_task.is_none()); @@ -233,16 +234,16 @@ pub impl Scheduler { this.enqueue_cleanup_job(GiveTask(blocked_task, f_opaque)); } - local_sched::put(this); + Local::put(this); unsafe { - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); let (sched_context, last_task_context, _) = (*sched).get_contexts(); let last_task_context = last_task_context.unwrap(); Context::swap(last_task_context, sched_context); // We could be executing in a different thread now - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); (*sched).run_cleanup_job(); } } @@ -262,17 +263,17 @@ pub impl Scheduler { this.enqueue_cleanup_job(GiveTask(old_running_task, f_opaque)); this.current_task = Some(next_task); - local_sched::put(this); + Local::put(this); unsafe { - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); let (_, last_task_context, next_task_context) = (*sched).get_contexts(); let last_task_context = last_task_context.unwrap(); let next_task_context = next_task_context.unwrap(); Context::swap(last_task_context, next_task_context); // We could be executing in a different thread now - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); (*sched).run_cleanup_job(); } } @@ -377,16 +378,16 @@ pub impl Coroutine { // context switch to the task. The previous context may // have asked us to do some cleanup. unsafe { - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); (*sched).run_cleanup_job(); - let sched = local_sched::unsafe_borrow(); + let sched = Local::unsafe_borrow::(); let task = (*sched).current_task.get_mut_ref(); // FIXME #6141: shouldn't neet to put `start()` in another closure task.task.run(||start()); } - let sched = local_sched::take(); + let sched = Local::take::(); sched.terminate_current_task(); }; return wrapper; @@ -409,6 +410,7 @@ mod test { use rt::uv::uvio::UvEventLoop; use unstable::run_in_bare_thread; use task::spawn; + use rt::local::Local; use rt::test::*; use super::*; @@ -456,14 +458,14 @@ mod test { let mut sched = ~UvEventLoop::new_scheduler(); let task1 = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *count_ptr = *count_ptr + 1; } - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let task2 = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *count_ptr = *count_ptr + 1; } }; // Context switch directly to the new task do sched.switch_running_tasks_and_then(task2) |task1| { let task1 = Cell(task1); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { sched.enqueue_task(task1.take()); } } @@ -493,7 +495,7 @@ mod test { assert_eq!(count, MAX); fn run_task(count_ptr: *mut int) { - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { let task = ~do Coroutine::new(&mut sched.stack_pool) { unsafe { *count_ptr = *count_ptr + 1; @@ -513,11 +515,11 @@ mod test { do run_in_bare_thread { let mut sched = ~UvEventLoop::new_scheduler(); let task = ~do Coroutine::new(&mut sched.stack_pool) { - let sched = local_sched::take(); + let sched = Local::take::(); assert!(sched.in_task_context()); do sched.deschedule_running_task_and_then() |task| { let task = Cell(task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { assert!(!sched.in_task_context()); sched.enqueue_task(task.take()); } @@ -536,17 +538,17 @@ mod test { // exit before emptying the work queue do run_in_newsched_task { do spawn { - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then |task| { - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let task = Cell(task); do sched.event_loop.callback_ms(10) { rtdebug!("in callback"); - let mut sched = local_sched::take(); + let mut sched = Local::take::(); sched.enqueue_task(task.take()); - local_sched::put(sched); + Local::put(sched); } - local_sched::put(sched); + Local::put(sched); } } } diff --git a/src/libcore/rt/task.rs b/src/libcore/rt/task.rs index 65b7c885b5735..cfb5b96586034 100644 --- a/src/libcore/rt/task.rs +++ b/src/libcore/rt/task.rs @@ -16,7 +16,8 @@ use prelude::*; use libc::{c_void, uintptr_t}; use cast::transmute; -use super::sched::local_sched; +use super::sched::{Scheduler, local_sched}; +use rt::local::Local; use super::local_heap::LocalHeap; use rt::logging::StdErrLogger; @@ -152,7 +153,7 @@ impl Unwinder { /// Borrow a pointer to the installed local services. /// Fails (likely aborting the process) if local services are not available. pub fn borrow_local_task(f: &fn(&mut Task)) { - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { match sched.current_task { Some(~ref mut task) => { f(&mut *task.task) @@ -165,7 +166,7 @@ pub fn borrow_local_task(f: &fn(&mut Task)) { } pub unsafe fn unsafe_borrow_local_task() -> *mut Task { - match (*local_sched::unsafe_borrow()).current_task { + match (*Local::unsafe_borrow::()).current_task { Some(~ref mut task) => { let s: *mut Task = &mut *task.task; return s; @@ -178,7 +179,7 @@ pub unsafe fn unsafe_borrow_local_task() -> *mut Task { } pub unsafe fn unsafe_try_borrow_local_task() -> Option<*mut Task> { - if local_sched::exists() { + if Local::exists::() { Some(unsafe_borrow_local_task()) } else { None diff --git a/src/libcore/rt/test.rs b/src/libcore/rt/test.rs index 66993041752cf..c60ae2bfeffc8 100644 --- a/src/libcore/rt/test.rs +++ b/src/libcore/rt/test.rs @@ -15,6 +15,7 @@ use result::{Result, Ok, Err}; use super::io::net::ip::{IpAddr, Ipv4}; use rt::task::Task; use rt::thread::Thread; +use rt::local::Local; /// Creates a new scheduler in a new thread and runs a task in it, /// then waits for the scheduler to exit. Failure of the task @@ -40,13 +41,13 @@ pub fn run_in_newsched_task(f: ~fn()) { pub fn spawntask(f: ~fn()) { use super::sched::*; - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let task = ~Coroutine::with_task(&mut sched.stack_pool, ~Task::without_unwinding(), f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); - let sched = local_sched::take(); + let sched = Local::take::(); sched.schedule_new_task(task.take()); } } @@ -55,13 +56,13 @@ pub fn spawntask(f: ~fn()) { pub fn spawntask_immediately(f: ~fn()) { use super::sched::*; - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let task = ~Coroutine::with_task(&mut sched.stack_pool, ~Task::without_unwinding(), f); do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { sched.enqueue_task(task.take()); } } @@ -71,13 +72,13 @@ pub fn spawntask_immediately(f: ~fn()) { pub fn spawntask_later(f: ~fn()) { use super::sched::*; - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let task = ~Coroutine::with_task(&mut sched.stack_pool, ~Task::without_unwinding(), f); sched.enqueue_task(task); - local_sched::put(sched); + Local::put(sched); } /// Spawn a task and either run it immediately or run it later @@ -88,7 +89,7 @@ pub fn spawntask_random(f: ~fn()) { let mut rng = rng(); let run_now: bool = Rand::rand(&mut rng); - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let task = ~Coroutine::with_task(&mut sched.stack_pool, ~Task::without_unwinding(), f); @@ -96,13 +97,13 @@ pub fn spawntask_random(f: ~fn()) { if run_now { do sched.switch_running_tasks_and_then(task) |task| { let task = Cell(task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { sched.enqueue_task(task.take()); } } } else { sched.enqueue_task(task); - local_sched::put(sched); + Local::put(sched); } } @@ -120,21 +121,21 @@ pub fn spawntask_try(f: ~fn()) -> Result<(), ()> { // Switch to the scheduler let f = Cell(Cell(f)); - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then() |old_task| { let old_task = Cell(old_task); let f = f.take(); - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let new_task = ~do Coroutine::new(&mut sched.stack_pool) { do (|| { (f.take())() }).finally { // Check for failure then resume the parent task unsafe { *failed_ptr = task::failing(); } - let sched = local_sched::take(); + let sched = Local::take::(); do sched.switch_running_tasks_and_then(old_task.take()) |new_task| { let new_task = Cell(new_task); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { sched.enqueue_task(new_task.take()); } } diff --git a/src/libcore/rt/tube.rs b/src/libcore/rt/tube.rs index bc9269f08faa9..2e6dc64986ebf 100644 --- a/src/libcore/rt/tube.rs +++ b/src/libcore/rt/tube.rs @@ -16,9 +16,10 @@ use option::*; use clone::Clone; use super::rc::RC; -use rt::sched::Coroutine; +use rt::sched::{Scheduler, Coroutine}; use rt::{context, TaskContext, SchedulerContext}; use rt::local_sched; +use rt::local::Local; use vec::OwnedVector; use container::Container; @@ -53,7 +54,7 @@ impl Tube { // There's a waiting task. Wake it up rtdebug!("waking blocked tube"); let task = (*state).blocked_task.swap_unwrap(); - let sched = local_sched::take(); + let sched = Local::take::(); sched.resume_task_immediately(task); } } @@ -71,7 +72,7 @@ impl Tube { rtdebug!("blocking on tube recv"); assert!(self.p.refcount() > 1); // There better be somebody to wake us up assert!((*state).blocked_task.is_none()); - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then |task| { (*state).blocked_task = Some(task); } @@ -97,6 +98,8 @@ mod test { use rt::local_sched; use rt::test::*; use rt::rtio::EventLoop; + use rt::sched::Scheduler; + use rt::local::Local; use super::*; #[test] @@ -105,11 +108,11 @@ mod test { let mut tube: Tube = Tube::new(); let tube_clone = tube.clone(); let tube_clone_cell = Cell(tube_clone); - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then |task| { let mut tube_clone = tube_clone_cell.take(); tube_clone.send(1); - let sched = local_sched::take(); + let sched = Local::take::(); sched.resume_task_immediately(task); } @@ -123,10 +126,10 @@ mod test { let mut tube: Tube = Tube::new(); let tube_clone = tube.clone(); let tube_clone = Cell(Cell(Cell(tube_clone))); - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then |task| { let tube_clone = tube_clone.take(); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { let tube_clone = tube_clone.take(); do sched.event_loop.callback { let mut tube_clone = tube_clone.take(); @@ -135,7 +138,7 @@ mod test { tube_clone.send(1); } } - let sched = local_sched::take(); + let sched = Local::take::(); sched.resume_task_immediately(task); } @@ -151,7 +154,7 @@ mod test { let mut tube: Tube = Tube::new(); let tube_clone = tube.clone(); let tube_clone = Cell(tube_clone); - let sched = local_sched::take(); + let sched = Local::take::(); do sched.deschedule_running_task_and_then |task| { callback_send(tube_clone.take(), 0); @@ -159,7 +162,7 @@ mod test { if i == 100 { return; } let tube = Cell(Cell(tube)); - do local_sched::borrow |sched| { + do Local::borrow:: |sched| { let tube = tube.take(); do sched.event_loop.callback { let mut tube = tube.take(); @@ -171,7 +174,7 @@ mod test { } } - let sched = local_sched::take(); + let sched = Local::take::(); sched.resume_task_immediately(task); } diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index 8aa1860f3521b..e83ab0dd80893 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -22,6 +22,7 @@ use rt::rtio::*; use rt::sched::{Scheduler, local_sched}; use rt::io::{standard_error, OtherIoError}; use rt::tube::Tube; +use rt::local::Local; #[cfg(test)] use container::Container; #[cfg(test)] use uint; @@ -118,14 +119,14 @@ impl IoFactory for UvIoFactory { let result_cell = empty_cell(); let result_cell_ptr: *Cell> = &result_cell; - let scheduler = local_sched::take(); + let scheduler = Local::take::(); assert!(scheduler.in_task_context()); // Block this task and take ownership, switch to scheduler context do scheduler.deschedule_running_task_and_then |task| { rtdebug!("connect: entered scheduler context"); - do local_sched::borrow |scheduler| { + do Local::borrow:: |scheduler| { assert!(!scheduler.in_task_context()); } let mut tcp_watcher = TcpWatcher::new(self.uv_loop()); @@ -142,7 +143,7 @@ impl IoFactory for UvIoFactory { unsafe { (*result_cell_ptr).put_back(res); } // Context switch - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_immediately(task_cell.take()); } else { rtdebug!("status is some"); @@ -150,7 +151,7 @@ impl IoFactory for UvIoFactory { do stream_watcher.close { let res = Err(uv_error_to_io_error(status.get())); unsafe { (*result_cell_ptr).put_back(res); } - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_immediately(task_cell.take()); } }; @@ -166,11 +167,11 @@ impl IoFactory for UvIoFactory { match watcher.bind(addr) { Ok(_) => Ok(~UvTcpListener::new(watcher)), Err(uverr) => { - let scheduler = local_sched::take(); + let scheduler = Local::take::(); do scheduler.deschedule_running_task_and_then |task| { let task_cell = Cell(task); do watcher.as_stream().close { - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_immediately(task_cell.take()); } } @@ -202,11 +203,11 @@ impl UvTcpListener { impl Drop for UvTcpListener { fn finalize(&self) { let watcher = self.watcher(); - let scheduler = local_sched::take(); + let scheduler = Local::take::(); do scheduler.deschedule_running_task_and_then |task| { let task_cell = Cell(task); do watcher.as_stream().close { - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_immediately(task_cell.take()); } } @@ -264,11 +265,11 @@ impl Drop for UvTcpStream { fn finalize(&self) { rtdebug!("closing tcp stream"); let watcher = self.watcher(); - let scheduler = local_sched::take(); + let scheduler = Local::take::(); do scheduler.deschedule_running_task_and_then |task| { let task_cell = Cell(task); do watcher.close { - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_immediately(task_cell.take()); } } @@ -280,13 +281,13 @@ impl RtioTcpStream for UvTcpStream { let result_cell = empty_cell(); let result_cell_ptr: *Cell> = &result_cell; - let scheduler = local_sched::take(); + let scheduler = Local::take::(); assert!(scheduler.in_task_context()); let watcher = self.watcher(); let buf_ptr: *&mut [u8] = &buf; do scheduler.deschedule_running_task_and_then |task| { rtdebug!("read: entered scheduler context"); - do local_sched::borrow |scheduler| { + do Local::borrow:: |scheduler| { assert!(!scheduler.in_task_context()); } let mut watcher = watcher; @@ -314,7 +315,7 @@ impl RtioTcpStream for UvTcpStream { unsafe { (*result_cell_ptr).put_back(result); } - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_immediately(task_cell.take()); } } @@ -326,7 +327,7 @@ impl RtioTcpStream for UvTcpStream { fn write(&mut self, buf: &[u8]) -> Result<(), IoError> { let result_cell = empty_cell(); let result_cell_ptr: *Cell> = &result_cell; - let scheduler = local_sched::take(); + let scheduler = Local::take::(); assert!(scheduler.in_task_context()); let watcher = self.watcher(); let buf_ptr: *&[u8] = &buf; @@ -343,7 +344,7 @@ impl RtioTcpStream for UvTcpStream { unsafe { (*result_cell_ptr).put_back(result); } - let scheduler = local_sched::take(); + let scheduler = Local::take::(); scheduler.resume_task_immediately(task_cell.take()); } } @@ -420,13 +421,13 @@ fn test_read_and_block() { } reads += 1; - let scheduler = local_sched::take(); + let scheduler = Local::take::(); // Yield to the other task in hopes that it // will trigger a read callback while we are // not ready for it do scheduler.deschedule_running_task_and_then |task| { let task = Cell(task); - do local_sched::borrow |scheduler| { + do Local::borrow:: |scheduler| { scheduler.enqueue_task(task.take()); } } diff --git a/src/libcore/task/spawn.rs b/src/libcore/task/spawn.rs index 8d287b5c51f7d..81e5af5caab11 100644 --- a/src/libcore/task/spawn.rs +++ b/src/libcore/task/spawn.rs @@ -90,6 +90,7 @@ use task::unkillable; use uint; use util; use unstable::sync::{Exclusive, exclusive}; +use rt::local::Local; #[cfg(test)] use task::default_task_opts; @@ -575,7 +576,7 @@ pub fn spawn_raw(opts: TaskOpts, f: ~fn()) { fn spawn_raw_newsched(_opts: TaskOpts, f: ~fn()) { use rt::sched::*; - let mut sched = local_sched::take(); + let mut sched = Local::take::(); let task = ~Coroutine::new(&mut sched.stack_pool, f); sched.schedule_new_task(task); } From 2f99fb8efad8803801628a507fe3ac06a70c7871 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 16:10:44 -0700 Subject: [PATCH 146/248] core::rt: Remove local_sched module --- src/libcore/rt/comm.rs | 1 - src/libcore/rt/io/net/tcp.rs | 2 +- src/libcore/rt/local_sched.rs | 32 -------------------------------- src/libcore/rt/mod.rs | 7 ++----- src/libcore/rt/sched.rs | 10 +++++++--- src/libcore/rt/task.rs | 2 +- src/libcore/rt/tube.rs | 2 -- src/libcore/rt/uv/uvio.rs | 17 +++++++++-------- 8 files changed, 20 insertions(+), 53 deletions(-) delete mode 100644 src/libcore/rt/local_sched.rs diff --git a/src/libcore/rt/comm.rs b/src/libcore/rt/comm.rs index 544d9817558c6..576a402b70919 100644 --- a/src/libcore/rt/comm.rs +++ b/src/libcore/rt/comm.rs @@ -22,7 +22,6 @@ use ops::Drop; use kinds::Owned; use rt::sched::{Scheduler, Coroutine}; use rt::local::Local; -use rt::local_sched; use unstable::intrinsics::{atomic_xchg, atomic_load}; use util::Void; use comm::{GenericChan, GenericSmartChan, GenericPort, Peekable}; diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index a5fd7a395de7f..d900341998117 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -10,7 +10,7 @@ use option::{Option, Some, None}; use result::{Ok, Err}; -use rt::sched::local_sched::unsafe_borrow_io; +use rt::sched::unsafe_borrow_io; use rt::io::net::ip::IpAddr; use rt::io::{Reader, Writer, Listener}; use rt::io::{io_error, read_error, EndOfFile}; diff --git a/src/libcore/rt/local_sched.rs b/src/libcore/rt/local_sched.rs deleted file mode 100644 index 48e3351c44f28..0000000000000 --- a/src/libcore/rt/local_sched.rs +++ /dev/null @@ -1,32 +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. - -//! Access to the thread-local Scheduler - -use prelude::*; -use ptr::mut_null; -use libc::c_void; -use cast; -use cell::Cell; - -use rt::sched::Scheduler; -use rt::rtio::{EventLoop, IoFactoryObject}; -use unstable::finally::Finally; -use rt::local_ptr; -use tls = rt::thread_local_storage; -use rt::local::Local; - -#[cfg(test)] use rt::uv::uvio::UvEventLoop; - -pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { - let sched = Local::unsafe_borrow::(); - let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); - return io; -} diff --git a/src/libcore/rt/mod.rs b/src/libcore/rt/mod.rs index c8532f6b94a3a..2fac1df01a495 100644 --- a/src/libcore/rt/mod.rs +++ b/src/libcore/rt/mod.rs @@ -67,9 +67,6 @@ pub mod task; /// The coroutine task scheduler, built on the `io` event loop. mod sched; -/// Thread-local access to the current Scheduler. -pub mod local_sched; - /// Synchronous I/O. #[path = "io/mod.rs"] pub mod io; @@ -189,7 +186,7 @@ pub fn context() -> RuntimeContext { use task::rt::rust_task; use self::local::Local; - use self::sched::{local_sched, Scheduler}; + use self::sched::Scheduler; // XXX: Hitting TLS twice to check if the scheduler exists // then to check for the task is not good for perf @@ -220,7 +217,7 @@ pub fn context() -> RuntimeContext { #[test] fn test_context() { use unstable::run_in_bare_thread; - use self::sched::{local_sched, Scheduler, Coroutine}; + use self::sched::{Scheduler, Coroutine}; use rt::uv::uvio::UvEventLoop; use cell::Cell; use rt::local::Local; diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 0004ef29de02a..20c24adaa0ad0 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -20,9 +20,7 @@ use super::context::Context; use super::task::Task; use rt::local_ptr; use rt::local::Local; - -// A more convenient name for external callers, e.g. `local_sched::take()` -pub mod local_sched; +use rt::rtio::IoFactoryObject; /// The Scheduler is responsible for coordinating execution of Coroutines /// on a single thread. When the scheduler is running it is owned by @@ -403,6 +401,12 @@ pub impl Coroutine { } } +pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { + let sched = Local::unsafe_borrow::(); + let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); + return io; +} + #[cfg(test)] mod test { use int; diff --git a/src/libcore/rt/task.rs b/src/libcore/rt/task.rs index cfb5b96586034..3f98ad74ef260 100644 --- a/src/libcore/rt/task.rs +++ b/src/libcore/rt/task.rs @@ -16,7 +16,7 @@ use prelude::*; use libc::{c_void, uintptr_t}; use cast::transmute; -use super::sched::{Scheduler, local_sched}; +use super::sched::Scheduler; use rt::local::Local; use super::local_heap::LocalHeap; use rt::logging::StdErrLogger; diff --git a/src/libcore/rt/tube.rs b/src/libcore/rt/tube.rs index 2e6dc64986ebf..b2f475a696605 100644 --- a/src/libcore/rt/tube.rs +++ b/src/libcore/rt/tube.rs @@ -18,7 +18,6 @@ use clone::Clone; use super::rc::RC; use rt::sched::{Scheduler, Coroutine}; use rt::{context, TaskContext, SchedulerContext}; -use rt::local_sched; use rt::local::Local; use vec::OwnedVector; use container::Container; @@ -95,7 +94,6 @@ impl Clone for Tube { mod test { use int; use cell::Cell; - use rt::local_sched; use rt::test::*; use rt::rtio::EventLoop; use rt::sched::Scheduler; diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index e83ab0dd80893..b89dfcab3d330 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -19,7 +19,8 @@ use rt::io::net::ip::IpAddr; use rt::uv::*; use rt::uv::idle::IdleWatcher; use rt::rtio::*; -use rt::sched::{Scheduler, local_sched}; +use rt::sched::unsafe_borrow_io; +use rt::sched::Scheduler; use rt::io::{standard_error, OtherIoError}; use rt::tube::Tube; use rt::local::Local; @@ -358,7 +359,7 @@ impl RtioTcpStream for UvTcpStream { fn test_simple_io_no_connect() { do run_in_newsched_task { unsafe { - let io = local_sched::unsafe_borrow_io(); + let io = unsafe_borrow_io(); let addr = next_test_ip4(); let maybe_chan = (*io).tcp_connect(addr); assert!(maybe_chan.is_err()); @@ -374,7 +375,7 @@ fn test_simple_tcp_server_and_client() { // Start the server first so it's listening when we connect do spawntask_immediately { unsafe { - let io = local_sched::unsafe_borrow_io(); + let io = unsafe_borrow_io(); let mut listener = (*io).tcp_bind(addr).unwrap(); let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; @@ -389,7 +390,7 @@ fn test_simple_tcp_server_and_client() { do spawntask_immediately { unsafe { - let io = local_sched::unsafe_borrow_io(); + let io = unsafe_borrow_io(); let mut stream = (*io).tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); } @@ -403,7 +404,7 @@ fn test_read_and_block() { let addr = next_test_ip4(); do spawntask_immediately { - let io = unsafe { local_sched::unsafe_borrow_io() }; + let io = unsafe { unsafe_borrow_io() }; let mut listener = unsafe { (*io).tcp_bind(addr).unwrap() }; let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; @@ -439,7 +440,7 @@ fn test_read_and_block() { do spawntask_immediately { unsafe { - let io = local_sched::unsafe_borrow_io(); + let io = unsafe_borrow_io(); let mut stream = (*io).tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); @@ -459,7 +460,7 @@ fn test_read_read_read() { do spawntask_immediately { unsafe { - let io = local_sched::unsafe_borrow_io(); + let io = unsafe_borrow_io(); let mut listener = (*io).tcp_bind(addr).unwrap(); let mut stream = listener.accept().unwrap(); let buf = [1, .. 2048]; @@ -473,7 +474,7 @@ fn test_read_read_read() { do spawntask_immediately { unsafe { - let io = local_sched::unsafe_borrow_io(); + let io = unsafe_borrow_io(); let mut stream = (*io).tcp_connect(addr).unwrap(); let mut buf = [0, .. 2048]; let mut total_bytes_read = 0; From 2042696236a600b6fedec771e0aeec4b0552709d Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 16:50:21 -0700 Subject: [PATCH 147/248] core::rt: Implement Local for Task --- src/libcore/logging.rs | 5 +++- src/libcore/rt/local.rs | 41 +++++++++++++++++++++++++++++ src/libcore/rt/task.rs | 40 ++-------------------------- src/libcore/sys.rs | 5 ++-- src/libcore/task/local_data_priv.rs | 6 ++--- src/libcore/task/mod.rs | 5 ++-- src/libcore/unstable/lang.rs | 7 ++--- 7 files changed, 60 insertions(+), 49 deletions(-) diff --git a/src/libcore/logging.rs b/src/libcore/logging.rs index 16a80866cf1ab..be71714a048e3 100644 --- a/src/libcore/logging.rs +++ b/src/libcore/logging.rs @@ -66,8 +66,11 @@ pub fn log_type(level: u32, object: &T) { } fn newsched_log_str(msg: ~str) { + use rt::task::Task; + use rt::local::Local; + unsafe { - match rt::task::unsafe_try_borrow_local_task() { + match Local::try_unsafe_borrow::() { Some(local) => { // Use the available logger (*local).logger.log(Left(msg)); diff --git a/src/libcore/rt/local.rs b/src/libcore/rt/local.rs index c054ba68d1082..471d6983db2aa 100644 --- a/src/libcore/rt/local.rs +++ b/src/libcore/rt/local.rs @@ -8,7 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use option::{Option, Some, None}; use rt::sched::Scheduler; +use rt::task::Task; use rt::local_ptr; pub trait Local { @@ -17,6 +19,7 @@ pub trait Local { fn exists() -> bool; fn borrow(f: &fn(&mut Self)); unsafe fn unsafe_borrow() -> *mut Self; + unsafe fn try_unsafe_borrow() -> Option<*mut Self>; } impl Local for Scheduler { @@ -25,6 +28,44 @@ impl Local for Scheduler { fn exists() -> bool { local_ptr::exists() } fn borrow(f: &fn(&mut Scheduler)) { unsafe { local_ptr::borrow(f) } } unsafe fn unsafe_borrow() -> *mut Scheduler { local_ptr::unsafe_borrow() } + unsafe fn try_unsafe_borrow() -> Option<*mut Scheduler> { abort!("unimpl") } +} + +impl Local for Task { + fn put(value: ~Task) { abort!("unimpl") } + fn take() -> ~Task { abort!("unimpl") } + fn exists() -> bool { abort!("unimpl") } + fn borrow(f: &fn(&mut Task)) { + do Local::borrow:: |sched| { + match sched.current_task { + Some(~ref mut task) => { + f(&mut *task.task) + } + None => { + abort!("no scheduler") + } + } + } + } + unsafe fn unsafe_borrow() -> *mut Task { + match (*Local::unsafe_borrow::()).current_task { + Some(~ref mut task) => { + let s: *mut Task = &mut *task.task; + return s; + } + None => { + // Don't fail. Infinite recursion + abort!("no scheduler") + } + } + } + unsafe fn try_unsafe_borrow() -> Option<*mut Task> { + if Local::exists::() { + Some(Local::unsafe_borrow()) + } else { + None + } + } } #[cfg(test)] diff --git a/src/libcore/rt/task.rs b/src/libcore/rt/task.rs index 3f98ad74ef260..0314137fc7f92 100644 --- a/src/libcore/rt/task.rs +++ b/src/libcore/rt/task.rs @@ -63,7 +63,7 @@ impl Task { pub fn run(&mut self, f: &fn()) { // This is just an assertion that `run` was called unsafely // and this instance of Task is still accessible. - do borrow_local_task |task| { + do Local::borrow:: |task| { assert!(ptr::ref_eq(task, self)); } @@ -88,7 +88,7 @@ impl Task { fn destroy(&mut self) { // This is just an assertion that `destroy` was called unsafely // and this instance of Task is still accessible. - do borrow_local_task |task| { + do Local::borrow:: |task| { assert!(ptr::ref_eq(task, self)); } match self.storage { @@ -150,42 +150,6 @@ impl Unwinder { } } -/// Borrow a pointer to the installed local services. -/// Fails (likely aborting the process) if local services are not available. -pub fn borrow_local_task(f: &fn(&mut Task)) { - do Local::borrow:: |sched| { - match sched.current_task { - Some(~ref mut task) => { - f(&mut *task.task) - } - None => { - fail!("no local services for schedulers yet") - } - } - } -} - -pub unsafe fn unsafe_borrow_local_task() -> *mut Task { - match (*Local::unsafe_borrow::()).current_task { - Some(~ref mut task) => { - let s: *mut Task = &mut *task.task; - return s; - } - None => { - // Don't fail. Infinite recursion - abort!("no local services for schedulers yet") - } - } -} - -pub unsafe fn unsafe_try_borrow_local_task() -> Option<*mut Task> { - if Local::exists::() { - Some(unsafe_borrow_local_task()) - } else { - None - } -} - #[cfg(test)] mod test { use rt::test::*; diff --git a/src/libcore/sys.rs b/src/libcore/sys.rs index c21ce5213142b..1f8dc8c00b5c9 100644 --- a/src/libcore/sys.rs +++ b/src/libcore/sys.rs @@ -204,7 +204,8 @@ impl FailWithCause for &'static str { pub fn begin_unwind_(msg: *c_char, file: *c_char, line: size_t) -> ! { use option::Option; use rt::{context, OldTaskContext, TaskContext}; - use rt::task::{unsafe_borrow_local_task, Unwinder}; + use rt::task::{Task, Unwinder}; + use rt::local::Local; let context = context(); match context { @@ -233,7 +234,7 @@ pub fn begin_unwind_(msg: *c_char, file: *c_char, line: size_t) -> ! { gc::cleanup_stack_for_failure(); - let task = unsafe_borrow_local_task(); + let task = Local::unsafe_borrow::(); let unwinder: &mut Option = &mut (*task).unwinder; match *unwinder { Some(ref mut unwinder) => unwinder.begin_unwind(), diff --git a/src/libcore/task/local_data_priv.rs b/src/libcore/task/local_data_priv.rs index 6871dd3aecd88..2f97eaacf4be2 100644 --- a/src/libcore/task/local_data_priv.rs +++ b/src/libcore/task/local_data_priv.rs @@ -18,7 +18,7 @@ use task::rt; use local_data::LocalDataKey; use super::rt::rust_task; -use rt::task::LocalStorage; +use rt::task::{Task, LocalStorage}; pub enum Handle { OldHandle(*rust_task), @@ -28,14 +28,14 @@ pub enum Handle { impl Handle { pub fn new() -> Handle { use rt::{context, OldTaskContext}; - use rt::task::unsafe_borrow_local_task; + use rt::local::Local; unsafe { match context() { OldTaskContext => { OldHandle(rt::rust_get_task()) } _ => { - let task = unsafe_borrow_local_task(); + let task = Local::unsafe_borrow::(); NewHandle(&mut (*task).storage) } } diff --git a/src/libcore/task/mod.rs b/src/libcore/task/mod.rs index 372a9f6defaff..490a69248eecb 100644 --- a/src/libcore/task/mod.rs +++ b/src/libcore/task/mod.rs @@ -504,7 +504,8 @@ pub fn failing() -> bool { //! True if the running task has failed use rt::{context, OldTaskContext}; - use rt::task::borrow_local_task; + use rt::local::Local; + use rt::task::Task; match context() { OldTaskContext => { @@ -514,7 +515,7 @@ pub fn failing() -> bool { } _ => { let mut unwinding = false; - do borrow_local_task |local| { + do Local::borrow:: |local| { unwinding = match local.unwinder { Some(unwinder) => { unwinder.unwinding diff --git a/src/libcore/unstable/lang.rs b/src/libcore/unstable/lang.rs index 1efe5d0d1a41d..350b18d454169 100644 --- a/src/libcore/unstable/lang.rs +++ b/src/libcore/unstable/lang.rs @@ -17,7 +17,8 @@ use managed::raw::BoxRepr; use str; use sys; use rt::{context, OldTaskContext}; -use rt::task::borrow_local_task; +use rt::task::Task; +use rt::local::Local; use option::{Option, Some, None}; use io; use rt::global_heap; @@ -243,7 +244,7 @@ pub unsafe fn local_malloc(td: *c_char, size: uintptr_t) -> *c_char { } _ => { let mut alloc = ::ptr::null(); - do borrow_local_task |task| { + do Local::borrow:: |task| { alloc = task.heap.alloc(td as *c_void, size as uint) as *c_char; } return alloc; @@ -261,7 +262,7 @@ pub unsafe fn local_free(ptr: *c_char) { rustrt::rust_upcall_free_noswitch(ptr); } _ => { - do borrow_local_task |task| { + do Local::borrow:: |task| { task.heap.free(ptr as *c_void); } } From a246e8faf362a1615b5bb4938455dd70642e0f4b Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Sun, 19 May 2013 19:11:59 -0700 Subject: [PATCH 148/248] core::rt: Convert unsafe_borrow_io to a Local impl --- src/libcore/rt/io/net/tcp.rs | 11 +++++++---- src/libcore/rt/local.rs | 15 +++++++++++++++ src/libcore/rt/sched.rs | 6 ------ src/libcore/rt/uv/uvio.rs | 15 +++++++-------- 4 files changed, 29 insertions(+), 18 deletions(-) diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libcore/rt/io/net/tcp.rs index d900341998117..f7c03c13a5812 100644 --- a/src/libcore/rt/io/net/tcp.rs +++ b/src/libcore/rt/io/net/tcp.rs @@ -10,13 +10,13 @@ use option::{Option, Some, None}; use result::{Ok, Err}; -use rt::sched::unsafe_borrow_io; use rt::io::net::ip::IpAddr; use rt::io::{Reader, Writer, Listener}; use rt::io::{io_error, read_error, EndOfFile}; -use rt::rtio::{IoFactory, +use rt::rtio::{IoFactory, IoFactoryObject, RtioTcpListener, RtioTcpListenerObject, RtioTcpStream, RtioTcpStreamObject}; +use rt::local::Local; pub struct TcpStream { rtstream: ~RtioTcpStreamObject @@ -32,7 +32,7 @@ impl TcpStream { pub fn connect(addr: IpAddr) -> Option { let stream = unsafe { rtdebug!("borrowing io to connect"); - let io = unsafe_borrow_io(); + let io = Local::unsafe_borrow::(); rtdebug!("about to connect"); (*io).tcp_connect(addr) }; @@ -88,7 +88,10 @@ pub struct TcpListener { impl TcpListener { pub fn bind(addr: IpAddr) -> Option { - let listener = unsafe { (*unsafe_borrow_io()).tcp_bind(addr) }; + let listener = unsafe { + let io = Local::unsafe_borrow::(); + (*io).tcp_bind(addr) + }; match listener { Ok(l) => { Some(TcpListener { diff --git a/src/libcore/rt/local.rs b/src/libcore/rt/local.rs index 471d6983db2aa..64a384ddff0b9 100644 --- a/src/libcore/rt/local.rs +++ b/src/libcore/rt/local.rs @@ -12,6 +12,7 @@ use option::{Option, Some, None}; use rt::sched::Scheduler; use rt::task::Task; use rt::local_ptr; +use rt::rtio::{EventLoop, IoFactoryObject}; pub trait Local { fn put(value: ~Self); @@ -68,6 +69,20 @@ impl Local for Task { } } +// XXX: This formulation won't work once ~IoFactoryObject is a real trait pointer +impl Local for IoFactoryObject { + fn put(value: ~IoFactoryObject) { abort!("unimpl") } + fn take() -> ~IoFactoryObject { abort!("unimpl") } + fn exists() -> bool { abort!("unimpl") } + fn borrow(f: &fn(&mut IoFactoryObject)) { abort!("unimpl") } + unsafe fn unsafe_borrow() -> *mut IoFactoryObject { + let sched = Local::unsafe_borrow::(); + let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); + return io; + } + unsafe fn try_unsafe_borrow() -> Option<*mut IoFactoryObject> { abort!("unimpl") } +} + #[cfg(test)] mod test { use rt::sched::Scheduler; diff --git a/src/libcore/rt/sched.rs b/src/libcore/rt/sched.rs index 20c24adaa0ad0..50c6a894093f3 100644 --- a/src/libcore/rt/sched.rs +++ b/src/libcore/rt/sched.rs @@ -401,12 +401,6 @@ pub impl Coroutine { } } -pub unsafe fn unsafe_borrow_io() -> *mut IoFactoryObject { - let sched = Local::unsafe_borrow::(); - let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); - return io; -} - #[cfg(test)] mod test { use int; diff --git a/src/libcore/rt/uv/uvio.rs b/src/libcore/rt/uv/uvio.rs index b89dfcab3d330..cacd67314ebac 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libcore/rt/uv/uvio.rs @@ -19,7 +19,6 @@ use rt::io::net::ip::IpAddr; use rt::uv::*; use rt::uv::idle::IdleWatcher; use rt::rtio::*; -use rt::sched::unsafe_borrow_io; use rt::sched::Scheduler; use rt::io::{standard_error, OtherIoError}; use rt::tube::Tube; @@ -359,7 +358,7 @@ impl RtioTcpStream for UvTcpStream { fn test_simple_io_no_connect() { do run_in_newsched_task { unsafe { - let io = unsafe_borrow_io(); + let io = Local::unsafe_borrow::(); let addr = next_test_ip4(); let maybe_chan = (*io).tcp_connect(addr); assert!(maybe_chan.is_err()); @@ -375,7 +374,7 @@ fn test_simple_tcp_server_and_client() { // Start the server first so it's listening when we connect do spawntask_immediately { unsafe { - let io = unsafe_borrow_io(); + let io = Local::unsafe_borrow::(); let mut listener = (*io).tcp_bind(addr).unwrap(); let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; @@ -390,7 +389,7 @@ fn test_simple_tcp_server_and_client() { do spawntask_immediately { unsafe { - let io = unsafe_borrow_io(); + let io = Local::unsafe_borrow::(); let mut stream = (*io).tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); } @@ -404,7 +403,7 @@ fn test_read_and_block() { let addr = next_test_ip4(); do spawntask_immediately { - let io = unsafe { unsafe_borrow_io() }; + let io = unsafe { Local::unsafe_borrow::() }; let mut listener = unsafe { (*io).tcp_bind(addr).unwrap() }; let mut stream = listener.accept().unwrap(); let mut buf = [0, .. 2048]; @@ -440,7 +439,7 @@ fn test_read_and_block() { do spawntask_immediately { unsafe { - let io = unsafe_borrow_io(); + let io = Local::unsafe_borrow::(); let mut stream = (*io).tcp_connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); @@ -460,7 +459,7 @@ fn test_read_read_read() { do spawntask_immediately { unsafe { - let io = unsafe_borrow_io(); + let io = Local::unsafe_borrow::(); let mut listener = (*io).tcp_bind(addr).unwrap(); let mut stream = listener.accept().unwrap(); let buf = [1, .. 2048]; @@ -474,7 +473,7 @@ fn test_read_read_read() { do spawntask_immediately { unsafe { - let io = unsafe_borrow_io(); + let io = Local::unsafe_borrow::(); let mut stream = (*io).tcp_connect(addr).unwrap(); let mut buf = [0, .. 2048]; let mut total_bytes_read = 0; From 474d9983beb8a5770a202c552f36c14fa52917a2 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Mon, 20 May 2013 17:28:06 -0700 Subject: [PATCH 149/248] rustllvm: Use target alignment for atomic load/store --- src/librustc/lib/llvm.rs | 6 ++++-- src/librustc/middle/trans/build.rs | 8 +++++--- src/rustllvm/RustWrapper.cpp | 14 ++++++++------ 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index 9198991e5360e..160f375897b82 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -1571,13 +1571,15 @@ pub mod llvm { pub unsafe fn LLVMBuildAtomicLoad(B: BuilderRef, PointerVal: ValueRef, Name: *c_char, - Order: AtomicOrdering) + Order: AtomicOrdering, + Alignment: c_uint) -> ValueRef; pub unsafe fn LLVMBuildAtomicStore(B: BuilderRef, Val: ValueRef, Ptr: ValueRef, - Order: AtomicOrdering) + Order: AtomicOrdering, + Alignment: c_uint) -> ValueRef; pub unsafe fn LLVMBuildAtomicCmpXchg(B: BuilderRef, diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index 362bcd483b41f..cd914e1072b31 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -14,6 +14,7 @@ use lib::llvm::{Opcode, IntPredicate, RealPredicate, False}; use lib::llvm::{ValueRef, TypeRef, BasicBlockRef, BuilderRef, ModuleRef}; use lib; use middle::trans::common::*; +use middle::trans::machine::llalign_of_min; use syntax::codemap::span; use core::hashmap::HashMap; @@ -544,7 +545,8 @@ pub fn AtomicLoad(cx: block, PointerVal: ValueRef, order: AtomicOrdering) -> Val return llvm::LLVMGetUndef(ccx.int_type); } count_insn(cx, "load.atomic"); - return llvm::LLVMBuildAtomicLoad(B(cx), PointerVal, noname(), order); + let align = llalign_of_min(*ccx, ccx.int_type); + return llvm::LLVMBuildAtomicLoad(B(cx), PointerVal, noname(), order, align as c_uint); } } @@ -558,7 +560,6 @@ pub fn LoadRangeAssert(cx: block, PointerVal: ValueRef, lo: c_ulonglong, let min = llvm::LLVMConstInt(t, lo, signed); let max = llvm::LLVMConstInt(t, hi, signed); - do vec::as_imm_buf([min, max]) |ptr, len| { llvm::LLVMSetMetadata(value, lib::llvm::MD_range as c_uint, llvm::LLVMMDNode(ptr, len as c_uint)); @@ -586,7 +587,8 @@ pub fn AtomicStore(cx: block, Val: ValueRef, Ptr: ValueRef, order: AtomicOrderin val_str(cx.ccx().tn, Val), val_str(cx.ccx().tn, Ptr)); count_insn(cx, "store.atomic"); - llvm::LLVMBuildAtomicStore(B(cx), Val, Ptr, order); + let align = llalign_of_min(cx.ccx(), cx.ccx().int_type); + llvm::LLVMBuildAtomicStore(B(cx), Val, Ptr, order, align as c_uint); } } diff --git a/src/rustllvm/RustWrapper.cpp b/src/rustllvm/RustWrapper.cpp index 9e44abe081c95..cff448b6a1a34 100644 --- a/src/rustllvm/RustWrapper.cpp +++ b/src/rustllvm/RustWrapper.cpp @@ -548,22 +548,24 @@ extern "C" LLVMTypeRef LLVMMetadataType(void) { extern "C" LLVMValueRef LLVMBuildAtomicLoad(LLVMBuilderRef B, LLVMValueRef source, const char* Name, - AtomicOrdering order) { + AtomicOrdering order, + unsigned alignment) { LoadInst* li = new LoadInst(unwrap(source),0); li->setVolatile(true); li->setAtomic(order); - li->setAlignment(sizeof(intptr_t)); + li->setAlignment(alignment); return wrap(unwrap(B)->Insert(li, Name)); } extern "C" LLVMValueRef LLVMBuildAtomicStore(LLVMBuilderRef B, - LLVMValueRef val, - LLVMValueRef target, - AtomicOrdering order) { + LLVMValueRef val, + LLVMValueRef target, + AtomicOrdering order, + unsigned alignment) { StoreInst* si = new StoreInst(unwrap(val),unwrap(target)); si->setVolatile(true); si->setAtomic(order); - si->setAlignment(sizeof(intptr_t)); + si->setAlignment(alignment); return wrap(unwrap(B)->Insert(si)); } From d86a32bbb2ff79232bf3edc0f475062f45b6ea90 Mon Sep 17 00:00:00 2001 From: Jyun-Yan You Date: Tue, 21 May 2013 11:58:08 +0800 Subject: [PATCH 150/248] fix mips stack alignment --- src/libcore/rt/context.rs | 4 +++- src/rt/arch/mips/context.cpp | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/libcore/rt/context.rs b/src/libcore/rt/context.rs index 2add314fd1196..f60ce3429579d 100644 --- a/src/libcore/rt/context.rs +++ b/src/libcore/rt/context.rs @@ -183,7 +183,9 @@ fn new_regs() -> ~Registers { ~([0, .. 32]) } #[cfg(target_arch = "mips")] fn initialize_call_frame(regs: &mut Registers, fptr: *c_void, arg: *c_void, sp: *mut uint) { - let sp = mut_offset(sp, -1); + let sp = align_down(sp); + // sp of mips o32 is 8-byte aligned + let sp = mut_offset(sp, -2); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } diff --git a/src/rt/arch/mips/context.cpp b/src/rt/arch/mips/context.cpp index 7347a92e98b92..e1e5776bc1a65 100644 --- a/src/rt/arch/mips/context.cpp +++ b/src/rt/arch/mips/context.cpp @@ -34,9 +34,11 @@ void context::call(void *f, void *arg, void *stack) // set up the stack uint32_t *sp = (uint32_t *)stack; - //sp = align_down(sp); + sp = align_down(sp); // The final return address. 0 indicates the bottom of the stack - *--sp = 0; + // sp of mips o32 is 8-byte aligned + sp -= 2; + *sp = 0; regs.data[4] = (uint32_t)arg; regs.data[29] = (uint32_t)sp; From 9390cdaa8b0a35c025a322d458fb54ab015f58f4 Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Tue, 21 May 2013 19:08:34 +0900 Subject: [PATCH 151/248] Correct span for expr_vec --- src/libsyntax/parse/parser.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 2de27285ce2b1..9f11b059a9535 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1311,7 +1311,7 @@ pub impl Parser { ex = expr_vec(~[first_expr], mutbl); } } - hi = self.span.hi; + hi = self.last_span.hi; } else if self.eat_keyword("__log") { // LOG expression self.expect(&token::LPAREN); From 258d20ea84c51deb0192f7f2576edfa8ca726059 Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Tue, 21 May 2013 19:09:22 +0900 Subject: [PATCH 152/248] Correct span for unused_import --- src/librustc/middle/resolve.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 12ad7251645f8..716ec32bf3ce3 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -5121,7 +5121,7 @@ pub impl Resolver { view_path_simple(_, _, id) | view_path_glob(_, id) => { if !self.used_imports.contains(&id) { self.session.add_lint(unused_imports, - id, vi.span, + id, p.span, ~"unused import"); } } From 8e9eba8013490e7b6ba059397bbe73b7128c04b3 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 17 May 2013 18:41:14 +1000 Subject: [PATCH 153/248] syntax/ext: remove the ~str dependence of the deriving code. --- src/libsyntax/ext/deriving/clone.rs | 8 +-- src/libsyntax/ext/deriving/cmp/eq.rs | 8 +-- src/libsyntax/ext/deriving/cmp/ord.rs | 14 ++-- src/libsyntax/ext/deriving/cmp/totaleq.rs | 6 +- src/libsyntax/ext/deriving/cmp/totalord.rs | 6 +- src/libsyntax/ext/deriving/generic.rs | 16 ++--- src/libsyntax/ext/deriving/iter_bytes.rs | 10 +-- src/libsyntax/ext/deriving/rand.rs | 10 +-- src/libsyntax/ext/deriving/to_str.rs | 6 +- src/libsyntax/ext/deriving/ty.rs | 76 +++++++++++----------- 10 files changed, 81 insertions(+), 79 deletions(-) diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index aceb60ebbd7d6..1759cde0fc975 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -21,12 +21,12 @@ pub fn expand_deriving_clone(cx: @ext_ctxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~[~"core", ~"clone", ~"Clone"]), + path: Path::new(~["core", "clone", "Clone"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { - name: ~"clone", + name: "clone", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[], @@ -48,12 +48,12 @@ pub fn expand_deriving_deep_clone(cx: @ext_ctxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~[~"core", ~"clone", ~"DeepClone"]), + path: Path::new(~["core", "clone", "DeepClone"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { - name: ~"deep_clone", + name: "deep_clone", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[], diff --git a/src/libsyntax/ext/deriving/cmp/eq.rs b/src/libsyntax/ext/deriving/cmp/eq.rs index 3d93f844ea3bb..e6fcfdf556354 100644 --- a/src/libsyntax/ext/deriving/cmp/eq.rs +++ b/src/libsyntax/ext/deriving/cmp/eq.rs @@ -36,7 +36,7 @@ pub fn expand_deriving_eq(cx: @ext_ctxt, generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], - ret_ty: Literal(Path::new(~[~"bool"])), + ret_ty: Literal(Path::new(~["bool"])), const_nonmatching: true, combine_substructure: $f }, @@ -44,12 +44,12 @@ pub fn expand_deriving_eq(cx: @ext_ctxt, ); let trait_def = TraitDef { - path: Path::new(~[~"core", ~"cmp", ~"Eq"]), + path: Path::new(~["core", "cmp", "Eq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ - md!(~"eq", cs_eq), - md!(~"ne", cs_ne) + md!("eq", cs_eq), + md!("ne", cs_ne) ] }; diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 5445aef4491be..5aae8454c09b4 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -26,7 +26,7 @@ pub fn expand_deriving_ord(cx: @ext_ctxt, generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], - ret_ty: Literal(Path::new(~[~"bool"])), + ret_ty: Literal(Path::new(~["bool"])), const_nonmatching: false, combine_substructure: |cx, span, substr| cs_ord($less, $equal, cx, span, substr) @@ -37,15 +37,15 @@ pub fn expand_deriving_ord(cx: @ext_ctxt, let trait_def = TraitDef { - path: Path::new(~[~"core", ~"cmp", ~"Ord"]), + path: Path::new(~["core", "cmp", "Ord"]), // XXX: Ord doesn't imply Eq yet - additional_bounds: ~[Literal(Path::new(~[~"core", ~"cmp", ~"Eq"]))], + additional_bounds: ~[Literal(Path::new(~["core", "cmp", "Eq"]))], generics: LifetimeBounds::empty(), methods: ~[ - md!(~"lt", true, false), - md!(~"le", true, true), - md!(~"gt", false, false), - md!(~"ge", false, true) + md!("lt", true, false), + md!("le", true, true), + md!("gt", false, false), + md!("ge", false, true) ] }; diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index 4541569b829ac..9ab44f506bade 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -26,16 +26,16 @@ pub fn expand_deriving_totaleq(cx: @ext_ctxt, } let trait_def = TraitDef { - path: Path::new(~[~"core", ~"cmp", ~"TotalEq"]), + path: Path::new(~["core", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { - name: ~"equals", + name: "equals", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], - ret_ty: Literal(Path::new(~[~"bool"])), + ret_ty: Literal(Path::new(~["bool"])), const_nonmatching: true, combine_substructure: cs_equals } diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index 8f156e6a9e315..1b6ea16b86e2d 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -20,16 +20,16 @@ pub fn expand_deriving_totalord(cx: @ext_ctxt, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~[~"core", ~"cmp", ~"TotalOrd"]), + path: Path::new(~["core", "cmp", "TotalOrd"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { - name: ~"cmp", + name: "cmp", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], - ret_ty: Literal(Path::new(~[~"core", ~"cmp", ~"Ordering"])), + ret_ty: Literal(Path::new(~["core", "cmp", "Ordering"])), const_nonmatching: false, combine_substructure: cs_cmp } diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index 2fc9dadfe2c1b..ae9c4c1fefb44 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -195,13 +195,13 @@ pub fn expand_deriving_generic(cx: @ext_ctxt, pub struct TraitDef<'self> { /// Path of the trait, including any type parameters - path: Path, + path: Path<'self>, /// Additional bounds required of any type parameters of the type, /// other than the current trait - additional_bounds: ~[Ty], + additional_bounds: ~[Ty<'self>], /// Any extra lifetimes and/or bounds, e.g. `D: std::serialize::Decoder` - generics: LifetimeBounds, + generics: LifetimeBounds<'self>, methods: ~[MethodDef<'self>] } @@ -209,20 +209,20 @@ pub struct TraitDef<'self> { pub struct MethodDef<'self> { /// name of the method - name: ~str, + name: &'self str, /// List of generics, e.g. `R: core::rand::Rng` - generics: LifetimeBounds, + generics: LifetimeBounds<'self>, /// Whether there is a self argument (outer Option) i.e. whether /// this is a static function, and whether it is a pointer (inner /// Option) - explicit_self: Option>, + explicit_self: Option>>, /// Arguments other than the self argument - args: ~[Ty], + args: ~[Ty<'self>], /// Return type - ret_ty: Ty, + ret_ty: Ty<'self>, /// if the value of the nonmatching enums is independent of the /// actual enum variants, i.e. can use _ => .. match. diff --git a/src/libsyntax/ext/deriving/iter_bytes.rs b/src/libsyntax/ext/deriving/iter_bytes.rs index 1c9ec6ece2e1d..9b8f127d42a0b 100644 --- a/src/libsyntax/ext/deriving/iter_bytes.rs +++ b/src/libsyntax/ext/deriving/iter_bytes.rs @@ -19,19 +19,19 @@ pub fn expand_deriving_iter_bytes(cx: @ext_ctxt, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~[~"core", ~"to_bytes", ~"IterBytes"]), + path: Path::new(~["core", "to_bytes", "IterBytes"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { - name: ~"iter_bytes", + name: "iter_bytes", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[ - Literal(Path::new(~[~"bool"])), - Literal(Path::new(~[~"core", ~"to_bytes", ~"Cb"])) + Literal(Path::new(~["bool"])), + Literal(Path::new(~["core", "to_bytes", "Cb"])) ], - ret_ty: Literal(Path::new(~[~"bool"])), + ret_ty: Literal(Path::new(~["bool"])), const_nonmatching: false, combine_substructure: iter_bytes_substructure } diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index 2d91fcd346ae5..2fb47c1e53ec2 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -21,20 +21,20 @@ pub fn expand_deriving_rand(cx: @ext_ctxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~[~"core", ~"rand", ~"Rand"]), + path: Path::new(~["core", "rand", "Rand"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { - name: ~"rand", + name: "rand", generics: LifetimeBounds { lifetimes: ~[], - bounds: ~[(~"R", - ~[ Path::new(~[~"core", ~"rand", ~"Rng"]) ])] + bounds: ~[("R", + ~[ Path::new(~["core", "rand", "Rng"]) ])] }, explicit_self: None, args: ~[ - Ptr(~Literal(Path::new_local(~"R")), + Ptr(~Literal(Path::new_local("R")), Borrowed(None, ast::m_mutbl)) ], ret_ty: Self, diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs index f155cb3790faa..0c12a1948cd4c 100644 --- a/src/libsyntax/ext/deriving/to_str.rs +++ b/src/libsyntax/ext/deriving/to_str.rs @@ -20,16 +20,16 @@ pub fn expand_deriving_to_str(cx: @ext_ctxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~[~"core", ~"to_str", ~"ToStr"]), + path: Path::new(~["core", "to_str", "ToStr"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ MethodDef { - name: ~"to_str", + name: "to_str", generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[], - ret_ty: Ptr(~Literal(Path::new_local(~"str")), Owned), + ret_ty: Ptr(~Literal(Path::new_local("str")), Owned), const_nonmatching: false, combine_substructure: to_str_substructure } diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index 5fc3aeb789c10..bbc6b6634e383 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -21,31 +21,30 @@ use codemap::{span,respan}; use opt_vec; /// The types of pointers -#[deriving(Eq)] -pub enum PtrTy { +pub enum PtrTy<'self> { Owned, // ~ Managed(ast::mutability), // @[mut] - Borrowed(Option<~str>, ast::mutability), // &['lifetime] [mut] + Borrowed(Option<&'self str>, ast::mutability), // &['lifetime] [mut] } /// A path, e.g. `::core::option::Option::` (global). Has support /// for type parameters and a lifetime. -#[deriving(Eq)] -pub struct Path { - path: ~[~str], - lifetime: Option<~str>, - params: ~[~Ty], +pub struct Path<'self> { + path: ~[&'self str], + lifetime: Option<&'self str>, + params: ~[~Ty<'self>], global: bool } -pub impl Path { - fn new(path: ~[~str]) -> Path { +pub impl<'self> Path<'self> { + fn new<'r>(path: ~[&'r str]) -> Path<'r> { Path::new_(path, None, ~[], true) } - fn new_local(path: ~str) -> Path { + fn new_local<'r>(path: &'r str) -> Path<'r> { Path::new_(~[ path ], None, ~[], false) } - fn new_(path: ~[~str], lifetime: Option<~str>, params: ~[~Ty], global: bool) -> Path { + fn new_<'r>(path: ~[&'r str], lifetime: Option<&'r str>, params: ~[~Ty<'r>], global: bool) + -> Path<'r> { Path { path: path, lifetime: lifetime, @@ -56,9 +55,9 @@ pub impl Path { fn to_ty(&self, cx: @ext_ctxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Ty { - build::mk_ty_path_path(cx, span, - self.to_path(cx, span, - self_ty, self_generics)) + build::mk_ty_path_path(cx, span, + self.to_path(cx, span, + self_ty, self_generics)) } fn to_path(&self, cx: @ext_ctxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Path { @@ -75,45 +74,44 @@ pub impl Path { } /// A type. Supports pointers (except for *), Self, and literals -#[deriving(Eq)] -pub enum Ty { +pub enum Ty<'self> { Self, // &/~/@ Ty - Ptr(~Ty, PtrTy), + Ptr(~Ty<'self>, PtrTy<'self>), // mod::mod::Type<[lifetime], [Params...]>, including a plain type // parameter, and things like `int` - Literal(Path), + Literal(Path<'self>), // includes nil - Tuple(~[Ty]) + Tuple(~[Ty<'self>]) } -pub fn borrowed_ptrty() -> PtrTy { +pub fn borrowed_ptrty<'r>() -> PtrTy<'r> { Borrowed(None, ast::m_imm) } -pub fn borrowed(ty: ~Ty) -> Ty { +pub fn borrowed<'r>(ty: ~Ty<'r>) -> Ty<'r> { Ptr(ty, borrowed_ptrty()) } -pub fn borrowed_explicit_self() -> Option> { +pub fn borrowed_explicit_self<'r>() -> Option>> { Some(Some(borrowed_ptrty())) } -pub fn borrowed_self() -> Ty { +pub fn borrowed_self<'r>() -> Ty<'r> { borrowed(~Self) } -pub fn nil_ty() -> Ty { +pub fn nil_ty() -> Ty<'static> { Tuple(~[]) } -fn mk_lifetime(cx: @ext_ctxt, span: span, lt: &Option<~str>) -> Option<@ast::Lifetime> { +fn mk_lifetime(cx: @ext_ctxt, span: span, lt: &Option<&str>) -> Option<@ast::Lifetime> { match *lt { Some(ref s) => Some(@build::mk_lifetime(cx, span, cx.ident_of(*s))), None => None } } -pub impl Ty { +pub impl<'self> Ty<'self> { fn to_ty(&self, cx: @ext_ctxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Ty { match *self { @@ -174,7 +172,7 @@ pub impl Ty { } -fn mk_ty_param(cx: @ext_ctxt, span: span, name: ~str, bounds: ~[Path], +fn mk_ty_param(cx: @ext_ctxt, span: span, name: &str, bounds: &[Path], self_ident: ident, self_generics: &Generics) -> ast::TyParam { let bounds = opt_vec::from( do bounds.map |b| { @@ -192,24 +190,28 @@ fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Gene } /// Lifetimes and bounds on type parameters -pub struct LifetimeBounds { - lifetimes: ~[~str], - bounds: ~[(~str, ~[Path])] +pub struct LifetimeBounds<'self> { + lifetimes: ~[&'self str], + bounds: ~[(&'self str, ~[Path<'self>])] } -pub impl LifetimeBounds { - fn empty() -> LifetimeBounds { +pub impl<'self> LifetimeBounds<'self> { + fn empty() -> LifetimeBounds<'static> { LifetimeBounds { lifetimes: ~[], bounds: ~[] } } fn to_generics(&self, cx: @ext_ctxt, span: span, self_ty: ident, self_generics: &Generics) -> Generics { - let lifetimes = do self.lifetimes.map |<| { - build::mk_lifetime(cx, span, cx.ident_of(lt)) + let lifetimes = do self.lifetimes.map |lt| { + build::mk_lifetime(cx, span, cx.ident_of(*lt)) }; - let ty_params = do self.bounds.map |&(name, bounds)| { - mk_ty_param(cx, span, name, bounds, self_ty, self_generics) + let ty_params = do self.bounds.map |t| { + match t { + &(ref name, ref bounds) => { + mk_ty_param(cx, span, *name, *bounds, self_ty, self_generics) + } + } }; mk_generics(lifetimes, ty_params) } From d543354d6c56e8962b0c03397d43df3f16b07d03 Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Tue, 21 May 2013 22:55:07 +0900 Subject: [PATCH 154/248] Remove unnecessary allocations flagged by lint from rustdoc --- src/librustdoc/attr_parser.rs | 6 ++--- src/librustdoc/config.rs | 8 +++--- src/librustdoc/desc_to_brief_pass.rs | 4 +-- src/librustdoc/escape_pass.rs | 2 +- src/librustdoc/markdown_index_pass.rs | 36 +++++++++++++-------------- src/librustdoc/markdown_pass.rs | 6 ++--- src/librustdoc/markdown_writer.rs | 6 ++--- src/librustdoc/sectionalize_pass.rs | 2 +- src/librustdoc/unindent_pass.rs | 2 +- 9 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/librustdoc/attr_parser.rs b/src/librustdoc/attr_parser.rs index 433809b9db291..ec31795337bb5 100644 --- a/src/librustdoc/attr_parser.rs +++ b/src/librustdoc/attr_parser.rs @@ -26,7 +26,7 @@ fn doc_metas( attrs: ~[ast::attribute] ) -> ~[@ast::meta_item] { - let doc_attrs = attr::find_attrs_by_name(attrs, ~"doc"); + let doc_attrs = attr::find_attrs_by_name(attrs, "doc"); let doc_metas = do doc_attrs.map |attr| { attr::attr_meta(attr::desugar_doc_attr(attr)) }; @@ -36,7 +36,7 @@ fn doc_metas( pub fn parse_crate(attrs: ~[ast::attribute]) -> CrateAttrs { let link_metas = attr::find_linkage_metas(attrs); - let name = attr::last_meta_item_value_str_by_name(link_metas, ~"name"); + let name = attr::last_meta_item_value_str_by_name(link_metas, "name"); CrateAttrs { name: name.map(|s| copy **s) @@ -58,7 +58,7 @@ pub fn parse_hidden(attrs: ~[ast::attribute]) -> bool { do doc_metas(attrs).find |meta| { match attr::get_meta_item_list(*meta) { Some(metas) => { - let hiddens = attr::find_meta_items_by_name(metas, ~"hidden"); + let hiddens = attr::find_meta_items_by_name(metas, "hidden"); !hiddens.is_empty() } None => false diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 0644b57a0f45b..7464b708045af 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -70,12 +70,12 @@ fn opts() -> ~[(getopts::Opt, ~str)] { pub fn usage() { use core::io::println; - println(~"Usage: rustdoc [options] \n"); - println(~"Options:\n"); + println("Usage: rustdoc [options] \n"); + println("Options:\n"); for opts().each |opt| { println(fmt!(" %s", opt.second())); } - println(~""); + println(""); } pub fn default_config(input_crate: &Path) -> Config { @@ -227,7 +227,7 @@ pub fn maybe_find_pandoc( }; let pandoc = do vec::find(possible_pandocs) |pandoc| { - let output = program_output(*pandoc, ~[~"--version"]); + let output = program_output(*pandoc, [~"--version"]); debug!("testing pandoc cmd %s: %?", *pandoc, output); output.status == 0 }; diff --git a/src/librustdoc/desc_to_brief_pass.rs b/src/librustdoc/desc_to_brief_pass.rs index c25764ab0601b..c61b38743fd1f 100644 --- a/src/librustdoc/desc_to_brief_pass.rs +++ b/src/librustdoc/desc_to_brief_pass.rs @@ -104,7 +104,7 @@ fn first_sentence(s: ~str) -> Option<~str> { let paras = paragraphs(s); if !paras.is_empty() { let first_para = paras.head(); - Some(str::replace(first_sentence_(*first_para), ~"\n", ~" ")) + Some(str::replace(first_sentence_(*first_para), "\n", " ")) } else { None } @@ -132,7 +132,7 @@ fn first_sentence_(s: &str) -> ~str { str::to_owned(str::slice(s, 0, idx - 1)) } _ => { - if str::ends_with(s, ~".") { + if str::ends_with(s, ".") { str::to_owned(s) } else { str::to_owned(s) diff --git a/src/librustdoc/escape_pass.rs b/src/librustdoc/escape_pass.rs index 11e9b71afdfff..045e916b11006 100644 --- a/src/librustdoc/escape_pass.rs +++ b/src/librustdoc/escape_pass.rs @@ -20,7 +20,7 @@ pub fn mk_pass() -> Pass { } fn escape(s: &str) -> ~str { - str::replace(s, ~"\\", ~"\\\\") + str::replace(s, "\\", "\\\\") } #[test] diff --git a/src/librustdoc/markdown_index_pass.rs b/src/librustdoc/markdown_index_pass.rs index 2c34f3543b734..c7329c4a54b5e 100644 --- a/src/librustdoc/markdown_index_pass.rs +++ b/src/librustdoc/markdown_index_pass.rs @@ -124,24 +124,24 @@ pub fn pandoc_header_id(header: &str) -> ~str { return header; fn remove_formatting(s: &str) -> ~str { - str::replace(s, ~"`", ~"") + str::replace(s, "`", "") } fn remove_punctuation(s: &str) -> ~str { - let s = str::replace(s, ~"<", ~""); - let s = str::replace(s, ~">", ~""); - let s = str::replace(s, ~"[", ~""); - let s = str::replace(s, ~"]", ~""); - let s = str::replace(s, ~"(", ~""); - let s = str::replace(s, ~")", ~""); - let s = str::replace(s, ~"@~", ~""); - let s = str::replace(s, ~"~", ~""); - let s = str::replace(s, ~"/", ~""); - let s = str::replace(s, ~":", ~""); - let s = str::replace(s, ~"&", ~""); - let s = str::replace(s, ~"^", ~""); - let s = str::replace(s, ~",", ~""); - let s = str::replace(s, ~"'", ~""); - let s = str::replace(s, ~"+", ~""); + let s = str::replace(s, "<", ""); + let s = str::replace(s, ">", ""); + let s = str::replace(s, "[", ""); + let s = str::replace(s, "]", ""); + let s = str::replace(s, "(", ""); + let s = str::replace(s, ")", ""); + let s = str::replace(s, "@~", ""); + let s = str::replace(s, "~", ""); + let s = str::replace(s, "/", ""); + let s = str::replace(s, ":", ""); + let s = str::replace(s, "&", ""); + let s = str::replace(s, "^", ""); + let s = str::replace(s, ",", ""); + let s = str::replace(s, "'", ""); + let s = str::replace(s, "+", ""); return s; } fn replace_with_hyphens(s: &str) -> ~str { @@ -149,8 +149,8 @@ pub fn pandoc_header_id(header: &str) -> ~str { // XXX: Hacky implementation here that only covers // one or two spaces. let s = str::trim(s); - let s = str::replace(s, ~" ", ~"-"); - let s = str::replace(s, ~" ", ~"-"); + let s = str::replace(s, " ", "-"); + let s = str::replace(s, " ", "-"); return s; } // FIXME: #4318 Instead of to_ascii and to_str_ascii, could use diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index 1eac09ea2056f..4f4bb4194a897 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -110,7 +110,7 @@ fn make_title(page: doc::Page) -> ~str { } }; let title = markdown_pass::header_text(item); - let title = str::replace(title, ~"`", ~""); + let title = str::replace(title, "`", ""); return title; } @@ -169,7 +169,7 @@ pub fn header_kind(doc: doc::ItemTag) -> ~str { } pub fn header_name(doc: doc::ItemTag) -> ~str { - let fullpath = str::connect(doc.path() + ~[doc.name()], ~"::"); + let fullpath = str::connect(doc.path() + ~[doc.name()], "::"); match &doc { &doc::ModTag(_) if doc.id() != syntax::ast::crate_node_id => { fullpath @@ -471,7 +471,7 @@ fn write_methods(ctxt: &Ctxt, docs: &[doc::MethodDoc]) { } fn write_method(ctxt: &Ctxt, doc: doc::MethodDoc) { - write_header_(ctxt, H3, header_text_(~"Method", doc.name)); + write_header_(ctxt, H3, header_text_("Method", doc.name)); write_fnlike( ctxt, copy doc.sig, diff --git a/src/librustdoc/markdown_writer.rs b/src/librustdoc/markdown_writer.rs index 94372127a22ed..671364f4dbb34 100644 --- a/src/librustdoc/markdown_writer.rs +++ b/src/librustdoc/markdown_writer.rs @@ -101,7 +101,7 @@ fn pandoc_writer( use core::io::WriterUtil; debug!("pandoc cmd: %s", pandoc_cmd); - debug!("pandoc args: %s", str::connect(pandoc_args, ~" ")); + debug!("pandoc args: %s", str::connect(pandoc_args, " ")); let pipe_in = os::pipe(); let pipe_out = os::pipe(); @@ -198,7 +198,7 @@ pub fn make_filename( } } doc::ItemPage(doc) => { - str::connect(doc.path() + ~[doc.name()], ~"_") + str::connect(doc.path() + ~[doc.name()], "_") } } }; @@ -213,7 +213,7 @@ pub fn make_filename( fn write_file(path: &Path, s: ~str) { use core::io::WriterUtil; - match io::file_writer(path, ~[io::Create, io::Truncate]) { + match io::file_writer(path, [io::Create, io::Truncate]) { result::Ok(writer) => { writer.write_str(s); } diff --git a/src/librustdoc/sectionalize_pass.rs b/src/librustdoc/sectionalize_pass.rs index 8c3704d55c7d9..afd29ab724867 100644 --- a/src/librustdoc/sectionalize_pass.rs +++ b/src/librustdoc/sectionalize_pass.rs @@ -149,7 +149,7 @@ fn sectionalize(desc: Option<~str>) -> (Option<~str>, ~[doc::Section]) { } fn parse_header(line: ~str) -> Option<~str> { - if str::starts_with(line, ~"# ") { + if str::starts_with(line, "# ") { Some(str::slice(line, 2u, str::len(line)).to_owned()) } else { None diff --git a/src/librustdoc/unindent_pass.rs b/src/librustdoc/unindent_pass.rs index 826012a244724..1e3e4acce050c 100644 --- a/src/librustdoc/unindent_pass.rs +++ b/src/librustdoc/unindent_pass.rs @@ -82,7 +82,7 @@ fn unindent(s: &str) -> ~str { str::slice(*line, min_indent, str::len(*line)).to_owned() } }; - str::connect(unindented, ~"\n") + str::connect(unindented, "\n") } else { s.to_str() } From d4724c1a178252c240c9ad012fc3cba93f18babc Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Tue, 21 May 2013 23:00:34 +0900 Subject: [PATCH 155/248] Remove unnecessary allocations flagged by lint from rustpkg --- src/librustpkg/rustpkg.rc | 26 +++++++++++++------------- src/librustpkg/usage.rs | 20 ++++++++++---------- src/librustpkg/util.rs | 12 ++++++------ 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index c1aaa4287156d..94fdcddfbb5b5 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -126,14 +126,14 @@ impl<'self> PkgScript<'self> { &exe, @copy os::args()[0], driver::cu_everything); debug!("Running program: %s %s %s", exe.to_str(), root.to_str(), what); - let status = run::run_program(exe.to_str(), ~[root.to_str(), what]); + let status = run::run_program(exe.to_str(), [root.to_str(), what]); if status != 0 { return (~[], status); } else { debug!("Running program (configs): %s %s %s", - exe.to_str(), root.to_str(), ~"configs"); - let output = run::program_output(exe.to_str(), ~[root.to_str(), ~"configs"]); + exe.to_str(), root.to_str(), "configs"); + let output = run::program_output(exe.to_str(), [root.to_str(), ~"configs"]); // Run the configs() function to get the configs let mut cfgs = ~[]; for str::each_word(output.out) |w| { @@ -360,9 +360,9 @@ pub fn main() { io::println("WARNING: The Rust package manager is experimental and may be unstable"); let args = os::args(); - let opts = ~[getopts::optflag(~"h"), getopts::optflag(~"help"), - getopts::optflag(~"j"), getopts::optflag(~"json"), - getopts::optmulti(~"c"), getopts::optmulti(~"cfg")]; + let opts = ~[getopts::optflag("h"), getopts::optflag("help"), + getopts::optflag("j"), getopts::optflag("json"), + getopts::optmulti("c"), getopts::optmulti("cfg")]; let matches = &match getopts::getopts(args, opts) { result::Ok(m) => m, result::Err(f) => { @@ -371,10 +371,10 @@ pub fn main() { return; } }; - let help = getopts::opt_present(matches, ~"h") || - getopts::opt_present(matches, ~"help"); - let json = getopts::opt_present(matches, ~"j") || - getopts::opt_present(matches, ~"json"); + let help = getopts::opt_present(matches, "h") || + getopts::opt_present(matches, "help"); + let json = getopts::opt_present(matches, "j") || + getopts::opt_present(matches, "json"); let mut args = copy matches.free; args.shift(); @@ -428,7 +428,7 @@ pub impl Crate { fn flag(&self, flag: ~str) -> Crate { Crate { - flags: vec::append(copy self.flags, ~[flag]), + flags: vec::append(copy self.flags, [flag]), .. copy *self } } @@ -442,7 +442,7 @@ pub impl Crate { fn cfg(&self, cfg: ~str) -> Crate { Crate { - cfgs: vec::append(copy self.cfgs, ~[cfg]), + cfgs: vec::append(copy self.cfgs, [cfg]), .. copy *self } } @@ -546,7 +546,7 @@ impl PkgSrc { let url = fmt!("https://%s", self.id.remote_path.to_str()); util::note(fmt!("git clone %s %s", url, local.to_str())); - if run::program_output(~"git", ~[~"clone", copy url, local.to_str()]).status != 0 { + if run::program_output("git", [~"clone", copy url, local.to_str()]).status != 0 { util::note(fmt!("fetching %s failed: can't clone repository", url)); return false; } diff --git a/src/librustpkg/usage.rs b/src/librustpkg/usage.rs index cfda56f777ab2..90c87210faaa8 100644 --- a/src/librustpkg/usage.rs +++ b/src/librustpkg/usage.rs @@ -11,7 +11,7 @@ use core::io; pub fn general() { - io::println(~"Usage: rustpkg [options] [args..] + io::println("Usage: rustpkg [options] [args..] Where is one of: build, clean, do, info, install, prefer, test, uninstall, unprefer @@ -23,7 +23,7 @@ Options: } pub fn build() { - io::println(~"rustpkg [options..] build + io::println("rustpkg [options..] build Build all targets described in the package script in the current directory. @@ -33,21 +33,21 @@ Options: } pub fn clean() { - io::println(~"rustpkg clean + io::println("rustpkg clean Remove all build files in the work cache for the package in the current directory."); } pub fn do_cmd() { - io::println(~"rustpkg do + io::println("rustpkg do Runs a command in the package script. You can listen to a command by tagging a function with the attribute `#[pkg_do(cmd)]`."); } pub fn info() { - io::println(~"rustpkg [options..] info + io::println("rustpkg [options..] info Probe the package script in the current directory for information. @@ -56,7 +56,7 @@ Options: } pub fn install() { - io::println(~"rustpkg [options..] install [url] [target] + io::println("rustpkg [options..] install [url] [target] Install a package from a URL by Git or cURL (FTP, HTTP, etc.). If target is provided, Git will checkout the branch or tag before @@ -76,14 +76,14 @@ Options: } pub fn uninstall() { - io::println(~"rustpkg uninstall [@version] + io::println("rustpkg uninstall [@version] Remove a package by id or name and optionally version. If the package(s) is/are depended on by another package then they cannot be removed."); } pub fn prefer() { - io::println(~"rustpkg [options..] prefer [@version] + io::println("rustpkg [options..] prefer [@version] By default all binaries are given a unique name so that multiple versions can coexist. The prefer command will symlink the uniquely named binary to @@ -101,7 +101,7 @@ Example: } pub fn unprefer() { - io::println(~"rustpkg [options..] unprefer [@version] + io::println("rustpkg [options..] unprefer [@version] Remove all symlinks from the store to the binary directory for a package name and optionally version. If version is not supplied, the latest version @@ -110,7 +110,7 @@ information."); } pub fn test() { - io::println(~"rustpkg [options..] test + io::println("rustpkg [options..] test Build all targets described in the package script in the current directory with the test flag. The test bootstraps will be run afterwards and the output diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index 0ae9539fecec3..2ee16c67ddde2 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -208,7 +208,7 @@ fn fold_item(ctx: @mut ReadyCtx, fold: @fold::ast_fold) -> Option<@ast::item> { ctx.path.push(item.ident); - let attrs = attr::find_attrs_by_name(item.attrs, ~"pkg_do"); + let attrs = attr::find_attrs_by_name(item.attrs, "pkg_do"); if attrs.len() > 0 { let mut cmds = ~[]; @@ -281,7 +281,7 @@ pub fn note(msg: ~str) { if term::color_supported() { term::fg(out, term::color_green); - out.write_str(~"note: "); + out.write_str("note: "); term::reset(out); out.write_line(msg); } else { @@ -294,7 +294,7 @@ pub fn warn(msg: ~str) { if term::color_supported() { term::fg(out, term::color_yellow); - out.write_str(~"warning: "); + out.write_str("warning: "); term::reset(out); out.write_line(msg); } else { @@ -307,7 +307,7 @@ pub fn error(msg: ~str) { if term::color_supported() { term::fg(out, term::color_red); - out.write_str(~"error: "); + out.write_str("error: "); term::reset(out); out.write_line(msg); } else { @@ -353,8 +353,8 @@ pub fn compile_input(sysroot: Option<@Path>, debug!("compiling %s into %s", in_file.to_str(), out_file.to_str()); - debug!("flags: %s", str::connect(flags, ~" ")); - debug!("cfgs: %s", str::connect(cfgs, ~" ")); + debug!("flags: %s", str::connect(flags, " ")); + debug!("cfgs: %s", str::connect(cfgs, " ")); debug!("compile_input's sysroot = %?", sysroot); let crate_type = match what { From eea265ea165cb0e6fa989a3712efd701456b265d Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 17 May 2013 20:10:26 +1000 Subject: [PATCH 156/248] syntax/ext: Remove the trait-object indirection of the ext_ctxt object. --- src/libsyntax/ext/base.rs | 188 +++++++++++++++++--------------------- 1 file changed, 82 insertions(+), 106 deletions(-) diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 2a7f8c8865b81..b387694c6c191 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -202,131 +202,107 @@ pub fn syntax_expander_table() -> SyntaxEnv { // One of these is made during expansion and incrementally updated as we go; // when a macro expansion occurs, the resulting nodes have the backtrace() // -> expn_info of their expansion context stored into their span. -pub trait ext_ctxt { - fn codemap(&self) -> @CodeMap; - fn parse_sess(&self) -> @mut parse::ParseSess; - fn cfg(&self) -> ast::crate_cfg; - fn call_site(&self) -> span; - fn print_backtrace(&self); - fn backtrace(&self) -> Option<@ExpnInfo>; - fn mod_push(&self, mod_name: ast::ident); - fn mod_pop(&self); - fn mod_path(&self) -> ~[ast::ident]; - fn bt_push(&self, ei: codemap::ExpnInfo); - fn bt_pop(&self); - fn span_fatal(&self, sp: span, msg: &str) -> !; - fn span_err(&self, sp: span, msg: &str); - fn span_warn(&self, sp: span, msg: &str); - fn span_unimpl(&self, sp: span, msg: &str) -> !; - fn span_bug(&self, sp: span, msg: &str) -> !; - fn bug(&self, msg: &str) -> !; - fn next_id(&self) -> ast::node_id; - fn trace_macros(&self) -> bool; - fn set_trace_macros(&self, x: bool); - /* for unhygienic identifier transformation */ - fn str_of(&self, id: ast::ident) -> ~str; - fn ident_of(&self, st: &str) -> ast::ident; +pub struct ext_ctxt { + parse_sess: @mut parse::ParseSess, + cfg: ast::crate_cfg, + backtrace: @mut Option<@ExpnInfo>, + + // These two @mut's should really not be here, + // but the self types for CtxtRepr are all wrong + // and there are bugs in the code for object + // types that make this hard to get right at the + // moment. - nmatsakis + mod_path: @mut ~[ast::ident], + trace_mac: @mut bool } -pub fn mk_ctxt(parse_sess: @mut parse::ParseSess, cfg: ast::crate_cfg) - -> @ext_ctxt { - struct CtxtRepr { - parse_sess: @mut parse::ParseSess, - cfg: ast::crate_cfg, - backtrace: @mut Option<@ExpnInfo>, - - // These two @mut's should really not be here, - // but the self types for CtxtRepr are all wrong - // and there are bugs in the code for object - // types that make this hard to get right at the - // moment. - nmatsakis - mod_path: @mut ~[ast::ident], - trace_mac: @mut bool - } - impl ext_ctxt for CtxtRepr { - fn codemap(&self) -> @CodeMap { self.parse_sess.cm } - fn parse_sess(&self) -> @mut parse::ParseSess { self.parse_sess } - fn cfg(&self) -> ast::crate_cfg { copy self.cfg } - fn call_site(&self) -> span { - match *self.backtrace { - Some(@ExpandedFrom(CallInfo {call_site: cs, _})) => cs, - None => self.bug("missing top span") - } +pub impl ext_ctxt { + fn codemap(&self) -> @CodeMap { self.parse_sess.cm } + fn parse_sess(&self) -> @mut parse::ParseSess { self.parse_sess } + fn cfg(&self) -> ast::crate_cfg { copy self.cfg } + fn call_site(&self) -> span { + match *self.backtrace { + Some(@ExpandedFrom(CallInfo {call_site: cs, _})) => cs, + None => self.bug("missing top span") } - fn print_backtrace(&self) { } - fn backtrace(&self) -> Option<@ExpnInfo> { *self.backtrace } - fn mod_push(&self, i: ast::ident) { self.mod_path.push(i); } - fn mod_pop(&self) { self.mod_path.pop(); } - fn mod_path(&self) -> ~[ast::ident] { copy *self.mod_path } - fn bt_push(&self, ei: codemap::ExpnInfo) { - match ei { - ExpandedFrom(CallInfo {call_site: cs, callee: ref callee}) => { + } + fn print_backtrace(&self) { } + fn backtrace(&self) -> Option<@ExpnInfo> { *self.backtrace } + fn mod_push(&self, i: ast::ident) { self.mod_path.push(i); } + fn mod_pop(&self) { self.mod_path.pop(); } + fn mod_path(&self) -> ~[ast::ident] { copy *self.mod_path } + fn bt_push(&self, ei: codemap::ExpnInfo) { + match ei { + ExpandedFrom(CallInfo {call_site: cs, callee: ref callee}) => { *self.backtrace = Some(@ExpandedFrom(CallInfo { call_site: span {lo: cs.lo, hi: cs.hi, expn_info: *self.backtrace}, callee: copy *callee})); - } } } - fn bt_pop(&self) { - match *self.backtrace { - Some(@ExpandedFrom(CallInfo { - call_site: span {expn_info: prev, _}, _ - })) => { + } + fn bt_pop(&self) { + match *self.backtrace { + Some(@ExpandedFrom( + CallInfo { + call_site: span {expn_info: prev, _}, _ + })) => { *self.backtrace = prev - } - _ => self.bug("tried to pop without a push") } - } - fn span_fatal(&self, sp: span, msg: &str) -> ! { - self.print_backtrace(); - self.parse_sess.span_diagnostic.span_fatal(sp, msg); - } - fn span_err(&self, sp: span, msg: &str) { - self.print_backtrace(); - self.parse_sess.span_diagnostic.span_err(sp, msg); - } - fn span_warn(&self, sp: span, msg: &str) { - self.print_backtrace(); - self.parse_sess.span_diagnostic.span_warn(sp, msg); - } - fn span_unimpl(&self, sp: span, msg: &str) -> ! { - self.print_backtrace(); - self.parse_sess.span_diagnostic.span_unimpl(sp, msg); - } - fn span_bug(&self, sp: span, msg: &str) -> ! { - self.print_backtrace(); - self.parse_sess.span_diagnostic.span_bug(sp, msg); - } - fn bug(&self, msg: &str) -> ! { - self.print_backtrace(); - self.parse_sess.span_diagnostic.handler().bug(msg); - } - fn next_id(&self) -> ast::node_id { - return parse::next_node_id(self.parse_sess); - } - fn trace_macros(&self) -> bool { - *self.trace_mac - } - fn set_trace_macros(&self, x: bool) { - *self.trace_mac = x - } - fn str_of(&self, id: ast::ident) -> ~str { - copy *self.parse_sess.interner.get(id) - } - fn ident_of(&self, st: &str) -> ast::ident { - self.parse_sess.interner.intern(st) + _ => self.bug("tried to pop without a push") } } - let imp: @CtxtRepr = @CtxtRepr { + fn span_fatal(&self, sp: span, msg: &str) -> ! { + self.print_backtrace(); + self.parse_sess.span_diagnostic.span_fatal(sp, msg); + } + fn span_err(&self, sp: span, msg: &str) { + self.print_backtrace(); + self.parse_sess.span_diagnostic.span_err(sp, msg); + } + fn span_warn(&self, sp: span, msg: &str) { + self.print_backtrace(); + self.parse_sess.span_diagnostic.span_warn(sp, msg); + } + fn span_unimpl(&self, sp: span, msg: &str) -> ! { + self.print_backtrace(); + self.parse_sess.span_diagnostic.span_unimpl(sp, msg); + } + fn span_bug(&self, sp: span, msg: &str) -> ! { + self.print_backtrace(); + self.parse_sess.span_diagnostic.span_bug(sp, msg); + } + fn bug(&self, msg: &str) -> ! { + self.print_backtrace(); + self.parse_sess.span_diagnostic.handler().bug(msg); + } + fn next_id(&self) -> ast::node_id { + parse::next_node_id(self.parse_sess) + } + fn trace_macros(&self) -> bool { + *self.trace_mac + } + fn set_trace_macros(&self, x: bool) { + *self.trace_mac = x + } + fn str_of(&self, id: ast::ident) -> ~str { + copy *self.parse_sess.interner.get(id) + } + fn ident_of(&self, st: &str) -> ast::ident { + self.parse_sess.interner.intern(st) + } +} + +pub fn mk_ctxt(parse_sess: @mut parse::ParseSess, cfg: ast::crate_cfg) + -> @ext_ctxt { + @ext_ctxt { parse_sess: parse_sess, cfg: cfg, backtrace: @mut None, mod_path: @mut ~[], trace_mac: @mut false - }; - ((imp) as @ext_ctxt) + } } pub fn expr_to_str(cx: @ext_ctxt, expr: @ast::expr, err_msg: ~str) -> ~str { From 4045da9f4f7290b02bee52caa42504e4ce5406f7 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 17 May 2013 21:27:17 +1000 Subject: [PATCH 157/248] syntax/ext: modernise ext_ctxt to be CamelCase and use new. --- src/librustc/front/test.rs | 6 +- src/librustpkg/util.rs | 6 +- src/libsyntax/ext/asm.rs | 2 +- src/libsyntax/ext/auto_encode.rs | 4 +- src/libsyntax/ext/base.rs | 41 +++--- src/libsyntax/ext/build.rs | 140 ++++++++++----------- src/libsyntax/ext/bytes.rs | 2 +- src/libsyntax/ext/concat_idents.rs | 2 +- src/libsyntax/ext/deriving/clone.rs | 8 +- src/libsyntax/ext/deriving/cmp/eq.rs | 8 +- src/libsyntax/ext/deriving/cmp/ord.rs | 6 +- src/libsyntax/ext/deriving/cmp/totaleq.rs | 6 +- src/libsyntax/ext/deriving/cmp/totalord.rs | 8 +- src/libsyntax/ext/deriving/decodable.rs | 26 ++-- src/libsyntax/ext/deriving/encodable.rs | 18 +-- src/libsyntax/ext/deriving/generic.rs | 52 ++++---- src/libsyntax/ext/deriving/iter_bytes.rs | 6 +- src/libsyntax/ext/deriving/mod.rs | 26 ++-- src/libsyntax/ext/deriving/rand.rs | 8 +- src/libsyntax/ext/deriving/to_str.rs | 6 +- src/libsyntax/ext/deriving/ty.rs | 18 +-- src/libsyntax/ext/env.rs | 2 +- src/libsyntax/ext/expand.rs | 16 +-- src/libsyntax/ext/fmt.rs | 24 ++-- src/libsyntax/ext/log_syntax.rs | 2 +- src/libsyntax/ext/pipes/ast_builder.rs | 4 +- src/libsyntax/ext/pipes/check.rs | 4 +- src/libsyntax/ext/pipes/liveness.rs | 4 +- src/libsyntax/ext/pipes/mod.rs | 4 +- src/libsyntax/ext/pipes/pipec.rs | 42 +++---- src/libsyntax/ext/pipes/proto.rs | 4 +- src/libsyntax/ext/quote.rs | 124 +++++++++--------- src/libsyntax/ext/source_util.rs | 18 +-- src/libsyntax/ext/trace_macros.rs | 4 +- src/libsyntax/ext/tt/macro_rules.rs | 8 +- src/test/run-pass-fulldeps/quote-tokens.rs | 4 +- 36 files changed, 331 insertions(+), 332 deletions(-) diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index eb199f6e10834..a0ff8cb5e4d24 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -17,7 +17,7 @@ use syntax::ast_util::*; use syntax::attr; use syntax::codemap::{dummy_sp, span, ExpandedFrom, CallInfo, NameAndSpan}; use syntax::codemap; -use syntax::ext::base::{mk_ctxt, ext_ctxt}; +use syntax::ext::base::ExtCtxt; use syntax::fold; use syntax::print::pprust; use syntax::{ast, ast_util}; @@ -36,7 +36,7 @@ struct TestCtxt { sess: session::Session, crate: @ast::crate, path: ~[ast::ident], - ext_cx: @ext_ctxt, + ext_cx: @ExtCtxt, testfns: ~[Test] } @@ -64,7 +64,7 @@ fn generate_test_harness(sess: session::Session, let cx: @mut TestCtxt = @mut TestCtxt { sess: sess, crate: crate, - ext_cx: mk_ctxt(sess.parse_sess, copy sess.opts.cfg), + ext_cx: ExtCtxt::new(sess.parse_sess, copy sess.opts.cfg), path: ~[], testfns: ~[] }; diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index 0ae9539fecec3..f18396f95be42 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -19,7 +19,7 @@ use std::semver; use std::term; use syntax::ast_util::*; use syntax::codemap::{dummy_sp, spanned, dummy_spanned}; -use syntax::ext::base::{mk_ctxt, ext_ctxt}; +use syntax::ext::base::ExtCtxt; use syntax::{ast, attr, codemap, diagnostic, fold}; use syntax::ast::{meta_name_value, meta_list}; use syntax::attr::{mk_attr}; @@ -178,7 +178,7 @@ struct ListenerFn { struct ReadyCtx { sess: session::Session, crate: @ast::crate, - ext_cx: @ext_ctxt, + ext_cx: @ExtCtxt, path: ~[ast::ident], fns: ~[ListenerFn] } @@ -247,7 +247,7 @@ pub fn ready_crate(sess: session::Session, let ctx = @mut ReadyCtx { sess: sess, crate: crate, - ext_cx: mk_ctxt(sess.parse_sess, copy sess.opts.cfg), + ext_cx: ExtCtxt::new(sess.parse_sess, copy sess.opts.cfg), path: ~[], fns: ~[] }; diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index 97c5797cf57d2..162eced11242b 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -37,7 +37,7 @@ fn next_state(s: State) -> Option { } } -pub fn expand_asm(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_asm(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let p = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), diff --git a/src/libsyntax/ext/auto_encode.rs b/src/libsyntax/ext/auto_encode.rs index 6bb3ac5eba4cd..64d2644b38310 100644 --- a/src/libsyntax/ext/auto_encode.rs +++ b/src/libsyntax/ext/auto_encode.rs @@ -15,7 +15,7 @@ use codemap::span; use ext::base::*; pub fn expand_auto_encode( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, _mitem: @ast::meta_item, in_items: ~[@ast::item] @@ -25,7 +25,7 @@ pub fn expand_auto_encode( } pub fn expand_auto_decode( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, _mitem: @ast::meta_item, in_items: ~[@ast::item] diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index b387694c6c191..9b71fb9647ce1 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -33,7 +33,7 @@ pub struct MacroDef { ext: SyntaxExtension } -pub type ItemDecorator = @fn(@ext_ctxt, +pub type ItemDecorator = @fn(@ExtCtxt, span, @ast::meta_item, ~[@ast::item]) @@ -44,7 +44,7 @@ pub struct SyntaxExpanderTT { span: Option } -pub type SyntaxExpanderTTFun = @fn(@ext_ctxt, +pub type SyntaxExpanderTTFun = @fn(@ExtCtxt, span, &[ast::token_tree]) -> MacResult; @@ -54,7 +54,7 @@ pub struct SyntaxExpanderTTItem { span: Option } -pub type SyntaxExpanderTTItemFun = @fn(@ext_ctxt, +pub type SyntaxExpanderTTItemFun = @fn(@ExtCtxt, span, ast::ident, ~[ast::token_tree]) @@ -202,7 +202,7 @@ pub fn syntax_expander_table() -> SyntaxEnv { // One of these is made during expansion and incrementally updated as we go; // when a macro expansion occurs, the resulting nodes have the backtrace() // -> expn_info of their expansion context stored into their span. -pub struct ext_ctxt { +pub struct ExtCtxt { parse_sess: @mut parse::ParseSess, cfg: ast::crate_cfg, backtrace: @mut Option<@ExpnInfo>, @@ -216,7 +216,17 @@ pub struct ext_ctxt { trace_mac: @mut bool } -pub impl ext_ctxt { +pub impl ExtCtxt { + fn new(parse_sess: @mut parse::ParseSess, cfg: ast::crate_cfg) -> @ExtCtxt { + @ExtCtxt { + parse_sess: parse_sess, + cfg: cfg, + backtrace: @mut None, + mod_path: @mut ~[], + trace_mac: @mut false + } + } + fn codemap(&self) -> @CodeMap { self.parse_sess.cm } fn parse_sess(&self) -> @mut parse::ParseSess { self.parse_sess } fn cfg(&self) -> ast::crate_cfg { copy self.cfg } @@ -294,18 +304,7 @@ pub impl ext_ctxt { } } -pub fn mk_ctxt(parse_sess: @mut parse::ParseSess, cfg: ast::crate_cfg) - -> @ext_ctxt { - @ext_ctxt { - parse_sess: parse_sess, - cfg: cfg, - backtrace: @mut None, - mod_path: @mut ~[], - trace_mac: @mut false - } -} - -pub fn expr_to_str(cx: @ext_ctxt, expr: @ast::expr, err_msg: ~str) -> ~str { +pub fn expr_to_str(cx: @ExtCtxt, expr: @ast::expr, err_msg: ~str) -> ~str { match expr.node { ast::expr_lit(l) => match l.node { ast::lit_str(s) => copy *s, @@ -315,7 +314,7 @@ pub fn expr_to_str(cx: @ext_ctxt, expr: @ast::expr, err_msg: ~str) -> ~str { } } -pub fn expr_to_ident(cx: @ext_ctxt, +pub fn expr_to_ident(cx: @ExtCtxt, expr: @ast::expr, err_msg: &str) -> ast::ident { match expr.node { @@ -329,14 +328,14 @@ pub fn expr_to_ident(cx: @ext_ctxt, } } -pub fn check_zero_tts(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree], +pub fn check_zero_tts(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree], name: &str) { if tts.len() != 0 { cx.span_fatal(sp, fmt!("%s takes no arguments", name)); } } -pub fn get_single_str_from_tts(cx: @ext_ctxt, +pub fn get_single_str_from_tts(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree], name: &str) -> ~str { @@ -351,7 +350,7 @@ pub fn get_single_str_from_tts(cx: @ext_ctxt, } } -pub fn get_exprs_from_tts(cx: @ext_ctxt, tts: &[ast::token_tree]) +pub fn get_exprs_from_tts(cx: @ExtCtxt, tts: &[ast::token_tree]) -> ~[@ast::expr] { let p = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 624e0495e5950..e28c04d198af3 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -12,7 +12,7 @@ use ast; use codemap; use codemap::span; use fold; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use opt_vec::OptVec; @@ -22,7 +22,7 @@ pub struct Field { ex: @ast::expr } -pub fn mk_expr(cx: @ext_ctxt, +pub fn mk_expr(cx: @ExtCtxt, sp: codemap::span, expr: ast::expr_) -> @ast::expr { @@ -34,32 +34,32 @@ pub fn mk_expr(cx: @ext_ctxt, } } -pub fn mk_lit(cx: @ext_ctxt, sp: span, lit: ast::lit_) -> @ast::expr { +pub fn mk_lit(cx: @ExtCtxt, sp: span, lit: ast::lit_) -> @ast::expr { let sp_lit = @codemap::spanned { node: lit, span: sp }; mk_expr(cx, sp, ast::expr_lit(sp_lit)) } -pub fn mk_int(cx: @ext_ctxt, sp: span, i: int) -> @ast::expr { +pub fn mk_int(cx: @ExtCtxt, sp: span, i: int) -> @ast::expr { let lit = ast::lit_int(i as i64, ast::ty_i); return mk_lit(cx, sp, lit); } -pub fn mk_uint(cx: @ext_ctxt, sp: span, u: uint) -> @ast::expr { +pub fn mk_uint(cx: @ExtCtxt, sp: span, u: uint) -> @ast::expr { let lit = ast::lit_uint(u as u64, ast::ty_u); return mk_lit(cx, sp, lit); } -pub fn mk_u8(cx: @ext_ctxt, sp: span, u: u8) -> @ast::expr { +pub fn mk_u8(cx: @ExtCtxt, sp: span, u: u8) -> @ast::expr { let lit = ast::lit_uint(u as u64, ast::ty_u8); return mk_lit(cx, sp, lit); } -pub fn mk_binary(cx: @ext_ctxt, sp: span, op: ast::binop, +pub fn mk_binary(cx: @ExtCtxt, sp: span, op: ast::binop, lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr { cx.next_id(); // see ast_util::op_expr_callee_id mk_expr(cx, sp, ast::expr_binary(op, lhs, rhs)) } -pub fn mk_deref(cx: @ext_ctxt, sp: span, e: @ast::expr) -> @ast::expr { +pub fn mk_deref(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { mk_unary(cx, sp, ast::deref, e) } -pub fn mk_unary(cx: @ext_ctxt, sp: span, op: ast::unop, e: @ast::expr) +pub fn mk_unary(cx: @ExtCtxt, sp: span, op: ast::unop, e: @ast::expr) -> @ast::expr { cx.next_id(); // see ast_util::op_expr_callee_id mk_expr(cx, sp, ast::expr_unary(op, e)) @@ -91,78 +91,78 @@ pub fn mk_raw_path_global_(sp: span, rp: rp, types: types } } -pub fn mk_path_raw(cx: @ext_ctxt, sp: span, path: @ast::Path)-> @ast::expr { +pub fn mk_path_raw(cx: @ExtCtxt, sp: span, path: @ast::Path)-> @ast::expr { mk_expr(cx, sp, ast::expr_path(path)) } -pub fn mk_path(cx: @ext_ctxt, sp: span, idents: ~[ast::ident]) +pub fn mk_path(cx: @ExtCtxt, sp: span, idents: ~[ast::ident]) -> @ast::expr { mk_path_raw(cx, sp, mk_raw_path(sp, idents)) } -pub fn mk_path_global(cx: @ext_ctxt, sp: span, idents: ~[ast::ident]) +pub fn mk_path_global(cx: @ExtCtxt, sp: span, idents: ~[ast::ident]) -> @ast::expr { mk_path_raw(cx, sp, mk_raw_path_global(sp, idents)) } -pub fn mk_access_(cx: @ext_ctxt, sp: span, p: @ast::expr, m: ast::ident) +pub fn mk_access_(cx: @ExtCtxt, sp: span, p: @ast::expr, m: ast::ident) -> @ast::expr { mk_expr(cx, sp, ast::expr_field(p, m, ~[])) } -pub fn mk_access(cx: @ext_ctxt, sp: span, p: ~[ast::ident], m: ast::ident) +pub fn mk_access(cx: @ExtCtxt, sp: span, p: ~[ast::ident], m: ast::ident) -> @ast::expr { let pathexpr = mk_path(cx, sp, p); return mk_access_(cx, sp, pathexpr, m); } -pub fn mk_addr_of(cx: @ext_ctxt, sp: span, e: @ast::expr) -> @ast::expr { +pub fn mk_addr_of(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { return mk_expr(cx, sp, ast::expr_addr_of(ast::m_imm, e)); } -pub fn mk_mut_addr_of(cx: @ext_ctxt, sp: span, e: @ast::expr) -> @ast::expr { +pub fn mk_mut_addr_of(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { return mk_expr(cx, sp, ast::expr_addr_of(ast::m_mutbl, e)); } -pub fn mk_method_call(cx: @ext_ctxt, +pub fn mk_method_call(cx: @ExtCtxt, sp: span, rcvr_expr: @ast::expr, method_ident: ast::ident, args: ~[@ast::expr]) -> @ast::expr { mk_expr(cx, sp, ast::expr_method_call(rcvr_expr, method_ident, ~[], args, ast::NoSugar)) } -pub fn mk_call_(cx: @ext_ctxt, sp: span, fn_expr: @ast::expr, +pub fn mk_call_(cx: @ExtCtxt, sp: span, fn_expr: @ast::expr, args: ~[@ast::expr]) -> @ast::expr { mk_expr(cx, sp, ast::expr_call(fn_expr, args, ast::NoSugar)) } -pub fn mk_call(cx: @ext_ctxt, sp: span, fn_path: ~[ast::ident], +pub fn mk_call(cx: @ExtCtxt, sp: span, fn_path: ~[ast::ident], args: ~[@ast::expr]) -> @ast::expr { let pathexpr = mk_path(cx, sp, fn_path); return mk_call_(cx, sp, pathexpr, args); } -pub fn mk_call_global(cx: @ext_ctxt, sp: span, fn_path: ~[ast::ident], +pub fn mk_call_global(cx: @ExtCtxt, sp: span, fn_path: ~[ast::ident], args: ~[@ast::expr]) -> @ast::expr { let pathexpr = mk_path_global(cx, sp, fn_path); return mk_call_(cx, sp, pathexpr, args); } // e = expr, t = type -pub fn mk_base_vec_e(cx: @ext_ctxt, sp: span, exprs: ~[@ast::expr]) +pub fn mk_base_vec_e(cx: @ExtCtxt, sp: span, exprs: ~[@ast::expr]) -> @ast::expr { let vecexpr = ast::expr_vec(exprs, ast::m_imm); mk_expr(cx, sp, vecexpr) } -pub fn mk_vstore_e(cx: @ext_ctxt, sp: span, expr: @ast::expr, +pub fn mk_vstore_e(cx: @ExtCtxt, sp: span, expr: @ast::expr, vst: ast::expr_vstore) -> @ast::expr { mk_expr(cx, sp, ast::expr_vstore(expr, vst)) } -pub fn mk_uniq_vec_e(cx: @ext_ctxt, sp: span, exprs: ~[@ast::expr]) +pub fn mk_uniq_vec_e(cx: @ExtCtxt, sp: span, exprs: ~[@ast::expr]) -> @ast::expr { mk_vstore_e(cx, sp, mk_base_vec_e(cx, sp, exprs), ast::expr_vstore_uniq) } -pub fn mk_slice_vec_e(cx: @ext_ctxt, sp: span, exprs: ~[@ast::expr]) +pub fn mk_slice_vec_e(cx: @ExtCtxt, sp: span, exprs: ~[@ast::expr]) -> @ast::expr { mk_vstore_e(cx, sp, mk_base_vec_e(cx, sp, exprs), ast::expr_vstore_slice) } -pub fn mk_base_str(cx: @ext_ctxt, sp: span, s: ~str) -> @ast::expr { +pub fn mk_base_str(cx: @ExtCtxt, sp: span, s: ~str) -> @ast::expr { let lit = ast::lit_str(@s); return mk_lit(cx, sp, lit); } -pub fn mk_uniq_str(cx: @ext_ctxt, sp: span, s: ~str) -> @ast::expr { +pub fn mk_uniq_str(cx: @ExtCtxt, sp: span, s: ~str) -> @ast::expr { mk_vstore_e(cx, sp, mk_base_str(cx, sp, s), ast::expr_vstore_uniq) } pub fn mk_field(sp: span, f: &Field) -> ast::field { @@ -174,7 +174,7 @@ pub fn mk_field(sp: span, f: &Field) -> ast::field { pub fn mk_fields(sp: span, fields: ~[Field]) -> ~[ast::field] { fields.map(|f| mk_field(sp, f)) } -pub fn mk_struct_e(cx: @ext_ctxt, +pub fn mk_struct_e(cx: @ExtCtxt, sp: span, ctor_path: ~[ast::ident], fields: ~[Field]) @@ -184,7 +184,7 @@ pub fn mk_struct_e(cx: @ext_ctxt, mk_fields(sp, fields), option::None::<@ast::expr>)) } -pub fn mk_global_struct_e(cx: @ext_ctxt, +pub fn mk_global_struct_e(cx: @ExtCtxt, sp: span, ctor_path: ~[ast::ident], fields: ~[Field]) @@ -194,7 +194,7 @@ pub fn mk_global_struct_e(cx: @ext_ctxt, mk_fields(sp, fields), option::None::<@ast::expr>)) } -pub fn mk_glob_use(cx: @ext_ctxt, +pub fn mk_glob_use(cx: @ExtCtxt, sp: span, vis: ast::visibility, path: ~[ast::ident]) -> @ast::view_item { @@ -207,7 +207,7 @@ pub fn mk_glob_use(cx: @ext_ctxt, vis: vis, span: sp } } -pub fn mk_local(cx: @ext_ctxt, sp: span, mutbl: bool, +pub fn mk_local(cx: @ExtCtxt, sp: span, mutbl: bool, ident: ast::ident, ex: @ast::expr) -> @ast::stmt { let pat = @ast::pat { @@ -232,7 +232,7 @@ pub fn mk_local(cx: @ext_ctxt, sp: span, mutbl: bool, let decl = codemap::spanned {node: ast::decl_local(~[local]), span: sp}; @codemap::spanned { node: ast::stmt_decl(@decl, cx.next_id()), span: sp } } -pub fn mk_block(cx: @ext_ctxt, span: span, +pub fn mk_block(cx: @ExtCtxt, span: span, view_items: ~[@ast::view_item], stmts: ~[@ast::stmt], expr: Option<@ast::expr>) -> @ast::expr { @@ -248,7 +248,7 @@ pub fn mk_block(cx: @ext_ctxt, span: span, }; mk_expr(cx, span, ast::expr_block(blk)) } -pub fn mk_block_(cx: @ext_ctxt, +pub fn mk_block_(cx: @ExtCtxt, span: span, stmts: ~[@ast::stmt]) -> ast::blk { @@ -263,7 +263,7 @@ pub fn mk_block_(cx: @ext_ctxt, span: span, } } -pub fn mk_simple_block(cx: @ext_ctxt, +pub fn mk_simple_block(cx: @ExtCtxt, span: span, expr: @ast::expr) -> ast::blk { @@ -278,14 +278,14 @@ pub fn mk_simple_block(cx: @ext_ctxt, span: span, } } -pub fn mk_lambda_(cx: @ext_ctxt, +pub fn mk_lambda_(cx: @ExtCtxt, span: span, fn_decl: ast::fn_decl, blk: ast::blk) -> @ast::expr { mk_expr(cx, span, ast::expr_fn_block(fn_decl, blk)) } -pub fn mk_lambda(cx: @ext_ctxt, +pub fn mk_lambda(cx: @ExtCtxt, span: span, fn_decl: ast::fn_decl, expr: @ast::expr) @@ -293,7 +293,7 @@ pub fn mk_lambda(cx: @ext_ctxt, let blk = mk_simple_block(cx, span, expr); mk_lambda_(cx, span, fn_decl, blk) } -pub fn mk_lambda_stmts(cx: @ext_ctxt, +pub fn mk_lambda_stmts(cx: @ExtCtxt, span: span, fn_decl: ast::fn_decl, stmts: ~[@ast::stmt]) @@ -301,37 +301,37 @@ pub fn mk_lambda_stmts(cx: @ext_ctxt, let blk = mk_block(cx, span, ~[], stmts, None); mk_lambda(cx, span, fn_decl, blk) } -pub fn mk_lambda_no_args(cx: @ext_ctxt, +pub fn mk_lambda_no_args(cx: @ExtCtxt, span: span, expr: @ast::expr) -> @ast::expr { let fn_decl = mk_fn_decl(~[], mk_ty_infer(cx, span)); mk_lambda(cx, span, fn_decl, expr) } -pub fn mk_copy(cx: @ext_ctxt, sp: span, e: @ast::expr) -> @ast::expr { +pub fn mk_copy(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { mk_expr(cx, sp, ast::expr_copy(e)) } -pub fn mk_managed(cx: @ext_ctxt, sp: span, e: @ast::expr) -> @ast::expr { +pub fn mk_managed(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { mk_expr(cx, sp, ast::expr_unary(ast::box(ast::m_imm), e)) } -pub fn mk_pat(cx: @ext_ctxt, span: span, pat: ast::pat_) -> @ast::pat { +pub fn mk_pat(cx: @ExtCtxt, span: span, pat: ast::pat_) -> @ast::pat { @ast::pat { id: cx.next_id(), node: pat, span: span } } -pub fn mk_pat_wild(cx: @ext_ctxt, span: span) -> @ast::pat { +pub fn mk_pat_wild(cx: @ExtCtxt, span: span) -> @ast::pat { mk_pat(cx, span, ast::pat_wild) } -pub fn mk_pat_lit(cx: @ext_ctxt, +pub fn mk_pat_lit(cx: @ExtCtxt, span: span, expr: @ast::expr) -> @ast::pat { mk_pat(cx, span, ast::pat_lit(expr)) } -pub fn mk_pat_ident(cx: @ext_ctxt, +pub fn mk_pat_ident(cx: @ExtCtxt, span: span, ident: ast::ident) -> @ast::pat { mk_pat_ident_with_binding_mode(cx, span, ident, ast::bind_by_copy) } -pub fn mk_pat_ident_with_binding_mode(cx: @ext_ctxt, +pub fn mk_pat_ident_with_binding_mode(cx: @ExtCtxt, span: span, ident: ast::ident, bm: ast::binding_mode) -> @ast::pat { @@ -339,7 +339,7 @@ pub fn mk_pat_ident_with_binding_mode(cx: @ext_ctxt, let pat = ast::pat_ident(bm, path, None); mk_pat(cx, span, pat) } -pub fn mk_pat_enum(cx: @ext_ctxt, +pub fn mk_pat_enum(cx: @ExtCtxt, span: span, path: @ast::Path, subpats: ~[@ast::pat]) @@ -347,7 +347,7 @@ pub fn mk_pat_enum(cx: @ext_ctxt, let pat = ast::pat_enum(path, Some(subpats)); mk_pat(cx, span, pat) } -pub fn mk_pat_struct(cx: @ext_ctxt, +pub fn mk_pat_struct(cx: @ExtCtxt, span: span, path: @ast::Path, field_pats: ~[ast::field_pat]) @@ -355,13 +355,13 @@ pub fn mk_pat_struct(cx: @ext_ctxt, let pat = ast::pat_struct(path, field_pats, false); mk_pat(cx, span, pat) } -pub fn mk_bool(cx: @ext_ctxt, span: span, value: bool) -> @ast::expr { +pub fn mk_bool(cx: @ExtCtxt, span: span, value: bool) -> @ast::expr { let lit_expr = ast::expr_lit(@codemap::spanned { node: ast::lit_bool(value), span: span }); build::mk_expr(cx, span, lit_expr) } -pub fn mk_stmt(cx: @ext_ctxt, span: span, expr: @ast::expr) -> @ast::stmt { +pub fn mk_stmt(cx: @ExtCtxt, span: span, expr: @ast::expr) -> @ast::stmt { let stmt_ = ast::stmt_semi(expr, cx.next_id()); @codemap::spanned { node: stmt_, span: span } } @@ -373,7 +373,7 @@ pub fn mk_ty_mt(ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt { } } -pub fn mk_ty(cx: @ext_ctxt, +pub fn mk_ty(cx: @ExtCtxt, span: span, ty: ast::ty_) -> @ast::Ty { @ast::Ty { @@ -383,7 +383,7 @@ pub fn mk_ty(cx: @ext_ctxt, } } -pub fn mk_ty_path(cx: @ext_ctxt, +pub fn mk_ty_path(cx: @ExtCtxt, span: span, idents: ~[ ast::ident ]) -> @ast::Ty { @@ -391,7 +391,7 @@ pub fn mk_ty_path(cx: @ext_ctxt, mk_ty_path_path(cx, span, ty) } -pub fn mk_ty_path_global(cx: @ext_ctxt, +pub fn mk_ty_path_global(cx: @ExtCtxt, span: span, idents: ~[ ast::ident ]) -> @ast::Ty { @@ -399,7 +399,7 @@ pub fn mk_ty_path_global(cx: @ext_ctxt, mk_ty_path_path(cx, span, ty) } -pub fn mk_ty_path_path(cx: @ext_ctxt, +pub fn mk_ty_path_path(cx: @ExtCtxt, span: span, path: @ast::Path) -> @ast::Ty { @@ -407,7 +407,7 @@ pub fn mk_ty_path_path(cx: @ext_ctxt, mk_ty(cx, span, ty) } -pub fn mk_ty_rptr(cx: @ext_ctxt, +pub fn mk_ty_rptr(cx: @ExtCtxt, span: span, ty: @ast::Ty, lifetime: Option<@ast::Lifetime>, @@ -416,39 +416,39 @@ pub fn mk_ty_rptr(cx: @ext_ctxt, mk_ty(cx, span, ast::ty_rptr(lifetime, mk_ty_mt(ty, mutbl))) } -pub fn mk_ty_uniq(cx: @ext_ctxt, span: span, ty: @ast::Ty) -> @ast::Ty { +pub fn mk_ty_uniq(cx: @ExtCtxt, span: span, ty: @ast::Ty) -> @ast::Ty { mk_ty(cx, span, ast::ty_uniq(mk_ty_mt(ty, ast::m_imm))) } -pub fn mk_ty_box(cx: @ext_ctxt, span: span, +pub fn mk_ty_box(cx: @ExtCtxt, span: span, ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty { mk_ty(cx, span, ast::ty_box(mk_ty_mt(ty, mutbl))) } -pub fn mk_ty_infer(cx: @ext_ctxt, span: span) -> @ast::Ty { +pub fn mk_ty_infer(cx: @ExtCtxt, span: span) -> @ast::Ty { mk_ty(cx, span, ast::ty_infer) } -pub fn mk_trait_ref_global(cx: @ext_ctxt, +pub fn mk_trait_ref_global(cx: @ExtCtxt, span: span, idents: ~[ ast::ident ]) -> @ast::trait_ref { mk_trait_ref_(cx, build::mk_raw_path_global(span, idents)) } -pub fn mk_trait_ref_(cx: @ext_ctxt, path: @ast::Path) -> @ast::trait_ref { +pub fn mk_trait_ref_(cx: @ExtCtxt, path: @ast::Path) -> @ast::trait_ref { @ast::trait_ref { path: path, ref_id: cx.next_id() } } -pub fn mk_simple_ty_path(cx: @ext_ctxt, +pub fn mk_simple_ty_path(cx: @ExtCtxt, span: span, ident: ast::ident) -> @ast::Ty { mk_ty_path(cx, span, ~[ ident ]) } -pub fn mk_arg(cx: @ext_ctxt, +pub fn mk_arg(cx: @ExtCtxt, span: span, ident: ast::ident, ty: @ast::Ty) @@ -464,29 +464,29 @@ pub fn mk_arg(cx: @ext_ctxt, pub fn mk_fn_decl(inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl { ast::fn_decl { inputs: inputs, output: output, cf: ast::return_val } } -pub fn mk_trait_ty_param_bound_global(cx: @ext_ctxt, +pub fn mk_trait_ty_param_bound_global(cx: @ExtCtxt, span: span, idents: ~[ast::ident]) -> ast::TyParamBound { ast::TraitTyParamBound(mk_trait_ref_global(cx, span, idents)) } -pub fn mk_trait_ty_param_bound_(cx: @ext_ctxt, +pub fn mk_trait_ty_param_bound_(cx: @ExtCtxt, path: @ast::Path) -> ast::TyParamBound { ast::TraitTyParamBound(mk_trait_ref_(cx, path)) } -pub fn mk_ty_param(cx: @ext_ctxt, +pub fn mk_ty_param(cx: @ExtCtxt, ident: ast::ident, bounds: @OptVec) -> ast::TyParam { ast::TyParam { ident: ident, id: cx.next_id(), bounds: bounds } } -pub fn mk_lifetime(cx: @ext_ctxt, +pub fn mk_lifetime(cx: @ExtCtxt, span: span, ident: ast::ident) -> ast::Lifetime { ast::Lifetime { id: cx.next_id(), span: span, ident: ident } } -pub fn mk_arm(cx: @ext_ctxt, +pub fn mk_arm(cx: @ExtCtxt, span: span, pats: ~[@ast::pat], expr: @ast::expr) @@ -497,7 +497,7 @@ pub fn mk_arm(cx: @ext_ctxt, body: mk_simple_block(cx, span, expr) } } -pub fn mk_unreachable(cx: @ext_ctxt, span: span) -> @ast::expr { +pub fn mk_unreachable(cx: @ExtCtxt, span: span) -> @ast::expr { let loc = cx.codemap().lookup_char_pos(span.lo); mk_call_global( cx, @@ -515,11 +515,11 @@ pub fn mk_unreachable(cx: @ext_ctxt, span: span) -> @ast::expr { ] ) } -pub fn mk_unreachable_arm(cx: @ext_ctxt, span: span) -> ast::arm { +pub fn mk_unreachable_arm(cx: @ExtCtxt, span: span) -> ast::arm { mk_arm(cx, span, ~[mk_pat_wild(cx, span)], mk_unreachable(cx, span)) } -pub fn make_self(cx: @ext_ctxt, span: span) -> @ast::expr { +pub fn make_self(cx: @ExtCtxt, span: span) -> @ast::expr { build::mk_expr(cx, span, ast::expr_self) } @@ -529,7 +529,7 @@ pub fn make_self(cx: @ext_ctxt, span: span) -> @ast::expr { // These functions just duplicate AST nodes. // -pub fn duplicate_expr(cx: @ext_ctxt, expr: @ast::expr) -> @ast::expr { +pub fn duplicate_expr(cx: @ExtCtxt, expr: @ast::expr) -> @ast::expr { let folder = fold::default_ast_fold(); let folder = @fold::AstFoldFns { new_id: |_| cx.next_id(), @@ -599,7 +599,7 @@ trait ExtCtxtMethods { -> @ast::expr; } -impl ExtCtxtMethods for @ext_ctxt { +impl ExtCtxtMethods for @ExtCtxt { fn bind_path( &self, _span: span, diff --git a/src/libsyntax/ext/bytes.rs b/src/libsyntax/ext/bytes.rs index 7c2f27ada3bce..da13c9bfa28e1 100644 --- a/src/libsyntax/ext/bytes.rs +++ b/src/libsyntax/ext/bytes.rs @@ -16,7 +16,7 @@ use ext::base::*; use ext::base; use ext::build::{mk_u8, mk_slice_vec_e}; -pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { +pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { // Gather all argument expressions let exprs = get_exprs_from_tts(cx, tts); let mut bytes = ~[]; diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index da32cc1162513..e6600e198fa6d 100644 --- a/src/libsyntax/ext/concat_idents.rs +++ b/src/libsyntax/ext/concat_idents.rs @@ -14,7 +14,7 @@ use ext::base::*; use ext::base; use parse::token; -pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let mut res_str = ~""; for tts.eachi |i, e| { diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 1759cde0fc975..c08b478e8ed6f 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -10,12 +10,12 @@ use ast::{meta_item, item, expr}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; -pub fn expand_deriving_clone(cx: @ext_ctxt, +pub fn expand_deriving_clone(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) @@ -42,7 +42,7 @@ pub fn expand_deriving_clone(cx: @ext_ctxt, &trait_def) } -pub fn expand_deriving_deep_clone(cx: @ext_ctxt, +pub fn expand_deriving_deep_clone(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) @@ -73,7 +73,7 @@ pub fn expand_deriving_deep_clone(cx: @ext_ctxt, fn cs_clone( name: &str, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { let clone_ident = substr.method_ident; let ctor_ident; diff --git a/src/libsyntax/ext/deriving/cmp/eq.rs b/src/libsyntax/ext/deriving/cmp/eq.rs index e6fcfdf556354..197366b09ae3c 100644 --- a/src/libsyntax/ext/deriving/cmp/eq.rs +++ b/src/libsyntax/ext/deriving/cmp/eq.rs @@ -10,21 +10,21 @@ use ast::{meta_item, item, expr}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; -pub fn expand_deriving_eq(cx: @ext_ctxt, +pub fn expand_deriving_eq(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { // structures are equal if all fields are equal, and non equal, if // any fields are not equal or if the enum variants are different - fn cs_eq(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr { + fn cs_eq(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cs_and(|cx, span, _, _| build::mk_bool(cx, span, false), cx, span, substr) } - fn cs_ne(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr { + fn cs_ne(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cs_or(|cx, span, _, _| build::mk_bool(cx, span, true), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 5aae8454c09b4..29fc2c7271c0b 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -11,11 +11,11 @@ use ast::{meta_item, item, expr_if, expr}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; -pub fn expand_deriving_ord(cx: @ext_ctxt, +pub fn expand_deriving_ord(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { @@ -55,7 +55,7 @@ pub fn expand_deriving_ord(cx: @ext_ctxt, /// `less`: is this `lt` or `le`? `equal`: is this `le` or `ge`? fn cs_ord(less: bool, equal: bool, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { let binop = if less { cx.ident_of("lt") diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index 9ab44f506bade..0ab99430d1078 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -11,16 +11,16 @@ use ast::{meta_item, item, expr}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; -pub fn expand_deriving_totaleq(cx: @ext_ctxt, +pub fn expand_deriving_totaleq(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { - fn cs_equals(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr { + fn cs_equals(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cs_and(|cx, span, _, _| build::mk_bool(cx, span, false), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index 1b6ea16b86e2d..2b4d8a28fbd93 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -10,12 +10,12 @@ use ast::{meta_item, item, expr}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; use core::cmp::{Ordering, Equal, Less, Greater}; -pub fn expand_deriving_totalord(cx: @ext_ctxt, +pub fn expand_deriving_totalord(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { @@ -41,7 +41,7 @@ pub fn expand_deriving_totalord(cx: @ext_ctxt, } -pub fn ordering_const(cx: @ext_ctxt, span: span, cnst: Ordering) -> @expr { +pub fn ordering_const(cx: @ExtCtxt, span: span, cnst: Ordering) -> @expr { let cnst = match cnst { Less => "Less", Equal => "Equal", @@ -53,7 +53,7 @@ pub fn ordering_const(cx: @ext_ctxt, span: span, cnst: Ordering) -> @expr { cx.ident_of(cnst)]) } -pub fn cs_cmp(cx: @ext_ctxt, span: span, +pub fn cs_cmp(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cs_same_method_fold( diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index fe20511204632..24f9b6acf8534 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -15,7 +15,7 @@ encodable.rs for more. use ast; use ast::*; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::*; use codemap::{span, spanned}; @@ -23,7 +23,7 @@ use ast_util; use opt_vec; pub fn expand_deriving_decodable( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, _mitem: @meta_item, in_items: ~[@item] @@ -38,7 +38,7 @@ pub fn expand_deriving_decodable( } fn create_derived_decodable_impl( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, type_ident: ident, generics: &Generics, @@ -91,7 +91,7 @@ fn create_derived_decodable_impl( // Creates a method from the given set of statements conforming to the // signature of the `decodable` method. fn create_decode_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, type_ident: ast::ident, generics: &Generics, @@ -142,7 +142,7 @@ fn create_decode_method( } fn call_substructure_decode_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span ) -> @ast::expr { // Call the substructure method. @@ -166,7 +166,7 @@ fn call_substructure_decode_method( } fn expand_deriving_decodable_struct_def( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, struct_def: &struct_def, type_ident: ident, @@ -192,7 +192,7 @@ fn expand_deriving_decodable_struct_def( } fn expand_deriving_decodable_enum_def( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, enum_definition: &enum_def, type_ident: ident, @@ -218,7 +218,7 @@ fn expand_deriving_decodable_enum_def( } fn create_read_struct_field( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, idx: uint, ident: ident @@ -251,7 +251,7 @@ fn create_read_struct_field( } fn create_read_struct_arg( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, idx: uint, ident: ident @@ -274,7 +274,7 @@ fn create_read_struct_arg( } fn expand_deriving_decodable_struct_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, struct_def: &struct_def, type_ident: ident, @@ -334,7 +334,7 @@ fn expand_deriving_decodable_struct_method( } fn create_read_variant_arg( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, idx: uint, variant: &ast::variant @@ -392,7 +392,7 @@ fn create_read_variant_arg( } fn create_read_enum_variant( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, enum_definition: &enum_def ) -> @expr { @@ -459,7 +459,7 @@ fn create_read_enum_variant( } fn expand_deriving_decodable_enum_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, enum_definition: &enum_def, type_ident: ast::ident, diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index b1df8405d7627..128bbf39b16c6 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -78,7 +78,7 @@ would yield functions like: use ast; use ast::*; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::*; use codemap::{span, spanned}; @@ -86,7 +86,7 @@ use ast_util; use opt_vec; pub fn expand_deriving_encodable( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, _mitem: @meta_item, in_items: ~[@item] @@ -101,7 +101,7 @@ pub fn expand_deriving_encodable( } fn create_derived_encodable_impl( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, type_ident: ident, generics: &Generics, @@ -154,7 +154,7 @@ fn create_derived_encodable_impl( // Creates a method from the given set of statements conforming to the // signature of the `encodable` method. fn create_encode_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, statements: ~[@stmt] ) -> @method { @@ -197,7 +197,7 @@ fn create_encode_method( } fn call_substructure_encode_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, self_field: @expr ) -> @ast::expr { @@ -217,7 +217,7 @@ fn call_substructure_encode_method( } fn expand_deriving_encodable_struct_def( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, struct_def: &struct_def, type_ident: ident, @@ -242,7 +242,7 @@ fn expand_deriving_encodable_struct_def( } fn expand_deriving_encodable_enum_def( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, enum_definition: &enum_def, type_ident: ident, @@ -267,7 +267,7 @@ fn expand_deriving_encodable_enum_def( } fn expand_deriving_encodable_struct_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, type_ident: ident, struct_def: &struct_def @@ -361,7 +361,7 @@ fn expand_deriving_encodable_struct_method( } fn expand_deriving_encodable_enum_method( - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, type_ident: ast::ident, enum_definition: &enum_def diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index ae9c4c1fefb44..0bb97ec31224c 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -165,7 +165,7 @@ StaticEnum(, ~[(, Left(1)), use ast; use ast::{enum_def, expr, ident, Generics, struct_def}; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::*; use codemap::{span,respan}; @@ -174,7 +174,7 @@ use opt_vec; pub use self::ty::*; mod ty; -pub fn expand_deriving_generic(cx: @ext_ctxt, +pub fn expand_deriving_generic(cx: @ExtCtxt, span: span, _mitem: @ast::meta_item, in_items: ~[@ast::item], @@ -281,7 +281,7 @@ Combine the values of all the fields together. The last argument is all the fields of all the structures, see above for details. */ pub type CombineSubstructureFunc<'self> = - &'self fn(@ext_ctxt, span, &Substructure) -> @expr; + &'self fn(@ExtCtxt, span, &Substructure) -> @expr; /** Deal with non-matching enum variants, the arguments are a list @@ -289,14 +289,14 @@ representing each variant: (variant index, ast::variant instance, [variant fields]), and a list of the nonself args of the type */ pub type EnumNonMatchFunc<'self> = - &'self fn(@ext_ctxt, span, + &'self fn(@ExtCtxt, span, &[(uint, ast::variant, ~[(Option, @expr)])], &[@expr]) -> @expr; impl<'self> TraitDef<'self> { - fn create_derived_impl(&self, cx: @ext_ctxt, span: span, + fn create_derived_impl(&self, cx: @ExtCtxt, span: span, type_ident: ident, generics: &Generics, methods: ~[@ast::method]) -> @ast::item { let trait_path = self.path.to_path(cx, span, type_ident, generics); @@ -315,7 +315,7 @@ impl<'self> TraitDef<'self> { additional_bounds) } - fn expand_struct_def(&self, cx: @ext_ctxt, + fn expand_struct_def(&self, cx: @ExtCtxt, span: span, struct_def: &struct_def, type_ident: ident, @@ -347,7 +347,7 @@ impl<'self> TraitDef<'self> { } fn expand_enum_def(&self, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, enum_def: &enum_def, type_ident: ident, generics: &Generics) -> @ast::item { @@ -380,7 +380,7 @@ impl<'self> TraitDef<'self> { impl<'self> MethodDef<'self> { fn call_substructure_method(&self, - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, type_ident: ident, self_args: &[@expr], @@ -398,7 +398,7 @@ impl<'self> MethodDef<'self> { &substructure) } - fn get_ret_ty(&self, cx: @ext_ctxt, span: span, + fn get_ret_ty(&self, cx: @ExtCtxt, span: span, generics: &Generics, type_ident: ident) -> @ast::Ty { self.ret_ty.to_ty(cx, span, type_ident, generics) } @@ -407,7 +407,7 @@ impl<'self> MethodDef<'self> { self.explicit_self.is_none() } - fn split_self_nonself_args(&self, cx: @ext_ctxt, span: span, + fn split_self_nonself_args(&self, cx: @ExtCtxt, span: span, type_ident: ident, generics: &Generics) -> (ast::explicit_self, ~[@expr], ~[@expr], ~[(ident, @ast::Ty)]) { @@ -451,7 +451,7 @@ impl<'self> MethodDef<'self> { (ast_explicit_self, self_args, nonself_args, arg_tys) } - fn create_method(&self, cx: @ext_ctxt, span: span, + fn create_method(&self, cx: @ExtCtxt, span: span, type_ident: ident, generics: &Generics, explicit_self: ast::explicit_self, @@ -509,7 +509,7 @@ impl<'self> MethodDef<'self> { ~~~ */ fn expand_struct_method_body(&self, - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, struct_def: &struct_def, type_ident: ident, @@ -567,7 +567,7 @@ impl<'self> MethodDef<'self> { } fn expand_static_struct_method_body(&self, - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, struct_def: &struct_def, type_ident: ident, @@ -609,7 +609,7 @@ impl<'self> MethodDef<'self> { ~~~ */ fn expand_enum_method_body(&self, - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, enum_def: &enum_def, type_ident: ident, @@ -645,7 +645,7 @@ impl<'self> MethodDef<'self> { the first call). */ fn build_enum_match(&self, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, enum_def: &enum_def, type_ident: ident, self_args: &[@expr], @@ -786,7 +786,7 @@ impl<'self> MethodDef<'self> { } fn expand_static_enum_method_body(&self, - cx: @ext_ctxt, + cx: @ExtCtxt, span: span, enum_def: &enum_def, type_ident: ident, @@ -810,7 +810,7 @@ impl<'self> MethodDef<'self> { } } -fn summarise_struct(cx: @ext_ctxt, span: span, +fn summarise_struct(cx: @ExtCtxt, span: span, struct_def: &struct_def) -> Either { let mut named_idents = ~[]; let mut unnamed_count = 0; @@ -840,12 +840,12 @@ Fold the fields. `use_foldl` controls whether this is done left-to-right (`true`) or right-to-left (`false`). */ pub fn cs_fold(use_foldl: bool, - f: &fn(@ext_ctxt, span, + f: &fn(@ExtCtxt, span, old: @expr, self_f: @expr, other_fs: &[@expr]) -> @expr, base: @expr, enum_nonmatch_f: EnumNonMatchFunc, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { match *substructure.fields { EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => { @@ -879,9 +879,9 @@ f(cx, span, ~[self_1.method(__arg_1_1, __arg_2_1), ~~~ */ #[inline(always)] -pub fn cs_same_method(f: &fn(@ext_ctxt, span, ~[@expr]) -> @expr, +pub fn cs_same_method(f: &fn(@ExtCtxt, span, ~[@expr]) -> @expr, enum_nonmatch_f: EnumNonMatchFunc, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { match *substructure.fields { EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => { @@ -911,10 +911,10 @@ fields. `use_foldl` controls whether this is done left-to-right */ #[inline(always)] pub fn cs_same_method_fold(use_foldl: bool, - f: &fn(@ext_ctxt, span, @expr, @expr) -> @expr, + f: &fn(@ExtCtxt, span, @expr, @expr) -> @expr, base: @expr, enum_nonmatch_f: EnumNonMatchFunc, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { cs_same_method( |cx, span, vals| { @@ -940,7 +940,7 @@ on all the fields. #[inline(always)] pub fn cs_binop(binop: ast::binop, base: @expr, enum_nonmatch_f: EnumNonMatchFunc, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { cs_same_method_fold( true, // foldl is good enough @@ -958,7 +958,7 @@ pub fn cs_binop(binop: ast::binop, base: @expr, /// cs_binop with binop == or #[inline(always)] pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { cs_binop(ast::or, build::mk_bool(cx, span, false), enum_nonmatch_f, @@ -967,7 +967,7 @@ pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc, /// cs_binop with binop == and #[inline(always)] pub fn cs_and(enum_nonmatch_f: EnumNonMatchFunc, - cx: @ext_ctxt, span: span, + cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { cs_binop(ast::and, build::mk_bool(cx, span, true), enum_nonmatch_f, diff --git a/src/libsyntax/ext/deriving/iter_bytes.rs b/src/libsyntax/ext/deriving/iter_bytes.rs index 9b8f127d42a0b..c655eef34d1eb 100644 --- a/src/libsyntax/ext/deriving/iter_bytes.rs +++ b/src/libsyntax/ext/deriving/iter_bytes.rs @@ -10,11 +10,11 @@ use ast::{meta_item, item, expr, and}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; -pub fn expand_deriving_iter_bytes(cx: @ext_ctxt, +pub fn expand_deriving_iter_bytes(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { @@ -41,7 +41,7 @@ pub fn expand_deriving_iter_bytes(cx: @ext_ctxt, expand_deriving_generic(cx, span, mitem, in_items, &trait_def) } -fn iter_bytes_substructure(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr { +fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { let lsb0_f = match substr.nonself_args { [l, f] => ~[l, f], _ => cx.span_bug(span, "Incorrect number of arguments in `deriving(IterBytes)`") diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 6f4429af12d75..4a6c78038389e 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -20,7 +20,7 @@ library. use ast; use ast::{Ty, enum_def, expr, ident, item, Generics, meta_item, struct_def}; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use codemap::{span, respan}; use parse::token::special_idents::clownshoes_extensions; @@ -45,20 +45,20 @@ pub mod totalord; pub mod generic; -pub type ExpandDerivingStructDefFn<'self> = &'self fn(@ext_ctxt, +pub type ExpandDerivingStructDefFn<'self> = &'self fn(@ExtCtxt, span, x: &struct_def, ident, y: &Generics) -> @item; -pub type ExpandDerivingEnumDefFn<'self> = &'self fn(@ext_ctxt, +pub type ExpandDerivingEnumDefFn<'self> = &'self fn(@ExtCtxt, span, x: &enum_def, ident, y: &Generics) -> @item; -pub fn expand_meta_deriving(cx: @ext_ctxt, +pub fn expand_meta_deriving(cx: @ExtCtxt, _span: span, mitem: @meta_item, in_items: ~[@item]) @@ -113,7 +113,7 @@ pub fn expand_meta_deriving(cx: @ext_ctxt, } } -pub fn expand_deriving(cx: @ext_ctxt, +pub fn expand_deriving(cx: @ExtCtxt, span: span, in_items: ~[@item], expand_deriving_struct_def: ExpandDerivingStructDefFn, @@ -143,7 +143,7 @@ pub fn expand_deriving(cx: @ext_ctxt, result } -fn create_impl_item(cx: @ext_ctxt, span: span, item: ast::item_) -> @item { +fn create_impl_item(cx: @ExtCtxt, span: span, item: ast::item_) -> @item { let doc_attr = respan(span, ast::lit_str(@~"Automatically derived.")); let doc_attr = respan(span, ast::meta_name_value(@~"doc", doc_attr)); @@ -164,7 +164,7 @@ fn create_impl_item(cx: @ext_ctxt, span: span, item: ast::item_) -> @item { } } -pub fn create_self_type_with_params(cx: @ext_ctxt, +pub fn create_self_type_with_params(cx: @ExtCtxt, span: span, type_ident: ident, generics: &Generics) @@ -193,7 +193,7 @@ pub fn create_self_type_with_params(cx: @ext_ctxt, build::mk_ty_path_path(cx, span, self_type) } -pub fn create_derived_impl(cx: @ext_ctxt, +pub fn create_derived_impl(cx: @ExtCtxt, span: span, type_ident: ident, generics: &Generics, @@ -249,7 +249,7 @@ pub fn create_derived_impl(cx: @ext_ctxt, return create_impl_item(cx, span, impl_item); } -pub fn create_subpatterns(cx: @ext_ctxt, +pub fn create_subpatterns(cx: @ExtCtxt, span: span, field_paths: ~[@ast::Path], mutbl: ast::mutability) @@ -265,7 +265,7 @@ enum StructType { Unknown, Record, Tuple } -pub fn create_struct_pattern(cx: @ext_ctxt, +pub fn create_struct_pattern(cx: @ExtCtxt, span: span, struct_ident: ident, struct_def: &struct_def, @@ -326,7 +326,7 @@ pub fn create_struct_pattern(cx: @ext_ctxt, (pattern, ident_expr) } -pub fn create_enum_variant_pattern(cx: @ext_ctxt, +pub fn create_enum_variant_pattern(cx: @ExtCtxt, span: span, variant: &ast::variant, prefix: &str, @@ -366,14 +366,14 @@ pub fn create_enum_variant_pattern(cx: @ext_ctxt, } } -pub fn variant_arg_count(_cx: @ext_ctxt, _span: span, variant: &ast::variant) -> uint { +pub fn variant_arg_count(_cx: @ExtCtxt, _span: span, variant: &ast::variant) -> uint { match variant.node.kind { ast::tuple_variant_kind(ref args) => args.len(), ast::struct_variant_kind(ref struct_def) => struct_def.fields.len(), } } -pub fn expand_enum_or_struct_match(cx: @ext_ctxt, +pub fn expand_enum_or_struct_match(cx: @ExtCtxt, span: span, arms: ~[ ast::arm ]) -> @expr { diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index 2fb47c1e53ec2..64cf7e93b92e8 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -11,11 +11,11 @@ use ast; use ast::{meta_item, item, expr, ident}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; -pub fn expand_deriving_rand(cx: @ext_ctxt, +pub fn expand_deriving_rand(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) @@ -47,7 +47,7 @@ pub fn expand_deriving_rand(cx: @ext_ctxt, expand_deriving_generic(cx, span, mitem, in_items, &trait_def) } -fn rand_substructure(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr { +fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { let rng = match substr.nonself_args { [rng] => ~[ rng ], _ => cx.bug("Incorrect number of arguments to `rand` in `deriving(Rand)`") @@ -113,7 +113,7 @@ fn rand_substructure(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr _ => cx.bug("Non-static method in `deriving(Rand)`") }; - fn rand_thing(cx: @ext_ctxt, span: span, + fn rand_thing(cx: @ExtCtxt, span: span, ctor_ident: ident, summary: &Either, rand_call: &fn() -> @expr) -> @expr { diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs index 0c12a1948cd4c..19fd601186b1e 100644 --- a/src/libsyntax/ext/deriving/to_str.rs +++ b/src/libsyntax/ext/deriving/to_str.rs @@ -10,11 +10,11 @@ use ast::{meta_item, item, expr}; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use ext::deriving::generic::*; -pub fn expand_deriving_to_str(cx: @ext_ctxt, +pub fn expand_deriving_to_str(cx: @ExtCtxt, span: span, mitem: @meta_item, in_items: ~[@item]) @@ -39,7 +39,7 @@ pub fn expand_deriving_to_str(cx: @ext_ctxt, expand_deriving_generic(cx, span, mitem, in_items, &trait_def) } -fn to_str_substructure(cx: @ext_ctxt, span: span, substr: &Substructure) -> @expr { +fn to_str_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { match substr.self_args { [self_obj] => { let self_addr = build::mk_addr_of(cx, span, self_obj); diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index bbc6b6634e383..154e7647bb560 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -15,7 +15,7 @@ explicit `Self` type to use when specifying impls to be derived. use ast; use ast::{expr,Generics,ident}; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::build; use codemap::{span,respan}; use opt_vec; @@ -53,13 +53,13 @@ pub impl<'self> Path<'self> { } } - fn to_ty(&self, cx: @ext_ctxt, span: span, + fn to_ty(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Ty { build::mk_ty_path_path(cx, span, self.to_path(cx, span, self_ty, self_generics)) } - fn to_path(&self, cx: @ext_ctxt, span: span, + fn to_path(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Path { let idents = self.path.map(|s| cx.ident_of(*s) ); let lt = mk_lifetime(cx, span, &self.lifetime); @@ -104,7 +104,7 @@ pub fn nil_ty() -> Ty<'static> { Tuple(~[]) } -fn mk_lifetime(cx: @ext_ctxt, span: span, lt: &Option<&str>) -> Option<@ast::Lifetime> { +fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<@ast::Lifetime> { match *lt { Some(ref s) => Some(@build::mk_lifetime(cx, span, cx.ident_of(*s))), None => None @@ -112,7 +112,7 @@ fn mk_lifetime(cx: @ext_ctxt, span: span, lt: &Option<&str>) -> Option<@ast::Lif } pub impl<'self> Ty<'self> { - fn to_ty(&self, cx: @ext_ctxt, span: span, + fn to_ty(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Ty { match *self { Ptr(ref ty, ref ptr) => { @@ -146,7 +146,7 @@ pub impl<'self> Ty<'self> { } } - fn to_path(&self, cx: @ext_ctxt, span: span, + fn to_path(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Path { match *self { Self => { @@ -172,7 +172,7 @@ pub impl<'self> Ty<'self> { } -fn mk_ty_param(cx: @ext_ctxt, span: span, name: &str, bounds: &[Path], +fn mk_ty_param(cx: @ExtCtxt, span: span, name: &str, bounds: &[Path], self_ident: ident, self_generics: &Generics) -> ast::TyParam { let bounds = opt_vec::from( do bounds.map |b| { @@ -201,7 +201,7 @@ pub impl<'self> LifetimeBounds<'self> { lifetimes: ~[], bounds: ~[] } } - fn to_generics(&self, cx: @ext_ctxt, span: span, + fn to_generics(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> Generics { let lifetimes = do self.lifetimes.map |lt| { build::mk_lifetime(cx, span, cx.ident_of(*lt)) @@ -218,7 +218,7 @@ pub impl<'self> LifetimeBounds<'self> { } -pub fn get_explicit_self(cx: @ext_ctxt, span: span, self_ptr: &Option) +pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option) -> (@expr, ast::explicit_self) { let self_path = build::make_self(cx, span); match *self_ptr { diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 4be75d9ee5b57..3d74595e645ae 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -20,7 +20,7 @@ use ext::base::*; use ext::base; use ext::build::mk_base_str; -pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let var = get_single_str_from_tts(cx, sp, tts, "env!"); diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index ff0cf6f28ad8f..b993162cfa3dd 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -23,7 +23,7 @@ use parse; use parse::{parse_item_from_source_str}; pub fn expand_expr(extsbox: @mut SyntaxEnv, - cx: @ext_ctxt, + cx: @ExtCtxt, e: &expr_, s: span, fld: @ast_fold, @@ -109,7 +109,7 @@ pub fn expand_expr(extsbox: @mut SyntaxEnv, // NB: there is some redundancy between this and expand_item, below, and // they might benefit from some amount of semantic and language-UI merger. pub fn expand_mod_items(extsbox: @mut SyntaxEnv, - cx: @ext_ctxt, + cx: @ExtCtxt, module_: &ast::_mod, fld: @ast_fold, orig: @fn(&ast::_mod, @ast_fold) -> ast::_mod) @@ -161,7 +161,7 @@ macro_rules! with_exts_frame ( // When we enter a module, record it, for the sake of `module!` pub fn expand_item(extsbox: @mut SyntaxEnv, - cx: @ext_ctxt, + cx: @ExtCtxt, it: @ast::item, fld: @ast_fold, orig: @fn(@ast::item, @ast_fold) -> Option<@ast::item>) @@ -227,7 +227,7 @@ macro_rules! without_macro_scoping( // Support for item-position macro invocations, exactly the same // logic as for expression-position macro invocations. pub fn expand_item_mac(extsbox: @mut SyntaxEnv, - cx: @ext_ctxt, it: @ast::item, + cx: @ExtCtxt, it: @ast::item, fld: @ast_fold) -> Option<@ast::item> { let (pth, tts) = match it.node { @@ -294,7 +294,7 @@ pub fn expand_item_mac(extsbox: @mut SyntaxEnv, // expand a stmt pub fn expand_stmt(extsbox: @mut SyntaxEnv, - cx: @ext_ctxt, + cx: @ExtCtxt, s: &stmt_, sp: span, fld: @ast_fold, @@ -360,7 +360,7 @@ pub fn expand_stmt(extsbox: @mut SyntaxEnv, pub fn expand_block(extsbox: @mut SyntaxEnv, - cx: @ext_ctxt, + cx: @ExtCtxt, blk: &blk_, sp: span, fld: @ast_fold, @@ -381,7 +381,7 @@ pub fn expand_block(extsbox: @mut SyntaxEnv, } } -pub fn new_span(cx: @ext_ctxt, sp: span) -> span { +pub fn new_span(cx: @ExtCtxt, sp: span) -> span { /* this discards information in the case of macro-defining macros */ return span {lo: sp.lo, hi: sp.hi, expn_info: cx.backtrace()}; } @@ -590,7 +590,7 @@ pub fn expand_crate(parse_sess: @mut parse::ParseSess, // every method/element of AstFoldFns in fold.rs. let extsbox = @mut syntax_expander_table(); let afp = default_ast_fold(); - let cx: @ext_ctxt = mk_ctxt(parse_sess, copy cfg); + let cx = ExtCtxt::new(parse_sess, copy cfg); let f_pre = @AstFoldFns { fold_expr: |expr,span,recur| expand_expr(extsbox, cx, expr, span, recur, afp.fold_expr), diff --git a/src/libsyntax/ext/fmt.rs b/src/libsyntax/ext/fmt.rs index 24046faa6849d..ca281a22e3922 100644 --- a/src/libsyntax/ext/fmt.rs +++ b/src/libsyntax/ext/fmt.rs @@ -23,7 +23,7 @@ use ext::build::*; use core::unstable::extfmt::ct::*; -pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let args = get_exprs_from_tts(cx, tts); if args.len() == 0 { @@ -34,7 +34,7 @@ pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) ~"first argument to fmt! must be a string literal."); let fmtspan = args[0].span; debug!("Format string: %s", fmt); - fn parse_fmt_err_(cx: @ext_ctxt, sp: span, msg: &str) -> ! { + fn parse_fmt_err_(cx: @ExtCtxt, sp: span, msg: &str) -> ! { cx.span_fatal(sp, msg); } let parse_fmt_err: @fn(&str) -> ! = |s| parse_fmt_err_(cx, fmtspan, s); @@ -46,23 +46,23 @@ pub fn expand_syntax_ext(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) // probably be factored out in common with other code that builds // expressions. Also: Cleanup the naming of these functions. // Note: Moved many of the common ones to build.rs --kevina -fn pieces_to_expr(cx: @ext_ctxt, sp: span, +fn pieces_to_expr(cx: @ExtCtxt, sp: span, pieces: ~[Piece], args: ~[@ast::expr]) -> @ast::expr { - fn make_path_vec(cx: @ext_ctxt, ident: &str) -> ~[ast::ident] { + fn make_path_vec(cx: @ExtCtxt, ident: &str) -> ~[ast::ident] { let intr = cx.parse_sess().interner; return ~[intr.intern("unstable"), intr.intern("extfmt"), intr.intern("rt"), intr.intern(ident)]; } - fn make_rt_path_expr(cx: @ext_ctxt, sp: span, nm: &str) -> @ast::expr { + fn make_rt_path_expr(cx: @ExtCtxt, sp: span, nm: &str) -> @ast::expr { let path = make_path_vec(cx, nm); return mk_path_global(cx, sp, path); } // Produces an AST expression that represents a RT::conv record, // which tells the RT::conv* functions how to perform the conversion - fn make_rt_conv_expr(cx: @ext_ctxt, sp: span, cnv: &Conv) -> @ast::expr { - fn make_flags(cx: @ext_ctxt, sp: span, flags: &[Flag]) -> @ast::expr { + fn make_rt_conv_expr(cx: @ExtCtxt, sp: span, cnv: &Conv) -> @ast::expr { + fn make_flags(cx: @ExtCtxt, sp: span, flags: &[Flag]) -> @ast::expr { let mut tmp_expr = make_rt_path_expr(cx, sp, "flag_none"); for flags.each |f| { let fstr = match *f { @@ -77,7 +77,7 @@ fn pieces_to_expr(cx: @ext_ctxt, sp: span, } return tmp_expr; } - fn make_count(cx: @ext_ctxt, sp: span, cnt: Count) -> @ast::expr { + fn make_count(cx: @ExtCtxt, sp: span, cnt: Count) -> @ast::expr { match cnt { CountImplied => { return make_rt_path_expr(cx, sp, "CountImplied"); @@ -91,7 +91,7 @@ fn pieces_to_expr(cx: @ext_ctxt, sp: span, _ => cx.span_unimpl(sp, "unimplemented fmt! conversion") } } - fn make_ty(cx: @ext_ctxt, sp: span, t: Ty) -> @ast::expr { + fn make_ty(cx: @ExtCtxt, sp: span, t: Ty) -> @ast::expr { let rt_type = match t { TyHex(c) => match c { CaseUpper => "TyHexUpper", @@ -103,7 +103,7 @@ fn pieces_to_expr(cx: @ext_ctxt, sp: span, }; return make_rt_path_expr(cx, sp, rt_type); } - fn make_conv_struct(cx: @ext_ctxt, sp: span, flags_expr: @ast::expr, + fn make_conv_struct(cx: @ExtCtxt, sp: span, flags_expr: @ast::expr, width_expr: @ast::expr, precision_expr: @ast::expr, ty_expr: @ast::expr) -> @ast::expr { let intr = cx.parse_sess().interner; @@ -134,7 +134,7 @@ fn pieces_to_expr(cx: @ext_ctxt, sp: span, make_conv_struct(cx, sp, rt_conv_flags, rt_conv_width, rt_conv_precision, rt_conv_ty) } - fn make_conv_call(cx: @ext_ctxt, sp: span, conv_type: &str, cnv: &Conv, + fn make_conv_call(cx: @ExtCtxt, sp: span, conv_type: &str, cnv: &Conv, arg: @ast::expr, buf: @ast::expr) -> @ast::expr { let fname = ~"conv_" + conv_type; let path = make_path_vec(cx, fname); @@ -143,7 +143,7 @@ fn pieces_to_expr(cx: @ext_ctxt, sp: span, return mk_call_global(cx, arg.span, path, args); } - fn make_new_conv(cx: @ext_ctxt, sp: span, cnv: &Conv, + fn make_new_conv(cx: @ExtCtxt, sp: span, cnv: &Conv, arg: @ast::expr, buf: @ast::expr) -> @ast::expr { fn is_signed_type(cnv: &Conv) -> bool { match cnv.ty { diff --git a/src/libsyntax/ext/log_syntax.rs b/src/libsyntax/ext/log_syntax.rs index 76d9a9420ce50..a3f6fb8e97d21 100644 --- a/src/libsyntax/ext/log_syntax.rs +++ b/src/libsyntax/ext/log_syntax.rs @@ -14,7 +14,7 @@ use ext::base::*; use ext::base; use print; -pub fn expand_syntax_ext(cx: @ext_ctxt, +pub fn expand_syntax_ext(cx: @ExtCtxt, sp: codemap::span, tt: &[ast::token_tree]) -> base::MacResult { diff --git a/src/libsyntax/ext/pipes/ast_builder.rs b/src/libsyntax/ext/pipes/ast_builder.rs index a514828725866..1f38b14efbecf 100644 --- a/src/libsyntax/ext/pipes/ast_builder.rs +++ b/src/libsyntax/ext/pipes/ast_builder.rs @@ -19,7 +19,7 @@ use ast; use ast_util; use codemap::{span, respan, dummy_sp, spanned}; use codemap; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::quote::rt::*; use opt_vec; use opt_vec::OptVec; @@ -135,7 +135,7 @@ pub trait ext_ctxt_ast_builder { fn strip_bounds(&self, bounds: &Generics) -> Generics; } -impl ext_ctxt_ast_builder for @ext_ctxt { +impl ext_ctxt_ast_builder for @ExtCtxt { fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty { self.ty_path_ast_builder(path_global(~[ self.ident_of("core"), diff --git a/src/libsyntax/ext/pipes/check.rs b/src/libsyntax/ext/pipes/check.rs index 38e43d1ade562..c0b7f5bbb8426 100644 --- a/src/libsyntax/ext/pipes/check.rs +++ b/src/libsyntax/ext/pipes/check.rs @@ -31,11 +31,11 @@ that. use ast; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::pipes::proto::{state, protocol, next_state}; use ext::pipes::proto; -impl proto::visitor<(), (), ()> for @ext_ctxt { +impl proto::visitor<(), (), ()> for @ExtCtxt { fn visit_proto(&self, _proto: protocol, _states: &[()]) { } fn visit_state(&self, state: state, _m: &[()]) { diff --git a/src/libsyntax/ext/pipes/liveness.rs b/src/libsyntax/ext/pipes/liveness.rs index 104e5f94d1770..8d45e47d54ef7 100644 --- a/src/libsyntax/ext/pipes/liveness.rs +++ b/src/libsyntax/ext/pipes/liveness.rs @@ -37,12 +37,12 @@ updating the states using rule (2) until there are no changes. */ -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::pipes::proto::{protocol_}; use std::bitv::Bitv; -pub fn analyze(proto: @mut protocol_, _cx: @ext_ctxt) { +pub fn analyze(proto: @mut protocol_, _cx: @ExtCtxt) { debug!("initializing colive analysis"); let num_states = proto.num_states(); let mut colive = do (copy proto.states).map_to_vec |state| { diff --git a/src/libsyntax/ext/pipes/mod.rs b/src/libsyntax/ext/pipes/mod.rs index 642f22e973680..46de21d1c0b2e 100644 --- a/src/libsyntax/ext/pipes/mod.rs +++ b/src/libsyntax/ext/pipes/mod.rs @@ -46,7 +46,7 @@ FIXME (#3072) - This is still incomplete. use ast; use codemap::span; use ext::base; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::pipes::parse_proto::proto_parser; use ext::pipes::pipec::gen_init; use ext::pipes::proto::visit; @@ -63,7 +63,7 @@ pub mod check; pub mod liveness; -pub fn expand_proto(cx: @ext_ctxt, _sp: span, id: ast::ident, +pub fn expand_proto(cx: @ExtCtxt, _sp: span, id: ast::ident, tt: ~[ast::token_tree]) -> base::MacResult { let sess = cx.parse_sess(); let cfg = cx.cfg(); diff --git a/src/libsyntax/ext/pipes/pipec.rs b/src/libsyntax/ext/pipes/pipec.rs index 8a9c714e7e939..83b3572c85f36 100644 --- a/src/libsyntax/ext/pipes/pipec.rs +++ b/src/libsyntax/ext/pipes/pipec.rs @@ -12,7 +12,7 @@ use ast; use codemap::{dummy_sp, spanned}; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::pipes::ast_builder::{append_types, ext_ctxt_ast_builder, path}; use ext::pipes::ast_builder::{path_global}; use ext::pipes::proto::*; @@ -21,27 +21,27 @@ use opt_vec; use opt_vec::OptVec; pub trait gen_send { - fn gen_send(&mut self, cx: @ext_ctxt, try: bool) -> @ast::item; - fn to_ty(&mut self, cx: @ext_ctxt) -> @ast::Ty; + fn gen_send(&mut self, cx: @ExtCtxt, try: bool) -> @ast::item; + fn to_ty(&mut self, cx: @ExtCtxt) -> @ast::Ty; } pub trait to_type_decls { - fn to_type_decls(&self, cx: @ext_ctxt) -> ~[@ast::item]; - fn to_endpoint_decls(&self, cx: @ext_ctxt, + fn to_type_decls(&self, cx: @ExtCtxt) -> ~[@ast::item]; + fn to_endpoint_decls(&self, cx: @ExtCtxt, dir: direction) -> ~[@ast::item]; } pub trait gen_init { - fn gen_init(&self, cx: @ext_ctxt) -> @ast::item; - fn compile(&self, cx: @ext_ctxt) -> @ast::item; - fn buffer_ty_path(&self, cx: @ext_ctxt) -> @ast::Ty; - fn gen_buffer_type(&self, cx: @ext_ctxt) -> @ast::item; - fn gen_buffer_init(&self, ext_cx: @ext_ctxt) -> @ast::expr; - fn gen_init_bounded(&self, ext_cx: @ext_ctxt) -> @ast::expr; + fn gen_init(&self, cx: @ExtCtxt) -> @ast::item; + fn compile(&self, cx: @ExtCtxt) -> @ast::item; + fn buffer_ty_path(&self, cx: @ExtCtxt) -> @ast::Ty; + fn gen_buffer_type(&self, cx: @ExtCtxt) -> @ast::item; + fn gen_buffer_init(&self, ext_cx: @ExtCtxt) -> @ast::expr; + fn gen_init_bounded(&self, ext_cx: @ExtCtxt) -> @ast::expr; } impl gen_send for message { - fn gen_send(&mut self, cx: @ext_ctxt, try: bool) -> @ast::item { + fn gen_send(&mut self, cx: @ExtCtxt, try: bool) -> @ast::item { debug!("pipec: gen_send"); let name = self.name(); @@ -184,14 +184,14 @@ impl gen_send for message { } } - fn to_ty(&mut self, cx: @ext_ctxt) -> @ast::Ty { + fn to_ty(&mut self, cx: @ExtCtxt) -> @ast::Ty { cx.ty_path_ast_builder(path(~[cx.ident_of(self.name())], self.span()) .add_tys(cx.ty_vars_global(&self.get_generics().ty_params))) } } impl to_type_decls for state { - fn to_type_decls(&self, cx: @ext_ctxt) -> ~[@ast::item] { + fn to_type_decls(&self, cx: @ExtCtxt) -> ~[@ast::item] { debug!("pipec: to_type_decls"); // This compiles into two different type declarations. Say the // state is called ping. This will generate both `ping` and @@ -240,7 +240,7 @@ impl to_type_decls for state { ] } - fn to_endpoint_decls(&self, cx: @ext_ctxt, + fn to_endpoint_decls(&self, cx: @ExtCtxt, dir: direction) -> ~[@ast::item] { debug!("pipec: to_endpoint_decls"); let dir = match dir { @@ -302,7 +302,7 @@ impl to_type_decls for state { } impl gen_init for protocol { - fn gen_init(&self, cx: @ext_ctxt) -> @ast::item { + fn gen_init(&self, cx: @ExtCtxt) -> @ast::item { let ext_cx = cx; debug!("gen_init"); @@ -340,7 +340,7 @@ impl gen_init for protocol { body.to_source(cx))) } - fn gen_buffer_init(&self, ext_cx: @ext_ctxt) -> @ast::expr { + fn gen_buffer_init(&self, ext_cx: @ExtCtxt) -> @ast::expr { ext_cx.struct_expr(path(~[ext_cx.ident_of("__Buffer")], dummy_sp()), self.states.map_to_vec(|s| { @@ -352,7 +352,7 @@ impl gen_init for protocol { })) } - fn gen_init_bounded(&self, ext_cx: @ext_ctxt) -> @ast::expr { + fn gen_init_bounded(&self, ext_cx: @ExtCtxt) -> @ast::expr { debug!("gen_init_bounded"); let buffer_fields = self.gen_buffer_init(ext_cx); let buffer = quote_expr!(~::core::pipes::Buffer { @@ -378,7 +378,7 @@ impl gen_init for protocol { }) } - fn buffer_ty_path(&self, cx: @ext_ctxt) -> @ast::Ty { + fn buffer_ty_path(&self, cx: @ExtCtxt) -> @ast::Ty { let mut params: OptVec = opt_vec::Empty; for (copy self.states).each |s| { for s.generics.ty_params.each |tp| { @@ -395,7 +395,7 @@ impl gen_init for protocol { .add_tys(cx.ty_vars_global(¶ms))) } - fn gen_buffer_type(&self, cx: @ext_ctxt) -> @ast::item { + fn gen_buffer_type(&self, cx: @ExtCtxt) -> @ast::item { let ext_cx = cx; let mut params: OptVec = opt_vec::Empty; let fields = do (copy self.states).map_to_vec |s| { @@ -436,7 +436,7 @@ impl gen_init for protocol { cx.strip_bounds(&generics)) } - fn compile(&self, cx: @ext_ctxt) -> @ast::item { + fn compile(&self, cx: @ExtCtxt) -> @ast::item { let mut items = ~[self.gen_init(cx)]; let mut client_states = ~[]; let mut server_states = ~[]; diff --git a/src/libsyntax/ext/pipes/proto.rs b/src/libsyntax/ext/pipes/proto.rs index 7bf58bc6f324c..12a0a0a24d616 100644 --- a/src/libsyntax/ext/pipes/proto.rs +++ b/src/libsyntax/ext/pipes/proto.rs @@ -10,7 +10,7 @@ use ast; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::pipes::ast_builder::{append_types, ext_ctxt_ast_builder, path}; #[deriving(Eq)] @@ -92,7 +92,7 @@ pub impl state_ { } /// Returns the type that is used for the messages. - fn to_ty(&self, cx: @ext_ctxt) -> @ast::Ty { + fn to_ty(&self, cx: @ExtCtxt) -> @ast::Ty { cx.ty_path_ast_builder (path(~[cx.ident_of(self.name)],self.span).add_tys( cx.ty_vars(&self.generics.ty_params))) diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 2134c2ba19bff..2ccceeec294fc 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -10,7 +10,7 @@ use ast; use codemap::{BytePos, Pos, span}; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::base; use ext::build; use parse::token::*; @@ -30,7 +30,7 @@ use parse; pub mod rt { use ast; - use ext::base::ext_ctxt; + use ext::base::ExtCtxt; use parse; use print::pprust; @@ -44,11 +44,11 @@ pub mod rt { use print::pprust::{item_to_str, ty_to_str}; pub trait ToTokens { - pub fn to_tokens(&self, _cx: @ext_ctxt) -> ~[token_tree]; + pub fn to_tokens(&self, _cx: @ExtCtxt) -> ~[token_tree]; } impl ToTokens for ~[token_tree] { - pub fn to_tokens(&self, _cx: @ext_ctxt) -> ~[token_tree] { + pub fn to_tokens(&self, _cx: @ExtCtxt) -> ~[token_tree] { copy *self } } @@ -57,10 +57,10 @@ pub mod rt { trait ToSource : ToTokens { // Takes a thing and generates a string containing rust code for it. - pub fn to_source(cx: @ext_ctxt) -> ~str; + pub fn to_source(cx: @ExtCtxt) -> ~str; // If you can make source, you can definitely make tokens. - pub fn to_tokens(cx: @ext_ctxt) -> ~[token_tree] { + pub fn to_tokens(cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } @@ -69,80 +69,80 @@ pub mod rt { pub trait ToSource { // Takes a thing and generates a string containing rust code for it. - pub fn to_source(&self, cx: @ext_ctxt) -> ~str; + pub fn to_source(&self, cx: @ExtCtxt) -> ~str; } impl ToSource for ast::ident { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { copy *cx.parse_sess().interner.get(*self) } } impl ToSource for @ast::item { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { item_to_str(*self, cx.parse_sess().interner) } } impl<'self> ToSource for &'self [@ast::item] { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { str::connect(self.map(|i| i.to_source(cx)), "\n\n") } } impl ToSource for @ast::Ty { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { ty_to_str(*self, cx.parse_sess().interner) } } impl<'self> ToSource for &'self [@ast::Ty] { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { str::connect(self.map(|i| i.to_source(cx)), ", ") } } impl ToSource for Generics { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { pprust::generics_to_str(self, cx.parse_sess().interner) } } impl ToSource for @ast::expr { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { pprust::expr_to_str(*self, cx.parse_sess().interner) } } impl ToSource for ast::blk { - fn to_source(&self, cx: @ext_ctxt) -> ~str { + fn to_source(&self, cx: @ExtCtxt) -> ~str { pprust::block_to_str(self, cx.parse_sess().interner) } } impl<'self> ToSource for &'self str { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_str(@str::to_owned(*self))); pprust::lit_to_str(@lit) } } impl ToSource for int { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_int(*self as i64, ast::ty_i)); pprust::lit_to_str(@lit) } } impl ToSource for i8 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_int(*self as i64, ast::ty_i8)); pprust::lit_to_str(@lit) } } impl ToSource for i16 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_int(*self as i64, ast::ty_i16)); pprust::lit_to_str(@lit) } @@ -150,49 +150,49 @@ pub mod rt { impl ToSource for i32 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_int(*self as i64, ast::ty_i32)); pprust::lit_to_str(@lit) } } impl ToSource for i64 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_int(*self as i64, ast::ty_i64)); pprust::lit_to_str(@lit) } } impl ToSource for uint { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_uint(*self as u64, ast::ty_u)); pprust::lit_to_str(@lit) } } impl ToSource for u8 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_uint(*self as u64, ast::ty_u8)); pprust::lit_to_str(@lit) } } impl ToSource for u16 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_uint(*self as u64, ast::ty_u16)); pprust::lit_to_str(@lit) } } impl ToSource for u32 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_uint(*self as u64, ast::ty_u32)); pprust::lit_to_str(@lit) } } impl ToSource for u64 { - fn to_source(&self, _cx: @ext_ctxt) -> ~str { + fn to_source(&self, _cx: @ExtCtxt) -> ~str { let lit = dummy_spanned(ast::lit_uint(*self as u64, ast::ty_u64)); pprust::lit_to_str(@lit) } @@ -201,115 +201,115 @@ pub mod rt { // Alas ... we write these out instead. All redundant. impl ToTokens for ast::ident { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for @ast::item { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl<'self> ToTokens for &'self [@ast::item] { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for @ast::Ty { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl<'self> ToTokens for &'self [@ast::Ty] { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for Generics { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for @ast::expr { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for ast::blk { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl<'self> ToTokens for &'self str { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for int { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for i8 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for i16 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for i32 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for i64 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for uint { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for u8 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for u16 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for u32 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } impl ToTokens for u64 { - fn to_tokens(&self, cx: @ext_ctxt) -> ~[token_tree] { + fn to_tokens(&self, cx: @ExtCtxt) -> ~[token_tree] { cx.parse_tts(self.to_source(cx)) } } @@ -321,7 +321,7 @@ pub mod rt { fn parse_tts(&self, s: ~str) -> ~[ast::token_tree]; } - impl ExtParseUtils for @ext_ctxt { + impl ExtParseUtils for ExtCtxt { fn parse_item(&self, s: ~str) -> @ast::item { let res = parse::parse_item_from_source_str( @@ -367,19 +367,19 @@ pub mod rt { } -pub fn expand_quote_tokens(cx: @ext_ctxt, +pub fn expand_quote_tokens(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::MRExpr(expand_tts(cx, sp, tts)) } -pub fn expand_quote_expr(cx: @ext_ctxt, +pub fn expand_quote_expr(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::MRExpr(expand_parse_call(cx, sp, "parse_expr", ~[], tts)) } -pub fn expand_quote_item(cx: @ext_ctxt, +pub fn expand_quote_item(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let e_attrs = build::mk_uniq_vec_e(cx, sp, ~[]); @@ -387,7 +387,7 @@ pub fn expand_quote_item(cx: @ext_ctxt, ~[e_attrs], tts)) } -pub fn expand_quote_pat(cx: @ext_ctxt, +pub fn expand_quote_pat(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let e_refutable = build::mk_lit(cx, sp, ast::lit_bool(true)); @@ -395,7 +395,7 @@ pub fn expand_quote_pat(cx: @ext_ctxt, ~[e_refutable], tts)) } -pub fn expand_quote_ty(cx: @ext_ctxt, +pub fn expand_quote_ty(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let e_param_colons = build::mk_lit(cx, sp, ast::lit_bool(false)); @@ -403,7 +403,7 @@ pub fn expand_quote_ty(cx: @ext_ctxt, ~[e_param_colons], tts)) } -pub fn expand_quote_stmt(cx: @ext_ctxt, +pub fn expand_quote_stmt(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let e_attrs = build::mk_uniq_vec_e(cx, sp, ~[]); @@ -411,16 +411,16 @@ pub fn expand_quote_stmt(cx: @ext_ctxt, ~[e_attrs], tts)) } -fn ids_ext(cx: @ext_ctxt, strs: ~[~str]) -> ~[ast::ident] { +fn ids_ext(cx: @ExtCtxt, strs: ~[~str]) -> ~[ast::ident] { strs.map(|str| cx.parse_sess().interner.intern(*str)) } -fn id_ext(cx: @ext_ctxt, str: &str) -> ast::ident { +fn id_ext(cx: @ExtCtxt, str: &str) -> ast::ident { cx.parse_sess().interner.intern(str) } // Lift an ident to the expr that evaluates to that ident. -fn mk_ident(cx: @ext_ctxt, sp: span, ident: ast::ident) -> @ast::expr { +fn mk_ident(cx: @ExtCtxt, sp: span, ident: ast::ident) -> @ast::expr { let e_str = build::mk_base_str(cx, sp, cx.str_of(ident)); build::mk_method_call(cx, sp, build::mk_path(cx, sp, ids_ext(cx, ~[~"ext_cx"])), @@ -428,13 +428,13 @@ fn mk_ident(cx: @ext_ctxt, sp: span, ident: ast::ident) -> @ast::expr { ~[e_str]) } -fn mk_bytepos(cx: @ext_ctxt, sp: span, bpos: BytePos) -> @ast::expr { +fn mk_bytepos(cx: @ExtCtxt, sp: span, bpos: BytePos) -> @ast::expr { let path = ids_ext(cx, ~[~"BytePos"]); let arg = build::mk_uint(cx, sp, bpos.to_uint()); build::mk_call(cx, sp, path, ~[arg]) } -fn mk_binop(cx: @ext_ctxt, sp: span, bop: token::binop) -> @ast::expr { +fn mk_binop(cx: @ExtCtxt, sp: span, bop: token::binop) -> @ast::expr { let name = match bop { PLUS => "PLUS", MINUS => "MINUS", @@ -451,7 +451,7 @@ fn mk_binop(cx: @ext_ctxt, sp: span, bop: token::binop) -> @ast::expr { ids_ext(cx, ~[name.to_owned()])) } -fn mk_token(cx: @ext_ctxt, sp: span, tok: &token::Token) -> @ast::expr { +fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { match *tok { BINOP(binop) => { @@ -600,7 +600,7 @@ fn mk_token(cx: @ext_ctxt, sp: span, tok: &token::Token) -> @ast::expr { } -fn mk_tt(cx: @ext_ctxt, sp: span, tt: &ast::token_tree) +fn mk_tt(cx: @ExtCtxt, sp: span, tt: &ast::token_tree) -> ~[@ast::stmt] { match *tt { @@ -646,7 +646,7 @@ fn mk_tt(cx: @ext_ctxt, sp: span, tt: &ast::token_tree) } } -fn mk_tts(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +fn mk_tts(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> ~[@ast::stmt] { let mut ss = ~[]; for tts.each |tt| { @@ -655,7 +655,7 @@ fn mk_tts(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) ss } -fn expand_tts(cx: @ext_ctxt, +fn expand_tts(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> @ast::expr { @@ -729,7 +729,7 @@ fn expand_tts(cx: @ext_ctxt, ids_ext(cx, ~[~"tt"])))) } -fn expand_parse_call(cx: @ext_ctxt, +fn expand_parse_call(cx: @ExtCtxt, sp: span, parse_method: &str, arg_exprs: ~[@ast::expr], diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index c0d9b3f06af56..d78c06bec0774 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -23,7 +23,7 @@ use print::pprust; // a given file into the current one. /* line!(): expands to the current line number */ -pub fn expand_line(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_line(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::check_zero_tts(cx, sp, tts, "line!"); @@ -34,7 +34,7 @@ pub fn expand_line(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) } /* col!(): expands to the current column number */ -pub fn expand_col(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_col(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::check_zero_tts(cx, sp, tts, "col!"); @@ -46,7 +46,7 @@ pub fn expand_col(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) /* file!(): expands to the current filename */ /* The filemap (`loc.file`) contains a bunch more information we could spit * out if we wanted. */ -pub fn expand_file(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_file(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::check_zero_tts(cx, sp, tts, "file!"); @@ -56,13 +56,13 @@ pub fn expand_file(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) base::MRExpr(mk_base_str(cx, topmost.call_site, filename)) } -pub fn expand_stringify(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_stringify(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let s = pprust::tts_to_str(tts, cx.parse_sess().interner); base::MRExpr(mk_base_str(cx, sp, s)) } -pub fn expand_mod(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_mod(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::check_zero_tts(cx, sp, tts, "module_path!"); base::MRExpr(mk_base_str(cx, sp, @@ -73,7 +73,7 @@ pub fn expand_mod(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) // include! : parse the given file as an expr // This is generally a bad idea because it's going to behave // unhygienically. -pub fn expand_include(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_include(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let file = get_single_str_from_tts(cx, sp, tts, "include!"); let p = parse::new_sub_parser_from_file( @@ -83,7 +83,7 @@ pub fn expand_include(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) } // include_str! : read the given file, insert it as a literal string expr -pub fn expand_include_str(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_include_str(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let file = get_single_str_from_tts(cx, sp, tts, "include_str!"); let res = io::read_whole_file_str(&res_rel_file(cx, sp, &Path(file))); @@ -97,7 +97,7 @@ pub fn expand_include_str(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) base::MRExpr(mk_base_str(cx, sp, result::unwrap(res))) } -pub fn expand_include_bin(cx: @ext_ctxt, sp: span, tts: &[ast::token_tree]) +pub fn expand_include_bin(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let file = get_single_str_from_tts(cx, sp, tts, "include_bin!"); match io::read_whole_file(&res_rel_file(cx, sp, &Path(file))) { @@ -141,7 +141,7 @@ fn topmost_expn_info(expn_info: @codemap::ExpnInfo) -> @codemap::ExpnInfo { // resolve a file-system path to an absolute file-system path (if it // isn't already) -fn res_rel_file(cx: @ext_ctxt, sp: codemap::span, arg: &Path) -> Path { +fn res_rel_file(cx: @ExtCtxt, sp: codemap::span, arg: &Path) -> Path { // NB: relative paths are resolved relative to the compilation unit if !arg.is_absolute { let cu = Path(cx.codemap().span_to_filename(sp)); diff --git a/src/libsyntax/ext/trace_macros.rs b/src/libsyntax/ext/trace_macros.rs index 0ecb3b2a3f47f..25607a8bfa76f 100644 --- a/src/libsyntax/ext/trace_macros.rs +++ b/src/libsyntax/ext/trace_macros.rs @@ -10,12 +10,12 @@ use ast; use codemap::span; -use ext::base::ext_ctxt; +use ext::base::ExtCtxt; use ext::base; use parse::lexer::{new_tt_reader, reader}; use parse::parser::Parser; -pub fn expand_trace_macros(cx: @ext_ctxt, +pub fn expand_trace_macros(cx: @ExtCtxt, sp: span, tt: &[ast::token_tree]) -> base::MacResult { diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index d34eca342e93e..3814243efc4c6 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -13,7 +13,7 @@ use ast::{ident, matcher_, matcher, match_tok, match_nonterminal, match_seq}; use ast::{tt_delim}; use ast; use codemap::{span, spanned, dummy_sp}; -use ext::base::{ext_ctxt, MacResult, MRAny, MRDef, MacroDef, NormalTT}; +use ext::base::{ExtCtxt, MacResult, MRAny, MRDef, MacroDef, NormalTT}; use ext::base; use ext::tt::macro_parser::{error}; use ext::tt::macro_parser::{named_match, matched_seq, matched_nonterminal}; @@ -26,7 +26,7 @@ use print; use core::io; -pub fn add_new_extension(cx: @ext_ctxt, +pub fn add_new_extension(cx: @ExtCtxt, sp: span, name: ident, arg: ~[ast::token_tree]) @@ -73,7 +73,7 @@ pub fn add_new_extension(cx: @ext_ctxt, }; // Given `lhses` and `rhses`, this is the new macro we create - fn generic_extension(cx: @ext_ctxt, sp: span, name: ident, + fn generic_extension(cx: @ExtCtxt, sp: span, name: ident, arg: &[ast::token_tree], lhses: &[@named_match], rhses: &[@named_match]) -> MacResult { @@ -145,7 +145,7 @@ pub fn add_new_extension(cx: @ext_ctxt, cx.span_fatal(best_fail_spot, best_fail_msg); } - let exp: @fn(@ext_ctxt, span, &[ast::token_tree]) -> MacResult = + let exp: @fn(@ExtCtxt, span, &[ast::token_tree]) -> MacResult = |cx, sp, arg| generic_extension(cx, sp, name, arg, *lhses, *rhses); return MRDef(MacroDef{ diff --git a/src/test/run-pass-fulldeps/quote-tokens.rs b/src/test/run-pass-fulldeps/quote-tokens.rs index 3ec54955229d3..0cd416afc8316 100644 --- a/src/test/run-pass-fulldeps/quote-tokens.rs +++ b/src/test/run-pass-fulldeps/quote-tokens.rs @@ -12,9 +12,9 @@ extern mod syntax; -use syntax::ext::base::ext_ctxt; +use syntax::ext::base::ExtCtxt; -fn syntax_extension(ext_cx: @ext_ctxt) { +fn syntax_extension(ext_cx: @ExtCtxt) { let e_toks : ~[syntax::ast::token_tree] = quote_tokens!(1 + 2); let p_toks : ~[syntax::ast::token_tree] = quote_tokens!((x, 1 .. 4, *)); From 8c15a0ec4cf023a08078d74ed615ecef0cc10a66 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Fri, 17 May 2013 23:51:25 +1000 Subject: [PATCH 158/248] syntax/ext: collect the ast building traits into a single trait. --- src/libsyntax/ext/build.rs | 488 ++++++++++++++++++++----- src/libsyntax/ext/pipes/ast_builder.rs | 382 +------------------ src/libsyntax/ext/pipes/pipec.rs | 38 +- src/libsyntax/ext/pipes/proto.rs | 5 +- 4 files changed, 420 insertions(+), 493 deletions(-) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index e28c04d198af3..a2d88c1f23a88 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -8,13 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use abi::AbiSet; +use ast::ident; use ast; +use ast_util; use codemap; -use codemap::span; +use codemap::{span, respan, dummy_sp, spanned}; use fold; use ext::base::ExtCtxt; -use ext::build; - +use ext::quote::rt::*; +use opt_vec; use opt_vec::OptVec; pub struct Field { @@ -547,14 +550,8 @@ mod syntax { pub use parse; } -trait ExtCtxtMethods { - fn bind_path(&self, - span: span, - ident: ast::ident, - path: @ast::Path, - bounds: @OptVec) - -> ast::TyParam; - fn expr(&self, span: span, node: ast::expr_) -> @ast::expr; +pub trait AstBuilder { + // paths fn path(&self, span: span, strs: ~[ast::ident]) -> @ast::Path; fn path_global(&self, span: span, strs: ~[ast::ident]) -> @ast::Path; fn path_tps(&self, span: span, strs: ~[ast::ident], tps: ~[@ast::Ty]) @@ -564,16 +561,35 @@ trait ExtCtxtMethods { strs: ~[ast::ident], tps: ~[@ast::Ty]) -> @ast::Path; - fn ty_path(&self, span: span, strs: ~[ast::ident], tps: ~[@ast::Ty]) - -> @ast::Ty; - fn binder_pat(&self, span: span, nm: ast::ident) -> @ast::pat; - fn stmt(&self, expr: @ast::expr) -> @ast::stmt; + + // types + fn ty_path(&self, @ast::Path) -> @ast::Ty; + + fn ty_param(&self, id: ast::ident, bounds: @OptVec) + -> ast::TyParam; + fn ty_vars(&self, ty_params: &OptVec) -> ~[@ast::Ty]; + fn ty_vars_global(&self, ty_params: &OptVec) -> ~[@ast::Ty]; + fn ty_field_imm(&self, name: ident, ty: @ast::Ty) -> ast::ty_field; + fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty; + fn ty_infer(&self) -> @ast::Ty; + fn ty_nil_ast_builder(&self) -> @ast::Ty; + fn strip_bounds(&self, bounds: &Generics) -> Generics; + + + // statements + fn stmt_expr(&self, expr: @ast::expr) -> @ast::stmt; + fn stmt_let(&self, ident: ident, e: @ast::expr) -> @ast::stmt; + + // literals fn lit_str(&self, span: span, s: @~str) -> @ast::expr; fn lit_uint(&self, span: span, i: uint) -> @ast::expr; - fn lambda0(&self, blk: ast::blk) -> @ast::expr; - fn lambda1(&self, blk: ast::blk, ident: ast::ident) -> @ast::expr; - fn blk(&self, span: span, stmts: ~[@ast::stmt]) -> ast::blk; - fn expr_blk(&self, expr: @ast::expr) -> ast::blk; + + // blocks + fn blk(&self, span: span, stmts: ~[@ast::stmt], expr: Option<@ast::expr>) -> ast::blk; + fn blk_expr(&self, expr: @ast::expr) -> ast::blk; + + // expressions + fn expr(&self, span: span, node: ast::expr_) -> @ast::expr; fn expr_path(&self, span: span, strs: ~[ast::ident]) -> @ast::expr; fn expr_path_global(&self, span: span, strs: ~[ast::ident]) -> @ast::expr; fn expr_var(&self, span: span, var: &str) -> @ast::expr; @@ -588,6 +604,13 @@ trait ExtCtxtMethods { ident: ast::ident, args: ~[@ast::expr]) -> @ast::expr; + fn expr_blk(&self, b: ast::blk) -> @ast::expr; + fn field_imm(&self, name: ident, e: @ast::expr) -> ast::field; + fn expr_struct(&self, + path: @ast::Path, + fields: ~[ast::field]) -> @ast::expr; + fn lambda0(&self, blk: ast::blk) -> @ast::expr; + fn lambda1(&self, blk: ast::blk, ident: ast::ident) -> @ast::expr; fn lambda_expr_0(&self, expr: @ast::expr) -> @ast::expr; fn lambda_expr_1(&self, expr: @ast::expr, ident: ast::ident) -> @ast::expr; @@ -597,37 +620,64 @@ trait ExtCtxtMethods { stmts: ~[@ast::stmt], ident: ast::ident) -> @ast::expr; -} -impl ExtCtxtMethods for @ExtCtxt { - fn bind_path( - &self, - _span: span, - ident: ast::ident, - path: @ast::Path, - bounds: @OptVec - ) -> ast::TyParam { - let bound = ast::TraitTyParamBound(@ast::trait_ref { - ref_id: self.next_id(), - path: path - }); + // items + fn item(&self, name: ident, span: span, node: ast::item_) -> @ast::item; - ast::TyParam { - ident: ident, - id: self.next_id(), - bounds: @bounds.prepend(bound) - } - } + fn arg(&self, name: ident, ty: @ast::Ty) -> ast::arg; + fn fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl; - fn expr(&self, span: span, node: ast::expr_) -> @ast::expr { - @ast::expr { - id: self.next_id(), - callee_id: self.next_id(), - node: node, - span: span, - } - } + fn item_fn_poly(&self, + ame: ident, + inputs: ~[ast::arg], + output: @ast::Ty, + generics: Generics, + body: ast::blk) -> @ast::item; + fn item_fn(&self, + name: ident, + inputs: ~[ast::arg], + output: @ast::Ty, + body: ast::blk) -> @ast::item; + + fn variant(&self, + name: ident, + span: span, + tys: ~[@ast::Ty]) -> ast::variant; + fn item_enum_poly(&self, + name: ident, + span: span, + enum_definition: ast::enum_def, + generics: Generics) -> @ast::item; + fn item_enum(&self, + name: ident, + span: span, + enum_definition: ast::enum_def) -> @ast::item; + + fn item_struct_poly(&self, + name: ident, + span: span, + struct_def: ast::struct_def, + generics: Generics) -> @ast::item; + fn item_struct(&self, + name: ident, + span: span, + struct_def: ast::struct_def) -> @ast::item; + + fn item_mod(&self, + name: ident, + span: span, + items: ~[@ast::item]) -> @ast::item; + + fn item_ty_poly(&self, + name: ident, + span: span, + ty: @ast::Ty, + generics: Generics) -> @ast::item; + fn item_ty(&self, name: ident, span: span, ty: @ast::Ty) -> @ast::item; + +} +impl AstBuilder for @ExtCtxt { fn path(&self, span: span, strs: ~[ast::ident]) -> @ast::Path { @ast::Path { span: span, @@ -678,37 +728,89 @@ impl ExtCtxtMethods for @ExtCtxt { } } - fn ty_path( - &self, - span: span, - strs: ~[ast::ident], - tps: ~[@ast::Ty] - ) -> @ast::Ty { + fn ty_path(&self, path: @ast::Path) -> @ast::Ty { + build::mk_ty(*self, path.span, + ast::ty_path(path, self.next_id())) + } + + fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty { + self.ty_path( + self.path_tps_global(dummy_sp(), + ~[ + self.ident_of("core"), + self.ident_of("option"), + self.ident_of("Option") + ], + ~[ ty ])) + } + + fn ty_field_imm(&self, name: ident, ty: @ast::Ty) -> ast::ty_field { + spanned { + node: ast::ty_field_ { + ident: name, + mt: ast::mt { ty: ty, mutbl: ast::m_imm }, + }, + span: dummy_sp(), + } + } + + fn ty_infer(&self) -> @ast::Ty { @ast::Ty { id: self.next_id(), - node: ast::ty_path( - self.path_tps(span, strs, tps), - self.next_id()), - span: span, + node: ast::ty_infer, + span: dummy_sp(), } } - fn binder_pat(&self, span: span, nm: ast::ident) -> @ast::pat { - @ast::pat { + fn ty_param(&self, id: ast::ident, bounds: @OptVec) + -> ast::TyParam + { + ast::TyParam { ident: id, id: self.next_id(), bounds: bounds } + } + + fn ty_nil_ast_builder(&self) -> @ast::Ty { + @ast::Ty { id: self.next_id(), - node: ast::pat_ident( - ast::bind_by_ref(ast::m_imm), - self.path(span, ~[nm]), - None), - span: span, + node: ast::ty_nil, + span: dummy_sp(), + } + } + + fn ty_vars(&self, ty_params: &OptVec) -> ~[@ast::Ty] { + opt_vec::take_vec( + ty_params.map(|p| self.ty_path( + mk_raw_path(dummy_sp(), ~[p.ident])))) + } + + fn ty_vars_global(&self, + ty_params: &OptVec) -> ~[@ast::Ty] { + opt_vec::take_vec( + ty_params.map(|p| self.ty_path( + mk_raw_path(dummy_sp(), ~[p.ident])))) + } + + fn strip_bounds(&self, generics: &Generics) -> Generics { + let no_bounds = @opt_vec::Empty; + let new_params = do generics.ty_params.map |ty_param| { + ast::TyParam { bounds: no_bounds, ..copy *ty_param } + }; + Generics { + ty_params: new_params, + .. copy *generics } } - fn stmt(&self, expr: @ast::expr) -> @ast::stmt { + + fn stmt_expr(&self, expr: @ast::expr) -> @ast::stmt { @codemap::spanned { node: ast::stmt_semi(expr, self.next_id()), span: expr.span } } + fn stmt_let(&self, ident: ident, e: @ast::expr) -> @ast::stmt { + let ext_cx = *self; + quote_stmt!( let $ident = $e; ) + } + fn lit_str(&self, span: span, s: @~str) -> @ast::expr { self.expr( span, @@ -729,24 +831,12 @@ impl ExtCtxtMethods for @ExtCtxt { span: span})) } - fn lambda0(&self, blk: ast::blk) -> @ast::expr { - let ext_cx = *self; - let blk_e = self.expr(copy blk.span, ast::expr_block(copy blk)); - quote_expr!( || $blk_e ) - } - - fn lambda1(&self, blk: ast::blk, ident: ast::ident) -> @ast::expr { - let ext_cx = *self; - let blk_e = self.expr(copy blk.span, ast::expr_block(copy blk)); - quote_expr!( |$ident| $blk_e ) - } - - fn blk(&self, span: span, stmts: ~[@ast::stmt]) -> ast::blk { + fn blk(&self, span: span, stmts: ~[@ast::stmt], expr: Option<@expr>) -> ast::blk { codemap::spanned { node: ast::blk_ { view_items: ~[], stmts: stmts, - expr: None, + expr: expr, id: self.next_id(), rules: ast::default_blk, }, @@ -754,16 +844,16 @@ impl ExtCtxtMethods for @ExtCtxt { } } - fn expr_blk(&self, expr: @ast::expr) -> ast::blk { - codemap::spanned { - node: ast::blk_ { - view_items: ~[], - stmts: ~[], - expr: Some(expr), - id: self.next_id(), - rules: ast::default_blk, - }, - span: expr.span, + fn blk_expr(&self, expr: @ast::expr) -> ast::blk { + self.blk(expr.span, ~[], Some(expr)) + } + + fn expr(&self, span: span, node: ast::expr_) -> @ast::expr { + @ast::expr { + id: self.next_id(), + callee_id: self.next_id(), + node: node, + span: span, } } @@ -815,18 +905,49 @@ impl ExtCtxtMethods for @ExtCtxt { self.expr(span, ast::expr_method_call(expr, ident, ~[], args, ast::NoSugar)) } + fn expr_blk(&self, b: ast::blk) -> @ast::expr { + self.expr(dummy_sp(), ast::expr_block(b)) + } + fn field_imm(&self, name: ident, e: @ast::expr) -> ast::field { + spanned { + node: ast::field_ { mutbl: ast::m_imm, ident: name, expr: e }, + span: dummy_sp(), + } + } + fn expr_struct(&self, path: @ast::Path, + fields: ~[ast::field]) -> @ast::expr { + @ast::expr { + id: self.next_id(), + callee_id: self.next_id(), + node: ast::expr_struct(path, fields, None), + span: dummy_sp() + } + } + + + fn lambda0(&self, blk: ast::blk) -> @ast::expr { + let ext_cx = *self; + let blk_e = self.expr(copy blk.span, ast::expr_block(copy blk)); + quote_expr!( || $blk_e ) + } + + fn lambda1(&self, blk: ast::blk, ident: ast::ident) -> @ast::expr { + let ext_cx = *self; + let blk_e = self.expr(copy blk.span, ast::expr_block(copy blk)); + quote_expr!( |$ident| $blk_e ) + } fn lambda_expr_0(&self, expr: @ast::expr) -> @ast::expr { - self.lambda0(self.expr_blk(expr)) + self.lambda0(self.blk_expr(expr)) } fn lambda_expr_1(&self, expr: @ast::expr, ident: ast::ident) -> @ast::expr { - self.lambda1(self.expr_blk(expr), ident) + self.lambda1(self.blk_expr(expr), ident) } fn lambda_stmts_0(&self, span: span, stmts: ~[@ast::stmt]) -> @ast::expr { - self.lambda0(self.blk(span, stmts)) + self.lambda0(self.blk(span, stmts, None)) } fn lambda_stmts_1(&self, @@ -834,6 +955,189 @@ impl ExtCtxtMethods for @ExtCtxt { stmts: ~[@ast::stmt], ident: ast::ident) -> @ast::expr { - self.lambda1(self.blk(span, stmts), ident) + self.lambda1(self.blk(span, stmts, None), ident) + } + + + fn arg(&self, name: ident, ty: @ast::Ty) -> ast::arg { + ast::arg { + is_mutbl: false, + ty: ty, + pat: @ast::pat { + id: self.next_id(), + node: ast::pat_ident( + ast::bind_by_copy, + ast_util::ident_to_path(dummy_sp(), name), + None), + span: dummy_sp(), + }, + id: self.next_id(), + } } + + fn fn_decl(&self, inputs: ~[ast::arg], + output: @ast::Ty) -> ast::fn_decl { + ast::fn_decl { + inputs: inputs, + output: output, + cf: ast::return_val, + } + } + + fn item(&self, name: ident, span: span, + node: ast::item_) -> @ast::item { + + // XXX: Would be nice if our generated code didn't violate + // Rust coding conventions + let non_camel_case_attribute = respan(dummy_sp(), ast::attribute_ { + style: ast::attr_outer, + value: @respan(dummy_sp(), + ast::meta_list(@~"allow", ~[ + @respan(dummy_sp(), + ast::meta_word( + @~"non_camel_case_types")) + ])), + is_sugared_doc: false + }); + + @ast::item { ident: name, + attrs: ~[non_camel_case_attribute], + id: self.next_id(), + node: node, + vis: ast::public, + span: span } + } + + fn item_fn_poly(&self, name: ident, + inputs: ~[ast::arg], + output: @ast::Ty, + generics: Generics, + body: ast::blk) -> @ast::item { + self.item(name, + dummy_sp(), + ast::item_fn(self.fn_decl(inputs, output), + ast::impure_fn, + AbiSet::Rust(), + generics, + body)) + } + + fn item_fn(&self, + name: ident, + inputs: ~[ast::arg], + output: @ast::Ty, + body: ast::blk + ) -> @ast::item { + self.item_fn_poly( + name, + inputs, + output, + ast_util::empty_generics(), + body + ) + } + + fn variant(&self, name: ident, span: span, + tys: ~[@ast::Ty]) -> ast::variant { + let args = do tys.map |ty| { + ast::variant_arg { ty: *ty, id: self.next_id() } + }; + + spanned { + node: ast::variant_ { + name: name, + attrs: ~[], + kind: ast::tuple_variant_kind(args), + id: self.next_id(), + disr_expr: None, + vis: ast::public + }, + span: span, + } + } + + fn item_enum_poly(&self, name: ident, span: span, + enum_definition: ast::enum_def, + generics: Generics) -> @ast::item { + self.item(name, span, ast::item_enum(enum_definition, generics)) + } + + fn item_enum(&self, name: ident, span: span, + enum_definition: ast::enum_def) -> @ast::item { + self.item_enum_poly(name, span, enum_definition, + ast_util::empty_generics()) + } + + fn item_struct( + &self, name: ident, + span: span, + struct_def: ast::struct_def + ) -> @ast::item { + self.item_struct_poly( + name, + span, + struct_def, + ast_util::empty_generics() + ) + } + + fn item_struct_poly( + &self, + name: ident, + span: span, + struct_def: ast::struct_def, + generics: Generics + ) -> @ast::item { + self.item(name, span, ast::item_struct(@struct_def, generics)) + } + + fn item_mod(&self, name: ident, span: span, + items: ~[@ast::item]) -> @ast::item { + + // XXX: Total hack: import `core::kinds::Owned` to work around a + // parser bug whereby `fn f` doesn't parse. + let vi = ast::view_item_use(~[ + @codemap::spanned { + node: ast::view_path_simple( + self.ident_of("Owned"), + mk_raw_path( + codemap::dummy_sp(), + ~[ + self.ident_of("core"), + self.ident_of("kinds"), + self.ident_of("Owned") + ] + ), + self.next_id() + ), + span: codemap::dummy_sp() + } + ]); + let vi = @ast::view_item { + node: vi, + attrs: ~[], + vis: ast::private, + span: codemap::dummy_sp() + }; + + self.item( + name, + span, + ast::item_mod(ast::_mod { + view_items: ~[vi], + items: items, + }) + ) + } + + fn item_ty_poly(&self, name: ident, span: span, ty: @ast::Ty, + generics: Generics) -> @ast::item { + self.item(name, span, ast::item_ty(ty, generics)) + } + + fn item_ty(&self, name: ident, span: span, ty: @ast::Ty) -> @ast::item { + self.item_ty_poly(name, span, ty, ast_util::empty_generics()) + } + + } diff --git a/src/libsyntax/ext/pipes/ast_builder.rs b/src/libsyntax/ext/pipes/ast_builder.rs index 1f38b14efbecf..44f47c0d588a4 100644 --- a/src/libsyntax/ext/pipes/ast_builder.rs +++ b/src/libsyntax/ext/pipes/ast_builder.rs @@ -13,16 +13,10 @@ // To start with, it will be use dummy spans, but it might someday do // something smarter. -use abi::AbiSet; use ast::ident; use ast; -use ast_util; -use codemap::{span, respan, dummy_sp, spanned}; -use codemap; -use ext::base::ExtCtxt; +use codemap::span; use ext::quote::rt::*; -use opt_vec; -use opt_vec::OptVec; // Transitional reexports so qquote can find the paths it is looking for mod syntax { @@ -66,377 +60,3 @@ impl append_types for @ast::Path { } } } - -pub trait ext_ctxt_ast_builder { - fn ty_param(&self, id: ast::ident, bounds: @OptVec) - -> ast::TyParam; - fn arg(&self, name: ident, ty: @ast::Ty) -> ast::arg; - fn expr_block(&self, e: @ast::expr) -> ast::blk; - fn fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl; - fn item(&self, name: ident, span: span, node: ast::item_) -> @ast::item; - fn item_fn_poly(&self, - ame: ident, - inputs: ~[ast::arg], - output: @ast::Ty, - generics: Generics, - body: ast::blk) -> @ast::item; - fn item_fn(&self, - name: ident, - inputs: ~[ast::arg], - output: @ast::Ty, - body: ast::blk) -> @ast::item; - fn item_enum_poly(&self, - name: ident, - span: span, - enum_definition: ast::enum_def, - generics: Generics) -> @ast::item; - fn item_enum(&self, - name: ident, - span: span, - enum_definition: ast::enum_def) -> @ast::item; - fn item_struct_poly(&self, - name: ident, - span: span, - struct_def: ast::struct_def, - generics: Generics) -> @ast::item; - fn item_struct(&self, - name: ident, - span: span, - struct_def: ast::struct_def) -> @ast::item; - fn struct_expr(&self, - path: @ast::Path, - fields: ~[ast::field]) -> @ast::expr; - fn variant(&self, - name: ident, - span: span, - tys: ~[@ast::Ty]) -> ast::variant; - fn item_mod(&self, - name: ident, - span: span, - items: ~[@ast::item]) -> @ast::item; - fn ty_path_ast_builder(&self, path: @ast::Path) -> @ast::Ty; - fn item_ty_poly(&self, - name: ident, - span: span, - ty: @ast::Ty, - generics: Generics) -> @ast::item; - fn item_ty(&self, name: ident, span: span, ty: @ast::Ty) -> @ast::item; - fn ty_vars(&self, ty_params: &OptVec) -> ~[@ast::Ty]; - fn ty_vars_global(&self, ty_params: &OptVec) -> ~[@ast::Ty]; - fn ty_field_imm(&self, name: ident, ty: @ast::Ty) -> ast::ty_field; - fn field_imm(&self, name: ident, e: @ast::expr) -> ast::field; - fn block(&self, stmts: ~[@ast::stmt], e: @ast::expr) -> ast::blk; - fn stmt_let(&self, ident: ident, e: @ast::expr) -> @ast::stmt; - fn stmt_expr(&self, e: @ast::expr) -> @ast::stmt; - fn block_expr(&self, b: ast::blk) -> @ast::expr; - fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty; - fn ty_infer(&self) -> @ast::Ty; - fn ty_nil_ast_builder(&self) -> @ast::Ty; - fn strip_bounds(&self, bounds: &Generics) -> Generics; -} - -impl ext_ctxt_ast_builder for @ExtCtxt { - fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty { - self.ty_path_ast_builder(path_global(~[ - self.ident_of("core"), - self.ident_of("option"), - self.ident_of("Option") - ], dummy_sp()).add_ty(ty)) - } - - fn block_expr(&self, b: ast::blk) -> @ast::expr { - @expr { - id: self.next_id(), - callee_id: self.next_id(), - node: ast::expr_block(b), - span: dummy_sp(), - } - } - - fn stmt_expr(&self, e: @ast::expr) -> @ast::stmt { - @spanned { node: ast::stmt_expr(e, self.next_id()), - span: dummy_sp()} - } - - fn stmt_let(&self, ident: ident, e: @ast::expr) -> @ast::stmt { - let ext_cx = *self; - quote_stmt!( let $ident = $e; ) - } - - fn field_imm(&self, name: ident, e: @ast::expr) -> ast::field { - spanned { - node: ast::field_ { mutbl: ast::m_imm, ident: name, expr: e }, - span: dummy_sp(), - } - } - - fn ty_field_imm(&self, name: ident, ty: @ast::Ty) -> ast::ty_field { - spanned { - node: ast::ty_field_ { - ident: name, - mt: ast::mt { ty: ty, mutbl: ast::m_imm }, - }, - span: dummy_sp(), - } - } - - fn ty_infer(&self) -> @ast::Ty { - @ast::Ty { - id: self.next_id(), - node: ast::ty_infer, - span: dummy_sp(), - } - } - - fn ty_param(&self, id: ast::ident, bounds: @OptVec) - -> ast::TyParam - { - ast::TyParam { ident: id, id: self.next_id(), bounds: bounds } - } - - fn arg(&self, name: ident, ty: @ast::Ty) -> ast::arg { - ast::arg { - is_mutbl: false, - ty: ty, - pat: @ast::pat { - id: self.next_id(), - node: ast::pat_ident( - ast::bind_by_copy, - ast_util::ident_to_path(dummy_sp(), name), - None), - span: dummy_sp(), - }, - id: self.next_id(), - } - } - - fn block(&self, stmts: ~[@ast::stmt], e: @ast::expr) -> ast::blk { - let blk = ast::blk_ { - view_items: ~[], - stmts: stmts, - expr: Some(e), - id: self.next_id(), - rules: ast::default_blk, - }; - - spanned { node: blk, span: dummy_sp() } - } - - fn expr_block(&self, e: @ast::expr) -> ast::blk { - self.block(~[], e) - } - - fn fn_decl(&self, inputs: ~[ast::arg], - output: @ast::Ty) -> ast::fn_decl { - ast::fn_decl { - inputs: inputs, - output: output, - cf: ast::return_val, - } - } - - fn item(&self, name: ident, span: span, - node: ast::item_) -> @ast::item { - - // XXX: Would be nice if our generated code didn't violate - // Rust coding conventions - let non_camel_case_attribute = respan(dummy_sp(), ast::attribute_ { - style: ast::attr_outer, - value: @respan(dummy_sp(), - ast::meta_list(@~"allow", ~[ - @respan(dummy_sp(), - ast::meta_word( - @~"non_camel_case_types")) - ])), - is_sugared_doc: false - }); - - @ast::item { ident: name, - attrs: ~[non_camel_case_attribute], - id: self.next_id(), - node: node, - vis: ast::public, - span: span } - } - - fn item_fn_poly(&self, name: ident, - inputs: ~[ast::arg], - output: @ast::Ty, - generics: Generics, - body: ast::blk) -> @ast::item { - self.item(name, - dummy_sp(), - ast::item_fn(self.fn_decl(inputs, output), - ast::impure_fn, - AbiSet::Rust(), - generics, - body)) - } - - fn item_fn(&self, - name: ident, - inputs: ~[ast::arg], - output: @ast::Ty, - body: ast::blk - ) -> @ast::item { - self.item_fn_poly( - name, - inputs, - output, - ast_util::empty_generics(), - body - ) - } - - fn item_enum_poly(&self, name: ident, span: span, - enum_definition: ast::enum_def, - generics: Generics) -> @ast::item { - self.item(name, span, ast::item_enum(enum_definition, generics)) - } - - fn item_enum(&self, name: ident, span: span, - enum_definition: ast::enum_def) -> @ast::item { - self.item_enum_poly(name, span, enum_definition, - ast_util::empty_generics()) - } - - fn item_struct( - &self, name: ident, - span: span, - struct_def: ast::struct_def - ) -> @ast::item { - self.item_struct_poly( - name, - span, - struct_def, - ast_util::empty_generics() - ) - } - - fn item_struct_poly( - &self, - name: ident, - span: span, - struct_def: ast::struct_def, - generics: Generics - ) -> @ast::item { - self.item(name, span, ast::item_struct(@struct_def, generics)) - } - - fn struct_expr(&self, path: @ast::Path, - fields: ~[ast::field]) -> @ast::expr { - @ast::expr { - id: self.next_id(), - callee_id: self.next_id(), - node: ast::expr_struct(path, fields, None), - span: dummy_sp() - } - } - - fn variant(&self, name: ident, span: span, - tys: ~[@ast::Ty]) -> ast::variant { - let args = do tys.map |ty| { - ast::variant_arg { ty: *ty, id: self.next_id() } - }; - - spanned { - node: ast::variant_ { - name: name, - attrs: ~[], - kind: ast::tuple_variant_kind(args), - id: self.next_id(), - disr_expr: None, - vis: ast::public - }, - span: span, - } - } - - fn item_mod(&self, name: ident, span: span, - items: ~[@ast::item]) -> @ast::item { - - // XXX: Total hack: import `core::kinds::Owned` to work around a - // parser bug whereby `fn f` doesn't parse. - let vi = ast::view_item_use(~[ - @codemap::spanned { - node: ast::view_path_simple( - self.ident_of("Owned"), - path( - ~[ - self.ident_of("core"), - self.ident_of("kinds"), - self.ident_of("Owned") - ], - codemap::dummy_sp() - ), - self.next_id() - ), - span: codemap::dummy_sp() - } - ]); - let vi = @ast::view_item { - node: vi, - attrs: ~[], - vis: ast::private, - span: codemap::dummy_sp() - }; - - self.item( - name, - span, - ast::item_mod(ast::_mod { - view_items: ~[vi], - items: items, - }) - ) - } - - fn ty_path_ast_builder(&self, path: @ast::Path) -> @ast::Ty { - @ast::Ty { - id: self.next_id(), - node: ast::ty_path(path, self.next_id()), - span: path.span, - } - } - - fn ty_nil_ast_builder(&self) -> @ast::Ty { - @ast::Ty { - id: self.next_id(), - node: ast::ty_nil, - span: dummy_sp(), - } - } - - fn strip_bounds(&self, generics: &Generics) -> Generics { - let no_bounds = @opt_vec::Empty; - let new_params = do generics.ty_params.map |ty_param| { - ast::TyParam { bounds: no_bounds, ..copy *ty_param } - }; - Generics { - ty_params: new_params, - .. copy *generics - } - } - - fn item_ty_poly(&self, name: ident, span: span, ty: @ast::Ty, - generics: Generics) -> @ast::item { - self.item(name, span, ast::item_ty(ty, generics)) - } - - fn item_ty(&self, name: ident, span: span, ty: @ast::Ty) -> @ast::item { - self.item_ty_poly(name, span, ty, ast_util::empty_generics()) - } - - fn ty_vars(&self, ty_params: &OptVec) -> ~[@ast::Ty] { - opt_vec::take_vec( - ty_params.map(|p| self.ty_path_ast_builder( - path(~[p.ident], dummy_sp())))) - } - - fn ty_vars_global(&self, - ty_params: &OptVec) -> ~[@ast::Ty] { - opt_vec::take_vec( - ty_params.map(|p| self.ty_path_ast_builder( - path(~[p.ident], dummy_sp())))) - } -} diff --git a/src/libsyntax/ext/pipes/pipec.rs b/src/libsyntax/ext/pipes/pipec.rs index 83b3572c85f36..4362699378344 100644 --- a/src/libsyntax/ext/pipes/pipec.rs +++ b/src/libsyntax/ext/pipes/pipec.rs @@ -13,7 +13,8 @@ use ast; use codemap::{dummy_sp, spanned}; use ext::base::ExtCtxt; -use ext::pipes::ast_builder::{append_types, ext_ctxt_ast_builder, path}; +use ext::build::AstBuilder; +use ext::pipes::ast_builder::{append_types, path}; use ext::pipes::ast_builder::{path_global}; use ext::pipes::proto::*; use ext::quote::rt::*; @@ -54,7 +55,7 @@ impl gen_send for message { let arg_names = tys.mapi(|i, _ty| cx.ident_of(~"x_"+i.to_str())); let args_ast = vec::map_zip(arg_names, *tys, |n, t| cx.arg(*n, *t)); - let pipe_ty = cx.ty_path_ast_builder( + let pipe_ty = cx.ty_path( path(~[this.data_name()], span) .add_tys(cx.ty_vars_global(&this.generics.ty_params))); let args_ast = vec::append( @@ -111,7 +112,7 @@ impl gen_send for message { let body = cx.parse_expr(body); - let mut rty = cx.ty_path_ast_builder(path(~[next.data_name()], + let mut rty = cx.ty_path(path(~[next.data_name()], span) .add_tys(copy next_state.tys)); if try { @@ -124,7 +125,7 @@ impl gen_send for message { args_ast, rty, self.get_generics(), - cx.expr_block(body)) + cx.blk_expr(body)) } message(ref _id, span, ref tys, this, None) => { @@ -137,7 +138,7 @@ impl gen_send for message { let args_ast = vec::append( ~[cx.arg(cx.ident_of("pipe"), - cx.ty_path_ast_builder( + cx.ty_path( path(~[this.data_name()], span) .add_tys(cx.ty_vars_global( &this.generics.ty_params))))], @@ -179,13 +180,13 @@ impl gen_send for message { cx.ty_nil_ast_builder() }, self.get_generics(), - cx.expr_block(body)) + cx.blk_expr(body)) } } } fn to_ty(&mut self, cx: @ExtCtxt) -> @ast::Ty { - cx.ty_path_ast_builder(path(~[cx.ident_of(self.name())], self.span()) + cx.ty_path(path(~[cx.ident_of(self.name())], self.span()) .add_tys(cx.ty_vars_global(&self.get_generics().ty_params))) } } @@ -217,7 +218,7 @@ impl to_type_decls for state { }; vec::append_one(tys, - cx.ty_path_ast_builder( + cx.ty_path( path(~[cx.ident_of(dir), cx.ident_of(next_name)], span) .add_tys(copy next_state.tys))) @@ -264,12 +265,12 @@ impl to_type_decls for state { cx.item_ty_poly( self.data_name(), self.span, - cx.ty_path_ast_builder( + cx.ty_path( path_global(~[cx.ident_of("core"), cx.ident_of("pipes"), cx.ident_of(dir.to_str() + "Packet")], dummy_sp()) - .add_ty(cx.ty_path_ast_builder( + .add_ty(cx.ty_path( path(~[cx.ident_of("super"), self.data_name()], dummy_sp()) @@ -282,13 +283,13 @@ impl to_type_decls for state { cx.item_ty_poly( self.data_name(), self.span, - cx.ty_path_ast_builder( + cx.ty_path( path_global(~[cx.ident_of("core"), cx.ident_of("pipes"), cx.ident_of(dir.to_str() + "PacketBuffered")], dummy_sp()) - .add_tys(~[cx.ty_path_ast_builder( + .add_tys(~[cx.ty_path( path(~[cx.ident_of("super"), self.data_name()], dummy_sp()) @@ -341,7 +342,7 @@ impl gen_init for protocol { } fn gen_buffer_init(&self, ext_cx: @ExtCtxt) -> @ast::expr { - ext_cx.struct_expr(path(~[ext_cx.ident_of("__Buffer")], + ext_cx.expr_struct(path(~[ext_cx.ident_of("__Buffer")], dummy_sp()), self.states.map_to_vec(|s| { let fty = s.to_ty(ext_cx); @@ -360,15 +361,16 @@ impl gen_init for protocol { data: $buffer_fields, }); - let entangle_body = ext_cx.block_expr( - ext_cx.block( + let entangle_body = ext_cx.expr_blk( + ext_cx.blk( + dummy_sp(), self.states.map_to_vec( |s| ext_cx.parse_stmt( fmt!("data.%s.set_buffer(buffer)", s.name))), - ext_cx.parse_expr(fmt!( + Some(ext_cx.parse_expr(fmt!( "::core::ptr::to_mut_unsafe_ptr(&mut (data.%s))", - self.states[0].name)))); + self.states[0].name))))); quote_expr!({ let buffer = $buffer; @@ -389,7 +391,7 @@ impl gen_init for protocol { } } - cx.ty_path_ast_builder(path(~[cx.ident_of("super"), + cx.ty_path(path(~[cx.ident_of("super"), cx.ident_of("__Buffer")], copy self.span) .add_tys(cx.ty_vars_global(¶ms))) diff --git a/src/libsyntax/ext/pipes/proto.rs b/src/libsyntax/ext/pipes/proto.rs index 12a0a0a24d616..4471c5bb9b855 100644 --- a/src/libsyntax/ext/pipes/proto.rs +++ b/src/libsyntax/ext/pipes/proto.rs @@ -11,7 +11,8 @@ use ast; use codemap::span; use ext::base::ExtCtxt; -use ext::pipes::ast_builder::{append_types, ext_ctxt_ast_builder, path}; +use ext::build::AstBuilder; +use ext::pipes::ast_builder::{append_types, path}; #[deriving(Eq)] pub enum direction { send, recv } @@ -93,7 +94,7 @@ pub impl state_ { /// Returns the type that is used for the messages. fn to_ty(&self, cx: @ExtCtxt) -> @ast::Ty { - cx.ty_path_ast_builder + cx.ty_path (path(~[cx.ident_of(self.name)],self.span).add_tys( cx.ty_vars(&self.generics.ty_params))) } From 70222b7e86da5a813f9bcf60d884389fc8b04ef7 Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Tue, 21 May 2013 23:05:45 +0900 Subject: [PATCH 159/248] Remove unnecessary allocations flagged by lint from fuzzer --- src/libfuzzer/fuzzer.rc | 46 ++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/libfuzzer/fuzzer.rc b/src/libfuzzer/fuzzer.rc index 6662af3b5965a..468f50a0cc1ff 100644 --- a/src/libfuzzer/fuzzer.rc +++ b/src/libfuzzer/fuzzer.rc @@ -38,7 +38,7 @@ pub enum test_mode { tm_converge, tm_run, } pub struct Context { mode: test_mode } // + rng pub fn write_file(filename: &Path, content: &str) { - result::get(&io::file_writer(filename, ~[io::Create, io::Truncate])) + result::get(&io::file_writer(filename, [io::Create, io::Truncate])) .write_str(content); } @@ -47,12 +47,12 @@ pub fn contains(haystack: &str, needle: &str) -> bool { } pub fn find_rust_files(files: &mut ~[Path], path: &Path) { - if path.filetype() == Some(~".rs") && !contains(path.to_str(), ~"utf8") { + if path.filetype() == Some(~".rs") && !contains(path.to_str(), "utf8") { // ignoring "utf8" tests because something is broken files.push(path.clone()); } else if os::path_is_dir(path) - && !contains(path.to_str(), ~"compile-fail") - && !contains(path.to_str(), ~"build") { + && !contains(path.to_str(), "compile-fail") + && !contains(path.to_str(), "build") { for os::list_dir_path(path).each |p| { find_rust_files(&mut *files, *p); } @@ -406,34 +406,34 @@ pub fn check_whole_compiler(code: &str, pub fn removeIfExists(filename: &Path) { // So sketchy! - assert!(!contains(filename.to_str(), ~" ")); - run::program_output(~"bash", ~[~"-c", ~"rm " + filename.to_str()]); + assert!(!contains(filename.to_str(), " ")); + run::program_output("bash", [~"-c", ~"rm " + filename.to_str()]); } pub fn removeDirIfExists(filename: &Path) { // So sketchy! - assert!(!contains(filename.to_str(), ~" ")); - run::program_output(~"bash", ~[~"-c", ~"rm -r " + filename.to_str()]); + assert!(!contains(filename.to_str(), " ")); + run::program_output("bash", [~"-c", ~"rm -r " + filename.to_str()]); } pub fn check_running(exe_filename: &Path) -> happiness { let p = run::program_output( - ~"/Users/jruderman/scripts/timed_run_rust_program.py", - ~[exe_filename.to_str()]); + "/Users/jruderman/scripts/timed_run_rust_program.py", + [exe_filename.to_str()]); let comb = p.out + ~"\n" + p.err; if str::len(comb) > 1u { error!("comb comb comb: %?", comb); } - if contains(comb, ~"Assertion failed:") { + if contains(comb, "Assertion failed:") { failed(~"C++ assertion failure") - } else if contains(comb, ~"leaked memory in rust main loop") { + } else if contains(comb, "leaked memory in rust main loop") { // might also use exit code 134 //failed("Leaked") known_bug(~"https://github.com/mozilla/rust/issues/910") - } else if contains(comb, ~"src/rt/") { + } else if contains(comb, "src/rt/") { failed(~"Mentioned src/rt/") - } else if contains(comb, ~"malloc") { + } else if contains(comb, "malloc") { failed(~"Mentioned malloc") } else { match p.status { @@ -457,26 +457,26 @@ pub fn check_running(exe_filename: &Path) -> happiness { pub fn check_compiling(filename: &Path) -> happiness { let p = run::program_output( - ~"/Users/jruderman/code/rust/build/x86_64-apple-darwin/\ + "/Users/jruderman/code/rust/build/x86_64-apple-darwin/\ stage1/bin/rustc", - ~[filename.to_str()]); + [filename.to_str()]); //error!("Status: %d", p.status); if p.status == 0 { passed } else if p.err != ~"" { - if contains(p.err, ~"error:") { + if contains(p.err, "error:") { cleanly_rejected(~"rejected with span_error") } else { error!("Stderr: %?", p.err); failed(~"Unfamiliar error message") } - } else if contains(p.out, ~"Assertion") && contains(p.out, ~"failed") { + } else if contains(p.out, "Assertion") && contains(p.out, "failed") { error!("Stdout: %?", p.out); failed(~"Looks like an llvm assertion failure") - } else if contains(p.out, ~"internal compiler error unimplemented") { + } else if contains(p.out, "internal compiler error unimplemented") { known_bug(~"Something unimplemented") - } else if contains(p.out, ~"internal compiler error") { + } else if contains(p.out, "internal compiler error") { error!("Stdout: %?", p.out); failed(~"internal compiler error") @@ -603,8 +603,8 @@ pub fn check_roundtrip_convergence(code: @~str, maxIters: uint) { error!("Did not converge after %u iterations!", i); write_file(&Path("round-trip-a.rs"), *oldv); write_file(&Path("round-trip-b.rs"), *newv); - run::run_program(~"diff", - ~[~"-w", ~"-u", ~"round-trip-a.rs", + run::run_program("diff", + [~"-w", ~"-u", ~"round-trip-a.rs", ~"round-trip-b.rs"]); fail!("Mismatch"); } @@ -635,7 +635,7 @@ pub fn check_variants(files: &[Path], cx: Context) { } let s = @result::get(&io::read_whole_file_str(file)); - if contains(*s, ~"#") { + if contains(*s, "#") { loop; // Macros are confusing } if cx.mode == tm_converge && content_might_not_converge(*s) { From 6e5051553050974eb9362e1465cc2d40e2c9a610 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sat, 18 May 2013 00:19:28 +1000 Subject: [PATCH 160/248] syntax/ext: migrate build.rs functions to AstBuilder methods. --- src/libsyntax/ext/build.rs | 1330 ++++++++++++-------- src/libsyntax/ext/bytes.rs | 12 +- src/libsyntax/ext/deriving/clone.rs | 9 +- src/libsyntax/ext/deriving/cmp/eq.rs | 6 +- src/libsyntax/ext/deriving/cmp/ord.rs | 24 +- src/libsyntax/ext/deriving/cmp/totaleq.rs | 4 +- src/libsyntax/ext/deriving/cmp/totalord.rs | 6 +- src/libsyntax/ext/deriving/decodable.rs | 168 ++- src/libsyntax/ext/deriving/encodable.rs | 131 +- src/libsyntax/ext/deriving/generic.rs | 34 +- src/libsyntax/ext/deriving/iter_bytes.rs | 8 +- src/libsyntax/ext/deriving/mod.rs | 52 +- src/libsyntax/ext/deriving/rand.rs | 40 +- src/libsyntax/ext/deriving/to_str.rs | 6 +- src/libsyntax/ext/deriving/ty.rs | 36 +- src/libsyntax/ext/env.rs | 6 +- src/libsyntax/ext/fmt.rs | 41 +- src/libsyntax/ext/quote.rs | 120 +- src/libsyntax/ext/source_util.rs | 18 +- 19 files changed, 1126 insertions(+), 925 deletions(-) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index a2d88c1f23a88..eb48ed583750d 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -25,525 +25,6 @@ pub struct Field { ex: @ast::expr } -pub fn mk_expr(cx: @ExtCtxt, - sp: codemap::span, - expr: ast::expr_) - -> @ast::expr { - @ast::expr { - id: cx.next_id(), - callee_id: cx.next_id(), - node: expr, - span: sp, - } -} - -pub fn mk_lit(cx: @ExtCtxt, sp: span, lit: ast::lit_) -> @ast::expr { - let sp_lit = @codemap::spanned { node: lit, span: sp }; - mk_expr(cx, sp, ast::expr_lit(sp_lit)) -} -pub fn mk_int(cx: @ExtCtxt, sp: span, i: int) -> @ast::expr { - let lit = ast::lit_int(i as i64, ast::ty_i); - return mk_lit(cx, sp, lit); -} -pub fn mk_uint(cx: @ExtCtxt, sp: span, u: uint) -> @ast::expr { - let lit = ast::lit_uint(u as u64, ast::ty_u); - return mk_lit(cx, sp, lit); -} -pub fn mk_u8(cx: @ExtCtxt, sp: span, u: u8) -> @ast::expr { - let lit = ast::lit_uint(u as u64, ast::ty_u8); - return mk_lit(cx, sp, lit); -} -pub fn mk_binary(cx: @ExtCtxt, sp: span, op: ast::binop, - lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr { - cx.next_id(); // see ast_util::op_expr_callee_id - mk_expr(cx, sp, ast::expr_binary(op, lhs, rhs)) -} - -pub fn mk_deref(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { - mk_unary(cx, sp, ast::deref, e) -} -pub fn mk_unary(cx: @ExtCtxt, sp: span, op: ast::unop, e: @ast::expr) - -> @ast::expr { - cx.next_id(); // see ast_util::op_expr_callee_id - mk_expr(cx, sp, ast::expr_unary(op, e)) -} -pub fn mk_raw_path(sp: span, idents: ~[ast::ident]) -> @ast::Path { - mk_raw_path_(sp, idents, None, ~[]) -} -pub fn mk_raw_path_(sp: span, - idents: ~[ast::ident], - rp: Option<@ast::Lifetime>, - types: ~[@ast::Ty]) - -> @ast::Path { - @ast::Path { span: sp, - global: false, - idents: idents, - rp: rp, - types: types } -} -pub fn mk_raw_path_global(sp: span, idents: ~[ast::ident]) -> @ast::Path { - mk_raw_path_global_(sp, idents, None, ~[]) -} -pub fn mk_raw_path_global_(sp: span, - idents: ~[ast::ident], - rp: Option<@ast::Lifetime>, - types: ~[@ast::Ty]) -> @ast::Path { - @ast::Path { span: sp, - global: true, - idents: idents, - rp: rp, - types: types } -} -pub fn mk_path_raw(cx: @ExtCtxt, sp: span, path: @ast::Path)-> @ast::expr { - mk_expr(cx, sp, ast::expr_path(path)) -} -pub fn mk_path(cx: @ExtCtxt, sp: span, idents: ~[ast::ident]) - -> @ast::expr { - mk_path_raw(cx, sp, mk_raw_path(sp, idents)) -} -pub fn mk_path_global(cx: @ExtCtxt, sp: span, idents: ~[ast::ident]) - -> @ast::expr { - mk_path_raw(cx, sp, mk_raw_path_global(sp, idents)) -} -pub fn mk_access_(cx: @ExtCtxt, sp: span, p: @ast::expr, m: ast::ident) - -> @ast::expr { - mk_expr(cx, sp, ast::expr_field(p, m, ~[])) -} -pub fn mk_access(cx: @ExtCtxt, sp: span, p: ~[ast::ident], m: ast::ident) - -> @ast::expr { - let pathexpr = mk_path(cx, sp, p); - return mk_access_(cx, sp, pathexpr, m); -} -pub fn mk_addr_of(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { - return mk_expr(cx, sp, ast::expr_addr_of(ast::m_imm, e)); -} -pub fn mk_mut_addr_of(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { - return mk_expr(cx, sp, ast::expr_addr_of(ast::m_mutbl, e)); -} -pub fn mk_method_call(cx: @ExtCtxt, - sp: span, - rcvr_expr: @ast::expr, - method_ident: ast::ident, - args: ~[@ast::expr]) -> @ast::expr { - mk_expr(cx, sp, ast::expr_method_call(rcvr_expr, method_ident, ~[], args, ast::NoSugar)) -} -pub fn mk_call_(cx: @ExtCtxt, sp: span, fn_expr: @ast::expr, - args: ~[@ast::expr]) -> @ast::expr { - mk_expr(cx, sp, ast::expr_call(fn_expr, args, ast::NoSugar)) -} -pub fn mk_call(cx: @ExtCtxt, sp: span, fn_path: ~[ast::ident], - args: ~[@ast::expr]) -> @ast::expr { - let pathexpr = mk_path(cx, sp, fn_path); - return mk_call_(cx, sp, pathexpr, args); -} -pub fn mk_call_global(cx: @ExtCtxt, sp: span, fn_path: ~[ast::ident], - args: ~[@ast::expr]) -> @ast::expr { - let pathexpr = mk_path_global(cx, sp, fn_path); - return mk_call_(cx, sp, pathexpr, args); -} -// e = expr, t = type -pub fn mk_base_vec_e(cx: @ExtCtxt, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr { - let vecexpr = ast::expr_vec(exprs, ast::m_imm); - mk_expr(cx, sp, vecexpr) -} -pub fn mk_vstore_e(cx: @ExtCtxt, sp: span, expr: @ast::expr, - vst: ast::expr_vstore) -> - @ast::expr { - mk_expr(cx, sp, ast::expr_vstore(expr, vst)) -} -pub fn mk_uniq_vec_e(cx: @ExtCtxt, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr { - mk_vstore_e(cx, sp, mk_base_vec_e(cx, sp, exprs), ast::expr_vstore_uniq) -} -pub fn mk_slice_vec_e(cx: @ExtCtxt, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr { - mk_vstore_e(cx, sp, mk_base_vec_e(cx, sp, exprs), - ast::expr_vstore_slice) -} -pub fn mk_base_str(cx: @ExtCtxt, sp: span, s: ~str) -> @ast::expr { - let lit = ast::lit_str(@s); - return mk_lit(cx, sp, lit); -} -pub fn mk_uniq_str(cx: @ExtCtxt, sp: span, s: ~str) -> @ast::expr { - mk_vstore_e(cx, sp, mk_base_str(cx, sp, s), ast::expr_vstore_uniq) -} -pub fn mk_field(sp: span, f: &Field) -> ast::field { - codemap::spanned { - node: ast::field_ { mutbl: ast::m_imm, ident: f.ident, expr: f.ex }, - span: sp, - } -} -pub fn mk_fields(sp: span, fields: ~[Field]) -> ~[ast::field] { - fields.map(|f| mk_field(sp, f)) -} -pub fn mk_struct_e(cx: @ExtCtxt, - sp: span, - ctor_path: ~[ast::ident], - fields: ~[Field]) - -> @ast::expr { - mk_expr(cx, sp, - ast::expr_struct(mk_raw_path(sp, ctor_path), - mk_fields(sp, fields), - option::None::<@ast::expr>)) -} -pub fn mk_global_struct_e(cx: @ExtCtxt, - sp: span, - ctor_path: ~[ast::ident], - fields: ~[Field]) - -> @ast::expr { - mk_expr(cx, sp, - ast::expr_struct(mk_raw_path_global(sp, ctor_path), - mk_fields(sp, fields), - option::None::<@ast::expr>)) -} -pub fn mk_glob_use(cx: @ExtCtxt, - sp: span, - vis: ast::visibility, - path: ~[ast::ident]) -> @ast::view_item { - let glob = @codemap::spanned { - node: ast::view_path_glob(mk_raw_path(sp, path), cx.next_id()), - span: sp, - }; - @ast::view_item { node: ast::view_item_use(~[glob]), - attrs: ~[], - vis: vis, - span: sp } -} -pub fn mk_local(cx: @ExtCtxt, sp: span, mutbl: bool, - ident: ast::ident, ex: @ast::expr) -> @ast::stmt { - - let pat = @ast::pat { - id: cx.next_id(), - node: ast::pat_ident( - ast::bind_by_copy, - mk_raw_path(sp, ~[ident]), - None), - span: sp, - }; - let ty = @ast::Ty { id: cx.next_id(), node: ast::ty_infer, span: sp }; - let local = @codemap::spanned { - node: ast::local_ { - is_mutbl: mutbl, - ty: ty, - pat: pat, - init: Some(ex), - id: cx.next_id(), - }, - span: sp, - }; - let decl = codemap::spanned {node: ast::decl_local(~[local]), span: sp}; - @codemap::spanned { node: ast::stmt_decl(@decl, cx.next_id()), span: sp } -} -pub fn mk_block(cx: @ExtCtxt, span: span, - view_items: ~[@ast::view_item], - stmts: ~[@ast::stmt], - expr: Option<@ast::expr>) -> @ast::expr { - let blk = codemap::spanned { - node: ast::blk_ { - view_items: view_items, - stmts: stmts, - expr: expr, - id: cx.next_id(), - rules: ast::default_blk, - }, - span: span, - }; - mk_expr(cx, span, ast::expr_block(blk)) -} -pub fn mk_block_(cx: @ExtCtxt, - span: span, - stmts: ~[@ast::stmt]) - -> ast::blk { - codemap::spanned { - node: ast::blk_ { - view_items: ~[], - stmts: stmts, - expr: None, - id: cx.next_id(), - rules: ast::default_blk, - }, - span: span, - } -} -pub fn mk_simple_block(cx: @ExtCtxt, - span: span, - expr: @ast::expr) - -> ast::blk { - codemap::spanned { - node: ast::blk_ { - view_items: ~[], - stmts: ~[], - expr: Some(expr), - id: cx.next_id(), - rules: ast::default_blk, - }, - span: span, - } -} -pub fn mk_lambda_(cx: @ExtCtxt, - span: span, - fn_decl: ast::fn_decl, - blk: ast::blk) - -> @ast::expr { - mk_expr(cx, span, ast::expr_fn_block(fn_decl, blk)) -} -pub fn mk_lambda(cx: @ExtCtxt, - span: span, - fn_decl: ast::fn_decl, - expr: @ast::expr) - -> @ast::expr { - let blk = mk_simple_block(cx, span, expr); - mk_lambda_(cx, span, fn_decl, blk) -} -pub fn mk_lambda_stmts(cx: @ExtCtxt, - span: span, - fn_decl: ast::fn_decl, - stmts: ~[@ast::stmt]) - -> @ast::expr { - let blk = mk_block(cx, span, ~[], stmts, None); - mk_lambda(cx, span, fn_decl, blk) -} -pub fn mk_lambda_no_args(cx: @ExtCtxt, - span: span, - expr: @ast::expr) - -> @ast::expr { - let fn_decl = mk_fn_decl(~[], mk_ty_infer(cx, span)); - mk_lambda(cx, span, fn_decl, expr) -} -pub fn mk_copy(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { - mk_expr(cx, sp, ast::expr_copy(e)) -} -pub fn mk_managed(cx: @ExtCtxt, sp: span, e: @ast::expr) -> @ast::expr { - mk_expr(cx, sp, ast::expr_unary(ast::box(ast::m_imm), e)) -} -pub fn mk_pat(cx: @ExtCtxt, span: span, pat: ast::pat_) -> @ast::pat { - @ast::pat { id: cx.next_id(), node: pat, span: span } -} -pub fn mk_pat_wild(cx: @ExtCtxt, span: span) -> @ast::pat { - mk_pat(cx, span, ast::pat_wild) -} -pub fn mk_pat_lit(cx: @ExtCtxt, - span: span, - expr: @ast::expr) -> @ast::pat { - mk_pat(cx, span, ast::pat_lit(expr)) -} -pub fn mk_pat_ident(cx: @ExtCtxt, - span: span, - ident: ast::ident) -> @ast::pat { - mk_pat_ident_with_binding_mode(cx, span, ident, ast::bind_by_copy) -} - -pub fn mk_pat_ident_with_binding_mode(cx: @ExtCtxt, - span: span, - ident: ast::ident, - bm: ast::binding_mode) -> @ast::pat { - let path = mk_raw_path(span, ~[ ident ]); - let pat = ast::pat_ident(bm, path, None); - mk_pat(cx, span, pat) -} -pub fn mk_pat_enum(cx: @ExtCtxt, - span: span, - path: @ast::Path, - subpats: ~[@ast::pat]) - -> @ast::pat { - let pat = ast::pat_enum(path, Some(subpats)); - mk_pat(cx, span, pat) -} -pub fn mk_pat_struct(cx: @ExtCtxt, - span: span, - path: @ast::Path, - field_pats: ~[ast::field_pat]) - -> @ast::pat { - let pat = ast::pat_struct(path, field_pats, false); - mk_pat(cx, span, pat) -} -pub fn mk_bool(cx: @ExtCtxt, span: span, value: bool) -> @ast::expr { - let lit_expr = ast::expr_lit(@codemap::spanned { - node: ast::lit_bool(value), - span: span }); - build::mk_expr(cx, span, lit_expr) -} -pub fn mk_stmt(cx: @ExtCtxt, span: span, expr: @ast::expr) -> @ast::stmt { - let stmt_ = ast::stmt_semi(expr, cx.next_id()); - @codemap::spanned { node: stmt_, span: span } -} - -pub fn mk_ty_mt(ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt { - ast::mt { - ty: ty, - mutbl: mutbl - } -} - -pub fn mk_ty(cx: @ExtCtxt, - span: span, - ty: ast::ty_) -> @ast::Ty { - @ast::Ty { - id: cx.next_id(), - span: span, - node: ty - } -} - -pub fn mk_ty_path(cx: @ExtCtxt, - span: span, - idents: ~[ ast::ident ]) - -> @ast::Ty { - let ty = build::mk_raw_path(span, idents); - mk_ty_path_path(cx, span, ty) -} - -pub fn mk_ty_path_global(cx: @ExtCtxt, - span: span, - idents: ~[ ast::ident ]) - -> @ast::Ty { - let ty = build::mk_raw_path_global(span, idents); - mk_ty_path_path(cx, span, ty) -} - -pub fn mk_ty_path_path(cx: @ExtCtxt, - span: span, - path: @ast::Path) - -> @ast::Ty { - let ty = ast::ty_path(path, cx.next_id()); - mk_ty(cx, span, ty) -} - -pub fn mk_ty_rptr(cx: @ExtCtxt, - span: span, - ty: @ast::Ty, - lifetime: Option<@ast::Lifetime>, - mutbl: ast::mutability) - -> @ast::Ty { - mk_ty(cx, span, - ast::ty_rptr(lifetime, mk_ty_mt(ty, mutbl))) -} -pub fn mk_ty_uniq(cx: @ExtCtxt, span: span, ty: @ast::Ty) -> @ast::Ty { - mk_ty(cx, span, ast::ty_uniq(mk_ty_mt(ty, ast::m_imm))) -} -pub fn mk_ty_box(cx: @ExtCtxt, span: span, - ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty { - mk_ty(cx, span, ast::ty_box(mk_ty_mt(ty, mutbl))) -} - - - -pub fn mk_ty_infer(cx: @ExtCtxt, span: span) -> @ast::Ty { - mk_ty(cx, span, ast::ty_infer) -} -pub fn mk_trait_ref_global(cx: @ExtCtxt, - span: span, - idents: ~[ ast::ident ]) - -> @ast::trait_ref -{ - mk_trait_ref_(cx, build::mk_raw_path_global(span, idents)) -} -pub fn mk_trait_ref_(cx: @ExtCtxt, path: @ast::Path) -> @ast::trait_ref { - @ast::trait_ref { - path: path, - ref_id: cx.next_id() - } -} -pub fn mk_simple_ty_path(cx: @ExtCtxt, - span: span, - ident: ast::ident) - -> @ast::Ty { - mk_ty_path(cx, span, ~[ ident ]) -} -pub fn mk_arg(cx: @ExtCtxt, - span: span, - ident: ast::ident, - ty: @ast::Ty) - -> ast::arg { - let arg_pat = mk_pat_ident(cx, span, ident); - ast::arg { - is_mutbl: false, - ty: ty, - pat: arg_pat, - id: cx.next_id() - } -} -pub fn mk_fn_decl(inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl { - ast::fn_decl { inputs: inputs, output: output, cf: ast::return_val } -} -pub fn mk_trait_ty_param_bound_global(cx: @ExtCtxt, - span: span, - idents: ~[ast::ident]) - -> ast::TyParamBound { - ast::TraitTyParamBound(mk_trait_ref_global(cx, span, idents)) -} -pub fn mk_trait_ty_param_bound_(cx: @ExtCtxt, - path: @ast::Path) -> ast::TyParamBound { - ast::TraitTyParamBound(mk_trait_ref_(cx, path)) -} -pub fn mk_ty_param(cx: @ExtCtxt, - ident: ast::ident, - bounds: @OptVec) - -> ast::TyParam { - ast::TyParam { ident: ident, id: cx.next_id(), bounds: bounds } -} -pub fn mk_lifetime(cx: @ExtCtxt, - span: span, - ident: ast::ident) - -> ast::Lifetime { - ast::Lifetime { id: cx.next_id(), span: span, ident: ident } -} -pub fn mk_arm(cx: @ExtCtxt, - span: span, - pats: ~[@ast::pat], - expr: @ast::expr) - -> ast::arm { - ast::arm { - pats: pats, - guard: None, - body: mk_simple_block(cx, span, expr) - } -} -pub fn mk_unreachable(cx: @ExtCtxt, span: span) -> @ast::expr { - let loc = cx.codemap().lookup_char_pos(span.lo); - mk_call_global( - cx, - span, - ~[ - cx.ident_of("core"), - cx.ident_of("sys"), - cx.ident_of("FailWithCause"), - cx.ident_of("fail_with"), - ], - ~[ - mk_base_str(cx, span, ~"internal error: entered unreachable code"), - mk_base_str(cx, span, copy loc.file.name), - mk_uint(cx, span, loc.line), - ] - ) -} -pub fn mk_unreachable_arm(cx: @ExtCtxt, span: span) -> ast::arm { - mk_arm(cx, span, ~[mk_pat_wild(cx, span)], mk_unreachable(cx, span)) -} - -pub fn make_self(cx: @ExtCtxt, span: span) -> @ast::expr { - build::mk_expr(cx, span, ast::expr_self) -} - -// -// Duplication functions -// -// These functions just duplicate AST nodes. -// - -pub fn duplicate_expr(cx: @ExtCtxt, expr: @ast::expr) -> @ast::expr { - let folder = fold::default_ast_fold(); - let folder = @fold::AstFoldFns { - new_id: |_| cx.next_id(), - ..*folder - }; - let folder = fold::make_fold(folder); - folder.fold_expr(expr) -} - - - // Transitional reexports so qquote can find the paths it is looking for mod syntax { pub use ext; @@ -555,12 +36,12 @@ pub trait AstBuilder { fn path(&self, span: span, strs: ~[ast::ident]) -> @ast::Path; fn path_global(&self, span: span, strs: ~[ast::ident]) -> @ast::Path; fn path_tps(&self, span: span, strs: ~[ast::ident], tps: ~[@ast::Ty]) - -> @ast::Path; + -> @ast::Path; fn path_tps_global(&self, span: span, strs: ~[ast::ident], tps: ~[@ast::Ty]) - -> @ast::Path; + -> @ast::Path; // types fn ty_path(&self, @ast::Path) -> @ast::Ty; @@ -595,15 +76,15 @@ pub trait AstBuilder { fn expr_var(&self, span: span, var: &str) -> @ast::expr; fn expr_self(&self, span: span) -> @ast::expr; fn expr_field(&self, span: span, expr: @ast::expr, ident: ast::ident) - -> @ast::expr; + -> @ast::expr; fn expr_call(&self, span: span, expr: @ast::expr, args: ~[@ast::expr]) - -> @ast::expr; + -> @ast::expr; fn expr_method_call(&self, span: span, expr: @ast::expr, ident: ast::ident, args: ~[@ast::expr]) - -> @ast::expr; + -> @ast::expr; fn expr_blk(&self, b: ast::blk) -> @ast::expr; fn field_imm(&self, name: ident, e: @ast::expr) -> ast::field; fn expr_struct(&self, @@ -613,13 +94,13 @@ pub trait AstBuilder { fn lambda1(&self, blk: ast::blk, ident: ast::ident) -> @ast::expr; fn lambda_expr_0(&self, expr: @ast::expr) -> @ast::expr; fn lambda_expr_1(&self, expr: @ast::expr, ident: ast::ident) - -> @ast::expr; + -> @ast::expr; fn lambda_stmts_0(&self, span: span, stmts: ~[@ast::stmt]) -> @ast::expr; fn lambda_stmts_1(&self, span: span, stmts: ~[@ast::stmt], ident: ast::ident) - -> @ast::expr; + -> @ast::expr; // items fn item(&self, name: ident, span: span, node: ast::item_) -> @ast::item; @@ -675,6 +156,226 @@ pub trait AstBuilder { generics: Generics) -> @ast::item; fn item_ty(&self, name: ident, span: span, ty: @ast::Ty) -> @ast::item; + + + + fn mk_expr(&self, + sp: codemap::span, + expr: ast::expr_) + -> @ast::expr; + + fn mk_lit(&self, sp: span, lit: ast::lit_) -> @ast::expr; + fn mk_int(&self, sp: span, i: int) -> @ast::expr; + fn mk_uint(&self, sp: span, u: uint) -> @ast::expr; + fn mk_u8(&self, sp: span, u: u8) -> @ast::expr; + fn mk_binary(&self, sp: span, op: ast::binop, + lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr; + + fn mk_deref(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn mk_unary(&self, sp: span, op: ast::unop, e: @ast::expr) + -> @ast::expr; + // XXX: unused self + fn mk_raw_path(&self, sp: span, idents: ~[ast::ident]) -> @ast::Path; + // XXX: unused self + fn mk_raw_path_(&self, sp: span, + idents: ~[ast::ident], + rp: Option<@ast::Lifetime>, + types: ~[@ast::Ty]) + -> @ast::Path; + // XXX: unused self + fn mk_raw_path_global(&self, sp: span,idents: ~[ast::ident]) -> @ast::Path; + // XXX: unused self + fn mk_raw_path_global_(&self, sp: span, + idents: ~[ast::ident], + rp: Option<@ast::Lifetime>, + types: ~[@ast::Ty]) -> @ast::Path; + fn mk_path_raw(&self, sp: span, path: @ast::Path)-> @ast::expr; + fn mk_path(&self, sp: span, idents: ~[ast::ident]) + -> @ast::expr; + fn mk_path_global(&self, sp: span, idents: ~[ast::ident]) + -> @ast::expr; + fn mk_access_(&self, sp: span, p: @ast::expr, m: ast::ident) + -> @ast::expr; + fn mk_access(&self, sp: span, p: ~[ast::ident], m: ast::ident) + -> @ast::expr; + fn mk_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn mk_mut_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn mk_method_call(&self, + sp: span, + rcvr_expr: @ast::expr, + method_ident: ast::ident, + args: ~[@ast::expr]) -> @ast::expr; + fn mk_call_(&self, sp: span, fn_expr: @ast::expr, + args: ~[@ast::expr]) -> @ast::expr; + fn mk_call(&self, sp: span, fn_path: ~[ast::ident], + args: ~[@ast::expr]) -> @ast::expr; + fn mk_call_global(&self, sp: span, fn_path: ~[ast::ident], + args: ~[@ast::expr]) -> @ast::expr; + // e = expr, t = type + fn mk_base_vec_e(&self, sp: span, exprs: ~[@ast::expr]) + -> @ast::expr; + fn mk_vstore_e(&self, sp: span, expr: @ast::expr, + vst: ast::expr_vstore) -> + @ast::expr; + fn mk_uniq_vec_e(&self, sp: span, exprs: ~[@ast::expr]) + -> @ast::expr; + fn mk_slice_vec_e(&self, sp: span, exprs: ~[@ast::expr]) + -> @ast::expr; + fn mk_base_str(&self, sp: span, s: ~str) -> @ast::expr; + fn mk_uniq_str(&self, sp: span, s: ~str) -> @ast::expr; + // XXX: unused self + fn mk_field(&self, sp: span, f: &Field) -> ast::field; + // XXX: unused self + fn mk_fields(&self, sp: span, fields: ~[Field]) -> ~[ast::field]; + fn mk_struct_e(&self, + sp: span, + ctor_path: ~[ast::ident], + fields: ~[Field]) + -> @ast::expr; + fn mk_global_struct_e(&self, + sp: span, + ctor_path: ~[ast::ident], + fields: ~[Field]) + -> @ast::expr; + fn mk_glob_use(&self, + sp: span, + vis: ast::visibility, + path: ~[ast::ident]) -> @ast::view_item; + fn mk_local(&self, sp: span, mutbl: bool, + ident: ast::ident, ex: @ast::expr) -> @ast::stmt; + fn mk_block(&self, span: span, + view_items: ~[@ast::view_item], + stmts: ~[@ast::stmt], + expr: Option<@ast::expr>) -> @ast::expr; + fn mk_block_(&self, + span: span, + stmts: ~[@ast::stmt]) + -> ast::blk; + fn mk_simple_block(&self, + span: span, + expr: @ast::expr) + -> ast::blk; + fn mk_lambda_(&self, + span: span, + fn_decl: ast::fn_decl, + blk: ast::blk) + -> @ast::expr; + fn mk_lambda(&self, + span: span, + fn_decl: ast::fn_decl, + expr: @ast::expr) + -> @ast::expr; + fn mk_lambda_stmts(&self, + span: span, + fn_decl: ast::fn_decl, + stmts: ~[@ast::stmt]) + -> @ast::expr ; + fn mk_lambda_no_args(&self, + span: span, + expr: @ast::expr) + -> @ast::expr; + fn mk_copy(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn mk_managed(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn mk_pat(&self, span: span, pat: ast::pat_) -> @ast::pat; + fn mk_pat_wild(&self, span: span) -> @ast::pat; + fn mk_pat_lit(&self, + span: span, + expr: @ast::expr) -> @ast::pat; + fn mk_pat_ident(&self, + span: span, + ident: ast::ident) -> @ast::pat; + + fn mk_pat_ident_with_binding_mode(&self, + span: span, + ident: ast::ident, + bm: ast::binding_mode) -> @ast::pat; + fn mk_pat_enum(&self, + span: span, + path: @ast::Path, + subpats: ~[@ast::pat]) + -> @ast::pat; + fn mk_pat_struct(&self, + span: span, + path: @ast::Path, + field_pats: ~[ast::field_pat]) + -> @ast::pat; + fn mk_bool(&self, span: span, value: bool) -> @ast::expr; + fn mk_stmt(&self, span: span, expr: @ast::expr) -> @ast::stmt; + + // XXX: unused self + fn mk_ty_mt(&self, ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt; + + fn mk_ty(&self, + span: span, + ty: ast::ty_) -> @ast::Ty; + + fn mk_ty_path(&self, + span: span, + idents: ~[ ast::ident ]) + -> @ast::Ty; + + fn mk_ty_path_global(&self, + span: span, + idents: ~[ ast::ident ]) + -> @ast::Ty; + + fn mk_ty_path_path(&self, + span: span, + path: @ast::Path) + -> @ast::Ty; + + fn mk_ty_rptr(&self, + span: span, + ty: @ast::Ty, + lifetime: Option<@ast::Lifetime>, + mutbl: ast::mutability) + -> @ast::Ty; + fn mk_ty_uniq(&self, span: span, ty: @ast::Ty) -> @ast::Ty; + fn mk_ty_box(&self, span: span, + ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty; + + + + fn mk_ty_infer(&self, span: span) -> @ast::Ty; + fn mk_trait_ref_global(&self, + span: span, + idents: ~[ ast::ident ]) + -> @ast::trait_ref; + fn mk_trait_ref_(&self, path: @ast::Path) -> @ast::trait_ref; + fn mk_simple_ty_path(&self, + span: span, + ident: ast::ident) + -> @ast::Ty; + fn mk_arg(&self, + span: span, + ident: ast::ident, + ty: @ast::Ty) + -> ast::arg; + // XXX unused self + fn mk_fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl; + fn mk_trait_ty_param_bound_global(&self, + span: span, + idents: ~[ast::ident]) + -> ast::TyParamBound; + fn mk_trait_ty_param_bound_(&self, + path: @ast::Path) -> ast::TyParamBound; + fn mk_ty_param(&self, + ident: ast::ident, + bounds: @OptVec) + -> ast::TyParam; + fn mk_lifetime(&self, + span: span, + ident: ast::ident) + -> ast::Lifetime; + fn mk_arm(&self, + span: span, + pats: ~[@ast::pat], + expr: @ast::expr) + -> ast::arm; + fn mk_unreachable(&self, span: span) -> @ast::expr; + fn mk_unreachable_arm(&self, span: span) -> ast::arm; + + fn make_self(&self, span: span) -> @ast::expr; } impl AstBuilder for @ExtCtxt { @@ -729,8 +430,8 @@ impl AstBuilder for @ExtCtxt { } fn ty_path(&self, path: @ast::Path) -> @ast::Ty { - build::mk_ty(*self, path.span, - ast::ty_path(path, self.next_id())) + self.mk_ty(path.span, + ast::ty_path(path, self.next_id())) } fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty { @@ -779,14 +480,14 @@ impl AstBuilder for @ExtCtxt { fn ty_vars(&self, ty_params: &OptVec) -> ~[@ast::Ty] { opt_vec::take_vec( ty_params.map(|p| self.ty_path( - mk_raw_path(dummy_sp(), ~[p.ident])))) + self.mk_raw_path(dummy_sp(), ~[p.ident])))) } fn ty_vars_global(&self, ty_params: &OptVec) -> ~[@ast::Ty] { opt_vec::take_vec( ty_params.map(|p| self.ty_path( - mk_raw_path(dummy_sp(), ~[p.ident])))) + self.mk_raw_path(dummy_sp(), ~[p.ident])))) } fn strip_bounds(&self, generics: &Generics) -> Generics { @@ -803,7 +504,7 @@ impl AstBuilder for @ExtCtxt { fn stmt_expr(&self, expr: @ast::expr) -> @ast::stmt { @codemap::spanned { node: ast::stmt_semi(expr, self.next_id()), - span: expr.span } + span: expr.span } } fn stmt_let(&self, ident: ident, e: @ast::expr) -> @ast::stmt { @@ -819,7 +520,7 @@ impl AstBuilder for @ExtCtxt { span, ast::expr_lit( @codemap::spanned { node: ast::lit_str(s), - span: span})), + span: span})), ast::expr_vstore_uniq)) } @@ -828,7 +529,7 @@ impl AstBuilder for @ExtCtxt { span, ast::expr_lit( @codemap::spanned { node: ast::lit_uint(i as u64, ast::ty_u), - span: span})) + span: span})) } fn blk(&self, span: span, stmts: ~[@ast::stmt], expr: Option<@expr>) -> ast::blk { @@ -942,7 +643,7 @@ impl AstBuilder for @ExtCtxt { } fn lambda_expr_1(&self, expr: @ast::expr, ident: ast::ident) - -> @ast::expr { + -> @ast::expr { self.lambda1(self.blk_expr(expr), ident) } @@ -954,7 +655,7 @@ impl AstBuilder for @ExtCtxt { span: span, stmts: ~[@ast::stmt], ident: ast::ident) - -> @ast::expr { + -> @ast::expr { self.lambda1(self.blk(span, stmts, None), ident) } @@ -992,20 +693,20 @@ impl AstBuilder for @ExtCtxt { let non_camel_case_attribute = respan(dummy_sp(), ast::attribute_ { style: ast::attr_outer, value: @respan(dummy_sp(), - ast::meta_list(@~"allow", ~[ - @respan(dummy_sp(), - ast::meta_word( - @~"non_camel_case_types")) - ])), + ast::meta_list(@~"allow", ~[ + @respan(dummy_sp(), + ast::meta_word( + @~"non_camel_case_types")) + ])), is_sugared_doc: false }); @ast::item { ident: name, - attrs: ~[non_camel_case_attribute], - id: self.next_id(), - node: node, - vis: ast::public, - span: span } + attrs: ~[non_camel_case_attribute], + id: self.next_id(), + node: node, + vis: ast::public, + span: span } } fn item_fn_poly(&self, name: ident, @@ -1027,7 +728,7 @@ impl AstBuilder for @ExtCtxt { inputs: ~[ast::arg], output: @ast::Ty, body: ast::blk - ) -> @ast::item { + ) -> @ast::item { self.item_fn_poly( name, inputs, @@ -1100,7 +801,7 @@ impl AstBuilder for @ExtCtxt { @codemap::spanned { node: ast::view_path_simple( self.ident_of("Owned"), - mk_raw_path( + self.mk_raw_path( codemap::dummy_sp(), ~[ self.ident_of("core"), @@ -1140,4 +841,539 @@ impl AstBuilder for @ExtCtxt { } + + + + + + fn mk_expr(&self, + sp: codemap::span, + expr: ast::expr_) + -> @ast::expr { + @ast::expr { + id: self.next_id(), + callee_id: self.next_id(), + node: expr, + span: sp, + } + } + + fn mk_lit(&self, sp: span, lit: ast::lit_) -> @ast::expr { + let sp_lit = @codemap::spanned { node: lit, span: sp }; + self.mk_expr( sp, ast::expr_lit(sp_lit)) + } + fn mk_int(&self, sp: span, i: int) -> @ast::expr { + let lit = ast::lit_int(i as i64, ast::ty_i); + return self.mk_lit( sp, lit); + } + fn mk_uint(&self, sp: span, u: uint) -> @ast::expr { + let lit = ast::lit_uint(u as u64, ast::ty_u); + return self.mk_lit( sp, lit); + } + fn mk_u8(&self, sp: span, u: u8) -> @ast::expr { + let lit = ast::lit_uint(u as u64, ast::ty_u8); + return self.mk_lit( sp, lit); + } + fn mk_binary(&self, sp: span, op: ast::binop, + lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr { + self.next_id(); // see ast_util::op_expr_callee_id + self.mk_expr( sp, ast::expr_binary(op, lhs, rhs)) + } + + fn mk_deref(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.mk_unary( sp, ast::deref, e) + } + fn mk_unary(&self, sp: span, op: ast::unop, e: @ast::expr) + -> @ast::expr { + self.next_id(); // see ast_util::op_expr_callee_id + self.mk_expr( sp, ast::expr_unary(op, e)) + } + // XXX: unused self + fn mk_raw_path(&self, sp: span, idents: ~[ast::ident]) -> @ast::Path { + self.mk_raw_path_(sp, idents, None, ~[]) + } + // XXX: unused self + fn mk_raw_path_(&self, sp: span, + idents: ~[ast::ident], + rp: Option<@ast::Lifetime>, + types: ~[@ast::Ty]) + -> @ast::Path { + @ast::Path { span: sp, + global: false, + idents: idents, + rp: rp, + types: types } + } + // XXX: unused self + fn mk_raw_path_global(&self, sp: span, idents: ~[ast::ident]) -> @ast::Path { + self.mk_raw_path_global_(sp, idents, None, ~[]) + } + // XXX: unused self + fn mk_raw_path_global_(&self, sp: span, + idents: ~[ast::ident], + rp: Option<@ast::Lifetime>, + types: ~[@ast::Ty]) -> @ast::Path { + @ast::Path { span: sp, + global: true, + idents: idents, + rp: rp, + types: types } + } + fn mk_path_raw(&self, sp: span, path: @ast::Path)-> @ast::expr { + self.mk_expr( sp, ast::expr_path(path)) + } + fn mk_path(&self, sp: span, idents: ~[ast::ident]) + -> @ast::expr { + self.mk_path_raw( sp, self.mk_raw_path(sp, idents)) + } + fn mk_path_global(&self, sp: span, idents: ~[ast::ident]) + -> @ast::expr { + self.mk_path_raw( sp, self.mk_raw_path_global(sp, idents)) + } + fn mk_access_(&self, sp: span, p: @ast::expr, m: ast::ident) + -> @ast::expr { + self.mk_expr( sp, ast::expr_field(p, m, ~[])) + } + fn mk_access(&self, sp: span, p: ~[ast::ident], m: ast::ident) + -> @ast::expr { + let pathexpr = self.mk_path( sp, p); + return self.mk_access_( sp, pathexpr, m); + } + fn mk_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr { + return self.mk_expr( sp, ast::expr_addr_of(ast::m_imm, e)); + } + fn mk_mut_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr { + return self.mk_expr( sp, ast::expr_addr_of(ast::m_mutbl, e)); + } + fn mk_method_call(&self, + sp: span, + rcvr_expr: @ast::expr, + method_ident: ast::ident, + args: ~[@ast::expr]) -> @ast::expr { + self.mk_expr( sp, ast::expr_method_call(rcvr_expr, method_ident, ~[], args, ast::NoSugar)) + } + fn mk_call_(&self, sp: span, fn_expr: @ast::expr, + args: ~[@ast::expr]) -> @ast::expr { + self.mk_expr( sp, ast::expr_call(fn_expr, args, ast::NoSugar)) + } + fn mk_call(&self, sp: span, fn_path: ~[ast::ident], + args: ~[@ast::expr]) -> @ast::expr { + let pathexpr = self.mk_path( sp, fn_path); + return self.mk_call_( sp, pathexpr, args); + } + fn mk_call_global(&self, sp: span, fn_path: ~[ast::ident], + args: ~[@ast::expr]) -> @ast::expr { + let pathexpr = self.mk_path_global( sp, fn_path); + return self.mk_call_( sp, pathexpr, args); + } + // e = expr, t = type + fn mk_base_vec_e(&self, sp: span, exprs: ~[@ast::expr]) + -> @ast::expr { + let vecexpr = ast::expr_vec(exprs, ast::m_imm); + self.mk_expr( sp, vecexpr) + } + fn mk_vstore_e(&self, sp: span, expr: @ast::expr, + vst: ast::expr_vstore) -> + @ast::expr { + self.mk_expr( sp, ast::expr_vstore(expr, vst)) + } + fn mk_uniq_vec_e(&self, sp: span, exprs: ~[@ast::expr]) + -> @ast::expr { + self.mk_vstore_e( sp, self.mk_base_vec_e( sp, exprs), ast::expr_vstore_uniq) + } + fn mk_slice_vec_e(&self, sp: span, exprs: ~[@ast::expr]) + -> @ast::expr { + self.mk_vstore_e( sp, self.mk_base_vec_e( sp, exprs), + ast::expr_vstore_slice) + } + fn mk_base_str(&self, sp: span, s: ~str) -> @ast::expr { + let lit = ast::lit_str(@s); + return self.mk_lit( sp, lit); + } + fn mk_uniq_str(&self, sp: span, s: ~str) -> @ast::expr { + self.mk_vstore_e( sp, self.mk_base_str( sp, s), ast::expr_vstore_uniq) + } + // XXX: unused self + fn mk_field(&self, sp: span, f: &Field) -> ast::field { + codemap::spanned { + node: ast::field_ { mutbl: ast::m_imm, ident: f.ident, expr: f.ex }, + span: sp, + } + } + // XXX: unused self + fn mk_fields(&self, sp: span, fields: ~[Field]) -> ~[ast::field] { + fields.map(|f| self.mk_field(sp, f)) + } + fn mk_struct_e(&self, + sp: span, + ctor_path: ~[ast::ident], + fields: ~[Field]) + -> @ast::expr { + self.mk_expr( sp, + ast::expr_struct(self.mk_raw_path(sp, ctor_path), + self.mk_fields(sp, fields), + option::None::<@ast::expr>)) + } + fn mk_global_struct_e(&self, + sp: span, + ctor_path: ~[ast::ident], + fields: ~[Field]) + -> @ast::expr { + self.mk_expr( sp, + ast::expr_struct(self.mk_raw_path_global(sp, ctor_path), + self.mk_fields(sp, fields), + option::None::<@ast::expr>)) + } + fn mk_glob_use(&self, + sp: span, + vis: ast::visibility, + path: ~[ast::ident]) -> @ast::view_item { + let glob = @codemap::spanned { + node: ast::view_path_glob(self.mk_raw_path(sp, path), self.next_id()), + span: sp, + }; + @ast::view_item { node: ast::view_item_use(~[glob]), + attrs: ~[], + vis: vis, + span: sp } + } + fn mk_local(&self, sp: span, mutbl: bool, + ident: ast::ident, ex: @ast::expr) -> @ast::stmt { + + let pat = @ast::pat { + id: self.next_id(), + node: ast::pat_ident( + ast::bind_by_copy, + self.mk_raw_path(sp, ~[ident]), + None), + span: sp, + }; + let ty = @ast::Ty { id: self.next_id(), node: ast::ty_infer, span: sp }; + let local = @codemap::spanned { + node: ast::local_ { + is_mutbl: mutbl, + ty: ty, + pat: pat, + init: Some(ex), + id: self.next_id(), + }, + span: sp, + }; + let decl = codemap::spanned {node: ast::decl_local(~[local]), span: sp}; + @codemap::spanned { node: ast::stmt_decl(@decl, self.next_id()), span: sp } + } + fn mk_block(&self, span: span, + view_items: ~[@ast::view_item], + stmts: ~[@ast::stmt], + expr: Option<@ast::expr>) -> @ast::expr { + let blk = codemap::spanned { + node: ast::blk_ { + view_items: view_items, + stmts: stmts, + expr: expr, + id: self.next_id(), + rules: ast::default_blk, + }, + span: span, + }; + self.mk_expr( span, ast::expr_block(blk)) + } + fn mk_block_(&self, + span: span, + stmts: ~[@ast::stmt]) + -> ast::blk { + codemap::spanned { + node: ast::blk_ { + view_items: ~[], + stmts: stmts, + expr: None, + id: self.next_id(), + rules: ast::default_blk, + }, + span: span, + } + } + fn mk_simple_block(&self, + span: span, + expr: @ast::expr) + -> ast::blk { + codemap::spanned { + node: ast::blk_ { + view_items: ~[], + stmts: ~[], + expr: Some(expr), + id: self.next_id(), + rules: ast::default_blk, + }, + span: span, + } + } + fn mk_lambda_(&self, + span: span, + fn_decl: ast::fn_decl, + blk: ast::blk) + -> @ast::expr { + self.mk_expr( span, ast::expr_fn_block(fn_decl, blk)) + } + fn mk_lambda(&self, + span: span, + fn_decl: ast::fn_decl, + expr: @ast::expr) + -> @ast::expr { + let blk = self.mk_simple_block( span, expr); + self.mk_lambda_( span, fn_decl, blk) + } + fn mk_lambda_stmts(&self, + span: span, + fn_decl: ast::fn_decl, + stmts: ~[@ast::stmt]) + -> @ast::expr { + let blk = self.mk_block( span, ~[], stmts, None); + self.mk_lambda( span, fn_decl, blk) + } + fn mk_lambda_no_args(&self, + span: span, + expr: @ast::expr) + -> @ast::expr { + let fn_decl = self.mk_fn_decl(~[], self.mk_ty_infer( span)); + self.mk_lambda( span, fn_decl, expr) + } + fn mk_copy(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.mk_expr( sp, ast::expr_copy(e)) + } + fn mk_managed(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.mk_expr( sp, ast::expr_unary(ast::box(ast::m_imm), e)) + } + fn mk_pat(&self, span: span, pat: ast::pat_) -> @ast::pat { + @ast::pat { id: self.next_id(), node: pat, span: span } + } + fn mk_pat_wild(&self, span: span) -> @ast::pat { + self.mk_pat( span, ast::pat_wild) + } + fn mk_pat_lit(&self, + span: span, + expr: @ast::expr) -> @ast::pat { + self.mk_pat( span, ast::pat_lit(expr)) + } + fn mk_pat_ident(&self, + span: span, + ident: ast::ident) -> @ast::pat { + self.mk_pat_ident_with_binding_mode( span, ident, ast::bind_by_copy) + } + + fn mk_pat_ident_with_binding_mode(&self, + span: span, + ident: ast::ident, + bm: ast::binding_mode) -> @ast::pat { + let path = self.mk_raw_path(span, ~[ ident ]); + let pat = ast::pat_ident(bm, path, None); + self.mk_pat( span, pat) + } + fn mk_pat_enum(&self, + span: span, + path: @ast::Path, + subpats: ~[@ast::pat]) + -> @ast::pat { + let pat = ast::pat_enum(path, Some(subpats)); + self.mk_pat( span, pat) + } + fn mk_pat_struct(&self, + span: span, + path: @ast::Path, + field_pats: ~[ast::field_pat]) + -> @ast::pat { + let pat = ast::pat_struct(path, field_pats, false); + self.mk_pat( span, pat) + } + fn mk_bool(&self, span: span, value: bool) -> @ast::expr { + let lit_expr = ast::expr_lit(@codemap::spanned { + node: ast::lit_bool(value), + span: span }); + self.mk_expr( span, lit_expr) + } + fn mk_stmt(&self, span: span, expr: @ast::expr) -> @ast::stmt { + let stmt_ = ast::stmt_semi(expr, self.next_id()); + @codemap::spanned { node: stmt_, span: span } + } + + // XXX: unused self + fn mk_ty_mt(&self, ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt { + ast::mt { + ty: ty, + mutbl: mutbl + } + } + + fn mk_ty(&self, + span: span, + ty: ast::ty_) -> @ast::Ty { + @ast::Ty { + id: self.next_id(), + span: span, + node: ty + } + } + + fn mk_ty_path(&self, + span: span, + idents: ~[ ast::ident ]) + -> @ast::Ty { + let ty = self.mk_raw_path(span, idents); + self.mk_ty_path_path( span, ty) + } + + fn mk_ty_path_global(&self, + span: span, + idents: ~[ ast::ident ]) + -> @ast::Ty { + let ty = self.mk_raw_path_global(span, idents); + self.mk_ty_path_path( span, ty) + } + + fn mk_ty_path_path(&self, + span: span, + path: @ast::Path) + -> @ast::Ty { + let ty = ast::ty_path(path, self.next_id()); + self.mk_ty( span, ty) + } + + fn mk_ty_rptr(&self, + span: span, + ty: @ast::Ty, + lifetime: Option<@ast::Lifetime>, + mutbl: ast::mutability) + -> @ast::Ty { + self.mk_ty( span, + ast::ty_rptr(lifetime, self.mk_ty_mt(ty, mutbl))) + } + fn mk_ty_uniq(&self, span: span, ty: @ast::Ty) -> @ast::Ty { + self.mk_ty( span, ast::ty_uniq(self.mk_ty_mt(ty, ast::m_imm))) + } + fn mk_ty_box(&self, span: span, + ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty { + self.mk_ty( span, ast::ty_box(self.mk_ty_mt(ty, mutbl))) + } + + + + fn mk_ty_infer(&self, span: span) -> @ast::Ty { + self.mk_ty( span, ast::ty_infer) + } + fn mk_trait_ref_global(&self, + span: span, + idents: ~[ ast::ident ]) + -> @ast::trait_ref + { + self.mk_trait_ref_( self.mk_raw_path_global(span, idents)) + } + fn mk_trait_ref_(&self, path: @ast::Path) -> @ast::trait_ref { + @ast::trait_ref { + path: path, + ref_id: self.next_id() + } + } + fn mk_simple_ty_path(&self, + span: span, + ident: ast::ident) + -> @ast::Ty { + self.mk_ty_path( span, ~[ ident ]) + } + fn mk_arg(&self, + span: span, + ident: ast::ident, + ty: @ast::Ty) + -> ast::arg { + let arg_pat = self.mk_pat_ident( span, ident); + ast::arg { + is_mutbl: false, + ty: ty, + pat: arg_pat, + id: self.next_id() + } + } + // XXX unused self + fn mk_fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl { + ast::fn_decl { inputs: inputs, output: output, cf: ast::return_val } + } + fn mk_trait_ty_param_bound_global(&self, + span: span, + idents: ~[ast::ident]) + -> ast::TyParamBound { + ast::TraitTyParamBound(self.mk_trait_ref_global( span, idents)) + } + fn mk_trait_ty_param_bound_(&self, + path: @ast::Path) -> ast::TyParamBound { + ast::TraitTyParamBound(self.mk_trait_ref_( path)) + } + fn mk_ty_param(&self, + ident: ast::ident, + bounds: @OptVec) + -> ast::TyParam { + ast::TyParam { ident: ident, id: self.next_id(), bounds: bounds } + } + fn mk_lifetime(&self, + span: span, + ident: ast::ident) + -> ast::Lifetime { + ast::Lifetime { id: self.next_id(), span: span, ident: ident } + } + fn mk_arm(&self, + span: span, + pats: ~[@ast::pat], + expr: @ast::expr) + -> ast::arm { + ast::arm { + pats: pats, + guard: None, + body: self.mk_simple_block( span, expr) + } + } + fn mk_unreachable(&self, span: span) -> @ast::expr { + let loc = self.codemap().lookup_char_pos(span.lo); + self.mk_call_global( + span, + ~[ + self.ident_of("core"), + self.ident_of("sys"), + self.ident_of("FailWithCause"), + self.ident_of("fail_with"), + ], + ~[ + self.mk_base_str( span, ~"internal error: entered unreachable code"), + self.mk_base_str( span, copy loc.file.name), + self.mk_uint( span, loc.line), + ] + ) + } + fn mk_unreachable_arm(&self, span: span) -> ast::arm { + self.mk_arm( span, ~[self.mk_pat_wild( span)], self.mk_unreachable( span)) + } + + fn make_self(&self, span: span) -> @ast::expr { + self.mk_expr( span, ast::expr_self) + } +} + + +pub trait Duplicate { + // + // Duplication functions + // + // These functions just duplicate AST nodes. + // + + fn duplicate(&self, cx: @ExtCtxt) -> Self; +} + +impl Duplicate for @ast::expr { + fn duplicate(&self, cx: @ExtCtxt) -> @ast::expr { + let folder = fold::default_ast_fold(); + let folder = @fold::AstFoldFns { + new_id: |_| cx.next_id(), + ..*folder + }; + let folder = fold::make_fold(folder); + folder.fold_expr(*self) + } } diff --git a/src/libsyntax/ext/bytes.rs b/src/libsyntax/ext/bytes.rs index da13c9bfa28e1..cdc6e267cccba 100644 --- a/src/libsyntax/ext/bytes.rs +++ b/src/libsyntax/ext/bytes.rs @@ -14,7 +14,7 @@ use ast; use codemap::span; use ext::base::*; use ext::base; -use ext::build::{mk_u8, mk_slice_vec_e}; +use ext::build::AstBuilder; pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { // Gather all argument expressions @@ -28,7 +28,7 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas // string literal, push each byte to vector expression ast::lit_str(s) => { for s.each |byte| { - bytes.push(mk_u8(cx, sp, byte)); + bytes.push(cx.mk_u8(sp, byte)); } } @@ -37,7 +37,7 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas if v > 0xFF { cx.span_err(sp, "Too large u8 literal in bytes!") } else { - bytes.push(mk_u8(cx, sp, v as u8)); + bytes.push(cx.mk_u8(sp, v as u8)); } } @@ -48,14 +48,14 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas } else if v < 0 { cx.span_err(sp, "Negative integer literal in bytes!") } else { - bytes.push(mk_u8(cx, sp, v as u8)); + bytes.push(cx.mk_u8(sp, v as u8)); } } // char literal, push to vector expression ast::lit_int(v, ast::ty_char) => { if (v as char).is_ascii() { - bytes.push(mk_u8(cx, sp, v as u8)); + bytes.push(cx.mk_u8(sp, v as u8)); } else { cx.span_err(sp, "Non-ascii char literal in bytes!") } @@ -68,6 +68,6 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas } } - let e = mk_slice_vec_e(cx, sp, bytes); + let e = cx.mk_slice_vec_e(sp, bytes); MRExpr(e) } diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index c08b478e8ed6f..07aead9588ac1 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -12,6 +12,7 @@ use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; use ext::build; +use ext::build::AstBuilder; use ext::deriving::generic::*; @@ -79,7 +80,7 @@ fn cs_clone( let ctor_ident; let all_fields; let subcall = |field| - build::mk_method_call(cx, span, field, clone_ident, ~[]); + cx.mk_method_call(span, field, clone_ident, ~[]); match *substr.fields { Struct(ref af) => { @@ -102,7 +103,7 @@ fn cs_clone( [(None, _, _), .. _] => { // enum-like let subcalls = all_fields.map(|&(_, self_f, _)| subcall(self_f)); - build::mk_call(cx, span, ctor_ident, subcalls) + cx.mk_call(span, ctor_ident, subcalls) }, _ => { // struct-like @@ -118,9 +119,9 @@ fn cs_clone( if fields.is_empty() { // no fields, so construct like `None` - build::mk_path(cx, span, ctor_ident) + cx.mk_path(span, ctor_ident) } else { - build::mk_struct_e(cx, span, + cx.mk_struct_e(span, ctor_ident, fields) } diff --git a/src/libsyntax/ext/deriving/cmp/eq.rs b/src/libsyntax/ext/deriving/cmp/eq.rs index 197366b09ae3c..1af6640448977 100644 --- a/src/libsyntax/ext/deriving/cmp/eq.rs +++ b/src/libsyntax/ext/deriving/cmp/eq.rs @@ -11,7 +11,7 @@ use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_eq(cx: @ExtCtxt, @@ -21,11 +21,11 @@ pub fn expand_deriving_eq(cx: @ExtCtxt, // structures are equal if all fields are equal, and non equal, if // any fields are not equal or if the enum variants are different fn cs_eq(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { - cs_and(|cx, span, _, _| build::mk_bool(cx, span, false), + cs_and(|cx, span, _, _| cx.mk_bool(span, false), cx, span, substr) } fn cs_ne(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { - cs_or(|cx, span, _, _| build::mk_bool(cx, span, true), + cs_or(|cx, span, _, _| cx.mk_bool(span, true), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 29fc2c7271c0b..41b5bf63aca34 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -12,7 +12,7 @@ use ast::{meta_item, item, expr_if, expr}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_ord(cx: @ExtCtxt, @@ -62,10 +62,10 @@ fn cs_ord(less: bool, equal: bool, } else { cx.ident_of("gt") }; - let false_blk_expr = build::mk_block(cx, span, + let false_blk_expr = cx.mk_block(span, ~[], ~[], - Some(build::mk_bool(cx, span, false))); - let base = build::mk_bool(cx, span, equal); + Some(cx.mk_bool(span, false))); + let base = cx.mk_bool(span, equal); cs_fold( false, // need foldr, @@ -98,19 +98,19 @@ fn cs_ord(less: bool, equal: bool, cx.span_bug(span, "Not exactly 2 arguments in `deriving(Ord)`"); } - let cmp = build::mk_method_call(cx, span, + let cmp = cx.mk_method_call(span, self_f, cx.ident_of("eq"), other_fs.to_owned()); - let subexpr = build::mk_simple_block(cx, span, subexpr); + let subexpr = cx.mk_simple_block(span, subexpr); let elseif = expr_if(cmp, subexpr, Some(false_blk_expr)); - let elseif = build::mk_expr(cx, span, elseif); + let elseif = cx.mk_expr(span, elseif); - let cmp = build::mk_method_call(cx, span, + let cmp = cx.mk_method_call(span, self_f, binop, other_fs.to_owned()); - let true_blk = build::mk_simple_block(cx, span, - build::mk_bool(cx, span, true)); + let true_blk = cx.mk_simple_block(span, + cx.mk_bool(span, true)); let if_ = expr_if(cmp, true_blk, Some(elseif)); - build::mk_expr(cx, span, if_) + cx.mk_expr(span, if_) }, base, |cx, span, args, _| { @@ -119,7 +119,7 @@ fn cs_ord(less: bool, equal: bool, match args { [(self_var, _, _), (other_var, _, _)] => - build::mk_bool(cx, span, + cx.mk_bool(span, if less { self_var < other_var } else { diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index 0ab99430d1078..48393efce6487 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -12,7 +12,7 @@ use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_totaleq(cx: @ExtCtxt, @@ -21,7 +21,7 @@ pub fn expand_deriving_totaleq(cx: @ExtCtxt, in_items: ~[@item]) -> ~[@item] { fn cs_equals(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { - cs_and(|cx, span, _, _| build::mk_bool(cx, span, false), + cs_and(|cx, span, _, _| cx.mk_bool(span, false), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index 2b4d8a28fbd93..3404a21edd0de 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -11,7 +11,7 @@ use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::generic::*; use core::cmp::{Ordering, Equal, Less, Greater}; @@ -47,7 +47,7 @@ pub fn ordering_const(cx: @ExtCtxt, span: span, cnst: Ordering) -> @expr { Equal => "Equal", Greater => "Greater" }; - build::mk_path_global(cx, span, + cx.mk_path_global(span, ~[cx.ident_of("core"), cx.ident_of("cmp"), cx.ident_of(cnst)]) @@ -60,7 +60,7 @@ pub fn cs_cmp(cx: @ExtCtxt, span: span, // foldr (possibly) nests the matches in lexical_ordering better false, |cx, span, old, new| { - build::mk_call_global(cx, span, + cx.mk_call_global(span, ~[cx.ident_of("core"), cx.ident_of("cmp"), cx.ident_of("lexical_ordering")], diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 24f9b6acf8534..781ac9814ec9b 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -16,7 +16,8 @@ encodable.rs for more. use ast; use ast::*; use ext::base::ExtCtxt; -use ext::build; +use ext::build::Field; +use ext::build::AstBuilder; use ext::deriving::*; use codemap::{span, spanned}; use ast_util; @@ -44,12 +45,10 @@ fn create_derived_decodable_impl( generics: &Generics, method: @method ) -> @item { - let decoder_ty_param = build::mk_ty_param( - cx, + let decoder_ty_param = cx.mk_ty_param( cx.ident_of("__D"), @opt_vec::with( - build::mk_trait_ty_param_bound_global( - cx, + cx.mk_trait_ty_param_bound_global( span, ~[ cx.ident_of("std"), @@ -64,7 +63,7 @@ fn create_derived_decodable_impl( let generic_ty_params = opt_vec::with(decoder_ty_param); let methods = [method]; - let trait_path = build::mk_raw_path_global_( + let trait_path = cx.mk_raw_path_global_( span, ~[ cx.ident_of("std"), @@ -73,7 +72,7 @@ fn create_derived_decodable_impl( ], None, ~[ - build::mk_simple_ty_path(cx, span, cx.ident_of("__D")) + cx.mk_simple_ty_path(span, cx.ident_of("__D")) ] ); create_derived_impl( @@ -98,15 +97,14 @@ fn create_decode_method( expr: @ast::expr ) -> @method { // Create the `e` parameter. - let d_arg_type = build::mk_ty_rptr( - cx, + let d_arg_type = cx.mk_ty_rptr( span, - build::mk_simple_ty_path(cx, span, cx.ident_of("__D")), + cx.mk_simple_ty_path(span, cx.ident_of("__D")), None, ast::m_mutbl ); let d_ident = cx.ident_of("__d"); - let d_arg = build::mk_arg(cx, span, d_ident, d_arg_type); + let d_arg = cx.mk_arg(span, d_ident, d_arg_type); // Create the type of the return value. let output_type = create_self_type_with_params( @@ -118,10 +116,10 @@ fn create_decode_method( // Create the function declaration. let inputs = ~[d_arg]; - let fn_decl = build::mk_fn_decl(inputs, output_type); + let fn_decl = cx.mk_fn_decl(inputs, output_type); // Create the body block. - let body_block = build::mk_simple_block(cx, span, expr); + let body_block = cx.mk_simple_block(span, expr); // Create the method. let explicit_self = spanned { node: sty_static, span: span }; @@ -146,11 +144,9 @@ fn call_substructure_decode_method( span: span ) -> @ast::expr { // Call the substructure method. - build::mk_call_( - cx, + cx.mk_call_( span, - build::mk_path_global( - cx, + cx.mk_path_global( span, ~[ cx.ident_of("std"), @@ -160,7 +156,7 @@ fn call_substructure_decode_method( ] ), ~[ - build::mk_path(cx, span, ~[cx.ident_of("__d")]) + cx.mk_path(span, ~[cx.ident_of("__d")]) ] ) } @@ -222,32 +218,31 @@ fn create_read_struct_field( span: span, idx: uint, ident: ident -) -> build::Field { +) -> Field { // Call the substructure method. let decode_expr = call_substructure_decode_method(cx, span); - let d_arg = build::mk_arg(cx, + let d_arg = cx.mk_arg( span, cx.ident_of("__d"), - build::mk_ty_infer(cx, span)); + cx.mk_ty_infer(span)); - let call_expr = build::mk_method_call( - cx, + let call_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__d")]), + cx.mk_path(span, ~[cx.ident_of("__d")]), cx.ident_of("read_struct_field"), ~[ - build::mk_base_str(cx, span, cx.str_of(ident)), - build::mk_uint(cx, span, idx), - build::mk_lambda(cx, + cx.mk_base_str(span, cx.str_of(ident)), + cx.mk_uint(span, idx), + cx.mk_lambda( span, - build::mk_fn_decl(~[d_arg], - build::mk_ty_infer(cx, span)), + cx.mk_fn_decl(~[d_arg], + cx.mk_ty_infer(span)), decode_expr), ] ); - build::Field { ident: ident, ex: call_expr } + Field { ident: ident, ex: call_expr } } fn create_read_struct_arg( @@ -255,22 +250,21 @@ fn create_read_struct_arg( span: span, idx: uint, ident: ident -) -> build::Field { +) -> Field { // Call the substructure method. let decode_expr = call_substructure_decode_method(cx, span); - let call_expr = build::mk_method_call( - cx, + let call_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__d")]), + cx.mk_path(span, ~[cx.ident_of("__d")]), cx.ident_of("read_struct_arg"), ~[ - build::mk_uint(cx, span, idx), - build::mk_lambda_no_args(cx, span, decode_expr), + cx.mk_uint(span, idx), + cx.mk_lambda_no_args(span, decode_expr), ] ); - build::Field { ident: ident, ex: call_expr } + Field { ident: ident, ex: call_expr } } fn expand_deriving_decodable_struct_method( @@ -298,29 +292,25 @@ fn expand_deriving_decodable_struct_method( i += 1; } - let d_arg = build::mk_arg(cx, + let d_arg = cx.mk_arg( span, cx.ident_of("__d"), - build::mk_ty_infer(cx, span)); + cx.mk_ty_infer(span)); - let read_struct_expr = build::mk_method_call( - cx, + let read_struct_expr = cx.mk_method_call( span, - build::mk_path( - cx, + cx.mk_path( span, ~[cx.ident_of("__d")] ), cx.ident_of("read_struct"), ~[ - build::mk_base_str(cx, span, cx.str_of(type_ident)), - build::mk_uint(cx, span, fields.len()), - build::mk_lambda( - cx, + cx.mk_base_str(span, cx.str_of(type_ident)), + cx.mk_uint(span, fields.len()), + cx.mk_lambda( span, - build::mk_fn_decl(~[d_arg], build::mk_ty_infer(cx, span)), - build::mk_struct_e( - cx, + cx.mk_fn_decl(~[d_arg], cx.mk_ty_infer(span)), + cx.mk_struct_e( span, ~[type_ident], fields @@ -340,14 +330,14 @@ fn create_read_variant_arg( variant: &ast::variant ) -> ast::arm { // Create the matching pattern. - let pat = build::mk_pat_lit(cx, span, build::mk_uint(cx, span, idx)); + let pat = cx.mk_pat_lit(span, cx.mk_uint(span, idx)); // Feed each argument in this variant to the decode function // as well. let variant_arg_len = variant_arg_count(cx, span, variant); let expr = if variant_arg_len == 0 { - build::mk_path(cx, span, ~[variant.node.name]) + cx.mk_path(span, ~[variant.node.name]) } else { // Feed the discriminant to the decode function. let mut args = ~[]; @@ -356,22 +346,21 @@ fn create_read_variant_arg( // Call the substructure method. let expr = call_substructure_decode_method(cx, span); - let d_arg = build::mk_arg(cx, + let d_arg = cx.mk_arg( span, cx.ident_of("__d"), - build::mk_ty_infer(cx, span)); - let t_infer = build::mk_ty_infer(cx, span); + cx.mk_ty_infer(span)); + let t_infer = cx.mk_ty_infer(span); - let call_expr = build::mk_method_call( - cx, + let call_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__d")]), + cx.mk_path(span, ~[cx.ident_of("__d")]), cx.ident_of("read_enum_variant_arg"), ~[ - build::mk_uint(cx, span, j), - build::mk_lambda(cx, + cx.mk_uint(span, j), + cx.mk_lambda( span, - build::mk_fn_decl(~[d_arg], t_infer), + cx.mk_fn_decl(~[d_arg], t_infer), expr), ] ); @@ -379,8 +368,7 @@ fn create_read_variant_arg( args.push(call_expr); } - build::mk_call( - cx, + cx.mk_call( span, ~[variant.node.name], args @@ -388,7 +376,7 @@ fn create_read_variant_arg( }; // Create the arm. - build::mk_arm(cx, span, ~[pat], expr) + cx.mk_arm(span, ~[pat], expr) } fn create_read_enum_variant( @@ -397,12 +385,10 @@ fn create_read_enum_variant( enum_definition: &enum_def ) -> @expr { // Create a vector that contains all the variant names. - let expr_arm_names = build::mk_base_vec_e( - cx, + let expr_arm_names = cx.mk_base_vec_e( span, do enum_definition.variants.map |variant| { - build::mk_base_str( - cx, + cx.mk_base_str( span, cx.str_of(variant.node.name) ) @@ -415,41 +401,36 @@ fn create_read_enum_variant( }; // Add the impossible case arm. - arms.push(build::mk_unreachable_arm(cx, span)); + arms.push(cx.mk_unreachable_arm(span)); // Create the read_enum_variant expression. - build::mk_method_call( - cx, + cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__d")]), + cx.mk_path(span, ~[cx.ident_of("__d")]), cx.ident_of("read_enum_variant"), ~[ expr_arm_names, - build::mk_lambda( - cx, + cx.mk_lambda( span, - build::mk_fn_decl( + cx.mk_fn_decl( ~[ - build::mk_arg( - cx, + cx.mk_arg( span, cx.ident_of("__d"), - build::mk_ty_infer(cx, span) + cx.mk_ty_infer(span) ), - build::mk_arg( - cx, + cx.mk_arg( span, cx.ident_of("__i"), - build::mk_ty_infer(cx, span) + cx.mk_ty_infer(span) ) ], - build::mk_ty_infer(cx, span) + cx.mk_ty_infer(span) ), - build::mk_expr( - cx, + cx.mk_expr( span, ast::expr_match( - build::mk_path(cx, span, ~[cx.ident_of("__i")]), + cx.mk_path(span, ~[cx.ident_of("__i")]), arms ) ) @@ -471,23 +452,22 @@ fn expand_deriving_decodable_enum_method( enum_definition ); - let d_arg = build::mk_arg(cx, + let d_arg = cx.mk_arg( span, cx.ident_of("__d"), - build::mk_ty_infer(cx, span)); + cx.mk_ty_infer(span)); // Create the read_enum expression - let read_enum_expr = build::mk_method_call( - cx, + let read_enum_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__d")]), + cx.mk_path(span, ~[cx.ident_of("__d")]), cx.ident_of("read_enum"), ~[ - build::mk_base_str(cx, span, cx.str_of(type_ident)), - build::mk_lambda(cx, + cx.mk_base_str(span, cx.str_of(type_ident)), + cx.mk_lambda( span, - build::mk_fn_decl(~[d_arg], - build::mk_ty_infer(cx, span)), + cx.mk_fn_decl(~[d_arg], + cx.mk_ty_infer(span)), read_enum_variant_expr), ] ); diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 128bbf39b16c6..eda1909aed4cb 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -79,7 +79,7 @@ would yield functions like: use ast; use ast::*; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::*; use codemap::{span, spanned}; use ast_util; @@ -107,12 +107,10 @@ fn create_derived_encodable_impl( generics: &Generics, method: @method ) -> @item { - let encoder_ty_param = build::mk_ty_param( - cx, + let encoder_ty_param = cx.mk_ty_param( cx.ident_of("__E"), @opt_vec::with( - build::mk_trait_ty_param_bound_global( - cx, + cx.mk_trait_ty_param_bound_global( span, ~[ cx.ident_of("std"), @@ -127,7 +125,7 @@ fn create_derived_encodable_impl( let generic_ty_params = opt_vec::with(encoder_ty_param); let methods = [method]; - let trait_path = build::mk_raw_path_global_( + let trait_path = cx.mk_raw_path_global_( span, ~[ cx.ident_of("std"), @@ -136,7 +134,7 @@ fn create_derived_encodable_impl( ], None, ~[ - build::mk_simple_ty_path(cx, span, cx.ident_of("__E")) + cx.mk_simple_ty_path(span, cx.ident_of("__E")) ] ); create_derived_impl( @@ -159,24 +157,23 @@ fn create_encode_method( statements: ~[@stmt] ) -> @method { // Create the `e` parameter. - let e_arg_type = build::mk_ty_rptr( - cx, + let e_arg_type = cx.mk_ty_rptr( span, - build::mk_simple_ty_path(cx, span, cx.ident_of("__E")), + cx.mk_simple_ty_path(span, cx.ident_of("__E")), None, ast::m_mutbl ); - let e_arg = build::mk_arg(cx, span, cx.ident_of("__e"), e_arg_type); + let e_arg = cx.mk_arg(span, cx.ident_of("__e"), e_arg_type); // Create the type of the return value. let output_type = @ast::Ty { id: cx.next_id(), node: ty_nil, span: span }; // Create the function declaration. let inputs = ~[e_arg]; - let fn_decl = build::mk_fn_decl(inputs, output_type); + let fn_decl = cx.mk_fn_decl(inputs, output_type); // Create the body block. - let body_block = build::mk_block_(cx, span, statements); + let body_block = cx.mk_block_(span, statements); // Create the method. let explicit_self = spanned { node: sty_region(None, m_imm), span: span }; @@ -203,12 +200,11 @@ fn call_substructure_encode_method( ) -> @ast::expr { // Gather up the parameters we want to chain along. let e_ident = cx.ident_of("__e"); - let e_expr = build::mk_path(cx, span, ~[e_ident]); + let e_expr = cx.mk_path(span, ~[e_ident]); // Call the substructure method. let encode_ident = cx.ident_of("encode"); - build::mk_method_call( - cx, + cx.mk_method_call( span, self_field, encode_ident, @@ -279,9 +275,9 @@ fn expand_deriving_encodable_struct_method( match struct_field.node.kind { named_field(ident, _) => { // Create the accessor for this field. - let self_field = build::mk_access_(cx, + let self_field = cx.mk_access_( span, - build::make_self(cx, span), + cx.make_self(span), ident); // Call the substructure method. @@ -292,31 +288,29 @@ fn expand_deriving_encodable_struct_method( ); let e_ident = cx.ident_of("__e"); - let e_arg = build::mk_arg(cx, + let e_arg = cx.mk_arg( span, e_ident, - build::mk_ty_infer(cx, span)); + cx.mk_ty_infer(span)); - let blk_expr = build::mk_lambda( - cx, + let blk_expr = cx.mk_lambda( span, - build::mk_fn_decl(~[e_arg], build::mk_ty_infer(cx, span)), + cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), encode_expr ); - let call_expr = build::mk_method_call( - cx, + let call_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__e")]), + cx.mk_path(span, ~[cx.ident_of("__e")]), cx.ident_of("emit_struct_field"), ~[ - build::mk_base_str(cx, span, cx.str_of(ident)), - build::mk_uint(cx, span, idx), + cx.mk_base_str(span, cx.str_of(ident)), + cx.mk_uint(span, idx), blk_expr ] ); - statements.push(build::mk_stmt(cx, span, call_expr)); + statements.push(cx.mk_stmt(span, call_expr)); } unnamed_field => { cx.span_unimpl( @@ -328,33 +322,30 @@ fn expand_deriving_encodable_struct_method( idx += 1; } - let e_arg = build::mk_arg(cx, + let e_arg = cx.mk_arg( span, cx.ident_of("__e"), - build::mk_ty_infer(cx, span)); + cx.mk_ty_infer(span)); - let emit_struct_stmt = build::mk_method_call( - cx, + let emit_struct_stmt = cx.mk_method_call( span, - build::mk_path( - cx, + cx.mk_path( span, ~[cx.ident_of("__e")] ), cx.ident_of("emit_struct"), ~[ - build::mk_base_str(cx, span, cx.str_of(type_ident)), - build::mk_uint(cx, span, statements.len()), - build::mk_lambda_stmts( - cx, + cx.mk_base_str(span, cx.str_of(type_ident)), + cx.mk_uint(span, statements.len()), + cx.mk_lambda_stmts( span, - build::mk_fn_decl(~[e_arg], build::mk_ty_infer(cx, span)), + cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), statements ), ] ); - let statements = ~[build::mk_stmt(cx, span, emit_struct_stmt)]; + let statements = ~[cx.mk_stmt(span, emit_struct_stmt)]; // Create the method itself. return create_encode_method(cx, span, statements); @@ -382,56 +373,52 @@ fn expand_deriving_encodable_enum_method( let expr = call_substructure_encode_method(cx, span, field); let e_ident = cx.ident_of("__e"); - let e_arg = build::mk_arg(cx, + let e_arg = cx.mk_arg( span, e_ident, - build::mk_ty_infer(cx, span)); + cx.mk_ty_infer(span)); - let blk_expr = build::mk_lambda( - cx, + let blk_expr = cx.mk_lambda( span, - build::mk_fn_decl(~[e_arg], build::mk_ty_infer(cx, span)), + cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), expr ); - let call_expr = build::mk_method_call( - cx, + let call_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__e")]), + cx.mk_path(span, ~[cx.ident_of("__e")]), cx.ident_of("emit_enum_variant_arg"), ~[ - build::mk_uint(cx, span, j), + cx.mk_uint(span, j), blk_expr, ] ); - stmts.push(build::mk_stmt(cx, span, call_expr)); + stmts.push(cx.mk_stmt(span, call_expr)); } // Create the pattern body. - let e_arg = build::mk_arg(cx, + let e_arg = cx.mk_arg( span, cx.ident_of("__e"), - build::mk_ty_infer(cx, span)); - let call_expr = build::mk_method_call( - cx, + cx.mk_ty_infer(span)); + let call_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__e")]), + cx.mk_path(span, ~[cx.ident_of("__e")]), cx.ident_of("emit_enum_variant"), ~[ - build::mk_base_str(cx, span, cx.str_of(variant.node.name)), - build::mk_uint(cx, span, i), - build::mk_uint(cx, span, variant_arg_len), - build::mk_lambda_stmts( - cx, + cx.mk_base_str(span, cx.str_of(variant.node.name)), + cx.mk_uint(span, i), + cx.mk_uint(span, variant_arg_len), + cx.mk_lambda_stmts( span, - build::mk_fn_decl(~[e_arg], build::mk_ty_infer(cx, span)), + cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), stmts ) ] ); - let match_body_block = build::mk_simple_block(cx, span, call_expr); + let match_body_block = cx.mk_simple_block(span, call_expr); // Create the arm. ast::arm { @@ -442,31 +429,29 @@ fn expand_deriving_encodable_enum_method( }; let e_ident = cx.ident_of("__e"); - let e_arg = build::mk_arg(cx, + let e_arg = cx.mk_arg( span, e_ident, - build::mk_ty_infer(cx, span)); + cx.mk_ty_infer(span)); // Create the method body. - let lambda_expr = build::mk_lambda( - cx, + let lambda_expr = cx.mk_lambda( span, - build::mk_fn_decl(~[e_arg], build::mk_ty_infer(cx, span)), + cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), expand_enum_or_struct_match(cx, span, arms) ); - let call_expr = build::mk_method_call( - cx, + let call_expr = cx.mk_method_call( span, - build::mk_path(cx, span, ~[cx.ident_of("__e")]), + cx.mk_path(span, ~[cx.ident_of("__e")]), cx.ident_of("emit_enum"), ~[ - build::mk_base_str(cx, span, cx.str_of(type_ident)), + cx.mk_base_str(span, cx.str_of(type_ident)), lambda_expr, ] ); - let stmt = build::mk_stmt(cx, span, call_expr); + let stmt = cx.mk_stmt(span, call_expr); // Create the method. create_encode_method(cx, span, ~[stmt]) diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index 0bb97ec31224c..4859fec2e4452 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -166,7 +166,7 @@ use ast; use ast::{enum_def, expr, ident, Generics, struct_def}; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::*; use codemap::{span,respan}; use opt_vec; @@ -431,7 +431,7 @@ impl<'self> MethodDef<'self> { let ident = cx.ident_of(fmt!("__arg_%u", i)); arg_tys.push((ident, ast_ty)); - let arg_expr = build::mk_path(cx, span, ~[ident]); + let arg_expr = cx.mk_path(span, ~[ident]); match *ty { // for static methods, just treat any Self @@ -440,7 +440,7 @@ impl<'self> MethodDef<'self> { self_args.push(arg_expr); } Ptr(~Self, _) if nonstatic => { - self_args.push(build::mk_deref(cx, span, arg_expr)) + self_args.push(cx.mk_deref(span, arg_expr)) } _ => { nonself_args.push(arg_expr); @@ -461,14 +461,14 @@ impl<'self> MethodDef<'self> { let fn_generics = self.generics.to_generics(cx, span, type_ident, generics); let args = do arg_types.map |&(id, ty)| { - build::mk_arg(cx, span, id, ty) + cx.mk_arg(span, id, ty) }; let ret_type = self.get_ret_ty(cx, span, generics, type_ident); let method_ident = cx.ident_of(self.name); - let fn_decl = build::mk_fn_decl(args, ret_type); - let body_block = build::mk_simple_block(cx, span, body); + let fn_decl = cx.mk_fn_decl(args, ret_type); + let body_block = cx.mk_simple_block(span, body); // Create the method. @@ -558,10 +558,10 @@ impl<'self> MethodDef<'self> { let match_arm = ast::arm { pats: ~[ pat ], guard: None, - body: build::mk_simple_block(cx, span, body) + body: cx.mk_simple_block(span, body) }; - body = build::mk_expr(cx, span, ast::expr_match(arg_expr, ~[match_arm])) + body = cx.mk_expr(span, ast::expr_match(arg_expr, ~[match_arm])) } body } @@ -738,15 +738,15 @@ impl<'self> MethodDef<'self> { matches_so_far, match_count + 1); matches_so_far.pop(); - arms.push(build::mk_arm(cx, span, ~[ pattern ], arm_expr)); + arms.push(cx.mk_arm(span, ~[ pattern ], arm_expr)); if enum_def.variants.len() > 1 { let e = &EnumNonMatching(&[]); let wild_expr = self.call_substructure_method(cx, span, type_ident, self_args, nonself_args, e); - let wild_arm = build::mk_arm(cx, span, - ~[ build::mk_pat_wild(cx, span) ], + let wild_arm = cx.mk_arm(span, + ~[ cx.mk_pat_wild(span) ], wild_expr); arms.push(wild_arm); } @@ -774,13 +774,13 @@ impl<'self> MethodDef<'self> { match_count + 1); matches_so_far.pop(); - let arm = build::mk_arm(cx, span, ~[ pattern ], arm_expr); + let arm = cx.mk_arm(span, ~[ pattern ], arm_expr); arms.push(arm); } } // match foo { arm, arm, arm, ... } - build::mk_expr(cx, span, + cx.mk_expr(span, ast::expr_match(self_args[match_count], arms)) } } @@ -887,7 +887,7 @@ pub fn cs_same_method(f: &fn(@ExtCtxt, span, ~[@expr]) -> @expr, EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => { // call self_n.method(other_1_n, other_2_n, ...) let called = do all_fields.map |&(_, self_field, other_fields)| { - build::mk_method_call(cx, span, + cx.mk_method_call(span, self_field, substructure.method_ident, other_fields) @@ -945,7 +945,7 @@ pub fn cs_binop(binop: ast::binop, base: @expr, cs_same_method_fold( true, // foldl is good enough |cx, span, old, new| { - build::mk_binary(cx, span, + cx.mk_binary(span, binop, old, new) @@ -960,7 +960,7 @@ pub fn cs_binop(binop: ast::binop, base: @expr, pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc, cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { - cs_binop(ast::or, build::mk_bool(cx, span, false), + cs_binop(ast::or, cx.mk_bool(span, false), enum_nonmatch_f, cx, span, substructure) } @@ -969,7 +969,7 @@ pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc, pub fn cs_and(enum_nonmatch_f: EnumNonMatchFunc, cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { - cs_binop(ast::and, build::mk_bool(cx, span, true), + cs_binop(ast::and, cx.mk_bool(span, true), enum_nonmatch_f, cx, span, substructure) } diff --git a/src/libsyntax/ext/deriving/iter_bytes.rs b/src/libsyntax/ext/deriving/iter_bytes.rs index c655eef34d1eb..cc89bae37b76f 100644 --- a/src/libsyntax/ext/deriving/iter_bytes.rs +++ b/src/libsyntax/ext/deriving/iter_bytes.rs @@ -11,7 +11,7 @@ use ast::{meta_item, item, expr, and}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_iter_bytes(cx: @ExtCtxt, @@ -48,7 +48,7 @@ fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @ }; let iter_bytes_ident = substr.method_ident; let call_iterbytes = |thing_expr| { - build::mk_method_call(cx, span, + cx.mk_method_call(span, thing_expr, iter_bytes_ident, copy lsb0_f) }; @@ -63,7 +63,7 @@ fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @ // iteration function. let discriminant = match variant.node.disr_expr { Some(copy d)=> d, - None => build::mk_uint(cx, span, index) + None => cx.mk_uint(span, index) }; exprs.push(call_iterbytes(discriminant)); @@ -82,6 +82,6 @@ fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @ } do vec::foldl(exprs[0], exprs.slice(1, exprs.len())) |prev, me| { - build::mk_binary(cx, span, and, prev, *me) + cx.mk_binary(span, and, prev, *me) } } diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 4a6c78038389e..a7f70236251ba 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -21,7 +21,7 @@ library. use ast; use ast::{Ty, enum_def, expr, ident, item, Generics, meta_item, struct_def}; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use codemap::{span, respan}; use parse::token::special_idents::clownshoes_extensions; use opt_vec; @@ -172,7 +172,7 @@ pub fn create_self_type_with_params(cx: @ExtCtxt, // Create the type parameters on the `self` path. let mut self_ty_params = ~[]; for generics.ty_params.each |ty_param| { - let self_ty_param = build::mk_simple_ty_path(cx, + let self_ty_param = cx.mk_simple_ty_path( span, ty_param.ident); self_ty_params.push(self_ty_param); @@ -186,11 +186,11 @@ pub fn create_self_type_with_params(cx: @ExtCtxt, // Create the type of `self`. - let self_type = build::mk_raw_path_(span, - ~[ type_ident ], + let self_type = cx.mk_raw_path_(span, + ~[ type_ident ], lifetime, self_ty_params); - build::mk_ty_path_path(cx, span, self_type) + cx.mk_ty_path_path(span, self_type) } pub fn create_derived_impl(cx: @ExtCtxt, @@ -222,18 +222,18 @@ pub fn create_derived_impl(cx: @ExtCtxt, for generics.ty_params.each |ty_param| { // extra restrictions on the generics parameters to the type being derived upon let mut bounds = do bounds_paths.map |&bound_path| { - build::mk_trait_ty_param_bound_(cx, bound_path) + cx.mk_trait_ty_param_bound_(bound_path) }; let this_trait_bound = - build::mk_trait_ty_param_bound_(cx, trait_path); + cx.mk_trait_ty_param_bound_(trait_path); bounds.push(this_trait_bound); - impl_generics.ty_params.push(build::mk_ty_param(cx, ty_param.ident, @bounds)); + impl_generics.ty_params.push(cx.mk_ty_param(ty_param.ident, @bounds)); } // Create the reference to the trait. - let trait_ref = build::mk_trait_ref_(cx, trait_path); + let trait_ref = cx.mk_trait_ref_(trait_path); // Create the type of `self`. let self_type = create_self_type_with_params(cx, @@ -255,7 +255,7 @@ pub fn create_subpatterns(cx: @ExtCtxt, mutbl: ast::mutability) -> ~[@ast::pat] { do field_paths.map |&path| { - build::mk_pat(cx, span, + cx.mk_pat(span, ast::pat_ident(ast::bind_by_ref(mutbl), path, None)) } } @@ -274,12 +274,12 @@ pub fn create_struct_pattern(cx: @ExtCtxt, -> (@ast::pat, ~[(Option, @expr)]) { if struct_def.fields.is_empty() { return ( - build::mk_pat_ident_with_binding_mode( - cx, span, struct_ident, ast::bind_infer), + cx.mk_pat_ident_with_binding_mode( + span, struct_ident, ast::bind_infer), ~[]); } - let matching_path = build::mk_raw_path(span, ~[ struct_ident ]); + let matching_path = cx.mk_raw_path(span, ~[ struct_ident ]); let mut paths = ~[], ident_expr = ~[]; @@ -301,10 +301,10 @@ pub fn create_struct_pattern(cx: @ExtCtxt, cx.span_bug(span, "A struct with named and unnamed fields in `deriving`"); } }; - let path = build::mk_raw_path(span, + let path = cx.mk_raw_path(span, ~[ cx.ident_of(fmt!("%s_%u", prefix, i)) ]); paths.push(path); - ident_expr.push((opt_id, build::mk_path_raw(cx, span, path))); + ident_expr.push((opt_id, cx.mk_path_raw(span, path))); } let subpats = create_subpatterns(cx, span, paths, mutbl); @@ -318,9 +318,9 @@ pub fn create_struct_pattern(cx: @ExtCtxt, push(ast::field_pat { ident: id.get(), pat: pat }) } }; - build::mk_pat_struct(cx, span, matching_path, field_pats) + cx.mk_pat_struct(span, matching_path, field_pats) } else { - build::mk_pat_enum(cx, span, matching_path, subpats) + cx.mk_pat_enum(span, matching_path, subpats) }; (pattern, ident_expr) @@ -337,24 +337,24 @@ pub fn create_enum_variant_pattern(cx: @ExtCtxt, match variant.node.kind { ast::tuple_variant_kind(ref variant_args) => { if variant_args.is_empty() { - return (build::mk_pat_ident_with_binding_mode( - cx, span, variant_ident, ast::bind_infer), ~[]); + return (cx.mk_pat_ident_with_binding_mode( + span, variant_ident, ast::bind_infer), ~[]); } - let matching_path = build::mk_raw_path(span, ~[ variant_ident ]); + let matching_path = cx.mk_raw_path(span, ~[ variant_ident ]); let mut paths = ~[], ident_expr = ~[]; for uint::range(0, variant_args.len()) |i| { - let path = build::mk_raw_path(span, + let path = cx.mk_raw_path(span, ~[ cx.ident_of(fmt!("%s_%u", prefix, i)) ]); paths.push(path); - ident_expr.push((None, build::mk_path_raw(cx, span, path))); + ident_expr.push((None, cx.mk_path_raw(span, path))); } let subpats = create_subpatterns(cx, span, paths, mutbl); - (build::mk_pat_enum(cx, span, matching_path, subpats), + (cx.mk_pat_enum(span, matching_path, subpats), ident_expr) } ast::struct_variant_kind(struct_def) => { @@ -377,8 +377,8 @@ pub fn expand_enum_or_struct_match(cx: @ExtCtxt, span: span, arms: ~[ ast::arm ]) -> @expr { - let self_expr = build::make_self(cx, span); - let self_expr = build::mk_unary(cx, span, ast::deref, self_expr); + let self_expr = cx.make_self(span); + let self_expr = cx.mk_unary(span, ast::deref, self_expr); let self_match_expr = ast::expr_match(self_expr, arms); - build::mk_expr(cx, span, self_match_expr) + cx.mk_expr(span, self_match_expr) } diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index 64cf7e93b92e8..b8e9de22fb0ef 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -12,7 +12,7 @@ use ast; use ast::{meta_item, item, expr, ident}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; +use ext::build::{AstBuilder, Duplicate, Field}; use ext::deriving::generic::*; pub fn expand_deriving_rand(cx: @ExtCtxt, @@ -59,10 +59,10 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cx.ident_of("rand") ]; let rand_call = || { - build::mk_call_global(cx, + cx.mk_call_global( span, copy rand_ident, - ~[ build::duplicate_expr(cx, rng[0]) ]) + ~[ rng[0].duplicate(cx) ]) }; return match *substr.fields { @@ -74,30 +74,30 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cx.span_fatal(span, "`Rand` cannot be derived for enums with no variants"); } - let variant_count = build::mk_uint(cx, span, variants.len()); + let variant_count = cx.mk_uint(span, variants.len()); // need to specify the uint-ness of the random number - let u32_ty = build::mk_ty_path(cx, span, ~[cx.ident_of("uint")]); - let r_ty = build::mk_ty_path(cx, span, ~[cx.ident_of("R")]); - let rand_name = build::mk_raw_path_(span, copy rand_ident, None, ~[ u32_ty, r_ty ]); - let rand_name = build::mk_path_raw(cx, span, rand_name); + let u32_ty = cx.mk_ty_path(span, ~[cx.ident_of("uint")]); + let r_ty = cx.mk_ty_path(span, ~[cx.ident_of("R")]); + let rand_name = cx.mk_raw_path_(span, copy rand_ident, None, ~[ u32_ty, r_ty ]); + let rand_name = cx.mk_path_raw(span, rand_name); - let rv_call = build::mk_call_(cx, + let rv_call = cx.mk_call_( span, rand_name, - ~[ build::duplicate_expr(cx, rng[0]) ]); + ~[ rng[0].duplicate(cx) ]); // rand() % variants.len() - let rand_variant = build::mk_binary(cx, span, ast::rem, + let rand_variant = cx.mk_binary(span, ast::rem, rv_call, variant_count); let mut arms = do variants.mapi |i, id_sum| { - let i_expr = build::mk_uint(cx, span, i); - let pat = build::mk_pat_lit(cx, span, i_expr); + let i_expr = cx.mk_uint(span, i); + let pat = cx.mk_pat_lit(span, i_expr); match *id_sum { (ident, ref summary) => { - build::mk_arm(cx, span, + cx.mk_arm(span, ~[ pat ], rand_thing(cx, span, ident, summary, rand_call)) } @@ -105,9 +105,9 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { }; // _ => {} at the end. Should never occur - arms.push(build::mk_unreachable_arm(cx, span)); + arms.push(cx.mk_unreachable_arm(span)); - build::mk_expr(cx, span, + cx.mk_expr(span, ast::expr_match(rand_variant, arms)) } _ => cx.bug("Non-static method in `deriving(Rand)`") @@ -121,20 +121,20 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { match *summary { Left(copy count) => { if count == 0 { - build::mk_path(cx, span, ctor_ident) + cx.mk_path(span, ctor_ident) } else { let exprs = vec::from_fn(count, |_| rand_call()); - build::mk_call(cx, span, ctor_ident, exprs) + cx.mk_call(span, ctor_ident, exprs) } } Right(ref fields) => { let rand_fields = do fields.map |ident| { - build::Field { + Field { ident: *ident, ex: rand_call() } }; - build::mk_struct_e(cx, span, ctor_ident, rand_fields) + cx.mk_struct_e(span, ctor_ident, rand_fields) } } } diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs index 19fd601186b1e..9198c67177e53 100644 --- a/src/libsyntax/ext/deriving/to_str.rs +++ b/src/libsyntax/ext/deriving/to_str.rs @@ -11,7 +11,7 @@ use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use ext::deriving::generic::*; pub fn expand_deriving_to_str(cx: @ExtCtxt, @@ -42,8 +42,8 @@ pub fn expand_deriving_to_str(cx: @ExtCtxt, fn to_str_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { match substr.self_args { [self_obj] => { - let self_addr = build::mk_addr_of(cx, span, self_obj); - build::mk_call_global(cx, span, + let self_addr = cx.mk_addr_of(span, self_obj); + cx.mk_call_global(span, ~[cx.ident_of("core"), cx.ident_of("sys"), cx.ident_of("log_str")], diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index 154e7647bb560..a9d13bfe79c48 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -16,7 +16,7 @@ explicit `Self` type to use when specifying impls to be derived. use ast; use ast::{expr,Generics,ident}; use ext::base::ExtCtxt; -use ext::build; +use ext::build::AstBuilder; use codemap::{span,respan}; use opt_vec; @@ -55,7 +55,7 @@ pub impl<'self> Path<'self> { fn to_ty(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Ty { - build::mk_ty_path_path(cx, span, + cx.mk_ty_path_path(span, self.to_path(cx, span, self_ty, self_generics)) } @@ -66,9 +66,9 @@ pub impl<'self> Path<'self> { let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics)); if self.global { - build::mk_raw_path_global_(span, idents, lt, tys) + cx.mk_raw_path_global_(span, idents, lt, tys) } else { - build::mk_raw_path_(span, idents, lt, tys) + cx.mk_raw_path_(span, idents, lt, tys) } } } @@ -106,7 +106,7 @@ pub fn nil_ty() -> Ty<'static> { fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<@ast::Lifetime> { match *lt { - Some(ref s) => Some(@build::mk_lifetime(cx, span, cx.ident_of(*s))), + Some(ref s) => Some(@cx.mk_lifetime(span, cx.ident_of(*s))), None => None } } @@ -119,20 +119,20 @@ pub impl<'self> Ty<'self> { let raw_ty = ty.to_ty(cx, span, self_ty, self_generics); match *ptr { Owned => { - build::mk_ty_uniq(cx, span, raw_ty) + cx.mk_ty_uniq(span, raw_ty) } Managed(mutbl) => { - build::mk_ty_box(cx, span, raw_ty, mutbl) + cx.mk_ty_box(span, raw_ty, mutbl) } Borrowed(ref lt, mutbl) => { let lt = mk_lifetime(cx, span, lt); - build::mk_ty_rptr(cx, span, raw_ty, lt, mutbl) + cx.mk_ty_rptr(span, raw_ty, lt, mutbl) } } } Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) } Self => { - build::mk_ty_path_path(cx, span, self.to_path(cx, span, self_ty, self_generics)) + cx.mk_ty_path_path(span, self.to_path(cx, span, self_ty, self_generics)) } Tuple(ref fields) => { let ty = if fields.is_empty() { @@ -141,7 +141,7 @@ pub impl<'self> Ty<'self> { ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics))) }; - build::mk_ty(cx, span, ty) + cx.mk_ty(span, ty) } } } @@ -151,7 +151,7 @@ pub impl<'self> Ty<'self> { match *self { Self => { let self_params = do self_generics.ty_params.map |ty_param| { - build::mk_ty_path(cx, span, ~[ ty_param.ident ]) + cx.mk_ty_path(span, ~[ ty_param.ident ]) }; let lifetime = if self_generics.lifetimes.is_empty() { None @@ -159,7 +159,7 @@ pub impl<'self> Ty<'self> { Some(@*self_generics.lifetimes.get(0)) }; - build::mk_raw_path_(span, ~[self_ty], lifetime, + cx.mk_raw_path_(span, ~[self_ty], lifetime, opt_vec::take_vec(self_params)) } Literal(ref p) => { @@ -177,9 +177,9 @@ fn mk_ty_param(cx: @ExtCtxt, span: span, name: &str, bounds: &[Path], let bounds = opt_vec::from( do bounds.map |b| { let path = b.to_path(cx, span, self_ident, self_generics); - build::mk_trait_ty_param_bound_(cx, path) + cx.mk_trait_ty_param_bound_(path) }); - build::mk_ty_param(cx, cx.ident_of(name), @bounds) + cx.mk_ty_param(cx.ident_of(name), @bounds) } fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics { @@ -204,7 +204,7 @@ pub impl<'self> LifetimeBounds<'self> { fn to_generics(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> Generics { let lifetimes = do self.lifetimes.map |lt| { - build::mk_lifetime(cx, span, cx.ident_of(*lt)) + cx.mk_lifetime(span, cx.ident_of(*lt)) }; let ty_params = do self.bounds.map |t| { match t { @@ -220,7 +220,7 @@ pub impl<'self> LifetimeBounds<'self> { pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option) -> (@expr, ast::explicit_self) { - let self_path = build::make_self(cx, span); + let self_path = cx.make_self(span); match *self_ptr { None => { (self_path, respan(span, ast::sty_value)) @@ -232,12 +232,12 @@ pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option) Owned => ast::sty_uniq(ast::m_imm), Managed(mutbl) => ast::sty_box(mutbl), Borrowed(ref lt, mutbl) => { - let lt = lt.map(|s| @build::mk_lifetime(cx, span, + let lt = lt.map(|s| @cx.mk_lifetime(span, cx.ident_of(*s))); ast::sty_region(lt, mutbl) } }); - let self_expr = build::mk_deref(cx, span, self_path); + let self_expr = cx.mk_deref(span, self_path); (self_expr, self_ty) } } diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 3d74595e645ae..fb7367b47bafc 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -18,7 +18,7 @@ use ast; use codemap::span; use ext::base::*; use ext::base; -use ext::build::mk_base_str; +use ext::build::AstBuilder; pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { @@ -29,8 +29,8 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) // Option rather than just an maybe-empty string. let e = match os::getenv(var) { - None => mk_base_str(cx, sp, ~""), - Some(ref s) => mk_base_str(cx, sp, copy *s) + None => cx.mk_base_str(sp, ~""), + Some(ref s) => cx.mk_base_str(sp, copy *s) }; MRExpr(e) } diff --git a/src/libsyntax/ext/fmt.rs b/src/libsyntax/ext/fmt.rs index ca281a22e3922..1e4ff03b610c8 100644 --- a/src/libsyntax/ext/fmt.rs +++ b/src/libsyntax/ext/fmt.rs @@ -19,7 +19,7 @@ use codemap::span; use ext::base::*; use ext::base; use ext::build; -use ext::build::*; +use ext::build::AstBuilder; use core::unstable::extfmt::ct::*; @@ -56,7 +56,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, } fn make_rt_path_expr(cx: @ExtCtxt, sp: span, nm: &str) -> @ast::expr { let path = make_path_vec(cx, nm); - return mk_path_global(cx, sp, path); + cx.mk_path_global(sp, path) } // Produces an AST expression that represents a RT::conv record, // which tells the RT::conv* functions how to perform the conversion @@ -72,7 +72,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, FlagSignAlways => "flag_sign_always", FlagAlternate => "flag_alternate" }; - tmp_expr = mk_binary(cx, sp, ast::bitor, tmp_expr, + tmp_expr = cx.mk_binary(sp, ast::bitor, tmp_expr, make_rt_path_expr(cx, sp, fstr)); } return tmp_expr; @@ -83,10 +83,10 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, return make_rt_path_expr(cx, sp, "CountImplied"); } CountIs(c) => { - let count_lit = mk_uint(cx, sp, c as uint); + let count_lit = cx.mk_uint(sp, c as uint); let count_is_path = make_path_vec(cx, "CountIs"); let count_is_args = ~[count_lit]; - return mk_call_global(cx, sp, count_is_path, count_is_args); + return cx.mk_call_global(sp, count_is_path, count_is_args); } _ => cx.span_unimpl(sp, "unimplemented fmt! conversion") } @@ -107,8 +107,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, width_expr: @ast::expr, precision_expr: @ast::expr, ty_expr: @ast::expr) -> @ast::expr { let intr = cx.parse_sess().interner; - mk_global_struct_e( - cx, + cx.mk_global_struct_e( sp, make_path_vec(cx, "Conv"), ~[ @@ -140,7 +139,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, let path = make_path_vec(cx, fname); let cnv_expr = make_rt_conv_expr(cx, sp, cnv); let args = ~[cnv_expr, arg, buf]; - return mk_call_global(cx, arg.span, path, args); + cx.mk_call_global(arg.span, path, args) } fn make_new_conv(cx: @ExtCtxt, sp: span, cnv: &Conv, @@ -198,10 +197,10 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, TyChar => ("char", arg), TyBits | TyOctal | TyHex(_) | TyInt(Unsigned) => ("uint", arg), TyFloat => ("float", arg), - TyPoly => ("poly", mk_addr_of(cx, sp, arg)) + TyPoly => ("poly", cx.mk_addr_of(sp, arg)) }; return make_conv_call(cx, arg.span, name, cnv, actual_arg, - mk_mut_addr_of(cx, arg.span, buf)); + cx.mk_mut_addr_of(arg.span, buf)); } fn log_conv(c: &Conv) { debug!("Building conversion:"); @@ -259,7 +258,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, /* 'ident' is the local buffer building up the result of fmt! */ let ident = cx.parse_sess().interner.intern("__fmtbuf"); - let buf = || mk_path(cx, fmt_sp, ~[ident]); + let buf = || cx.mk_path(fmt_sp, ~[ident]); let str_ident = cx.parse_sess().interner.intern("str"); let push_ident = cx.parse_sess().interner.intern("push_str"); let mut stms = ~[]; @@ -276,14 +275,14 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, buffer with it directly. If it's actually the only piece, then there's no need for it to be mutable */ if i == 0 { - stms.push(mk_local(cx, fmt_sp, npieces > 1, ident, mk_uniq_str(cx, fmt_sp, s))); + stms.push(cx.mk_local(fmt_sp, npieces > 1, ident, cx.mk_uniq_str(fmt_sp, s))); } else { - let args = ~[mk_mut_addr_of(cx, fmt_sp, buf()), mk_base_str(cx, fmt_sp, s)]; - let call = mk_call_global(cx, + let args = ~[cx.mk_mut_addr_of(fmt_sp, buf()), cx.mk_base_str(fmt_sp, s)]; + let call = cx.mk_call_global( fmt_sp, ~[str_ident, push_ident], args); - stms.push(mk_stmt(cx, fmt_sp, call)); + stms.push(cx.mk_stmt(fmt_sp, call)); } } @@ -300,12 +299,12 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, /* If the first portion is a conversion, then the local buffer must be initialized as an empty string */ if i == 0 { - stms.push(mk_local(cx, fmt_sp, true, ident, - mk_uniq_str(cx, fmt_sp, ~""))); + stms.push(cx.mk_local(fmt_sp, true, ident, + cx.mk_uniq_str(fmt_sp, ~""))); } - stms.push(mk_stmt(cx, fmt_sp, - make_new_conv(cx, fmt_sp, conv, - args[n], buf()))); + stms.push(cx.mk_stmt(fmt_sp, + make_new_conv(cx, fmt_sp, conv, + args[n], buf()))); } } } @@ -317,5 +316,5 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, nargs, expected_nargs)); } - return mk_block(cx, fmt_sp, ~[], stms, Some(buf())); + cx.mk_block(fmt_sp, ~[], stms, Some(buf())) } diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 2ccceeec294fc..5ab28b50e841c 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -12,7 +12,7 @@ use ast; use codemap::{BytePos, Pos, span}; use ext::base::ExtCtxt; use ext::base; -use ext::build; +use ext::build::AstBuilder; use parse::token::*; use parse::token; use parse; @@ -382,7 +382,7 @@ pub fn expand_quote_expr(cx: @ExtCtxt, pub fn expand_quote_item(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_attrs = build::mk_uniq_vec_e(cx, sp, ~[]); + let e_attrs = cx.mk_uniq_vec_e(sp, ~[]); base::MRExpr(expand_parse_call(cx, sp, "parse_item", ~[e_attrs], tts)) } @@ -390,7 +390,7 @@ pub fn expand_quote_item(cx: @ExtCtxt, pub fn expand_quote_pat(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_refutable = build::mk_lit(cx, sp, ast::lit_bool(true)); + let e_refutable = cx.mk_lit(sp, ast::lit_bool(true)); base::MRExpr(expand_parse_call(cx, sp, "parse_pat", ~[e_refutable], tts)) } @@ -398,7 +398,7 @@ pub fn expand_quote_pat(cx: @ExtCtxt, pub fn expand_quote_ty(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_param_colons = build::mk_lit(cx, sp, ast::lit_bool(false)); + let e_param_colons = cx.mk_lit(sp, ast::lit_bool(false)); base::MRExpr(expand_parse_call(cx, sp, "parse_ty", ~[e_param_colons], tts)) } @@ -406,7 +406,7 @@ pub fn expand_quote_ty(cx: @ExtCtxt, pub fn expand_quote_stmt(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_attrs = build::mk_uniq_vec_e(cx, sp, ~[]); + let e_attrs = cx.mk_uniq_vec_e(sp, ~[]); base::MRExpr(expand_parse_call(cx, sp, "parse_stmt", ~[e_attrs], tts)) } @@ -421,17 +421,17 @@ fn id_ext(cx: @ExtCtxt, str: &str) -> ast::ident { // Lift an ident to the expr that evaluates to that ident. fn mk_ident(cx: @ExtCtxt, sp: span, ident: ast::ident) -> @ast::expr { - let e_str = build::mk_base_str(cx, sp, cx.str_of(ident)); - build::mk_method_call(cx, sp, - build::mk_path(cx, sp, ids_ext(cx, ~[~"ext_cx"])), - id_ext(cx, "ident_of"), - ~[e_str]) + let e_str = cx.mk_base_str(sp, cx.str_of(ident)); + cx.mk_method_call(sp, + cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), + id_ext(cx, "ident_of"), + ~[e_str]) } fn mk_bytepos(cx: @ExtCtxt, sp: span, bpos: BytePos) -> @ast::expr { let path = ids_ext(cx, ~[~"BytePos"]); - let arg = build::mk_uint(cx, sp, bpos.to_uint()); - build::mk_call(cx, sp, path, ~[arg]) + let arg = cx.mk_uint(sp, bpos.to_uint()); + cx.mk_call(sp, path, ~[arg]) } fn mk_binop(cx: @ExtCtxt, sp: span, bop: token::binop) -> @ast::expr { @@ -447,7 +447,7 @@ fn mk_binop(cx: @ExtCtxt, sp: span, bop: token::binop) -> @ast::expr { SHL => "SHL", SHR => "SHR" }; - build::mk_path(cx, sp, + cx.mk_path(sp, ids_ext(cx, ~[name.to_owned()])) } @@ -455,12 +455,12 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { match *tok { BINOP(binop) => { - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"BINOP"]), ~[mk_binop(cx, sp, binop)]); } BINOPEQ(binop) => { - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"BINOPEQ"]), ~[mk_binop(cx, sp, binop)]); } @@ -475,12 +475,12 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { ast::ty_i64 => ~"ty_i64" }; let e_ity = - build::mk_path(cx, sp, + cx.mk_path(sp, ids_ext(cx, ~[s_ity])); - let e_i64 = build::mk_lit(cx, sp, ast::lit_int(i, ast::ty_i64)); + let e_i64 = cx.mk_lit(sp, ast::lit_int(i, ast::ty_i64)); - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"LIT_INT"]), ~[e_i64, e_ity]); } @@ -494,21 +494,21 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { ast::ty_u64 => ~"ty_u64" }; let e_uty = - build::mk_path(cx, sp, + cx.mk_path(sp, ids_ext(cx, ~[s_uty])); - let e_u64 = build::mk_lit(cx, sp, ast::lit_uint(u, ast::ty_u64)); + let e_u64 = cx.mk_lit(sp, ast::lit_uint(u, ast::ty_u64)); - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"LIT_UINT"]), ~[e_u64, e_uty]); } LIT_INT_UNSUFFIXED(i) => { - let e_i64 = build::mk_lit(cx, sp, + let e_i64 = cx.mk_lit(sp, ast::lit_int(i, ast::ty_i64)); - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"LIT_INT_UNSUFFIXED"]), ~[e_i64]); } @@ -520,37 +520,37 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { ast::ty_f64 => ~"ty_f64" }; let e_fty = - build::mk_path(cx, sp, + cx.mk_path(sp, ids_ext(cx, ~[s_fty])); let e_fident = mk_ident(cx, sp, fident); - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"LIT_FLOAT"]), ~[e_fident, e_fty]); } LIT_STR(ident) => { - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"LIT_STR"]), ~[mk_ident(cx, sp, ident)]); } IDENT(ident, b) => { - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"IDENT"]), ~[mk_ident(cx, sp, ident), - build::mk_lit(cx, sp, ast::lit_bool(b))]); + cx.mk_lit(sp, ast::lit_bool(b))]); } LIFETIME(ident) => { - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"LIFETIME"]), ~[mk_ident(cx, sp, ident)]); } DOC_COMMENT(ident) => { - return build::mk_call(cx, sp, + return cx.mk_call(sp, ids_ext(cx, ~[~"DOC_COMMENT"]), ~[mk_ident(cx, sp, ident)]); } @@ -595,7 +595,7 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { EOF => "EOF", _ => fail!() }; - build::mk_path(cx, sp, + cx.mk_path(sp, ids_ext(cx, ~[name.to_owned()])) } @@ -606,18 +606,18 @@ fn mk_tt(cx: @ExtCtxt, sp: span, tt: &ast::token_tree) match *tt { ast::tt_tok(sp, ref tok) => { - let e_sp = build::mk_path(cx, sp, + let e_sp = cx.mk_path(sp, ids_ext(cx, ~[~"sp"])); let e_tok = - build::mk_call(cx, sp, + cx.mk_call(sp, ids_ext(cx, ~[~"tt_tok"]), ~[e_sp, mk_token(cx, sp, tok)]); let e_push = - build::mk_method_call(cx, sp, - build::mk_path(cx, sp, ids_ext(cx, ~[~"tt"])), + cx.mk_method_call(sp, + cx.mk_path(sp, ids_ext(cx, ~[~"tt"])), id_ext(cx, "push"), ~[e_tok]); - ~[build::mk_stmt(cx, sp, e_push)] + ~[cx.mk_stmt(sp, e_push)] } @@ -629,19 +629,19 @@ fn mk_tt(cx: @ExtCtxt, sp: span, tt: &ast::token_tree) // tt.push_all_move($ident.to_tokens(ext_cx)) let e_to_toks = - build::mk_method_call(cx, sp, - build::mk_path(cx, sp, ~[ident]), + cx.mk_method_call(sp, + cx.mk_path(sp, ~[ident]), id_ext(cx, "to_tokens"), - ~[build::mk_path(cx, sp, + ~[cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"]))]); let e_push = - build::mk_method_call(cx, sp, - build::mk_path(cx, sp, ids_ext(cx, ~[~"tt"])), + cx.mk_method_call(sp, + cx.mk_path(sp, ids_ext(cx, ~[~"tt"])), id_ext(cx, "push_all_move"), ~[e_to_toks]); - ~[build::mk_stmt(cx, sp, e_push)] + ~[cx.mk_stmt(sp, e_push)] } } } @@ -677,11 +677,11 @@ fn expand_tts(cx: @ExtCtxt, // We want to emit a block expression that does a sequence of 'use's to // import the runtime module, followed by a tt-building expression. - let uses = ~[ build::mk_glob_use(cx, sp, ast::public, - ids_ext(cx, ~[~"syntax", - ~"ext", - ~"quote", - ~"rt"])) ]; + let uses = ~[ cx.mk_glob_use(sp, ast::public, + ids_ext(cx, ~[~"syntax", + ~"ext", + ~"quote", + ~"rt"])) ]; // We also bind a single value, sp, to ext_cx.call_site() // @@ -709,23 +709,23 @@ fn expand_tts(cx: @ExtCtxt, // of quotes, for example) but at this point it seems not likely to be // worth the hassle. - let e_sp = build::mk_method_call(cx, sp, - build::mk_path(cx, sp, ids_ext(cx, ~[~"ext_cx"])), + let e_sp = cx.mk_method_call(sp, + cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), id_ext(cx, "call_site"), ~[]); - let stmt_let_sp = build::mk_local(cx, sp, false, + let stmt_let_sp = cx.mk_local(sp, false, id_ext(cx, "sp"), e_sp); - let stmt_let_tt = build::mk_local(cx, sp, true, + let stmt_let_tt = cx.mk_local(sp, true, id_ext(cx, "tt"), - build::mk_uniq_vec_e(cx, sp, ~[])); + cx.mk_uniq_vec_e(sp, ~[])); - build::mk_block(cx, sp, uses, + cx.mk_block(sp, uses, ~[stmt_let_sp, stmt_let_tt] + mk_tts(cx, sp, tts), - Some(build::mk_path(cx, sp, + Some(cx.mk_path(sp, ids_ext(cx, ~[~"tt"])))) } @@ -736,16 +736,16 @@ fn expand_parse_call(cx: @ExtCtxt, tts: &[ast::token_tree]) -> @ast::expr { let tts_expr = expand_tts(cx, sp, tts); - let cfg_call = || build::mk_method_call( - cx, sp, build::mk_path(cx, sp, ids_ext(cx, ~[~"ext_cx"])), + let cfg_call = || cx.mk_method_call( + sp, cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), id_ext(cx, "cfg"), ~[]); - let parse_sess_call = || build::mk_method_call( - cx, sp, build::mk_path(cx, sp, ids_ext(cx, ~[~"ext_cx"])), + let parse_sess_call = || cx.mk_method_call( + sp, cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), id_ext(cx, "parse_sess"), ~[]); let new_parser_call = - build::mk_call_global(cx, sp, + cx.mk_call_global(sp, ids_ext(cx, ~[~"syntax", ~"ext", ~"quote", @@ -755,7 +755,7 @@ fn expand_parse_call(cx: @ExtCtxt, cfg_call(), tts_expr]); - build::mk_method_call(cx, sp, + cx.mk_method_call(sp, new_parser_call, id_ext(cx, parse_method), arg_exprs) diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index d78c06bec0774..40dc44ca99326 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -14,7 +14,7 @@ use codemap::{FileMap, Loc, Pos, ExpandedFrom, span}; use codemap::{CallInfo, NameAndSpan}; use ext::base::*; use ext::base; -use ext::build::{mk_base_vec_e, mk_uint, mk_u8, mk_base_str}; +use ext::build::AstBuilder; use parse; use print::pprust; @@ -30,7 +30,7 @@ pub fn expand_line(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) let topmost = topmost_expn_info(cx.backtrace().get()); let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); - base::MRExpr(mk_uint(cx, topmost.call_site, loc.line)) + base::MRExpr(cx.mk_uint(topmost.call_site, loc.line)) } /* col!(): expands to the current column number */ @@ -40,7 +40,7 @@ pub fn expand_col(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) let topmost = topmost_expn_info(cx.backtrace().get()); let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); - base::MRExpr(mk_uint(cx, topmost.call_site, loc.col.to_uint())) + base::MRExpr(cx.mk_uint(topmost.call_site, loc.col.to_uint())) } /* file!(): expands to the current filename */ @@ -53,19 +53,19 @@ pub fn expand_file(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) let topmost = topmost_expn_info(cx.backtrace().get()); let Loc { file: @FileMap { name: filename, _ }, _ } = cx.codemap().lookup_char_pos(topmost.call_site.lo); - base::MRExpr(mk_base_str(cx, topmost.call_site, filename)) + base::MRExpr(cx.mk_base_str(topmost.call_site, filename)) } pub fn expand_stringify(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let s = pprust::tts_to_str(tts, cx.parse_sess().interner); - base::MRExpr(mk_base_str(cx, sp, s)) + base::MRExpr(cx.mk_base_str(sp, s)) } pub fn expand_mod(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::check_zero_tts(cx, sp, tts, "module_path!"); - base::MRExpr(mk_base_str(cx, sp, + base::MRExpr(cx.mk_base_str(sp, str::connect(cx.mod_path().map( |x| cx.str_of(*x)), "::"))) } @@ -94,7 +94,7 @@ pub fn expand_include_str(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) } } - base::MRExpr(mk_base_str(cx, sp, result::unwrap(res))) + base::MRExpr(cx.mk_base_str(sp, result::unwrap(res))) } pub fn expand_include_bin(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) @@ -103,9 +103,9 @@ pub fn expand_include_bin(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) match io::read_whole_file(&res_rel_file(cx, sp, &Path(file))) { result::Ok(src) => { let u8_exprs = vec::map(src, |char| { - mk_u8(cx, sp, *char) + cx.mk_u8(sp, *char) }); - base::MRExpr(mk_base_vec_e(cx, sp, u8_exprs)) + base::MRExpr(cx.mk_base_vec_e(sp, u8_exprs)) } result::Err(ref e) => { cx.parse_sess().span_diagnostic.handler().fatal((*e)) From a59bec43e34715880f471db7d7c9d57939649d92 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sun, 19 May 2013 15:53:42 +1000 Subject: [PATCH 161/248] syntax/ext: convert all AstBuilder methods to a uniform syntax. --- src/libsyntax/ext/build.rs | 1562 +++++++------------- src/libsyntax/ext/bytes.rs | 10 +- src/libsyntax/ext/deriving/clone.rs | 17 +- src/libsyntax/ext/deriving/cmp/eq.rs | 4 +- src/libsyntax/ext/deriving/cmp/ord.rs | 29 +- src/libsyntax/ext/deriving/cmp/totaleq.rs | 2 +- src/libsyntax/ext/deriving/cmp/totalord.rs | 19 +- src/libsyntax/ext/deriving/decodable.rs | 204 +-- src/libsyntax/ext/deriving/encodable.rs | 165 +-- src/libsyntax/ext/deriving/generic.rs | 52 +- src/libsyntax/ext/deriving/iter_bytes.rs | 6 +- src/libsyntax/ext/deriving/mod.rs | 102 +- src/libsyntax/ext/deriving/rand.rs | 55 +- src/libsyntax/ext/deriving/to_str.rs | 12 +- src/libsyntax/ext/deriving/ty.rs | 43 +- src/libsyntax/ext/env.rs | 4 +- src/libsyntax/ext/fmt.rs | 64 +- src/libsyntax/ext/pipes/ast_builder.rs | 2 +- src/libsyntax/ext/pipes/pipec.rs | 90 +- src/libsyntax/ext/quote.rs | 226 ++- src/libsyntax/ext/source_util.rs | 16 +- 21 files changed, 998 insertions(+), 1686 deletions(-) diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index eb48ed583750d..01a504101b914 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -12,8 +12,7 @@ use abi::AbiSet; use ast::ident; use ast; use ast_util; -use codemap; -use codemap::{span, respan, dummy_sp, spanned}; +use codemap::{span, respan, dummy_sp}; use fold; use ext::base::ExtCtxt; use ext::quote::rt::*; @@ -34,442 +33,291 @@ mod syntax { pub trait AstBuilder { // paths fn path(&self, span: span, strs: ~[ast::ident]) -> @ast::Path; + fn path_ident(&self, span: span, id: ast::ident) -> @ast::Path; fn path_global(&self, span: span, strs: ~[ast::ident]) -> @ast::Path; - fn path_tps(&self, span: span, strs: ~[ast::ident], tps: ~[@ast::Ty]) - -> @ast::Path; - fn path_tps_global(&self, - span: span, - strs: ~[ast::ident], - tps: ~[@ast::Ty]) + fn path_all(&self, sp: span, + global: bool, + idents: ~[ast::ident], + rp: Option<@ast::Lifetime>, + types: ~[@ast::Ty]) -> @ast::Path; // types + fn ty_mt(&self, ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt; + + fn ty(&self, span: span, ty: ast::ty_) -> @ast::Ty; fn ty_path(&self, @ast::Path) -> @ast::Ty; + fn ty_ident(&self, span: span, idents: ast::ident) -> @ast::Ty; + + fn ty_rptr(&self, span: span, + ty: @ast::Ty, + lifetime: Option<@ast::Lifetime>, + mutbl: ast::mutability) + -> @ast::Ty; + fn ty_uniq(&self, span: span, ty: @ast::Ty) -> @ast::Ty; + fn ty_box(&self, span: span, ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty; + + fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty; + fn ty_infer(&self, sp: span) -> @ast::Ty; + fn ty_nil(&self) -> @ast::Ty; - fn ty_param(&self, id: ast::ident, bounds: @OptVec) - -> ast::TyParam; fn ty_vars(&self, ty_params: &OptVec) -> ~[@ast::Ty]; fn ty_vars_global(&self, ty_params: &OptVec) -> ~[@ast::Ty]; - fn ty_field_imm(&self, name: ident, ty: @ast::Ty) -> ast::ty_field; - fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty; - fn ty_infer(&self) -> @ast::Ty; - fn ty_nil_ast_builder(&self) -> @ast::Ty; + fn ty_field_imm(&self, span: span, name: ident, ty: @ast::Ty) -> ast::ty_field; fn strip_bounds(&self, bounds: &Generics) -> Generics; + fn typaram(&self, id: ast::ident, bounds: @OptVec) -> ast::TyParam; + + fn trait_ref(&self, path: @ast::Path) -> @ast::trait_ref; + fn typarambound(&self, path: @ast::Path) -> ast::TyParamBound; + fn lifetime(&self, span: span, ident: ast::ident) -> ast::Lifetime; // statements fn stmt_expr(&self, expr: @ast::expr) -> @ast::stmt; - fn stmt_let(&self, ident: ident, e: @ast::expr) -> @ast::stmt; - - // literals - fn lit_str(&self, span: span, s: @~str) -> @ast::expr; - fn lit_uint(&self, span: span, i: uint) -> @ast::expr; + fn stmt_let(&self, sp: span, mutbl: bool, ident: ast::ident, ex: @ast::expr) -> @ast::stmt; // blocks fn blk(&self, span: span, stmts: ~[@ast::stmt], expr: Option<@ast::expr>) -> ast::blk; fn blk_expr(&self, expr: @ast::expr) -> ast::blk; + fn blk_all(&self, span: span, + view_items: ~[@ast::view_item], + stmts: ~[@ast::stmt], + expr: Option<@ast::expr>) -> ast::blk; // expressions fn expr(&self, span: span, node: ast::expr_) -> @ast::expr; - fn expr_path(&self, span: span, strs: ~[ast::ident]) -> @ast::expr; - fn expr_path_global(&self, span: span, strs: ~[ast::ident]) -> @ast::expr; - fn expr_var(&self, span: span, var: &str) -> @ast::expr; + fn expr_path(&self, path: @ast::Path) -> @ast::expr; + fn expr_ident(&self, span: span, id: ast::ident) -> @ast::expr; + fn expr_self(&self, span: span) -> @ast::expr; - fn expr_field(&self, span: span, expr: @ast::expr, ident: ast::ident) - -> @ast::expr; - fn expr_call(&self, span: span, expr: @ast::expr, args: ~[@ast::expr]) - -> @ast::expr; - fn expr_method_call(&self, - span: span, - expr: @ast::expr, - ident: ast::ident, - args: ~[@ast::expr]) - -> @ast::expr; + fn expr_binary(&self, sp: span, op: ast::binop, + lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr; + fn expr_deref(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn expr_unary(&self, sp: span, op: ast::unop, e: @ast::expr) -> @ast::expr; + + fn expr_copy(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn expr_managed(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn expr_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn expr_mut_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr; + fn expr_field_access(&self, span: span, expr: @ast::expr, ident: ast::ident) -> @ast::expr; + fn expr_call(&self, span: span, expr: @ast::expr, args: ~[@ast::expr]) -> @ast::expr; + fn expr_call_ident(&self, span: span, id: ast::ident, args: ~[@ast::expr]) -> @ast::expr; + fn expr_call_global(&self, sp: span, fn_path: ~[ast::ident], + args: ~[@ast::expr]) -> @ast::expr; + fn expr_method_call(&self, span: span, + expr: @ast::expr, ident: ast::ident, + args: ~[@ast::expr]) -> @ast::expr; fn expr_blk(&self, b: ast::blk) -> @ast::expr; - fn field_imm(&self, name: ident, e: @ast::expr) -> ast::field; - fn expr_struct(&self, - path: @ast::Path, - fields: ~[ast::field]) -> @ast::expr; - fn lambda0(&self, blk: ast::blk) -> @ast::expr; - fn lambda1(&self, blk: ast::blk, ident: ast::ident) -> @ast::expr; - fn lambda_expr_0(&self, expr: @ast::expr) -> @ast::expr; - fn lambda_expr_1(&self, expr: @ast::expr, ident: ast::ident) - -> @ast::expr; + + fn field_imm(&self, span: span, name: ident, e: @ast::expr) -> ast::field; + fn expr_struct(&self, span: span, path: @ast::Path, fields: ~[ast::field]) -> @ast::expr; + fn expr_struct_ident(&self, span: span, id: ast::ident, fields: ~[ast::field]) -> @ast::expr; + + fn expr_lit(&self, sp: span, lit: ast::lit_) -> @ast::expr; + + fn expr_uint(&self, span: span, i: uint) -> @ast::expr; + fn expr_int(&self, sp: span, i: int) -> @ast::expr; + fn expr_u8(&self, sp: span, u: u8) -> @ast::expr; + fn expr_bool(&self, sp: span, value: bool) -> @ast::expr; + + fn expr_vstore(&self, sp: span, expr: @ast::expr, vst: ast::expr_vstore) -> @ast::expr; + fn expr_vec(&self, sp: span, exprs: ~[@ast::expr]) -> @ast::expr; + fn expr_vec_uniq(&self, sp: span, exprs: ~[@ast::expr]) -> @ast::expr; + fn expr_vec_slice(&self, sp: span, exprs: ~[@ast::expr]) -> @ast::expr; + fn expr_str(&self, sp: span, s: ~str) -> @ast::expr; + fn expr_str_uniq(&self, sp: span, s: ~str) -> @ast::expr; + + fn expr_unreachable(&self, span: span) -> @ast::expr; + + fn pat(&self, span: span, pat: ast::pat_) -> @ast::pat; + fn pat_wild(&self, span: span) -> @ast::pat; + fn pat_lit(&self, span: span, expr: @ast::expr) -> @ast::pat; + fn pat_ident(&self, span: span, ident: ast::ident) -> @ast::pat; + + fn pat_ident_binding_mode(&self, + span: span, + ident: ast::ident, + bm: ast::binding_mode) -> @ast::pat; + fn pat_enum(&self, span: span, path: @ast::Path, subpats: ~[@ast::pat]) -> @ast::pat; + fn pat_struct(&self, span: span, + path: @ast::Path, field_pats: ~[ast::field_pat]) -> @ast::pat; + + fn arm(&self, span: span, pats: ~[@ast::pat], expr: @ast::expr) -> ast::arm; + fn arm_unreachable(&self, span: span) -> ast::arm; + + fn expr_match(&self, span: span, arg: @ast::expr, arms: ~[ast::arm]) -> @ast::expr; + fn expr_if(&self, span: span, + cond: @ast::expr, then: @ast::expr, els: Option<@ast::expr>) -> @ast::expr; + + fn lambda_fn_decl(&self, span: span, fn_decl: ast::fn_decl, blk: ast::blk) -> @ast::expr; + + fn lambda(&self, span: span, ids: ~[ast::ident], blk: ast::blk) -> @ast::expr; + fn lambda0(&self, span: span, blk: ast::blk) -> @ast::expr; + fn lambda1(&self, span: span, blk: ast::blk, ident: ast::ident) -> @ast::expr; + + fn lambda_expr(&self, span: span, ids: ~[ast::ident], blk: @ast::expr) -> @ast::expr; + fn lambda_expr_0(&self, span: span, expr: @ast::expr) -> @ast::expr; + fn lambda_expr_1(&self, span: span, expr: @ast::expr, ident: ast::ident) -> @ast::expr; + + fn lambda_stmts(&self, span: span, ids: ~[ast::ident], blk: ~[@ast::stmt]) -> @ast::expr; fn lambda_stmts_0(&self, span: span, stmts: ~[@ast::stmt]) -> @ast::expr; - fn lambda_stmts_1(&self, - span: span, - stmts: ~[@ast::stmt], - ident: ast::ident) - -> @ast::expr; + fn lambda_stmts_1(&self, span: span, stmts: ~[@ast::stmt], ident: ast::ident) -> @ast::expr; // items - fn item(&self, name: ident, span: span, node: ast::item_) -> @ast::item; + fn item(&self, span: span, + name: ident, attrs: ~[ast::attribute], node: ast::item_) -> @ast::item; - fn arg(&self, name: ident, ty: @ast::Ty) -> ast::arg; + fn arg(&self, span: span, name: ident, ty: @ast::Ty) -> ast::arg; + // XXX unused self fn fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl; fn item_fn_poly(&self, - ame: ident, + span: span, + name: ident, inputs: ~[ast::arg], output: @ast::Ty, generics: Generics, body: ast::blk) -> @ast::item; fn item_fn(&self, + span: span, name: ident, inputs: ~[ast::arg], output: @ast::Ty, body: ast::blk) -> @ast::item; - fn variant(&self, - name: ident, - span: span, - tys: ~[@ast::Ty]) -> ast::variant; + fn variant(&self, span: span, name: ident, tys: ~[@ast::Ty]) -> ast::variant; fn item_enum_poly(&self, - name: ident, span: span, + name: ident, enum_definition: ast::enum_def, generics: Generics) -> @ast::item; - fn item_enum(&self, - name: ident, - span: span, - enum_definition: ast::enum_def) -> @ast::item; + fn item_enum(&self, span: span, name: ident, enum_def: ast::enum_def) -> @ast::item; fn item_struct_poly(&self, - name: ident, span: span, + name: ident, struct_def: ast::struct_def, generics: Generics) -> @ast::item; - fn item_struct(&self, - name: ident, - span: span, - struct_def: ast::struct_def) -> @ast::item; + fn item_struct(&self, span: span, name: ident, struct_def: ast::struct_def) -> @ast::item; - fn item_mod(&self, - name: ident, - span: span, - items: ~[@ast::item]) -> @ast::item; + fn item_mod(&self, span: span, + name: ident, attrs: ~[ast::attribute], + vi: ~[@ast::view_item], items: ~[@ast::item]) -> @ast::item; fn item_ty_poly(&self, - name: ident, span: span, + name: ident, ty: @ast::Ty, generics: Generics) -> @ast::item; - fn item_ty(&self, name: ident, span: span, ty: @ast::Ty) -> @ast::item; - - - - - fn mk_expr(&self, - sp: codemap::span, - expr: ast::expr_) - -> @ast::expr; - - fn mk_lit(&self, sp: span, lit: ast::lit_) -> @ast::expr; - fn mk_int(&self, sp: span, i: int) -> @ast::expr; - fn mk_uint(&self, sp: span, u: uint) -> @ast::expr; - fn mk_u8(&self, sp: span, u: u8) -> @ast::expr; - fn mk_binary(&self, sp: span, op: ast::binop, - lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr; - - fn mk_deref(&self, sp: span, e: @ast::expr) -> @ast::expr; - fn mk_unary(&self, sp: span, op: ast::unop, e: @ast::expr) - -> @ast::expr; - // XXX: unused self - fn mk_raw_path(&self, sp: span, idents: ~[ast::ident]) -> @ast::Path; - // XXX: unused self - fn mk_raw_path_(&self, sp: span, - idents: ~[ast::ident], - rp: Option<@ast::Lifetime>, - types: ~[@ast::Ty]) - -> @ast::Path; - // XXX: unused self - fn mk_raw_path_global(&self, sp: span,idents: ~[ast::ident]) -> @ast::Path; - // XXX: unused self - fn mk_raw_path_global_(&self, sp: span, - idents: ~[ast::ident], - rp: Option<@ast::Lifetime>, - types: ~[@ast::Ty]) -> @ast::Path; - fn mk_path_raw(&self, sp: span, path: @ast::Path)-> @ast::expr; - fn mk_path(&self, sp: span, idents: ~[ast::ident]) - -> @ast::expr; - fn mk_path_global(&self, sp: span, idents: ~[ast::ident]) - -> @ast::expr; - fn mk_access_(&self, sp: span, p: @ast::expr, m: ast::ident) - -> @ast::expr; - fn mk_access(&self, sp: span, p: ~[ast::ident], m: ast::ident) - -> @ast::expr; - fn mk_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr; - fn mk_mut_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr; - fn mk_method_call(&self, - sp: span, - rcvr_expr: @ast::expr, - method_ident: ast::ident, - args: ~[@ast::expr]) -> @ast::expr; - fn mk_call_(&self, sp: span, fn_expr: @ast::expr, - args: ~[@ast::expr]) -> @ast::expr; - fn mk_call(&self, sp: span, fn_path: ~[ast::ident], - args: ~[@ast::expr]) -> @ast::expr; - fn mk_call_global(&self, sp: span, fn_path: ~[ast::ident], - args: ~[@ast::expr]) -> @ast::expr; - // e = expr, t = type - fn mk_base_vec_e(&self, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr; - fn mk_vstore_e(&self, sp: span, expr: @ast::expr, - vst: ast::expr_vstore) -> - @ast::expr; - fn mk_uniq_vec_e(&self, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr; - fn mk_slice_vec_e(&self, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr; - fn mk_base_str(&self, sp: span, s: ~str) -> @ast::expr; - fn mk_uniq_str(&self, sp: span, s: ~str) -> @ast::expr; - // XXX: unused self - fn mk_field(&self, sp: span, f: &Field) -> ast::field; - // XXX: unused self - fn mk_fields(&self, sp: span, fields: ~[Field]) -> ~[ast::field]; - fn mk_struct_e(&self, - sp: span, - ctor_path: ~[ast::ident], - fields: ~[Field]) - -> @ast::expr; - fn mk_global_struct_e(&self, - sp: span, - ctor_path: ~[ast::ident], - fields: ~[Field]) - -> @ast::expr; - fn mk_glob_use(&self, - sp: span, - vis: ast::visibility, - path: ~[ast::ident]) -> @ast::view_item; - fn mk_local(&self, sp: span, mutbl: bool, - ident: ast::ident, ex: @ast::expr) -> @ast::stmt; - fn mk_block(&self, span: span, - view_items: ~[@ast::view_item], - stmts: ~[@ast::stmt], - expr: Option<@ast::expr>) -> @ast::expr; - fn mk_block_(&self, - span: span, - stmts: ~[@ast::stmt]) - -> ast::blk; - fn mk_simple_block(&self, - span: span, - expr: @ast::expr) - -> ast::blk; - fn mk_lambda_(&self, - span: span, - fn_decl: ast::fn_decl, - blk: ast::blk) - -> @ast::expr; - fn mk_lambda(&self, - span: span, - fn_decl: ast::fn_decl, - expr: @ast::expr) - -> @ast::expr; - fn mk_lambda_stmts(&self, - span: span, - fn_decl: ast::fn_decl, - stmts: ~[@ast::stmt]) - -> @ast::expr ; - fn mk_lambda_no_args(&self, - span: span, - expr: @ast::expr) - -> @ast::expr; - fn mk_copy(&self, sp: span, e: @ast::expr) -> @ast::expr; - fn mk_managed(&self, sp: span, e: @ast::expr) -> @ast::expr; - fn mk_pat(&self, span: span, pat: ast::pat_) -> @ast::pat; - fn mk_pat_wild(&self, span: span) -> @ast::pat; - fn mk_pat_lit(&self, - span: span, - expr: @ast::expr) -> @ast::pat; - fn mk_pat_ident(&self, - span: span, - ident: ast::ident) -> @ast::pat; - - fn mk_pat_ident_with_binding_mode(&self, - span: span, - ident: ast::ident, - bm: ast::binding_mode) -> @ast::pat; - fn mk_pat_enum(&self, - span: span, - path: @ast::Path, - subpats: ~[@ast::pat]) - -> @ast::pat; - fn mk_pat_struct(&self, - span: span, - path: @ast::Path, - field_pats: ~[ast::field_pat]) - -> @ast::pat; - fn mk_bool(&self, span: span, value: bool) -> @ast::expr; - fn mk_stmt(&self, span: span, expr: @ast::expr) -> @ast::stmt; - - // XXX: unused self - fn mk_ty_mt(&self, ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt; - - fn mk_ty(&self, - span: span, - ty: ast::ty_) -> @ast::Ty; - - fn mk_ty_path(&self, - span: span, - idents: ~[ ast::ident ]) - -> @ast::Ty; - - fn mk_ty_path_global(&self, - span: span, - idents: ~[ ast::ident ]) - -> @ast::Ty; - - fn mk_ty_path_path(&self, - span: span, - path: @ast::Path) - -> @ast::Ty; + fn item_ty(&self, span: span, name: ident, ty: @ast::Ty) -> @ast::item; - fn mk_ty_rptr(&self, - span: span, - ty: @ast::Ty, - lifetime: Option<@ast::Lifetime>, - mutbl: ast::mutability) - -> @ast::Ty; - fn mk_ty_uniq(&self, span: span, ty: @ast::Ty) -> @ast::Ty; - fn mk_ty_box(&self, span: span, - ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty; + fn attribute(&self, sp: span, mi: @ast::meta_item) -> ast::attribute; + fn meta_word(&self, sp: span, w: ~str) -> @ast::meta_item; + fn meta_list(&self, sp: span, name: ~str, mis: ~[@ast::meta_item]) -> @ast::meta_item; + fn meta_name_value(&self, sp: span, name: ~str, value: ast::lit_) -> @ast::meta_item; - - fn mk_ty_infer(&self, span: span) -> @ast::Ty; - fn mk_trait_ref_global(&self, - span: span, - idents: ~[ ast::ident ]) - -> @ast::trait_ref; - fn mk_trait_ref_(&self, path: @ast::Path) -> @ast::trait_ref; - fn mk_simple_ty_path(&self, - span: span, - ident: ast::ident) - -> @ast::Ty; - fn mk_arg(&self, - span: span, - ident: ast::ident, - ty: @ast::Ty) - -> ast::arg; - // XXX unused self - fn mk_fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl; - fn mk_trait_ty_param_bound_global(&self, - span: span, - idents: ~[ast::ident]) - -> ast::TyParamBound; - fn mk_trait_ty_param_bound_(&self, - path: @ast::Path) -> ast::TyParamBound; - fn mk_ty_param(&self, - ident: ast::ident, - bounds: @OptVec) - -> ast::TyParam; - fn mk_lifetime(&self, - span: span, - ident: ast::ident) - -> ast::Lifetime; - fn mk_arm(&self, - span: span, - pats: ~[@ast::pat], - expr: @ast::expr) - -> ast::arm; - fn mk_unreachable(&self, span: span) -> @ast::expr; - fn mk_unreachable_arm(&self, span: span) -> ast::arm; - - fn make_self(&self, span: span) -> @ast::expr; + fn view_use(&self, sp: span, + vis: ast::visibility, vp: ~[@ast::view_path]) -> @ast::view_item; + fn view_use_list(&self, sp: span, vis: ast::visibility, + path: ~[ast::ident], imports: &[ast::ident]) -> @ast::view_item; + fn view_use_glob(&self, sp: span, + vis: ast::visibility, path: ~[ast::ident]) -> @ast::view_item; } impl AstBuilder for @ExtCtxt { fn path(&self, span: span, strs: ~[ast::ident]) -> @ast::Path { - @ast::Path { - span: span, - global: false, - idents: strs, - rp: None, - types: ~[] - } + self.path_all(span, false, strs, None, ~[]) + } + fn path_ident(&self, span: span, id: ast::ident) -> @ast::Path { + self.path(span, ~[id]) } - fn path_global(&self, span: span, strs: ~[ast::ident]) -> @ast::Path { + self.path_all(span, true, strs, None, ~[]) + } + fn path_all(&self, sp: span, + global: bool, + idents: ~[ast::ident], + rp: Option<@ast::Lifetime>, + types: ~[@ast::Ty]) + -> @ast::Path { @ast::Path { - span: span, - global: true, - idents: strs, - rp: None, - types: ~[] + span: sp, + global: global, + idents: idents, + rp: rp, + types: types } } - fn path_tps( - &self, - span: span, - strs: ~[ast::ident], - tps: ~[@ast::Ty] - ) -> @ast::Path { - @ast::Path { - span: span, - global: false, - idents: strs, - rp: None, - types: tps + fn ty_mt(&self, ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt { + ast::mt { + ty: ty, + mutbl: mutbl } } - fn path_tps_global( - &self, - span: span, - strs: ~[ast::ident], - tps: ~[@ast::Ty] - ) -> @ast::Path { - @ast::Path { + fn ty(&self, span: span, ty: ast::ty_) -> @ast::Ty { + @ast::Ty { + id: self.next_id(), span: span, - global: true, - idents: strs, - rp: None, - types: tps + node: ty } } fn ty_path(&self, path: @ast::Path) -> @ast::Ty { - self.mk_ty(path.span, - ast::ty_path(path, self.next_id())) + self.ty(path.span, + ast::ty_path(path, self.next_id())) + } + + fn ty_ident(&self, span: span, ident: ast::ident) + -> @ast::Ty { + self.ty_path(self.path_ident(span, ident)) + } + + fn ty_rptr(&self, + span: span, + ty: @ast::Ty, + lifetime: Option<@ast::Lifetime>, + mutbl: ast::mutability) + -> @ast::Ty { + self.ty(span, + ast::ty_rptr(lifetime, self.ty_mt(ty, mutbl))) + } + fn ty_uniq(&self, span: span, ty: @ast::Ty) -> @ast::Ty { + self.ty(span, ast::ty_uniq(self.ty_mt(ty, ast::m_imm))) + } + fn ty_box(&self, span: span, + ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty { + self.ty(span, ast::ty_box(self.ty_mt(ty, mutbl))) } fn ty_option(&self, ty: @ast::Ty) -> @ast::Ty { self.ty_path( - self.path_tps_global(dummy_sp(), - ~[ - self.ident_of("core"), - self.ident_of("option"), - self.ident_of("Option") - ], - ~[ ty ])) - } - - fn ty_field_imm(&self, name: ident, ty: @ast::Ty) -> ast::ty_field { - spanned { - node: ast::ty_field_ { - ident: name, - mt: ast::mt { ty: ty, mutbl: ast::m_imm }, - }, - span: dummy_sp(), - } + self.path_all(dummy_sp(), + true, + ~[ + self.ident_of("core"), + self.ident_of("option"), + self.ident_of("Option") + ], + None, + ~[ ty ])) } - fn ty_infer(&self) -> @ast::Ty { - @ast::Ty { - id: self.next_id(), - node: ast::ty_infer, - span: dummy_sp(), - } + fn ty_field_imm(&self, span: span, name: ident, ty: @ast::Ty) -> ast::ty_field { + respan(span, + ast::ty_field_ { + ident: name, + mt: ast::mt { ty: ty, mutbl: ast::m_imm }, + }) } - fn ty_param(&self, id: ast::ident, bounds: @OptVec) - -> ast::TyParam - { - ast::TyParam { ident: id, id: self.next_id(), bounds: bounds } + fn ty_infer(&self, span: span) -> @ast::Ty { + self.ty(span, ast::ty_infer) } - fn ty_nil_ast_builder(&self) -> @ast::Ty { + fn ty_nil(&self) -> @ast::Ty { @ast::Ty { id: self.next_id(), node: ast::ty_nil, @@ -477,17 +325,22 @@ impl AstBuilder for @ExtCtxt { } } + fn typaram(&self, id: ast::ident, bounds: @OptVec) -> ast::TyParam { + ast::TyParam { ident: id, id: self.next_id(), bounds: bounds } + } + + // these are strange, and probably shouldn't be used outside of + // pipes. Specifically, the global version possible generates + // incorrect code. fn ty_vars(&self, ty_params: &OptVec) -> ~[@ast::Ty] { opt_vec::take_vec( - ty_params.map(|p| self.ty_path( - self.mk_raw_path(dummy_sp(), ~[p.ident])))) + ty_params.map(|p| self.ty_ident(dummy_sp(), p.ident))) } - fn ty_vars_global(&self, - ty_params: &OptVec) -> ~[@ast::Ty] { + fn ty_vars_global(&self, ty_params: &OptVec) -> ~[@ast::Ty] { opt_vec::take_vec( ty_params.map(|p| self.ty_path( - self.mk_raw_path(dummy_sp(), ~[p.ident])))) + self.path_global(dummy_sp(), ~[p.ident])))) } fn strip_bounds(&self, generics: &Generics) -> Generics { @@ -501,52 +354,59 @@ impl AstBuilder for @ExtCtxt { } } + fn trait_ref(&self, path: @ast::Path) -> @ast::trait_ref { + @ast::trait_ref { + path: path, + ref_id: self.next_id() + } + } - fn stmt_expr(&self, expr: @ast::expr) -> @ast::stmt { - @codemap::spanned { node: ast::stmt_semi(expr, self.next_id()), - span: expr.span } + fn typarambound(&self, path: @ast::Path) -> ast::TyParamBound { + ast::TraitTyParamBound(self.trait_ref(path)) } - fn stmt_let(&self, ident: ident, e: @ast::expr) -> @ast::stmt { - let ext_cx = *self; - quote_stmt!( let $ident = $e; ) + fn lifetime(&self, span: span, ident: ast::ident) -> ast::Lifetime { + ast::Lifetime { id: self.next_id(), span: span, ident: ident } } - fn lit_str(&self, span: span, s: @~str) -> @ast::expr { - self.expr( - span, - ast::expr_vstore( - self.expr( - span, - ast::expr_lit( - @codemap::spanned { node: ast::lit_str(s), - span: span})), - ast::expr_vstore_uniq)) + fn stmt_expr(&self, expr: @ast::expr) -> @ast::stmt { + @respan(expr.span, ast::stmt_semi(expr, self.next_id())) } - fn lit_uint(&self, span: span, i: uint) -> @ast::expr { - self.expr( - span, - ast::expr_lit( - @codemap::spanned { node: ast::lit_uint(i as u64, ast::ty_u), - span: span})) + fn stmt_let(&self, sp: span, mutbl: bool, ident: ast::ident, ex: @ast::expr) -> @ast::stmt { + let pat = self.pat_ident(sp, ident); + let local = @respan(sp, + ast::local_ { + is_mutbl: mutbl, + ty: self.ty_infer(sp), + pat: pat, + init: Some(ex), + id: self.next_id(), + }); + let decl = respan(sp, ast::decl_local(~[local])); + @respan(sp, ast::stmt_decl(@decl, self.next_id())) } fn blk(&self, span: span, stmts: ~[@ast::stmt], expr: Option<@expr>) -> ast::blk { - codemap::spanned { - node: ast::blk_ { - view_items: ~[], - stmts: stmts, - expr: expr, - id: self.next_id(), - rules: ast::default_blk, - }, - span: span, - } + self.blk_all(span, ~[], stmts, expr) } fn blk_expr(&self, expr: @ast::expr) -> ast::blk { - self.blk(expr.span, ~[], Some(expr)) + self.blk_all(expr.span, ~[], ~[], Some(expr)) + } + fn blk_all(&self, + span: span, + view_items: ~[@ast::view_item], + stmts: ~[@ast::stmt], + expr: Option<@ast::expr>) -> ast::blk { + respan(span, + ast::blk_ { + view_items: view_items, + stmts: stmts, + expr: expr, + id: self.next_id(), + rules: ast::default_blk, + }) } fn expr(&self, span: span, node: ast::expr_) -> @ast::expr { @@ -558,126 +418,243 @@ impl AstBuilder for @ExtCtxt { } } - fn expr_path(&self, span: span, strs: ~[ast::ident]) -> @ast::expr { - self.expr(span, ast::expr_path(self.path(span, strs))) + fn expr_path(&self, path: @ast::Path) -> @ast::expr { + self.expr(path.span, ast::expr_path(path)) } - fn expr_path_global( - &self, - span: span, - strs: ~[ast::ident] - ) -> @ast::expr { - self.expr(span, ast::expr_path(self.path_global(span, strs))) + fn expr_ident(&self, span: span, id: ast::ident) -> @ast::expr { + self.expr_path(self.path_ident(span, id)) + } + fn expr_self(&self, span: span) -> @ast::expr { + self.expr(span, ast::expr_self) } - fn expr_var(&self, span: span, var: &str) -> @ast::expr { - self.expr_path(span, ~[self.ident_of(var)]) + fn expr_binary(&self, sp: span, op: ast::binop, + lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr { + self.next_id(); // see ast_util::op_expr_callee_id + self.expr(sp, ast::expr_binary(op, lhs, rhs)) } - fn expr_self(&self, span: span) -> @ast::expr { - self.expr(span, ast::expr_self) + fn expr_deref(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.expr_unary(sp, ast::deref, e) + } + fn expr_unary(&self, sp: span, op: ast::unop, e: @ast::expr) + -> @ast::expr { + self.next_id(); // see ast_util::op_expr_callee_id + self.expr(sp, ast::expr_unary(op, e)) } - fn expr_field( - &self, - span: span, - expr: @ast::expr, - ident: ast::ident - ) -> @ast::expr { - self.expr(span, ast::expr_field(expr, ident, ~[])) + fn expr_copy(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.expr(sp, ast::expr_copy(e)) + } + fn expr_managed(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.expr_unary(sp, ast::box(ast::m_imm), e) } - fn expr_call( - &self, - span: span, - expr: @ast::expr, - args: ~[@ast::expr] - ) -> @ast::expr { - self.expr(span, ast::expr_call(expr, args, ast::NoSugar)) + fn expr_field_access(&self, sp: span, expr: @ast::expr, ident: ast::ident) -> @ast::expr { + self.expr(sp, ast::expr_field(expr, ident, ~[])) + } + fn expr_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.expr(sp, ast::expr_addr_of(ast::m_imm, e)) + } + fn expr_mut_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr { + self.expr(sp, ast::expr_addr_of(ast::m_mutbl, e)) } - fn expr_method_call( - &self, - span: span, - expr: @ast::expr, - ident: ast::ident, - args: ~[@ast::expr] - ) -> @ast::expr { + fn expr_call(&self, span: span, expr: @ast::expr, args: ~[@ast::expr]) -> @ast::expr { + self.expr(span, ast::expr_call(expr, args, ast::NoSugar)) + } + fn expr_call_ident(&self, span: span, id: ast::ident, args: ~[@ast::expr]) -> @ast::expr { + self.expr(span, + ast::expr_call(self.expr_ident(span, id), args, ast::NoSugar)) + } + fn expr_call_global(&self, sp: span, fn_path: ~[ast::ident], + args: ~[@ast::expr]) -> @ast::expr { + let pathexpr = self.expr_path(self.path_global(sp, fn_path)); + self.expr_call(sp, pathexpr, args) + } + fn expr_method_call(&self, span: span, + expr: @ast::expr, + ident: ast::ident, + args: ~[@ast::expr]) -> @ast::expr { self.expr(span, ast::expr_method_call(expr, ident, ~[], args, ast::NoSugar)) } fn expr_blk(&self, b: ast::blk) -> @ast::expr { - self.expr(dummy_sp(), ast::expr_block(b)) + self.expr(b.span, ast::expr_block(b)) } - fn field_imm(&self, name: ident, e: @ast::expr) -> ast::field { - spanned { - node: ast::field_ { mutbl: ast::m_imm, ident: name, expr: e }, - span: dummy_sp(), - } + fn field_imm(&self, span: span, name: ident, e: @ast::expr) -> ast::field { + respan(span, ast::field_ { mutbl: ast::m_imm, ident: name, expr: e }) } - fn expr_struct(&self, path: @ast::Path, - fields: ~[ast::field]) -> @ast::expr { - @ast::expr { - id: self.next_id(), - callee_id: self.next_id(), - node: ast::expr_struct(path, fields, None), - span: dummy_sp() + fn expr_struct(&self, span: span, path: @ast::Path, fields: ~[ast::field]) -> @ast::expr { + self.expr(span, ast::expr_struct(path, fields, None)) + } + fn expr_struct_ident(&self, span: span, + id: ast::ident, fields: ~[ast::field]) -> @ast::expr { + self.expr_struct(span, self.path_ident(span, id), fields) + } + + fn expr_lit(&self, sp: span, lit: ast::lit_) -> @ast::expr { + self.expr(sp, ast::expr_lit(@respan(sp, lit))) + } + fn expr_uint(&self, span: span, i: uint) -> @ast::expr { + self.expr_lit(span, ast::lit_uint(i as u64, ast::ty_u)) + } + fn expr_int(&self, sp: span, i: int) -> @ast::expr { + self.expr_lit(sp, ast::lit_int(i as i64, ast::ty_i)) + } + fn expr_u8(&self, sp: span, u: u8) -> @ast::expr { + self.expr_lit(sp, ast::lit_uint(u as u64, ast::ty_u8)) + } + fn expr_bool(&self, sp: span, value: bool) -> @ast::expr { + self.expr_lit(sp, ast::lit_bool(value)) + } + + fn expr_vstore(&self, sp: span, expr: @ast::expr, vst: ast::expr_vstore) -> @ast::expr { + self.expr(sp, ast::expr_vstore(expr, vst)) + } + fn expr_vec(&self, sp: span, exprs: ~[@ast::expr]) -> @ast::expr { + self.expr(sp, ast::expr_vec(exprs, ast::m_imm)) + } + fn expr_vec_uniq(&self, sp: span, exprs: ~[@ast::expr]) -> @ast::expr { + self.expr_vstore(sp, self.expr_vec(sp, exprs), ast::expr_vstore_uniq) + } + fn expr_vec_slice(&self, sp: span, exprs: ~[@ast::expr]) -> @ast::expr { + self.expr_vstore(sp, self.expr_vec(sp, exprs), ast::expr_vstore_slice) + } + fn expr_str(&self, sp: span, s: ~str) -> @ast::expr { + self.expr_lit(sp, ast::lit_str(@s)) + } + fn expr_str_uniq(&self, sp: span, s: ~str) -> @ast::expr { + self.expr_vstore(sp, self.expr_str(sp, s), ast::expr_vstore_uniq) + } + + + fn expr_unreachable(&self, span: span) -> @ast::expr { + let loc = self.codemap().lookup_char_pos(span.lo); + self.expr_call_global( + span, + ~[ + self.ident_of("core"), + self.ident_of("sys"), + self.ident_of("FailWithCause"), + self.ident_of("fail_with"), + ], + ~[ + self.expr_str(span, ~"internal error: entered unreachable code"), + self.expr_str(span, copy loc.file.name), + self.expr_uint(span, loc.line), + ]) + } + + + fn pat(&self, span: span, pat: ast::pat_) -> @ast::pat { + @ast::pat { id: self.next_id(), node: pat, span: span } + } + fn pat_wild(&self, span: span) -> @ast::pat { + self.pat(span, ast::pat_wild) + } + fn pat_lit(&self, span: span, expr: @ast::expr) -> @ast::pat { + self.pat(span, ast::pat_lit(expr)) + } + fn pat_ident(&self, span: span, ident: ast::ident) -> @ast::pat { + self.pat_ident_binding_mode(span, ident, ast::bind_by_copy) + } + + fn pat_ident_binding_mode(&self, + span: span, + ident: ast::ident, + bm: ast::binding_mode) -> @ast::pat { + let path = self.path_ident(span, ident); + let pat = ast::pat_ident(bm, path, None); + self.pat(span, pat) + } + fn pat_enum(&self, span: span, path: @ast::Path, subpats: ~[@ast::pat]) -> @ast::pat { + let pat = ast::pat_enum(path, Some(subpats)); + self.pat(span, pat) + } + fn pat_struct(&self, span: span, + path: @ast::Path, field_pats: ~[ast::field_pat]) -> @ast::pat { + let pat = ast::pat_struct(path, field_pats, false); + self.pat(span, pat) + } + + fn arm(&self, _span: span, pats: ~[@ast::pat], expr: @ast::expr) -> ast::arm { + ast::arm { + pats: pats, + guard: None, + body: self.blk_expr(expr) } } + fn arm_unreachable(&self, span: span) -> ast::arm { + self.arm(span, ~[self.pat_wild(span)], self.expr_unreachable(span)) + } + + fn expr_match(&self, span: span, arg: @ast::expr, arms: ~[ast::arm]) -> @expr { + self.expr(span, ast::expr_match(arg, arms)) + } - fn lambda0(&self, blk: ast::blk) -> @ast::expr { + fn expr_if(&self, span: span, + cond: @ast::expr, then: @ast::expr, els: Option<@ast::expr>) -> @ast::expr { + let els = els.map(|x| self.expr_blk(self.blk_expr(*x))); + self.expr(span, ast::expr_if(cond, self.blk_expr(then), els)) + } + + fn lambda_fn_decl(&self, span: span, fn_decl: ast::fn_decl, blk: ast::blk) -> @ast::expr { + self.expr(span, ast::expr_fn_block(fn_decl, blk)) + } + fn lambda(&self, span: span, ids: ~[ast::ident], blk: ast::blk) -> @ast::expr { + let fn_decl = self.fn_decl( + ids.map(|id| self.arg(span, *id, self.ty_infer(span))), + self.ty_infer(span)); + + self.expr(span, ast::expr_fn_block(fn_decl, blk)) + } + fn lambda0(&self, _span: span, blk: ast::blk) -> @ast::expr { let ext_cx = *self; let blk_e = self.expr(copy blk.span, ast::expr_block(copy blk)); - quote_expr!( || $blk_e ) + quote_expr!(|| $blk_e ) } - fn lambda1(&self, blk: ast::blk, ident: ast::ident) -> @ast::expr { + fn lambda1(&self, _span: span, blk: ast::blk, ident: ast::ident) -> @ast::expr { let ext_cx = *self; let blk_e = self.expr(copy blk.span, ast::expr_block(copy blk)); - quote_expr!( |$ident| $blk_e ) + quote_expr!(|$ident| $blk_e ) } - fn lambda_expr_0(&self, expr: @ast::expr) -> @ast::expr { - self.lambda0(self.blk_expr(expr)) + fn lambda_expr(&self, span: span, ids: ~[ast::ident], expr: @ast::expr) -> @ast::expr { + self.lambda(span, ids, self.blk_expr(expr)) } - - fn lambda_expr_1(&self, expr: @ast::expr, ident: ast::ident) - -> @ast::expr { - self.lambda1(self.blk_expr(expr), ident) + fn lambda_expr_0(&self, span: span, expr: @ast::expr) -> @ast::expr { + self.lambda0(span, self.blk_expr(expr)) + } + fn lambda_expr_1(&self, span: span, expr: @ast::expr, ident: ast::ident) -> @ast::expr { + self.lambda1(span, self.blk_expr(expr), ident) } + fn lambda_stmts(&self, span: span, ids: ~[ast::ident], stmts: ~[@ast::stmt]) -> @ast::expr { + self.lambda(span, ids, self.blk(span, stmts, None)) + } fn lambda_stmts_0(&self, span: span, stmts: ~[@ast::stmt]) -> @ast::expr { - self.lambda0(self.blk(span, stmts, None)) + self.lambda0(span, self.blk(span, stmts, None)) } - - fn lambda_stmts_1(&self, - span: span, - stmts: ~[@ast::stmt], - ident: ast::ident) - -> @ast::expr { - self.lambda1(self.blk(span, stmts, None), ident) + fn lambda_stmts_1(&self, span: span, stmts: ~[@ast::stmt], ident: ast::ident) -> @ast::expr { + self.lambda1(span, self.blk(span, stmts, None), ident) } - - fn arg(&self, name: ident, ty: @ast::Ty) -> ast::arg { + fn arg(&self, span: span, ident: ast::ident, ty: @ast::Ty) -> ast::arg { + let arg_pat = self.pat_ident(span, ident); ast::arg { is_mutbl: false, ty: ty, - pat: @ast::pat { - id: self.next_id(), - node: ast::pat_ident( - ast::bind_by_copy, - ast_util::ident_to_path(dummy_sp(), name), - None), - span: dummy_sp(), - }, - id: self.next_id(), + pat: arg_pat, + id: self.next_id() } } - fn fn_decl(&self, inputs: ~[ast::arg], - output: @ast::Ty) -> ast::fn_decl { + // XXX unused self + fn fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl { ast::fn_decl { inputs: inputs, output: output, @@ -685,37 +662,28 @@ impl AstBuilder for @ExtCtxt { } } - fn item(&self, name: ident, span: span, - node: ast::item_) -> @ast::item { - + fn item(&self, span: span, + name: ident, attrs: ~[ast::attribute], node: ast::item_) -> @ast::item { // XXX: Would be nice if our generated code didn't violate // Rust coding conventions - let non_camel_case_attribute = respan(dummy_sp(), ast::attribute_ { - style: ast::attr_outer, - value: @respan(dummy_sp(), - ast::meta_list(@~"allow", ~[ - @respan(dummy_sp(), - ast::meta_word( - @~"non_camel_case_types")) - ])), - is_sugared_doc: false - }); - @ast::item { ident: name, - attrs: ~[non_camel_case_attribute], + attrs: attrs, id: self.next_id(), node: node, vis: ast::public, span: span } } - fn item_fn_poly(&self, name: ident, + fn item_fn_poly(&self, + span: span, + name: ident, inputs: ~[ast::arg], output: @ast::Ty, generics: Generics, body: ast::blk) -> @ast::item { - self.item(name, - dummy_sp(), + self.item(span, + name, + ~[], ast::item_fn(self.fn_decl(inputs, output), ast::impure_fn, AbiSet::Rust(), @@ -724,59 +692,58 @@ impl AstBuilder for @ExtCtxt { } fn item_fn(&self, + span: span, name: ident, inputs: ~[ast::arg], output: @ast::Ty, body: ast::blk ) -> @ast::item { self.item_fn_poly( + span, name, inputs, output, ast_util::empty_generics(), - body - ) + body) } - fn variant(&self, name: ident, span: span, - tys: ~[@ast::Ty]) -> ast::variant { + fn variant(&self, span: span, name: ident, tys: ~[@ast::Ty]) -> ast::variant { let args = do tys.map |ty| { ast::variant_arg { ty: *ty, id: self.next_id() } }; - spanned { - node: ast::variant_ { - name: name, - attrs: ~[], - kind: ast::tuple_variant_kind(args), - id: self.next_id(), - disr_expr: None, - vis: ast::public - }, - span: span, - } + respan(span, + ast::variant_ { + name: name, + attrs: ~[], + kind: ast::tuple_variant_kind(args), + id: self.next_id(), + disr_expr: None, + vis: ast::public + }) } - fn item_enum_poly(&self, name: ident, span: span, + fn item_enum_poly(&self, span: span, name: ident, enum_definition: ast::enum_def, generics: Generics) -> @ast::item { - self.item(name, span, ast::item_enum(enum_definition, generics)) + self.item(span, name, ~[], ast::item_enum(enum_definition, generics)) } - fn item_enum(&self, name: ident, span: span, + fn item_enum(&self, span: span, name: ident, enum_definition: ast::enum_def) -> @ast::item { - self.item_enum_poly(name, span, enum_definition, + self.item_enum_poly(span, name, enum_definition, ast_util::empty_generics()) } fn item_struct( - &self, name: ident, + &self, span: span, + name: ident, struct_def: ast::struct_def ) -> @ast::item { self.item_struct_poly( - name, span, + name, struct_def, ast_util::empty_generics() ) @@ -784,574 +751,85 @@ impl AstBuilder for @ExtCtxt { fn item_struct_poly( &self, - name: ident, span: span, + name: ident, struct_def: ast::struct_def, generics: Generics ) -> @ast::item { - self.item(name, span, ast::item_struct(@struct_def, generics)) + self.item(span, name, ~[], ast::item_struct(@struct_def, generics)) } - fn item_mod(&self, name: ident, span: span, + fn item_mod(&self, span: span, name: ident, + attrs: ~[ast::attribute], + vi: ~[@ast::view_item], items: ~[@ast::item]) -> @ast::item { - - // XXX: Total hack: import `core::kinds::Owned` to work around a - // parser bug whereby `fn f` doesn't parse. - let vi = ast::view_item_use(~[ - @codemap::spanned { - node: ast::view_path_simple( - self.ident_of("Owned"), - self.mk_raw_path( - codemap::dummy_sp(), - ~[ - self.ident_of("core"), - self.ident_of("kinds"), - self.ident_of("Owned") - ] - ), - self.next_id() - ), - span: codemap::dummy_sp() - } - ]); - let vi = @ast::view_item { - node: vi, - attrs: ~[], - vis: ast::private, - span: codemap::dummy_sp() - }; - self.item( - name, span, + name, + attrs, ast::item_mod(ast::_mod { - view_items: ~[vi], + view_items: vi, items: items, }) ) } - fn item_ty_poly(&self, name: ident, span: span, ty: @ast::Ty, + fn item_ty_poly(&self, span: span, name: ident, ty: @ast::Ty, generics: Generics) -> @ast::item { - self.item(name, span, ast::item_ty(ty, generics)) + self.item(span, name, ~[], ast::item_ty(ty, generics)) } - fn item_ty(&self, name: ident, span: span, ty: @ast::Ty) -> @ast::item { - self.item_ty_poly(name, span, ty, ast_util::empty_generics()) + fn item_ty(&self, span: span, name: ident, ty: @ast::Ty) -> @ast::item { + self.item_ty_poly(span, name, ty, ast_util::empty_generics()) } - - - - - - - fn mk_expr(&self, - sp: codemap::span, - expr: ast::expr_) - -> @ast::expr { - @ast::expr { - id: self.next_id(), - callee_id: self.next_id(), - node: expr, - span: sp, - } + fn attribute(&self, sp: span, mi: @ast::meta_item) -> ast::attribute { + respan(sp, + ast::attribute_ { + style: ast::attr_outer, + value: mi, + is_sugared_doc: false + }) } - fn mk_lit(&self, sp: span, lit: ast::lit_) -> @ast::expr { - let sp_lit = @codemap::spanned { node: lit, span: sp }; - self.mk_expr( sp, ast::expr_lit(sp_lit)) + fn meta_word(&self, sp: span, w: ~str) -> @ast::meta_item { + @respan(sp, ast::meta_word(@w)) } - fn mk_int(&self, sp: span, i: int) -> @ast::expr { - let lit = ast::lit_int(i as i64, ast::ty_i); - return self.mk_lit( sp, lit); + fn meta_list(&self, sp: span, name: ~str, mis: ~[@ast::meta_item]) -> @ast::meta_item { + @respan(sp, ast::meta_list(@name, mis)) } - fn mk_uint(&self, sp: span, u: uint) -> @ast::expr { - let lit = ast::lit_uint(u as u64, ast::ty_u); - return self.mk_lit( sp, lit); - } - fn mk_u8(&self, sp: span, u: u8) -> @ast::expr { - let lit = ast::lit_uint(u as u64, ast::ty_u8); - return self.mk_lit( sp, lit); - } - fn mk_binary(&self, sp: span, op: ast::binop, - lhs: @ast::expr, rhs: @ast::expr) -> @ast::expr { - self.next_id(); // see ast_util::op_expr_callee_id - self.mk_expr( sp, ast::expr_binary(op, lhs, rhs)) + fn meta_name_value(&self, sp: span, name: ~str, value: ast::lit_) -> @ast::meta_item { + @respan(sp, ast::meta_name_value(@name, respan(sp, value))) } - fn mk_deref(&self, sp: span, e: @ast::expr) -> @ast::expr { - self.mk_unary( sp, ast::deref, e) - } - fn mk_unary(&self, sp: span, op: ast::unop, e: @ast::expr) - -> @ast::expr { - self.next_id(); // see ast_util::op_expr_callee_id - self.mk_expr( sp, ast::expr_unary(op, e)) - } - // XXX: unused self - fn mk_raw_path(&self, sp: span, idents: ~[ast::ident]) -> @ast::Path { - self.mk_raw_path_(sp, idents, None, ~[]) - } - // XXX: unused self - fn mk_raw_path_(&self, sp: span, - idents: ~[ast::ident], - rp: Option<@ast::Lifetime>, - types: ~[@ast::Ty]) - -> @ast::Path { - @ast::Path { span: sp, - global: false, - idents: idents, - rp: rp, - types: types } - } - // XXX: unused self - fn mk_raw_path_global(&self, sp: span, idents: ~[ast::ident]) -> @ast::Path { - self.mk_raw_path_global_(sp, idents, None, ~[]) - } - // XXX: unused self - fn mk_raw_path_global_(&self, sp: span, - idents: ~[ast::ident], - rp: Option<@ast::Lifetime>, - types: ~[@ast::Ty]) -> @ast::Path { - @ast::Path { span: sp, - global: true, - idents: idents, - rp: rp, - types: types } - } - fn mk_path_raw(&self, sp: span, path: @ast::Path)-> @ast::expr { - self.mk_expr( sp, ast::expr_path(path)) - } - fn mk_path(&self, sp: span, idents: ~[ast::ident]) - -> @ast::expr { - self.mk_path_raw( sp, self.mk_raw_path(sp, idents)) - } - fn mk_path_global(&self, sp: span, idents: ~[ast::ident]) - -> @ast::expr { - self.mk_path_raw( sp, self.mk_raw_path_global(sp, idents)) - } - fn mk_access_(&self, sp: span, p: @ast::expr, m: ast::ident) - -> @ast::expr { - self.mk_expr( sp, ast::expr_field(p, m, ~[])) - } - fn mk_access(&self, sp: span, p: ~[ast::ident], m: ast::ident) - -> @ast::expr { - let pathexpr = self.mk_path( sp, p); - return self.mk_access_( sp, pathexpr, m); - } - fn mk_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr { - return self.mk_expr( sp, ast::expr_addr_of(ast::m_imm, e)); - } - fn mk_mut_addr_of(&self, sp: span, e: @ast::expr) -> @ast::expr { - return self.mk_expr( sp, ast::expr_addr_of(ast::m_mutbl, e)); - } - fn mk_method_call(&self, - sp: span, - rcvr_expr: @ast::expr, - method_ident: ast::ident, - args: ~[@ast::expr]) -> @ast::expr { - self.mk_expr( sp, ast::expr_method_call(rcvr_expr, method_ident, ~[], args, ast::NoSugar)) - } - fn mk_call_(&self, sp: span, fn_expr: @ast::expr, - args: ~[@ast::expr]) -> @ast::expr { - self.mk_expr( sp, ast::expr_call(fn_expr, args, ast::NoSugar)) - } - fn mk_call(&self, sp: span, fn_path: ~[ast::ident], - args: ~[@ast::expr]) -> @ast::expr { - let pathexpr = self.mk_path( sp, fn_path); - return self.mk_call_( sp, pathexpr, args); - } - fn mk_call_global(&self, sp: span, fn_path: ~[ast::ident], - args: ~[@ast::expr]) -> @ast::expr { - let pathexpr = self.mk_path_global( sp, fn_path); - return self.mk_call_( sp, pathexpr, args); - } - // e = expr, t = type - fn mk_base_vec_e(&self, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr { - let vecexpr = ast::expr_vec(exprs, ast::m_imm); - self.mk_expr( sp, vecexpr) - } - fn mk_vstore_e(&self, sp: span, expr: @ast::expr, - vst: ast::expr_vstore) -> - @ast::expr { - self.mk_expr( sp, ast::expr_vstore(expr, vst)) - } - fn mk_uniq_vec_e(&self, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr { - self.mk_vstore_e( sp, self.mk_base_vec_e( sp, exprs), ast::expr_vstore_uniq) - } - fn mk_slice_vec_e(&self, sp: span, exprs: ~[@ast::expr]) - -> @ast::expr { - self.mk_vstore_e( sp, self.mk_base_vec_e( sp, exprs), - ast::expr_vstore_slice) - } - fn mk_base_str(&self, sp: span, s: ~str) -> @ast::expr { - let lit = ast::lit_str(@s); - return self.mk_lit( sp, lit); - } - fn mk_uniq_str(&self, sp: span, s: ~str) -> @ast::expr { - self.mk_vstore_e( sp, self.mk_base_str( sp, s), ast::expr_vstore_uniq) - } - // XXX: unused self - fn mk_field(&self, sp: span, f: &Field) -> ast::field { - codemap::spanned { - node: ast::field_ { mutbl: ast::m_imm, ident: f.ident, expr: f.ex }, - span: sp, + fn view_use(&self, sp: span, + vis: ast::visibility, vp: ~[@ast::view_path]) -> @ast::view_item { + @ast::view_item { + node: ast::view_item_use(vp), + attrs: ~[], + vis: vis, + span: sp } } - // XXX: unused self - fn mk_fields(&self, sp: span, fields: ~[Field]) -> ~[ast::field] { - fields.map(|f| self.mk_field(sp, f)) - } - fn mk_struct_e(&self, - sp: span, - ctor_path: ~[ast::ident], - fields: ~[Field]) - -> @ast::expr { - self.mk_expr( sp, - ast::expr_struct(self.mk_raw_path(sp, ctor_path), - self.mk_fields(sp, fields), - option::None::<@ast::expr>)) - } - fn mk_global_struct_e(&self, - sp: span, - ctor_path: ~[ast::ident], - fields: ~[Field]) - -> @ast::expr { - self.mk_expr( sp, - ast::expr_struct(self.mk_raw_path_global(sp, ctor_path), - self.mk_fields(sp, fields), - option::None::<@ast::expr>)) - } - fn mk_glob_use(&self, - sp: span, - vis: ast::visibility, - path: ~[ast::ident]) -> @ast::view_item { - let glob = @codemap::spanned { - node: ast::view_path_glob(self.mk_raw_path(sp, path), self.next_id()), - span: sp, - }; - @ast::view_item { node: ast::view_item_use(~[glob]), - attrs: ~[], - vis: vis, - span: sp } - } - fn mk_local(&self, sp: span, mutbl: bool, - ident: ast::ident, ex: @ast::expr) -> @ast::stmt { - let pat = @ast::pat { - id: self.next_id(), - node: ast::pat_ident( - ast::bind_by_copy, - self.mk_raw_path(sp, ~[ident]), - None), - span: sp, - }; - let ty = @ast::Ty { id: self.next_id(), node: ast::ty_infer, span: sp }; - let local = @codemap::spanned { - node: ast::local_ { - is_mutbl: mutbl, - ty: ty, - pat: pat, - init: Some(ex), - id: self.next_id(), - }, - span: sp, + fn view_use_list(&self, sp: span, vis: ast::visibility, + path: ~[ast::ident], imports: &[ast::ident]) -> @ast::view_item { + let imports = do imports.map |id| { + respan(sp, ast::path_list_ident_ { name: *id, id: self.next_id() }) }; - let decl = codemap::spanned {node: ast::decl_local(~[local]), span: sp}; - @codemap::spanned { node: ast::stmt_decl(@decl, self.next_id()), span: sp } - } - fn mk_block(&self, span: span, - view_items: ~[@ast::view_item], - stmts: ~[@ast::stmt], - expr: Option<@ast::expr>) -> @ast::expr { - let blk = codemap::spanned { - node: ast::blk_ { - view_items: view_items, - stmts: stmts, - expr: expr, - id: self.next_id(), - rules: ast::default_blk, - }, - span: span, - }; - self.mk_expr( span, ast::expr_block(blk)) - } - fn mk_block_(&self, - span: span, - stmts: ~[@ast::stmt]) - -> ast::blk { - codemap::spanned { - node: ast::blk_ { - view_items: ~[], - stmts: stmts, - expr: None, - id: self.next_id(), - rules: ast::default_blk, - }, - span: span, - } - } - fn mk_simple_block(&self, - span: span, - expr: @ast::expr) - -> ast::blk { - codemap::spanned { - node: ast::blk_ { - view_items: ~[], - stmts: ~[], - expr: Some(expr), - id: self.next_id(), - rules: ast::default_blk, - }, - span: span, - } - } - fn mk_lambda_(&self, - span: span, - fn_decl: ast::fn_decl, - blk: ast::blk) - -> @ast::expr { - self.mk_expr( span, ast::expr_fn_block(fn_decl, blk)) - } - fn mk_lambda(&self, - span: span, - fn_decl: ast::fn_decl, - expr: @ast::expr) - -> @ast::expr { - let blk = self.mk_simple_block( span, expr); - self.mk_lambda_( span, fn_decl, blk) - } - fn mk_lambda_stmts(&self, - span: span, - fn_decl: ast::fn_decl, - stmts: ~[@ast::stmt]) - -> @ast::expr { - let blk = self.mk_block( span, ~[], stmts, None); - self.mk_lambda( span, fn_decl, blk) - } - fn mk_lambda_no_args(&self, - span: span, - expr: @ast::expr) - -> @ast::expr { - let fn_decl = self.mk_fn_decl(~[], self.mk_ty_infer( span)); - self.mk_lambda( span, fn_decl, expr) - } - fn mk_copy(&self, sp: span, e: @ast::expr) -> @ast::expr { - self.mk_expr( sp, ast::expr_copy(e)) - } - fn mk_managed(&self, sp: span, e: @ast::expr) -> @ast::expr { - self.mk_expr( sp, ast::expr_unary(ast::box(ast::m_imm), e)) - } - fn mk_pat(&self, span: span, pat: ast::pat_) -> @ast::pat { - @ast::pat { id: self.next_id(), node: pat, span: span } - } - fn mk_pat_wild(&self, span: span) -> @ast::pat { - self.mk_pat( span, ast::pat_wild) - } - fn mk_pat_lit(&self, - span: span, - expr: @ast::expr) -> @ast::pat { - self.mk_pat( span, ast::pat_lit(expr)) - } - fn mk_pat_ident(&self, - span: span, - ident: ast::ident) -> @ast::pat { - self.mk_pat_ident_with_binding_mode( span, ident, ast::bind_by_copy) - } - - fn mk_pat_ident_with_binding_mode(&self, - span: span, - ident: ast::ident, - bm: ast::binding_mode) -> @ast::pat { - let path = self.mk_raw_path(span, ~[ ident ]); - let pat = ast::pat_ident(bm, path, None); - self.mk_pat( span, pat) - } - fn mk_pat_enum(&self, - span: span, - path: @ast::Path, - subpats: ~[@ast::pat]) - -> @ast::pat { - let pat = ast::pat_enum(path, Some(subpats)); - self.mk_pat( span, pat) - } - fn mk_pat_struct(&self, - span: span, - path: @ast::Path, - field_pats: ~[ast::field_pat]) - -> @ast::pat { - let pat = ast::pat_struct(path, field_pats, false); - self.mk_pat( span, pat) - } - fn mk_bool(&self, span: span, value: bool) -> @ast::expr { - let lit_expr = ast::expr_lit(@codemap::spanned { - node: ast::lit_bool(value), - span: span }); - self.mk_expr( span, lit_expr) - } - fn mk_stmt(&self, span: span, expr: @ast::expr) -> @ast::stmt { - let stmt_ = ast::stmt_semi(expr, self.next_id()); - @codemap::spanned { node: stmt_, span: span } - } - - // XXX: unused self - fn mk_ty_mt(&self, ty: @ast::Ty, mutbl: ast::mutability) -> ast::mt { - ast::mt { - ty: ty, - mutbl: mutbl - } - } - - fn mk_ty(&self, - span: span, - ty: ast::ty_) -> @ast::Ty { - @ast::Ty { - id: self.next_id(), - span: span, - node: ty - } - } - - fn mk_ty_path(&self, - span: span, - idents: ~[ ast::ident ]) - -> @ast::Ty { - let ty = self.mk_raw_path(span, idents); - self.mk_ty_path_path( span, ty) - } - fn mk_ty_path_global(&self, - span: span, - idents: ~[ ast::ident ]) - -> @ast::Ty { - let ty = self.mk_raw_path_global(span, idents); - self.mk_ty_path_path( span, ty) - } - - fn mk_ty_path_path(&self, - span: span, - path: @ast::Path) - -> @ast::Ty { - let ty = ast::ty_path(path, self.next_id()); - self.mk_ty( span, ty) - } - - fn mk_ty_rptr(&self, - span: span, - ty: @ast::Ty, - lifetime: Option<@ast::Lifetime>, - mutbl: ast::mutability) - -> @ast::Ty { - self.mk_ty( span, - ast::ty_rptr(lifetime, self.mk_ty_mt(ty, mutbl))) - } - fn mk_ty_uniq(&self, span: span, ty: @ast::Ty) -> @ast::Ty { - self.mk_ty( span, ast::ty_uniq(self.mk_ty_mt(ty, ast::m_imm))) - } - fn mk_ty_box(&self, span: span, - ty: @ast::Ty, mutbl: ast::mutability) -> @ast::Ty { - self.mk_ty( span, ast::ty_box(self.mk_ty_mt(ty, mutbl))) - } - - - - fn mk_ty_infer(&self, span: span) -> @ast::Ty { - self.mk_ty( span, ast::ty_infer) - } - fn mk_trait_ref_global(&self, - span: span, - idents: ~[ ast::ident ]) - -> @ast::trait_ref - { - self.mk_trait_ref_( self.mk_raw_path_global(span, idents)) - } - fn mk_trait_ref_(&self, path: @ast::Path) -> @ast::trait_ref { - @ast::trait_ref { - path: path, - ref_id: self.next_id() - } - } - fn mk_simple_ty_path(&self, - span: span, - ident: ast::ident) - -> @ast::Ty { - self.mk_ty_path( span, ~[ ident ]) - } - fn mk_arg(&self, - span: span, - ident: ast::ident, - ty: @ast::Ty) - -> ast::arg { - let arg_pat = self.mk_pat_ident( span, ident); - ast::arg { - is_mutbl: false, - ty: ty, - pat: arg_pat, - id: self.next_id() - } - } - // XXX unused self - fn mk_fn_decl(&self, inputs: ~[ast::arg], output: @ast::Ty) -> ast::fn_decl { - ast::fn_decl { inputs: inputs, output: output, cf: ast::return_val } - } - fn mk_trait_ty_param_bound_global(&self, - span: span, - idents: ~[ast::ident]) - -> ast::TyParamBound { - ast::TraitTyParamBound(self.mk_trait_ref_global( span, idents)) - } - fn mk_trait_ty_param_bound_(&self, - path: @ast::Path) -> ast::TyParamBound { - ast::TraitTyParamBound(self.mk_trait_ref_( path)) - } - fn mk_ty_param(&self, - ident: ast::ident, - bounds: @OptVec) - -> ast::TyParam { - ast::TyParam { ident: ident, id: self.next_id(), bounds: bounds } - } - fn mk_lifetime(&self, - span: span, - ident: ast::ident) - -> ast::Lifetime { - ast::Lifetime { id: self.next_id(), span: span, ident: ident } - } - fn mk_arm(&self, - span: span, - pats: ~[@ast::pat], - expr: @ast::expr) - -> ast::arm { - ast::arm { - pats: pats, - guard: None, - body: self.mk_simple_block( span, expr) - } - } - fn mk_unreachable(&self, span: span) -> @ast::expr { - let loc = self.codemap().lookup_char_pos(span.lo); - self.mk_call_global( - span, - ~[ - self.ident_of("core"), - self.ident_of("sys"), - self.ident_of("FailWithCause"), - self.ident_of("fail_with"), - ], - ~[ - self.mk_base_str( span, ~"internal error: entered unreachable code"), - self.mk_base_str( span, copy loc.file.name), - self.mk_uint( span, loc.line), - ] - ) - } - fn mk_unreachable_arm(&self, span: span) -> ast::arm { - self.mk_arm( span, ~[self.mk_pat_wild( span)], self.mk_unreachable( span)) + self.view_use(sp, vis, + ~[@respan(sp, + ast::view_path_list(self.path(sp, path), + imports, + self.next_id()))]) } - fn make_self(&self, span: span) -> @ast::expr { - self.mk_expr( span, ast::expr_self) + fn view_use_glob(&self, sp: span, + vis: ast::visibility, path: ~[ast::ident]) -> @ast::view_item { + self.view_use(sp, vis, + ~[@respan(sp, + ast::view_path_glob(self.path(sp, path), self.next_id()))]) } } diff --git a/src/libsyntax/ext/bytes.rs b/src/libsyntax/ext/bytes.rs index cdc6e267cccba..a046395b6f5c8 100644 --- a/src/libsyntax/ext/bytes.rs +++ b/src/libsyntax/ext/bytes.rs @@ -28,7 +28,7 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas // string literal, push each byte to vector expression ast::lit_str(s) => { for s.each |byte| { - bytes.push(cx.mk_u8(sp, byte)); + bytes.push(cx.expr_u8(sp, byte)); } } @@ -37,7 +37,7 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas if v > 0xFF { cx.span_err(sp, "Too large u8 literal in bytes!") } else { - bytes.push(cx.mk_u8(sp, v as u8)); + bytes.push(cx.expr_u8(sp, v as u8)); } } @@ -48,14 +48,14 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas } else if v < 0 { cx.span_err(sp, "Negative integer literal in bytes!") } else { - bytes.push(cx.mk_u8(sp, v as u8)); + bytes.push(cx.expr_u8(sp, v as u8)); } } // char literal, push to vector expression ast::lit_int(v, ast::ty_char) => { if (v as char).is_ascii() { - bytes.push(cx.mk_u8(sp, v as u8)); + bytes.push(cx.expr_u8(sp, v as u8)); } else { cx.span_err(sp, "Non-ascii char literal in bytes!") } @@ -68,6 +68,6 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> bas } } - let e = cx.mk_slice_vec_e(sp, bytes); + let e = cx.expr_vec_slice(sp, bytes); MRExpr(e) } diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 07aead9588ac1..007826a84165d 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -11,7 +11,6 @@ use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; -use ext::build; use ext::build::AstBuilder; use ext::deriving::generic::*; @@ -80,15 +79,15 @@ fn cs_clone( let ctor_ident; let all_fields; let subcall = |field| - cx.mk_method_call(span, field, clone_ident, ~[]); + cx.expr_method_call(span, field, clone_ident, ~[]); match *substr.fields { Struct(ref af) => { - ctor_ident = ~[ substr.type_ident ]; + ctor_ident = substr.type_ident; all_fields = af; } EnumMatching(_, variant, ref af) => { - ctor_ident = ~[ variant.node.name ]; + ctor_ident = variant.node.name; all_fields = af; }, EnumNonMatching(*) => cx.span_bug(span, @@ -103,7 +102,7 @@ fn cs_clone( [(None, _, _), .. _] => { // enum-like let subcalls = all_fields.map(|&(_, self_f, _)| subcall(self_f)); - cx.mk_call(span, ctor_ident, subcalls) + cx.expr_call_ident(span, ctor_ident, subcalls) }, _ => { // struct-like @@ -114,16 +113,14 @@ fn cs_clone( fmt!("unnamed field in normal struct in `deriving(%s)`", name)) }; - build::Field { ident: ident, ex: subcall(self_f) } + cx.field_imm(span, ident, subcall(self_f)) }; if fields.is_empty() { // no fields, so construct like `None` - cx.mk_path(span, ctor_ident) + cx.expr_ident(span, ctor_ident) } else { - cx.mk_struct_e(span, - ctor_ident, - fields) + cx.expr_struct_ident(span, ctor_ident, fields) } } } diff --git a/src/libsyntax/ext/deriving/cmp/eq.rs b/src/libsyntax/ext/deriving/cmp/eq.rs index 1af6640448977..11c0a597cebab 100644 --- a/src/libsyntax/ext/deriving/cmp/eq.rs +++ b/src/libsyntax/ext/deriving/cmp/eq.rs @@ -21,11 +21,11 @@ pub fn expand_deriving_eq(cx: @ExtCtxt, // structures are equal if all fields are equal, and non equal, if // any fields are not equal or if the enum variants are different fn cs_eq(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { - cs_and(|cx, span, _, _| cx.mk_bool(span, false), + cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) } fn cs_ne(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { - cs_or(|cx, span, _, _| cx.mk_bool(span, true), + cs_or(|cx, span, _, _| cx.expr_bool(span, true), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 41b5bf63aca34..9438e1b0f858d 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -9,7 +9,7 @@ // except according to those terms. -use ast::{meta_item, item, expr_if, expr}; +use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; use ext::build::AstBuilder; @@ -62,10 +62,7 @@ fn cs_ord(less: bool, equal: bool, } else { cx.ident_of("gt") }; - let false_blk_expr = cx.mk_block(span, - ~[], ~[], - Some(cx.mk_bool(span, false))); - let base = cx.mk_bool(span, equal); + let base = cx.expr_bool(span, equal); cs_fold( false, // need foldr, @@ -98,19 +95,15 @@ fn cs_ord(less: bool, equal: bool, cx.span_bug(span, "Not exactly 2 arguments in `deriving(Ord)`"); } - let cmp = cx.mk_method_call(span, - self_f, cx.ident_of("eq"), other_fs.to_owned()); - let subexpr = cx.mk_simple_block(span, subexpr); - let elseif = expr_if(cmp, subexpr, Some(false_blk_expr)); - let elseif = cx.mk_expr(span, elseif); + let cmp = cx.expr_method_call(span, + self_f, cx.ident_of("eq"), other_fs.to_owned()); + let elseif = cx.expr_if(span, cmp, + subexpr, Some(cx.expr_bool(span, false))); - let cmp = cx.mk_method_call(span, - self_f, binop, other_fs.to_owned()); - let true_blk = cx.mk_simple_block(span, - cx.mk_bool(span, true)); - let if_ = expr_if(cmp, true_blk, Some(elseif)); - - cx.mk_expr(span, if_) + let cmp = cx.expr_method_call(span, + self_f, binop, other_fs.to_owned()); + cx.expr_if(span, cmp, + cx.expr_bool(span, true), Some(elseif)) }, base, |cx, span, args, _| { @@ -119,7 +112,7 @@ fn cs_ord(less: bool, equal: bool, match args { [(self_var, _, _), (other_var, _, _)] => - cx.mk_bool(span, + cx.expr_bool(span, if less { self_var < other_var } else { diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index 48393efce6487..f1e952eb5f63c 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -21,7 +21,7 @@ pub fn expand_deriving_totaleq(cx: @ExtCtxt, in_items: ~[@item]) -> ~[@item] { fn cs_equals(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { - cs_and(|cx, span, _, _| cx.mk_bool(span, false), + cs_and(|cx, span, _, _| cx.expr_bool(span, false), cx, span, substr) } diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index 3404a21edd0de..e26f4a34304cb 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -47,10 +47,11 @@ pub fn ordering_const(cx: @ExtCtxt, span: span, cnst: Ordering) -> @expr { Equal => "Equal", Greater => "Greater" }; - cx.mk_path_global(span, - ~[cx.ident_of("core"), - cx.ident_of("cmp"), - cx.ident_of(cnst)]) + cx.expr_path( + cx.path_global(span, + ~[cx.ident_of("core"), + cx.ident_of("cmp"), + cx.ident_of(cnst)])) } pub fn cs_cmp(cx: @ExtCtxt, span: span, @@ -60,11 +61,11 @@ pub fn cs_cmp(cx: @ExtCtxt, span: span, // foldr (possibly) nests the matches in lexical_ordering better false, |cx, span, old, new| { - cx.mk_call_global(span, - ~[cx.ident_of("core"), - cx.ident_of("cmp"), - cx.ident_of("lexical_ordering")], - ~[old, new]) + cx.expr_call_global(span, + ~[cx.ident_of("core"), + cx.ident_of("cmp"), + cx.ident_of("lexical_ordering")], + ~[old, new]) }, ordering_const(cx, span, Equal), |cx, span, list, _| { diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index 781ac9814ec9b..a8c84e8e361e5 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -16,7 +16,6 @@ encodable.rs for more. use ast; use ast::*; use ext::base::ExtCtxt; -use ext::build::Field; use ext::build::AstBuilder; use ext::deriving::*; use codemap::{span, spanned}; @@ -45,26 +44,25 @@ fn create_derived_decodable_impl( generics: &Generics, method: @method ) -> @item { - let decoder_ty_param = cx.mk_ty_param( + let decoder_ty_param = cx.typaram( cx.ident_of("__D"), @opt_vec::with( - cx.mk_trait_ty_param_bound_global( - span, - ~[ - cx.ident_of("std"), - cx.ident_of("serialize"), - cx.ident_of("Decoder"), - ] - ) - ) - ); + cx.typarambound( + cx.path_global( + span, + ~[ + cx.ident_of("std"), + cx.ident_of("serialize"), + cx.ident_of("Decoder"), + ])))); // All the type parameters need to bound to the trait. let generic_ty_params = opt_vec::with(decoder_ty_param); let methods = [method]; - let trait_path = cx.mk_raw_path_global_( + let trait_path = cx.path_all( span, + true, ~[ cx.ident_of("std"), cx.ident_of("serialize"), @@ -72,7 +70,7 @@ fn create_derived_decodable_impl( ], None, ~[ - cx.mk_simple_ty_path(span, cx.ident_of("__D")) + cx.ty_ident(span, cx.ident_of("__D")) ] ); create_derived_impl( @@ -97,14 +95,14 @@ fn create_decode_method( expr: @ast::expr ) -> @method { // Create the `e` parameter. - let d_arg_type = cx.mk_ty_rptr( + let d_arg_type = cx.ty_rptr( span, - cx.mk_simple_ty_path(span, cx.ident_of("__D")), + cx.ty_ident(span, cx.ident_of("__D")), None, ast::m_mutbl ); let d_ident = cx.ident_of("__d"); - let d_arg = cx.mk_arg(span, d_ident, d_arg_type); + let d_arg = cx.arg(span, d_ident, d_arg_type); // Create the type of the return value. let output_type = create_self_type_with_params( @@ -116,10 +114,10 @@ fn create_decode_method( // Create the function declaration. let inputs = ~[d_arg]; - let fn_decl = cx.mk_fn_decl(inputs, output_type); + let fn_decl = cx.fn_decl(inputs, output_type); // Create the body block. - let body_block = cx.mk_simple_block(span, expr); + let body_block = cx.blk_expr(expr); // Create the method. let explicit_self = spanned { node: sty_static, span: span }; @@ -144,19 +142,21 @@ fn call_substructure_decode_method( span: span ) -> @ast::expr { // Call the substructure method. - cx.mk_call_( + cx.expr_call( span, - cx.mk_path_global( - span, - ~[ - cx.ident_of("std"), - cx.ident_of("serialize"), - cx.ident_of("Decodable"), - cx.ident_of("decode"), - ] + cx.expr_path( + cx.path_global( + span, + ~[ + cx.ident_of("std"), + cx.ident_of("serialize"), + cx.ident_of("Decodable"), + cx.ident_of("decode"), + ] + ) ), ~[ - cx.mk_path(span, ~[cx.ident_of("__d")]) + cx.expr_ident(span, cx.ident_of("__d")) ] ) } @@ -218,31 +218,24 @@ fn create_read_struct_field( span: span, idx: uint, ident: ident -) -> Field { +) -> ast::field { // Call the substructure method. let decode_expr = call_substructure_decode_method(cx, span); - let d_arg = cx.mk_arg( - span, - cx.ident_of("__d"), - cx.mk_ty_infer(span)); + let d_id = cx.ident_of("__d"); - let call_expr = cx.mk_method_call( + let call_expr = cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__d")]), + cx.expr_ident(span, d_id), cx.ident_of("read_struct_field"), ~[ - cx.mk_base_str(span, cx.str_of(ident)), - cx.mk_uint(span, idx), - cx.mk_lambda( - span, - cx.mk_fn_decl(~[d_arg], - cx.mk_ty_infer(span)), - decode_expr), + cx.expr_str(span, cx.str_of(ident)), + cx.expr_uint(span, idx), + cx.lambda_expr_1(span, decode_expr, d_id) ] ); - Field { ident: ident, ex: call_expr } + cx.field_imm(span, ident, call_expr) } fn create_read_struct_arg( @@ -250,21 +243,21 @@ fn create_read_struct_arg( span: span, idx: uint, ident: ident -) -> Field { +) -> ast::field { // Call the substructure method. let decode_expr = call_substructure_decode_method(cx, span); - let call_expr = cx.mk_method_call( + let call_expr = cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__d")]), + cx.expr_ident(span, cx.ident_of("__d")), cx.ident_of("read_struct_arg"), ~[ - cx.mk_uint(span, idx), - cx.mk_lambda_no_args(span, decode_expr), + cx.expr_uint(span, idx), + cx.lambda_expr_0(span, decode_expr), ] ); - Field { ident: ident, ex: call_expr } + cx.field_imm(span, ident, call_expr) } fn expand_deriving_decodable_struct_method( @@ -292,30 +285,19 @@ fn expand_deriving_decodable_struct_method( i += 1; } - let d_arg = cx.mk_arg( - span, - cx.ident_of("__d"), - cx.mk_ty_infer(span)); + let d_id = cx.ident_of("__d"); - let read_struct_expr = cx.mk_method_call( + let read_struct_expr = cx.expr_method_call( span, - cx.mk_path( - span, - ~[cx.ident_of("__d")] - ), + cx.expr_ident(span, d_id), cx.ident_of("read_struct"), ~[ - cx.mk_base_str(span, cx.str_of(type_ident)), - cx.mk_uint(span, fields.len()), - cx.mk_lambda( + cx.expr_str(span, cx.str_of(type_ident)), + cx.expr_uint(span, fields.len()), + cx.lambda_expr_1( span, - cx.mk_fn_decl(~[d_arg], cx.mk_ty_infer(span)), - cx.mk_struct_e( - span, - ~[type_ident], - fields - ) - ), + cx.expr_struct_ident(span, type_ident, fields), + d_id) ] ); @@ -330,14 +312,14 @@ fn create_read_variant_arg( variant: &ast::variant ) -> ast::arm { // Create the matching pattern. - let pat = cx.mk_pat_lit(span, cx.mk_uint(span, idx)); + let pat = cx.pat_lit(span, cx.expr_uint(span, idx)); // Feed each argument in this variant to the decode function // as well. let variant_arg_len = variant_arg_count(cx, span, variant); let expr = if variant_arg_len == 0 { - cx.mk_path(span, ~[variant.node.name]) + cx.expr_ident(span, variant.node.name) } else { // Feed the discriminant to the decode function. let mut args = ~[]; @@ -346,37 +328,26 @@ fn create_read_variant_arg( // Call the substructure method. let expr = call_substructure_decode_method(cx, span); - let d_arg = cx.mk_arg( - span, - cx.ident_of("__d"), - cx.mk_ty_infer(span)); - let t_infer = cx.mk_ty_infer(span); + let d_id = cx.ident_of("__d"); - let call_expr = cx.mk_method_call( + let call_expr = cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__d")]), + cx.expr_ident(span, d_id), cx.ident_of("read_enum_variant_arg"), ~[ - cx.mk_uint(span, j), - cx.mk_lambda( - span, - cx.mk_fn_decl(~[d_arg], t_infer), - expr), + cx.expr_uint(span, j), + cx.lambda_expr_1(span, expr, d_id), ] ); args.push(call_expr); } - cx.mk_call( - span, - ~[variant.node.name], - args - ) + cx.expr_call_ident(span, variant.node.name, args) }; // Create the arm. - cx.mk_arm(span, ~[pat], expr) + cx.arm(span, ~[pat], expr) } fn create_read_enum_variant( @@ -385,10 +356,10 @@ fn create_read_enum_variant( enum_definition: &enum_def ) -> @expr { // Create a vector that contains all the variant names. - let expr_arm_names = cx.mk_base_vec_e( + let expr_arm_names = cx.expr_vec( span, do enum_definition.variants.map |variant| { - cx.mk_base_str( + cx.expr_str( span, cx.str_of(variant.node.name) ) @@ -401,40 +372,18 @@ fn create_read_enum_variant( }; // Add the impossible case arm. - arms.push(cx.mk_unreachable_arm(span)); + arms.push(cx.arm_unreachable(span)); // Create the read_enum_variant expression. - cx.mk_method_call( + cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__d")]), + cx.expr_ident(span, cx.ident_of("__d")), cx.ident_of("read_enum_variant"), ~[ expr_arm_names, - cx.mk_lambda( - span, - cx.mk_fn_decl( - ~[ - cx.mk_arg( - span, - cx.ident_of("__d"), - cx.mk_ty_infer(span) - ), - cx.mk_arg( - span, - cx.ident_of("__i"), - cx.mk_ty_infer(span) - ) - ], - cx.mk_ty_infer(span) - ), - cx.mk_expr( - span, - ast::expr_match( - cx.mk_path(span, ~[cx.ident_of("__i")]), - arms - ) - ) - ) + cx.lambda_expr(span, + ~[cx.ident_of("__d"), cx.ident_of("__i")], + cx.expr_match(span, cx.expr_ident(span, cx.ident_of("__i")), arms)) ] ) } @@ -452,23 +401,16 @@ fn expand_deriving_decodable_enum_method( enum_definition ); - let d_arg = cx.mk_arg( - span, - cx.ident_of("__d"), - cx.mk_ty_infer(span)); + let d_id = cx.ident_of("__d"); // Create the read_enum expression - let read_enum_expr = cx.mk_method_call( + let read_enum_expr = cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__d")]), + cx.expr_ident(span, d_id), cx.ident_of("read_enum"), ~[ - cx.mk_base_str(span, cx.str_of(type_ident)), - cx.mk_lambda( - span, - cx.mk_fn_decl(~[d_arg], - cx.mk_ty_infer(span)), - read_enum_variant_expr), + cx.expr_str(span, cx.str_of(type_ident)), + cx.lambda_expr_1(span, read_enum_variant_expr, d_id) ] ); diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index eda1909aed4cb..72a1745f902be 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -107,26 +107,25 @@ fn create_derived_encodable_impl( generics: &Generics, method: @method ) -> @item { - let encoder_ty_param = cx.mk_ty_param( + let encoder_ty_param = cx.typaram( cx.ident_of("__E"), @opt_vec::with( - cx.mk_trait_ty_param_bound_global( - span, - ~[ - cx.ident_of("std"), - cx.ident_of("serialize"), - cx.ident_of("Encoder"), - ] - ) - ) - ); + cx.typarambound( + cx.path_global( + span, + ~[ + cx.ident_of("std"), + cx.ident_of("serialize"), + cx.ident_of("Encoder"), + ])))); // All the type parameters need to bound to the trait. let generic_ty_params = opt_vec::with(encoder_ty_param); let methods = [method]; - let trait_path = cx.mk_raw_path_global_( + let trait_path = cx.path_all( span, + true, ~[ cx.ident_of("std"), cx.ident_of("serialize"), @@ -134,7 +133,7 @@ fn create_derived_encodable_impl( ], None, ~[ - cx.mk_simple_ty_path(span, cx.ident_of("__E")) + cx.ty_ident(span, cx.ident_of("__E")) ] ); create_derived_impl( @@ -157,23 +156,23 @@ fn create_encode_method( statements: ~[@stmt] ) -> @method { // Create the `e` parameter. - let e_arg_type = cx.mk_ty_rptr( + let e_arg_type = cx.ty_rptr( span, - cx.mk_simple_ty_path(span, cx.ident_of("__E")), + cx.ty_ident(span, cx.ident_of("__E")), None, ast::m_mutbl ); - let e_arg = cx.mk_arg(span, cx.ident_of("__e"), e_arg_type); + let e_arg = cx.arg(span, cx.ident_of("__e"), e_arg_type); // Create the type of the return value. - let output_type = @ast::Ty { id: cx.next_id(), node: ty_nil, span: span }; + let output_type = cx.ty_nil(); // Create the function declaration. let inputs = ~[e_arg]; - let fn_decl = cx.mk_fn_decl(inputs, output_type); + let fn_decl = cx.fn_decl(inputs, output_type); // Create the body block. - let body_block = cx.mk_block_(span, statements); + let body_block = cx.blk(span, statements, None); // Create the method. let explicit_self = spanned { node: sty_region(None, m_imm), span: span }; @@ -200,11 +199,11 @@ fn call_substructure_encode_method( ) -> @ast::expr { // Gather up the parameters we want to chain along. let e_ident = cx.ident_of("__e"); - let e_expr = cx.mk_path(span, ~[e_ident]); + let e_expr = cx.expr_ident(span, e_ident); // Call the substructure method. let encode_ident = cx.ident_of("encode"); - cx.mk_method_call( + cx.expr_method_call( span, self_field, encode_ident, @@ -275,10 +274,9 @@ fn expand_deriving_encodable_struct_method( match struct_field.node.kind { named_field(ident, _) => { // Create the accessor for this field. - let self_field = cx.mk_access_( - span, - cx.make_self(span), - ident); + let self_field = cx.expr_field_access(span, + cx.expr_self(span), + ident); // Call the substructure method. let encode_expr = call_substructure_encode_method( @@ -288,29 +286,19 @@ fn expand_deriving_encodable_struct_method( ); let e_ident = cx.ident_of("__e"); - let e_arg = cx.mk_arg( - span, - e_ident, - cx.mk_ty_infer(span)); - let blk_expr = cx.mk_lambda( + let call_expr = cx.expr_method_call( span, - cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), - encode_expr - ); - - let call_expr = cx.mk_method_call( - span, - cx.mk_path(span, ~[cx.ident_of("__e")]), + cx.expr_ident(span, e_ident), cx.ident_of("emit_struct_field"), ~[ - cx.mk_base_str(span, cx.str_of(ident)), - cx.mk_uint(span, idx), - blk_expr + cx.expr_str(span, cx.str_of(ident)), + cx.expr_uint(span, idx), + cx.lambda_expr_1(span, encode_expr, e_ident) ] ); - statements.push(cx.mk_stmt(span, call_expr)); + statements.push(cx.stmt_expr(call_expr)); } unnamed_field => { cx.span_unimpl( @@ -322,30 +310,19 @@ fn expand_deriving_encodable_struct_method( idx += 1; } - let e_arg = cx.mk_arg( - span, - cx.ident_of("__e"), - cx.mk_ty_infer(span)); - - let emit_struct_stmt = cx.mk_method_call( + let e_id = cx.ident_of("__e"); + let emit_struct_stmt = cx.expr_method_call( span, - cx.mk_path( - span, - ~[cx.ident_of("__e")] - ), + cx.expr_ident(span, e_id), cx.ident_of("emit_struct"), ~[ - cx.mk_base_str(span, cx.str_of(type_ident)), - cx.mk_uint(span, statements.len()), - cx.mk_lambda_stmts( - span, - cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), - statements - ), + cx.expr_str(span, cx.str_of(type_ident)), + cx.expr_uint(span, statements.len()), + cx.lambda_stmts_1(span, statements, e_id), ] ); - let statements = ~[cx.mk_stmt(span, emit_struct_stmt)]; + let statements = ~[cx.stmt_expr(emit_struct_stmt)]; // Create the method itself. return create_encode_method(cx, span, statements); @@ -373,85 +350,59 @@ fn expand_deriving_encodable_enum_method( let expr = call_substructure_encode_method(cx, span, field); let e_ident = cx.ident_of("__e"); - let e_arg = cx.mk_arg( - span, - e_ident, - cx.mk_ty_infer(span)); - - let blk_expr = cx.mk_lambda( - span, - cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), - expr - ); - - let call_expr = cx.mk_method_call( + let call_expr = cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__e")]), + cx.expr_ident(span, e_ident), cx.ident_of("emit_enum_variant_arg"), ~[ - cx.mk_uint(span, j), - blk_expr, + cx.expr_uint(span, j), + cx.lambda_expr_1(span, expr, e_ident), ] ); - stmts.push(cx.mk_stmt(span, call_expr)); + stmts.push(cx.stmt_expr(call_expr)); } // Create the pattern body. - let e_arg = cx.mk_arg( - span, - cx.ident_of("__e"), - cx.mk_ty_infer(span)); - let call_expr = cx.mk_method_call( + let e_id = cx.ident_of("__e"); + + let call_expr = cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__e")]), + cx.expr_ident(span, e_id), cx.ident_of("emit_enum_variant"), ~[ - cx.mk_base_str(span, cx.str_of(variant.node.name)), - cx.mk_uint(span, i), - cx.mk_uint(span, variant_arg_len), - cx.mk_lambda_stmts( - span, - cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), - stmts - ) + cx.expr_str(span, cx.str_of(variant.node.name)), + cx.expr_uint(span, i), + cx.expr_uint(span, variant_arg_len), + cx.lambda_stmts_1(span, stmts, e_id) ] ); - let match_body_block = cx.mk_simple_block(span, call_expr); + //let match_body_block = cx.blk_expr(call_expr); // Create the arm. - ast::arm { - pats: ~[pat], - guard: None, - body: match_body_block, - } + cx.arm(span, ~[pat], call_expr) //match_body_block) }; let e_ident = cx.ident_of("__e"); - let e_arg = cx.mk_arg( - span, - e_ident, - cx.mk_ty_infer(span)); // Create the method body. - let lambda_expr = cx.mk_lambda( + let lambda_expr = cx.lambda_expr_1( span, - cx.mk_fn_decl(~[e_arg], cx.mk_ty_infer(span)), - expand_enum_or_struct_match(cx, span, arms) - ); + expand_enum_or_struct_match(cx, span, arms), + e_ident); - let call_expr = cx.mk_method_call( + let call_expr = cx.expr_method_call( span, - cx.mk_path(span, ~[cx.ident_of("__e")]), + cx.expr_ident(span, e_ident), cx.ident_of("emit_enum"), ~[ - cx.mk_base_str(span, cx.str_of(type_ident)), + cx.expr_str(span, cx.str_of(type_ident)), lambda_expr, ] ); - let stmt = cx.mk_stmt(span, call_expr); + let stmt = cx.stmt_expr(call_expr); // Create the method. create_encode_method(cx, span, ~[stmt]) diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index 4859fec2e4452..b61c78721fee9 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -431,7 +431,7 @@ impl<'self> MethodDef<'self> { let ident = cx.ident_of(fmt!("__arg_%u", i)); arg_tys.push((ident, ast_ty)); - let arg_expr = cx.mk_path(span, ~[ident]); + let arg_expr = cx.expr_ident(span, ident); match *ty { // for static methods, just treat any Self @@ -440,7 +440,7 @@ impl<'self> MethodDef<'self> { self_args.push(arg_expr); } Ptr(~Self, _) if nonstatic => { - self_args.push(cx.mk_deref(span, arg_expr)) + self_args.push(cx.expr_deref(span, arg_expr)) } _ => { nonself_args.push(arg_expr); @@ -461,14 +461,14 @@ impl<'self> MethodDef<'self> { let fn_generics = self.generics.to_generics(cx, span, type_ident, generics); let args = do arg_types.map |&(id, ty)| { - cx.mk_arg(span, id, ty) + cx.arg(span, id, ty) }; let ret_type = self.get_ret_ty(cx, span, generics, type_ident); let method_ident = cx.ident_of(self.name); - let fn_decl = cx.mk_fn_decl(args, ret_type); - let body_block = cx.mk_simple_block(span, body); + let fn_decl = cx.fn_decl(args, ret_type); + let body_block = cx.blk_expr(body); // Create the method. @@ -555,13 +555,8 @@ impl<'self> MethodDef<'self> { // structs. This is actually right-to-left, but it shoudn't // matter. for vec::each2(self_args, patterns) |&arg_expr, &pat| { - let match_arm = ast::arm { - pats: ~[ pat ], - guard: None, - body: cx.mk_simple_block(span, body) - }; - - body = cx.mk_expr(span, ast::expr_match(arg_expr, ~[match_arm])) + body = cx.expr_match(span, arg_expr, + ~[ cx.arm(span, ~[pat], body) ]) } body } @@ -690,7 +685,7 @@ impl<'self> MethodDef<'self> { } let field_tuples = do vec::map_zip(*self_vec, - enum_matching_fields) |&(id, self_f), &other| { + enum_matching_fields) |&(id, self_f), &other| { (id, self_f, other) }; substructure = EnumMatching(variant_index, variant, field_tuples); @@ -738,16 +733,16 @@ impl<'self> MethodDef<'self> { matches_so_far, match_count + 1); matches_so_far.pop(); - arms.push(cx.mk_arm(span, ~[ pattern ], arm_expr)); + arms.push(cx.arm(span, ~[ pattern ], arm_expr)); if enum_def.variants.len() > 1 { let e = &EnumNonMatching(&[]); let wild_expr = self.call_substructure_method(cx, span, type_ident, self_args, nonself_args, e); - let wild_arm = cx.mk_arm(span, - ~[ cx.mk_pat_wild(span) ], - wild_expr); + let wild_arm = cx.arm(span, + ~[ cx.pat_wild(span) ], + wild_expr); arms.push(wild_arm); } } else { @@ -774,14 +769,13 @@ impl<'self> MethodDef<'self> { match_count + 1); matches_so_far.pop(); - let arm = cx.mk_arm(span, ~[ pattern ], arm_expr); + let arm = cx.arm(span, ~[ pattern ], arm_expr); arms.push(arm); } } // match foo { arm, arm, arm, ... } - cx.mk_expr(span, - ast::expr_match(self_args[match_count], arms)) + cx.expr_match(span, self_args[match_count], arms) } } @@ -887,10 +881,10 @@ pub fn cs_same_method(f: &fn(@ExtCtxt, span, ~[@expr]) -> @expr, EnumMatching(_, _, ref all_fields) | Struct(ref all_fields) => { // call self_n.method(other_1_n, other_2_n, ...) let called = do all_fields.map |&(_, self_field, other_fields)| { - cx.mk_method_call(span, - self_field, - substructure.method_ident, - other_fields) + cx.expr_method_call(span, + self_field, + substructure.method_ident, + other_fields) }; f(cx, span, called) @@ -945,9 +939,9 @@ pub fn cs_binop(binop: ast::binop, base: @expr, cs_same_method_fold( true, // foldl is good enough |cx, span, old, new| { - cx.mk_binary(span, - binop, - old, new) + cx.expr_binary(span, + binop, + old, new) }, base, @@ -960,7 +954,7 @@ pub fn cs_binop(binop: ast::binop, base: @expr, pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc, cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { - cs_binop(ast::or, cx.mk_bool(span, false), + cs_binop(ast::or, cx.expr_bool(span, false), enum_nonmatch_f, cx, span, substructure) } @@ -969,7 +963,7 @@ pub fn cs_or(enum_nonmatch_f: EnumNonMatchFunc, pub fn cs_and(enum_nonmatch_f: EnumNonMatchFunc, cx: @ExtCtxt, span: span, substructure: &Substructure) -> @expr { - cs_binop(ast::and, cx.mk_bool(span, true), + cs_binop(ast::and, cx.expr_bool(span, true), enum_nonmatch_f, cx, span, substructure) } diff --git a/src/libsyntax/ext/deriving/iter_bytes.rs b/src/libsyntax/ext/deriving/iter_bytes.rs index cc89bae37b76f..ae321c3e40956 100644 --- a/src/libsyntax/ext/deriving/iter_bytes.rs +++ b/src/libsyntax/ext/deriving/iter_bytes.rs @@ -48,7 +48,7 @@ fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @ }; let iter_bytes_ident = substr.method_ident; let call_iterbytes = |thing_expr| { - cx.mk_method_call(span, + cx.expr_method_call(span, thing_expr, iter_bytes_ident, copy lsb0_f) }; @@ -63,7 +63,7 @@ fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @ // iteration function. let discriminant = match variant.node.disr_expr { Some(copy d)=> d, - None => cx.mk_uint(span, index) + None => cx.expr_uint(span, index) }; exprs.push(call_iterbytes(discriminant)); @@ -82,6 +82,6 @@ fn iter_bytes_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @ } do vec::foldl(exprs[0], exprs.slice(1, exprs.len())) |prev, me| { - cx.mk_binary(span, and, prev, *me) + cx.expr_binary(span, and, prev, *me) } } diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index a7f70236251ba..7da66f88ca908 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -22,7 +22,7 @@ use ast; use ast::{Ty, enum_def, expr, ident, item, Generics, meta_item, struct_def}; use ext::base::ExtCtxt; use ext::build::AstBuilder; -use codemap::{span, respan}; +use codemap::span; use parse::token::special_idents::clownshoes_extensions; use opt_vec; @@ -143,38 +143,15 @@ pub fn expand_deriving(cx: @ExtCtxt, result } -fn create_impl_item(cx: @ExtCtxt, span: span, item: ast::item_) -> @item { - let doc_attr = respan(span, - ast::lit_str(@~"Automatically derived.")); - let doc_attr = respan(span, ast::meta_name_value(@~"doc", doc_attr)); - let doc_attr = ast::attribute_ { - style: ast::attr_outer, - value: @doc_attr, - is_sugared_doc: false - }; - let doc_attr = respan(span, doc_attr); - - @ast::item { - ident: clownshoes_extensions, - attrs: ~[doc_attr], - id: cx.next_id(), - node: item, - vis: ast::public, - span: span, - } -} - pub fn create_self_type_with_params(cx: @ExtCtxt, - span: span, - type_ident: ident, - generics: &Generics) - -> @Ty { + span: span, + type_ident: ident, + generics: &Generics) + -> @Ty { // Create the type parameters on the `self` path. let mut self_ty_params = ~[]; for generics.ty_params.each |ty_param| { - let self_ty_param = cx.mk_simple_ty_path( - span, - ty_param.ident); + let self_ty_param = cx.ty_ident(span, ty_param.ident); self_ty_params.push(self_ty_param); } @@ -186,11 +163,7 @@ pub fn create_self_type_with_params(cx: @ExtCtxt, // Create the type of `self`. - let self_type = cx.mk_raw_path_(span, - ~[ type_ident ], - lifetime, - self_ty_params); - cx.mk_ty_path_path(span, self_type) + cx.ty_path(cx.path_all(span, false, ~[ type_ident ], lifetime, self_ty_params)) } pub fn create_derived_impl(cx: @ExtCtxt, @@ -222,18 +195,17 @@ pub fn create_derived_impl(cx: @ExtCtxt, for generics.ty_params.each |ty_param| { // extra restrictions on the generics parameters to the type being derived upon let mut bounds = do bounds_paths.map |&bound_path| { - cx.mk_trait_ty_param_bound_(bound_path) + cx.typarambound(bound_path) }; - let this_trait_bound = - cx.mk_trait_ty_param_bound_(trait_path); + let this_trait_bound = cx.typarambound(trait_path); bounds.push(this_trait_bound); - impl_generics.ty_params.push(cx.mk_ty_param(ty_param.ident, @bounds)); + impl_generics.ty_params.push(cx.typaram(ty_param.ident, @bounds)); } // Create the reference to the trait. - let trait_ref = cx.mk_trait_ref_(trait_path); + let trait_ref = cx.trait_ref(trait_path); // Create the type of `self`. let self_type = create_self_type_with_params(cx, @@ -241,12 +213,18 @@ pub fn create_derived_impl(cx: @ExtCtxt, type_ident, generics); - // Create the impl item. - let impl_item = ast::item_impl(impl_generics, - Some(trait_ref), - self_type, - methods.map(|x| *x)); - return create_impl_item(cx, span, impl_item); + let doc_attr = cx.attribute( + span, + cx.meta_name_value(span, + ~"doc", ast::lit_str(@~"Automatically derived."))); + cx.item( + span, + clownshoes_extensions, + ~[doc_attr], + ast::item_impl(impl_generics, + Some(trait_ref), + self_type, + methods.map(|x| *x))) } pub fn create_subpatterns(cx: @ExtCtxt, @@ -255,7 +233,7 @@ pub fn create_subpatterns(cx: @ExtCtxt, mutbl: ast::mutability) -> ~[@ast::pat] { do field_paths.map |&path| { - cx.mk_pat(span, + cx.pat(span, ast::pat_ident(ast::bind_by_ref(mutbl), path, None)) } } @@ -274,12 +252,12 @@ pub fn create_struct_pattern(cx: @ExtCtxt, -> (@ast::pat, ~[(Option, @expr)]) { if struct_def.fields.is_empty() { return ( - cx.mk_pat_ident_with_binding_mode( + cx.pat_ident_binding_mode( span, struct_ident, ast::bind_infer), ~[]); } - let matching_path = cx.mk_raw_path(span, ~[ struct_ident ]); + let matching_path = cx.path(span, ~[ struct_ident ]); let mut paths = ~[], ident_expr = ~[]; @@ -301,10 +279,10 @@ pub fn create_struct_pattern(cx: @ExtCtxt, cx.span_bug(span, "A struct with named and unnamed fields in `deriving`"); } }; - let path = cx.mk_raw_path(span, - ~[ cx.ident_of(fmt!("%s_%u", prefix, i)) ]); + let path = cx.path_ident(span, + cx.ident_of(fmt!("%s_%u", prefix, i))); paths.push(path); - ident_expr.push((opt_id, cx.mk_path_raw(span, path))); + ident_expr.push((opt_id, cx.expr_path(path))); } let subpats = create_subpatterns(cx, span, paths, mutbl); @@ -318,9 +296,9 @@ pub fn create_struct_pattern(cx: @ExtCtxt, push(ast::field_pat { ident: id.get(), pat: pat }) } }; - cx.mk_pat_struct(span, matching_path, field_pats) + cx.pat_struct(span, matching_path, field_pats) } else { - cx.mk_pat_enum(span, matching_path, subpats) + cx.pat_enum(span, matching_path, subpats) }; (pattern, ident_expr) @@ -337,24 +315,24 @@ pub fn create_enum_variant_pattern(cx: @ExtCtxt, match variant.node.kind { ast::tuple_variant_kind(ref variant_args) => { if variant_args.is_empty() { - return (cx.mk_pat_ident_with_binding_mode( + return (cx.pat_ident_binding_mode( span, variant_ident, ast::bind_infer), ~[]); } - let matching_path = cx.mk_raw_path(span, ~[ variant_ident ]); + let matching_path = cx.path_ident(span, variant_ident); let mut paths = ~[], ident_expr = ~[]; for uint::range(0, variant_args.len()) |i| { - let path = cx.mk_raw_path(span, - ~[ cx.ident_of(fmt!("%s_%u", prefix, i)) ]); + let path = cx.path_ident(span, + cx.ident_of(fmt!("%s_%u", prefix, i))); paths.push(path); - ident_expr.push((None, cx.mk_path_raw(span, path))); + ident_expr.push((None, cx.expr_path(path))); } let subpats = create_subpatterns(cx, span, paths, mutbl); - (cx.mk_pat_enum(span, matching_path, subpats), + (cx.pat_enum(span, matching_path, subpats), ident_expr) } ast::struct_variant_kind(struct_def) => { @@ -377,8 +355,6 @@ pub fn expand_enum_or_struct_match(cx: @ExtCtxt, span: span, arms: ~[ ast::arm ]) -> @expr { - let self_expr = cx.make_self(span); - let self_expr = cx.mk_unary(span, ast::deref, self_expr); - let self_match_expr = ast::expr_match(self_expr, arms); - cx.mk_expr(span, self_match_expr) + let self_expr = cx.expr_deref(span, cx.expr_self(span)); + cx.expr_match(span, self_expr, arms) } diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index b8e9de22fb0ef..16f754727b078 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -12,7 +12,7 @@ use ast; use ast::{meta_item, item, expr, ident}; use codemap::span; use ext::base::ExtCtxt; -use ext::build::{AstBuilder, Duplicate, Field}; +use ext::build::{AstBuilder, Duplicate}; use ext::deriving::generic::*; pub fn expand_deriving_rand(cx: @ExtCtxt, @@ -59,10 +59,9 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cx.ident_of("rand") ]; let rand_call = || { - cx.mk_call_global( - span, - copy rand_ident, - ~[ rng[0].duplicate(cx) ]) + cx.expr_call_global(span, + copy rand_ident, + ~[ rng[0].duplicate(cx) ]) }; return match *substr.fields { @@ -74,41 +73,39 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { cx.span_fatal(span, "`Rand` cannot be derived for enums with no variants"); } - let variant_count = cx.mk_uint(span, variants.len()); + let variant_count = cx.expr_uint(span, variants.len()); // need to specify the uint-ness of the random number - let u32_ty = cx.mk_ty_path(span, ~[cx.ident_of("uint")]); - let r_ty = cx.mk_ty_path(span, ~[cx.ident_of("R")]); - let rand_name = cx.mk_raw_path_(span, copy rand_ident, None, ~[ u32_ty, r_ty ]); - let rand_name = cx.mk_path_raw(span, rand_name); + let u32_ty = cx.ty_ident(span, cx.ident_of("uint")); + let r_ty = cx.ty_ident(span, cx.ident_of("R")); + let rand_name = cx.path_all(span, false, copy rand_ident, None, ~[ u32_ty, r_ty ]); + let rand_name = cx.expr_path(rand_name); - let rv_call = cx.mk_call_( - span, - rand_name, - ~[ rng[0].duplicate(cx) ]); + let rv_call = cx.expr_call(span, + rand_name, + ~[ rng[0].duplicate(cx) ]); // rand() % variants.len() - let rand_variant = cx.mk_binary(span, ast::rem, + let rand_variant = cx.expr_binary(span, ast::rem, rv_call, variant_count); let mut arms = do variants.mapi |i, id_sum| { - let i_expr = cx.mk_uint(span, i); - let pat = cx.mk_pat_lit(span, i_expr); + let i_expr = cx.expr_uint(span, i); + let pat = cx.pat_lit(span, i_expr); match *id_sum { (ident, ref summary) => { - cx.mk_arm(span, - ~[ pat ], - rand_thing(cx, span, ident, summary, rand_call)) + cx.arm(span, + ~[ pat ], + rand_thing(cx, span, ident, summary, rand_call)) } } }; // _ => {} at the end. Should never occur - arms.push(cx.mk_unreachable_arm(span)); + arms.push(cx.arm_unreachable(span)); - cx.mk_expr(span, - ast::expr_match(rand_variant, arms)) + cx.expr_match(span, rand_variant, arms) } _ => cx.bug("Non-static method in `deriving(Rand)`") }; @@ -117,24 +114,20 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { ctor_ident: ident, summary: &Either, rand_call: &fn() -> @expr) -> @expr { - let ctor_ident = ~[ ctor_ident ]; match *summary { Left(copy count) => { if count == 0 { - cx.mk_path(span, ctor_ident) + cx.expr_ident(span, ctor_ident) } else { let exprs = vec::from_fn(count, |_| rand_call()); - cx.mk_call(span, ctor_ident, exprs) + cx.expr_call_ident(span, ctor_ident, exprs) } } Right(ref fields) => { let rand_fields = do fields.map |ident| { - Field { - ident: *ident, - ex: rand_call() - } + cx.field_imm(span, *ident, rand_call()) }; - cx.mk_struct_e(span, ctor_ident, rand_fields) + cx.expr_struct_ident(span, ctor_ident, rand_fields) } } } diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs index 9198c67177e53..89b469575e54b 100644 --- a/src/libsyntax/ext/deriving/to_str.rs +++ b/src/libsyntax/ext/deriving/to_str.rs @@ -42,12 +42,12 @@ pub fn expand_deriving_to_str(cx: @ExtCtxt, fn to_str_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { match substr.self_args { [self_obj] => { - let self_addr = cx.mk_addr_of(span, self_obj); - cx.mk_call_global(span, - ~[cx.ident_of("core"), - cx.ident_of("sys"), - cx.ident_of("log_str")], - ~[self_addr]) + let self_addr = cx.expr_addr_of(span, self_obj); + cx.expr_call_global(span, + ~[cx.ident_of("core"), + cx.ident_of("sys"), + cx.ident_of("log_str")], + ~[self_addr]) } _ => cx.span_bug(span, "Invalid number of arguments in `deriving(ToStr)`") } diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index a9d13bfe79c48..99bc2d87b3095 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -55,9 +55,8 @@ pub impl<'self> Path<'self> { fn to_ty(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Ty { - cx.mk_ty_path_path(span, - self.to_path(cx, span, - self_ty, self_generics)) + cx.ty_path(self.to_path(cx, span, + self_ty, self_generics)) } fn to_path(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> @ast::Path { @@ -65,11 +64,7 @@ pub impl<'self> Path<'self> { let lt = mk_lifetime(cx, span, &self.lifetime); let tys = self.params.map(|t| t.to_ty(cx, span, self_ty, self_generics)); - if self.global { - cx.mk_raw_path_global_(span, idents, lt, tys) - } else { - cx.mk_raw_path_(span, idents, lt, tys) - } + cx.path_all(span, self.global, idents, lt, tys) } } @@ -106,7 +101,7 @@ pub fn nil_ty() -> Ty<'static> { fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<@ast::Lifetime> { match *lt { - Some(ref s) => Some(@cx.mk_lifetime(span, cx.ident_of(*s))), + Some(ref s) => Some(@cx.lifetime(span, cx.ident_of(*s))), None => None } } @@ -119,20 +114,20 @@ pub impl<'self> Ty<'self> { let raw_ty = ty.to_ty(cx, span, self_ty, self_generics); match *ptr { Owned => { - cx.mk_ty_uniq(span, raw_ty) + cx.ty_uniq(span, raw_ty) } Managed(mutbl) => { - cx.mk_ty_box(span, raw_ty, mutbl) + cx.ty_box(span, raw_ty, mutbl) } Borrowed(ref lt, mutbl) => { let lt = mk_lifetime(cx, span, lt); - cx.mk_ty_rptr(span, raw_ty, lt, mutbl) + cx.ty_rptr(span, raw_ty, lt, mutbl) } } } Literal(ref p) => { p.to_ty(cx, span, self_ty, self_generics) } Self => { - cx.mk_ty_path_path(span, self.to_path(cx, span, self_ty, self_generics)) + cx.ty_path(self.to_path(cx, span, self_ty, self_generics)) } Tuple(ref fields) => { let ty = if fields.is_empty() { @@ -141,7 +136,7 @@ pub impl<'self> Ty<'self> { ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics))) }; - cx.mk_ty(span, ty) + cx.ty(span, ty) } } } @@ -151,7 +146,7 @@ pub impl<'self> Ty<'self> { match *self { Self => { let self_params = do self_generics.ty_params.map |ty_param| { - cx.mk_ty_path(span, ~[ ty_param.ident ]) + cx.ty_ident(span, ty_param.ident) }; let lifetime = if self_generics.lifetimes.is_empty() { None @@ -159,8 +154,8 @@ pub impl<'self> Ty<'self> { Some(@*self_generics.lifetimes.get(0)) }; - cx.mk_raw_path_(span, ~[self_ty], lifetime, - opt_vec::take_vec(self_params)) + cx.path_all(span, false, ~[self_ty], lifetime, + opt_vec::take_vec(self_params)) } Literal(ref p) => { p.to_path(cx, span, self_ty, self_generics) @@ -177,9 +172,9 @@ fn mk_ty_param(cx: @ExtCtxt, span: span, name: &str, bounds: &[Path], let bounds = opt_vec::from( do bounds.map |b| { let path = b.to_path(cx, span, self_ident, self_generics); - cx.mk_trait_ty_param_bound_(path) + cx.typarambound(path) }); - cx.mk_ty_param(cx.ident_of(name), @bounds) + cx.typaram(cx.ident_of(name), @bounds) } fn mk_generics(lifetimes: ~[ast::Lifetime], ty_params: ~[ast::TyParam]) -> Generics { @@ -204,7 +199,7 @@ pub impl<'self> LifetimeBounds<'self> { fn to_generics(&self, cx: @ExtCtxt, span: span, self_ty: ident, self_generics: &Generics) -> Generics { let lifetimes = do self.lifetimes.map |lt| { - cx.mk_lifetime(span, cx.ident_of(*lt)) + cx.lifetime(span, cx.ident_of(*lt)) }; let ty_params = do self.bounds.map |t| { match t { @@ -220,7 +215,7 @@ pub impl<'self> LifetimeBounds<'self> { pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option) -> (@expr, ast::explicit_self) { - let self_path = cx.make_self(span); + let self_path = cx.expr_self(span); match *self_ptr { None => { (self_path, respan(span, ast::sty_value)) @@ -232,12 +227,12 @@ pub fn get_explicit_self(cx: @ExtCtxt, span: span, self_ptr: &Option) Owned => ast::sty_uniq(ast::m_imm), Managed(mutbl) => ast::sty_box(mutbl), Borrowed(ref lt, mutbl) => { - let lt = lt.map(|s| @cx.mk_lifetime(span, - cx.ident_of(*s))); + let lt = lt.map(|s| @cx.lifetime(span, + cx.ident_of(*s))); ast::sty_region(lt, mutbl) } }); - let self_expr = cx.mk_deref(span, self_path); + let self_expr = cx.expr_deref(span, self_path); (self_expr, self_ty) } } diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index fb7367b47bafc..32fbc9139998e 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -29,8 +29,8 @@ pub fn expand_syntax_ext(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) // Option rather than just an maybe-empty string. let e = match os::getenv(var) { - None => cx.mk_base_str(sp, ~""), - Some(ref s) => cx.mk_base_str(sp, copy *s) + None => cx.expr_str(sp, ~""), + Some(ref s) => cx.expr_str(sp, copy *s) }; MRExpr(e) } diff --git a/src/libsyntax/ext/fmt.rs b/src/libsyntax/ext/fmt.rs index 1e4ff03b610c8..55d3d4ee8349d 100644 --- a/src/libsyntax/ext/fmt.rs +++ b/src/libsyntax/ext/fmt.rs @@ -18,7 +18,6 @@ use ast; use codemap::span; use ext::base::*; use ext::base; -use ext::build; use ext::build::AstBuilder; use core::unstable::extfmt::ct::*; @@ -56,7 +55,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, } fn make_rt_path_expr(cx: @ExtCtxt, sp: span, nm: &str) -> @ast::expr { let path = make_path_vec(cx, nm); - cx.mk_path_global(sp, path) + cx.expr_path(cx.path_global(sp, path)) } // Produces an AST expression that represents a RT::conv record, // which tells the RT::conv* functions how to perform the conversion @@ -72,8 +71,8 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, FlagSignAlways => "flag_sign_always", FlagAlternate => "flag_alternate" }; - tmp_expr = cx.mk_binary(sp, ast::bitor, tmp_expr, - make_rt_path_expr(cx, sp, fstr)); + tmp_expr = cx.expr_binary(sp, ast::bitor, tmp_expr, + make_rt_path_expr(cx, sp, fstr)); } return tmp_expr; } @@ -83,10 +82,10 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, return make_rt_path_expr(cx, sp, "CountImplied"); } CountIs(c) => { - let count_lit = cx.mk_uint(sp, c as uint); + let count_lit = cx.expr_uint(sp, c as uint); let count_is_path = make_path_vec(cx, "CountIs"); let count_is_args = ~[count_lit]; - return cx.mk_call_global(sp, count_is_path, count_is_args); + return cx.expr_call_global(sp, count_is_path, count_is_args); } _ => cx.span_unimpl(sp, "unimplemented fmt! conversion") } @@ -107,22 +106,14 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, width_expr: @ast::expr, precision_expr: @ast::expr, ty_expr: @ast::expr) -> @ast::expr { let intr = cx.parse_sess().interner; - cx.mk_global_struct_e( + cx.expr_struct( sp, - make_path_vec(cx, "Conv"), + cx.path_global(sp, make_path_vec(cx, "Conv")), ~[ - build::Field { - ident: intr.intern("flags"), ex: flags_expr - }, - build::Field { - ident: intr.intern("width"), ex: width_expr - }, - build::Field { - ident: intr.intern("precision"), ex: precision_expr - }, - build::Field { - ident: intr.intern("ty"), ex: ty_expr - }, + cx.field_imm(sp, intr.intern("flags"), flags_expr), + cx.field_imm(sp, intr.intern("width"), width_expr), + cx.field_imm(sp, intr.intern("precision"), precision_expr), + cx.field_imm(sp, intr.intern("ty"), ty_expr) ] ) } @@ -139,7 +130,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, let path = make_path_vec(cx, fname); let cnv_expr = make_rt_conv_expr(cx, sp, cnv); let args = ~[cnv_expr, arg, buf]; - cx.mk_call_global(arg.span, path, args) + cx.expr_call_global(arg.span, path, args) } fn make_new_conv(cx: @ExtCtxt, sp: span, cnv: &Conv, @@ -197,10 +188,10 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, TyChar => ("char", arg), TyBits | TyOctal | TyHex(_) | TyInt(Unsigned) => ("uint", arg), TyFloat => ("float", arg), - TyPoly => ("poly", cx.mk_addr_of(sp, arg)) + TyPoly => ("poly", cx.expr_addr_of(sp, arg)) }; return make_conv_call(cx, arg.span, name, cnv, actual_arg, - cx.mk_mut_addr_of(arg.span, buf)); + cx.expr_mut_addr_of(arg.span, buf)); } fn log_conv(c: &Conv) { debug!("Building conversion:"); @@ -258,7 +249,7 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, /* 'ident' is the local buffer building up the result of fmt! */ let ident = cx.parse_sess().interner.intern("__fmtbuf"); - let buf = || cx.mk_path(fmt_sp, ~[ident]); + let buf = || cx.expr_ident(fmt_sp, ident); let str_ident = cx.parse_sess().interner.intern("str"); let push_ident = cx.parse_sess().interner.intern("push_str"); let mut stms = ~[]; @@ -275,14 +266,14 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, buffer with it directly. If it's actually the only piece, then there's no need for it to be mutable */ if i == 0 { - stms.push(cx.mk_local(fmt_sp, npieces > 1, ident, cx.mk_uniq_str(fmt_sp, s))); + stms.push(cx.stmt_let(fmt_sp, npieces > 1, + ident, cx.expr_str_uniq(fmt_sp, s))); } else { - let args = ~[cx.mk_mut_addr_of(fmt_sp, buf()), cx.mk_base_str(fmt_sp, s)]; - let call = cx.mk_call_global( - fmt_sp, - ~[str_ident, push_ident], - args); - stms.push(cx.mk_stmt(fmt_sp, call)); + let args = ~[cx.expr_mut_addr_of(fmt_sp, buf()), cx.expr_str(fmt_sp, s)]; + let call = cx.expr_call_global(fmt_sp, + ~[str_ident, push_ident], + args); + stms.push(cx.stmt_expr(call)); } } @@ -299,12 +290,11 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, /* If the first portion is a conversion, then the local buffer must be initialized as an empty string */ if i == 0 { - stms.push(cx.mk_local(fmt_sp, true, ident, - cx.mk_uniq_str(fmt_sp, ~""))); + stms.push(cx.stmt_let(fmt_sp, true, ident, + cx.expr_str_uniq(fmt_sp, ~""))); } - stms.push(cx.mk_stmt(fmt_sp, - make_new_conv(cx, fmt_sp, conv, - args[n], buf()))); + stms.push(cx.stmt_expr(make_new_conv(cx, fmt_sp, conv, + args[n], buf()))); } } } @@ -316,5 +306,5 @@ fn pieces_to_expr(cx: @ExtCtxt, sp: span, nargs, expected_nargs)); } - cx.mk_block(fmt_sp, ~[], stms, Some(buf())) + cx.expr_blk(cx.blk(fmt_sp, stms, Some(buf()))) } diff --git a/src/libsyntax/ext/pipes/ast_builder.rs b/src/libsyntax/ext/pipes/ast_builder.rs index 44f47c0d588a4..1f2e3f06a7310 100644 --- a/src/libsyntax/ext/pipes/ast_builder.rs +++ b/src/libsyntax/ext/pipes/ast_builder.rs @@ -16,7 +16,7 @@ use ast::ident; use ast; use codemap::span; -use ext::quote::rt::*; +// use ext::quote::rt::*; // Transitional reexports so qquote can find the paths it is looking for mod syntax { diff --git a/src/libsyntax/ext/pipes/pipec.rs b/src/libsyntax/ext/pipes/pipec.rs index 4362699378344..0482dffe6d44c 100644 --- a/src/libsyntax/ext/pipes/pipec.rs +++ b/src/libsyntax/ext/pipes/pipec.rs @@ -53,14 +53,13 @@ impl gen_send for message { assert!(next_state.tys.len() == next.generics.ty_params.len()); let arg_names = tys.mapi(|i, _ty| cx.ident_of(~"x_"+i.to_str())); - let args_ast = vec::map_zip(arg_names, *tys, |n, t| cx.arg(*n, *t)); + let args_ast = vec::map_zip(arg_names, *tys, |n, t| cx.arg(span, *n, *t)); let pipe_ty = cx.ty_path( path(~[this.data_name()], span) - .add_tys(cx.ty_vars_global(&this.generics.ty_params))); + .add_tys(cx.ty_vars(&this.generics.ty_params))); let args_ast = vec::append( - ~[cx.arg(cx.ident_of("pipe"), - pipe_ty)], + ~[cx.arg(span, cx.ident_of("pipe"), pipe_ty)], args_ast); let mut body = ~"{\n"; @@ -113,15 +112,16 @@ impl gen_send for message { let body = cx.parse_expr(body); let mut rty = cx.ty_path(path(~[next.data_name()], - span) - .add_tys(copy next_state.tys)); + span) + .add_tys(copy next_state.tys)); if try { rty = cx.ty_option(rty); } let name = cx.ident_of(if try { ~"try_" + name } else { name } ); - cx.item_fn_poly(name, + cx.item_fn_poly(dummy_sp(), + name, args_ast, rty, self.get_generics(), @@ -133,14 +133,15 @@ impl gen_send for message { let arg_names = tys.mapi(|i, _ty| (~"x_" + i.to_str())); let args_ast = do vec::map_zip(arg_names, *tys) |n, t| { - cx.arg(cx.ident_of(*n), *t) + cx.arg(span, cx.ident_of(*n), *t) }; let args_ast = vec::append( - ~[cx.arg(cx.ident_of("pipe"), + ~[cx.arg(span, + cx.ident_of("pipe"), cx.ty_path( path(~[this.data_name()], span) - .add_tys(cx.ty_vars_global( + .add_tys(cx.ty_vars( &this.generics.ty_params))))], args_ast); @@ -172,12 +173,13 @@ impl gen_send for message { let name = if try { ~"try_" + name } else { name }; - cx.item_fn_poly(cx.ident_of(name), + cx.item_fn_poly(dummy_sp(), + cx.ident_of(name), args_ast, if try { - cx.ty_option(cx.ty_nil_ast_builder()) + cx.ty_option(cx.ty_nil()) } else { - cx.ty_nil_ast_builder() + cx.ty_nil() }, self.get_generics(), cx.blk_expr(body)) @@ -187,7 +189,7 @@ impl gen_send for message { fn to_ty(&mut self, cx: @ExtCtxt) -> @ast::Ty { cx.ty_path(path(~[cx.ident_of(self.name())], self.span()) - .add_tys(cx.ty_vars_global(&self.get_generics().ty_params))) + .add_tys(cx.ty_vars(&self.get_generics().ty_params))) } } @@ -226,15 +228,15 @@ impl to_type_decls for state { None => tys }; - let v = cx.variant(cx.ident_of(name), span, tys); + let v = cx.variant(span, cx.ident_of(name), tys); items_msg.push(v); } ~[ cx.item_enum_poly( - name, self.span, + name, ast::enum_def { variants: items_msg }, cx.strip_bounds(&self.generics) ) @@ -263,8 +265,8 @@ impl to_type_decls for state { if !self.proto.is_bounded() { items.push( cx.item_ty_poly( - self.data_name(), self.span, + self.data_name(), cx.ty_path( path_global(~[cx.ident_of("core"), cx.ident_of("pipes"), @@ -274,15 +276,15 @@ impl to_type_decls for state { path(~[cx.ident_of("super"), self.data_name()], dummy_sp()) - .add_tys(cx.ty_vars_global( + .add_tys(cx.ty_vars( &self.generics.ty_params))))), cx.strip_bounds(&self.generics))); } else { items.push( cx.item_ty_poly( - self.data_name(), self.span, + self.data_name(), cx.ty_path( path_global(~[cx.ident_of("core"), cx.ident_of("pipes"), @@ -342,15 +344,18 @@ impl gen_init for protocol { } fn gen_buffer_init(&self, ext_cx: @ExtCtxt) -> @ast::expr { - ext_cx.expr_struct(path(~[ext_cx.ident_of("__Buffer")], - dummy_sp()), - self.states.map_to_vec(|s| { - let fty = s.to_ty(ext_cx); - ext_cx.field_imm(ext_cx.ident_of(s.name), - quote_expr!( - ::core::pipes::mk_packet::<$fty>() - )) - })) + ext_cx.expr_struct( + dummy_sp(), + path(~[ext_cx.ident_of("__Buffer")], + dummy_sp()), + self.states.map_to_vec(|s| { + let fty = s.to_ty(ext_cx); + ext_cx.field_imm(dummy_sp(), + ext_cx.ident_of(s.name), + quote_expr!( + ::core::pipes::mk_packet::<$fty>() + )) + })) } fn gen_init_bounded(&self, ext_cx: @ExtCtxt) -> @ast::expr { @@ -392,9 +397,9 @@ impl gen_init for protocol { } cx.ty_path(path(~[cx.ident_of("super"), - cx.ident_of("__Buffer")], - copy self.span) - .add_tys(cx.ty_vars_global(¶ms))) + cx.ident_of("__Buffer")], + copy self.span) + .add_tys(cx.ty_vars_global(¶ms))) } fn gen_buffer_type(&self, cx: @ExtCtxt) -> @ast::item { @@ -429,8 +434,8 @@ impl gen_init for protocol { }; cx.item_struct_poly( - cx.ident_of("__Buffer"), dummy_sp(), + cx.ident_of("__Buffer"), ast::struct_def { fields: fields, ctor_id: None @@ -454,13 +459,24 @@ impl gen_init for protocol { items.push(self.gen_buffer_type(cx)) } - items.push(cx.item_mod(cx.ident_of("client"), - copy self.span, + items.push(cx.item_mod(copy self.span, + cx.ident_of("client"), + ~[], ~[], client_states)); - items.push(cx.item_mod(cx.ident_of("server"), - copy self.span, + items.push(cx.item_mod(copy self.span, + cx.ident_of("server"), + ~[], ~[], server_states)); - cx.item_mod(cx.ident_of(copy self.name), copy self.span, items) + // XXX: Would be nice if our generated code didn't violate + // Rust coding conventions + let allows = cx.attribute( + copy self.span, + cx.meta_list(copy self.span, + ~"allow", + ~[cx.meta_word(copy self.span, ~"non_camel_case_types"), + cx.meta_word(copy self.span, ~"unused_mut")])); + cx.item_mod(copy self.span, cx.ident_of(copy self.name), + ~[allows], ~[], items) } } diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 5ab28b50e841c..1c57d500c221a 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -382,7 +382,7 @@ pub fn expand_quote_expr(cx: @ExtCtxt, pub fn expand_quote_item(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_attrs = cx.mk_uniq_vec_e(sp, ~[]); + let e_attrs = cx.expr_vec_uniq(sp, ~[]); base::MRExpr(expand_parse_call(cx, sp, "parse_item", ~[e_attrs], tts)) } @@ -390,7 +390,7 @@ pub fn expand_quote_item(cx: @ExtCtxt, pub fn expand_quote_pat(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_refutable = cx.mk_lit(sp, ast::lit_bool(true)); + let e_refutable = cx.expr_lit(sp, ast::lit_bool(true)); base::MRExpr(expand_parse_call(cx, sp, "parse_pat", ~[e_refutable], tts)) } @@ -398,7 +398,7 @@ pub fn expand_quote_pat(cx: @ExtCtxt, pub fn expand_quote_ty(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_param_colons = cx.mk_lit(sp, ast::lit_bool(false)); + let e_param_colons = cx.expr_lit(sp, ast::lit_bool(false)); base::MRExpr(expand_parse_call(cx, sp, "parse_ty", ~[e_param_colons], tts)) } @@ -406,7 +406,7 @@ pub fn expand_quote_ty(cx: @ExtCtxt, pub fn expand_quote_stmt(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { - let e_attrs = cx.mk_uniq_vec_e(sp, ~[]); + let e_attrs = cx.expr_vec_uniq(sp, ~[]); base::MRExpr(expand_parse_call(cx, sp, "parse_stmt", ~[e_attrs], tts)) } @@ -421,17 +421,17 @@ fn id_ext(cx: @ExtCtxt, str: &str) -> ast::ident { // Lift an ident to the expr that evaluates to that ident. fn mk_ident(cx: @ExtCtxt, sp: span, ident: ast::ident) -> @ast::expr { - let e_str = cx.mk_base_str(sp, cx.str_of(ident)); - cx.mk_method_call(sp, - cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), - id_ext(cx, "ident_of"), - ~[e_str]) + let e_str = cx.expr_str(sp, cx.str_of(ident)); + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext(cx, "ext_cx")), + id_ext(cx, "ident_of"), + ~[e_str]) } fn mk_bytepos(cx: @ExtCtxt, sp: span, bpos: BytePos) -> @ast::expr { - let path = ids_ext(cx, ~[~"BytePos"]); - let arg = cx.mk_uint(sp, bpos.to_uint()); - cx.mk_call(sp, path, ~[arg]) + let path = id_ext(cx, "BytePos"); + let arg = cx.expr_uint(sp, bpos.to_uint()); + cx.expr_call_ident(sp, path, ~[arg]) } fn mk_binop(cx: @ExtCtxt, sp: span, bop: token::binop) -> @ast::expr { @@ -447,22 +447,21 @@ fn mk_binop(cx: @ExtCtxt, sp: span, bop: token::binop) -> @ast::expr { SHL => "SHL", SHR => "SHR" }; - cx.mk_path(sp, - ids_ext(cx, ~[name.to_owned()])) + cx.expr_ident(sp, id_ext(cx, name)) } fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { match *tok { BINOP(binop) => { - return cx.mk_call(sp, - ids_ext(cx, ~[~"BINOP"]), - ~[mk_binop(cx, sp, binop)]); + return cx.expr_call_ident(sp, + id_ext(cx, "BINOP"), + ~[mk_binop(cx, sp, binop)]); } BINOPEQ(binop) => { - return cx.mk_call(sp, - ids_ext(cx, ~[~"BINOPEQ"]), - ~[mk_binop(cx, sp, binop)]); + return cx.expr_call_ident(sp, + id_ext(cx, "BINOPEQ"), + ~[mk_binop(cx, sp, binop)]); } LIT_INT(i, ity) => { @@ -474,15 +473,13 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { ast::ty_i32 => ~"ty_i32", ast::ty_i64 => ~"ty_i64" }; - let e_ity = - cx.mk_path(sp, - ids_ext(cx, ~[s_ity])); + let e_ity = cx.expr_ident(sp, id_ext(cx, s_ity)); - let e_i64 = cx.mk_lit(sp, ast::lit_int(i, ast::ty_i64)); + let e_i64 = cx.expr_lit(sp, ast::lit_int(i, ast::ty_i64)); - return cx.mk_call(sp, - ids_ext(cx, ~[~"LIT_INT"]), - ~[e_i64, e_ity]); + return cx.expr_call_ident(sp, + id_ext(cx, "LIT_INT"), + ~[e_i64, e_ity]); } LIT_UINT(u, uty) => { @@ -493,24 +490,21 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { ast::ty_u32 => ~"ty_u32", ast::ty_u64 => ~"ty_u64" }; - let e_uty = - cx.mk_path(sp, - ids_ext(cx, ~[s_uty])); + let e_uty = cx.expr_ident(sp, id_ext(cx, s_uty)); - let e_u64 = cx.mk_lit(sp, ast::lit_uint(u, ast::ty_u64)); + let e_u64 = cx.expr_lit(sp, ast::lit_uint(u, ast::ty_u64)); - return cx.mk_call(sp, - ids_ext(cx, ~[~"LIT_UINT"]), - ~[e_u64, e_uty]); + return cx.expr_call_ident(sp, + id_ext(cx, "LIT_UINT"), + ~[e_u64, e_uty]); } LIT_INT_UNSUFFIXED(i) => { - let e_i64 = cx.mk_lit(sp, - ast::lit_int(i, ast::ty_i64)); + let e_i64 = cx.expr_lit(sp, ast::lit_int(i, ast::ty_i64)); - return cx.mk_call(sp, - ids_ext(cx, ~[~"LIT_INT_UNSUFFIXED"]), - ~[e_i64]); + return cx.expr_call_ident(sp, + id_ext(cx, "LIT_INT_UNSUFFIXED"), + ~[e_i64]); } LIT_FLOAT(fident, fty) => { @@ -519,40 +513,38 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { ast::ty_f32 => ~"ty_f32", ast::ty_f64 => ~"ty_f64" }; - let e_fty = - cx.mk_path(sp, - ids_ext(cx, ~[s_fty])); + let e_fty = cx.expr_ident(sp, id_ext(cx, s_fty)); let e_fident = mk_ident(cx, sp, fident); - return cx.mk_call(sp, - ids_ext(cx, ~[~"LIT_FLOAT"]), - ~[e_fident, e_fty]); + return cx.expr_call_ident(sp, + id_ext(cx, "LIT_FLOAT"), + ~[e_fident, e_fty]); } LIT_STR(ident) => { - return cx.mk_call(sp, - ids_ext(cx, ~[~"LIT_STR"]), - ~[mk_ident(cx, sp, ident)]); + return cx.expr_call_ident(sp, + id_ext(cx, "LIT_STR"), + ~[mk_ident(cx, sp, ident)]); } IDENT(ident, b) => { - return cx.mk_call(sp, - ids_ext(cx, ~[~"IDENT"]), - ~[mk_ident(cx, sp, ident), - cx.mk_lit(sp, ast::lit_bool(b))]); + return cx.expr_call_ident(sp, + id_ext(cx, "IDENT"), + ~[mk_ident(cx, sp, ident), + cx.expr_bool(sp, b)]); } LIFETIME(ident) => { - return cx.mk_call(sp, - ids_ext(cx, ~[~"LIFETIME"]), - ~[mk_ident(cx, sp, ident)]); + return cx.expr_call_ident(sp, + id_ext(cx, "LIFETIME"), + ~[mk_ident(cx, sp, ident)]); } DOC_COMMENT(ident) => { - return cx.mk_call(sp, - ids_ext(cx, ~[~"DOC_COMMENT"]), - ~[mk_ident(cx, sp, ident)]); + return cx.expr_call_ident(sp, + id_ext(cx, "DOC_COMMENT"), + ~[mk_ident(cx, sp, ident)]); } INTERPOLATED(_) => fail!("quote! with interpolated token"), @@ -595,8 +587,7 @@ fn mk_token(cx: @ExtCtxt, sp: span, tok: &token::Token) -> @ast::expr { EOF => "EOF", _ => fail!() }; - cx.mk_path(sp, - ids_ext(cx, ~[name.to_owned()])) + cx.expr_ident(sp, id_ext(cx, name)) } @@ -606,19 +597,16 @@ fn mk_tt(cx: @ExtCtxt, sp: span, tt: &ast::token_tree) match *tt { ast::tt_tok(sp, ref tok) => { - let e_sp = cx.mk_path(sp, - ids_ext(cx, ~[~"sp"])); - let e_tok = - cx.mk_call(sp, - ids_ext(cx, ~[~"tt_tok"]), - ~[e_sp, mk_token(cx, sp, tok)]); + let e_sp = cx.expr_ident(sp, id_ext(cx, "sp")); + let e_tok = cx.expr_call_ident(sp, + id_ext(cx, "tt_tok"), + ~[e_sp, mk_token(cx, sp, tok)]); let e_push = - cx.mk_method_call(sp, - cx.mk_path(sp, ids_ext(cx, ~[~"tt"])), - id_ext(cx, "push"), - ~[e_tok]); - ~[cx.mk_stmt(sp, e_push)] - + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext(cx, "tt")), + id_ext(cx, "push"), + ~[e_tok]); + ~[cx.stmt_expr(e_push)] } ast::tt_delim(ref tts) => mk_tts(cx, sp, *tts), @@ -629,19 +617,18 @@ fn mk_tt(cx: @ExtCtxt, sp: span, tt: &ast::token_tree) // tt.push_all_move($ident.to_tokens(ext_cx)) let e_to_toks = - cx.mk_method_call(sp, - cx.mk_path(sp, ~[ident]), - id_ext(cx, "to_tokens"), - ~[cx.mk_path(sp, - ids_ext(cx, ~[~"ext_cx"]))]); + cx.expr_method_call(sp, + cx.expr_ident(sp, ident), + id_ext(cx, "to_tokens"), + ~[cx.expr_ident(sp, id_ext(cx, "ext_cx"))]); let e_push = - cx.mk_method_call(sp, - cx.mk_path(sp, ids_ext(cx, ~[~"tt"])), - id_ext(cx, "push_all_move"), - ~[e_to_toks]); + cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext(cx, "tt")), + id_ext(cx, "push_all_move"), + ~[e_to_toks]); - ~[cx.mk_stmt(sp, e_push)] + ~[cx.stmt_expr(e_push)] } } } @@ -677,11 +664,11 @@ fn expand_tts(cx: @ExtCtxt, // We want to emit a block expression that does a sequence of 'use's to // import the runtime module, followed by a tt-building expression. - let uses = ~[ cx.mk_glob_use(sp, ast::public, - ids_ext(cx, ~[~"syntax", - ~"ext", - ~"quote", - ~"rt"])) ]; + let uses = ~[ cx.view_use_glob(sp, ast::public, + ids_ext(cx, ~[~"syntax", + ~"ext", + ~"quote", + ~"rt"])) ]; // We also bind a single value, sp, to ext_cx.call_site() // @@ -709,24 +696,24 @@ fn expand_tts(cx: @ExtCtxt, // of quotes, for example) but at this point it seems not likely to be // worth the hassle. - let e_sp = cx.mk_method_call(sp, - cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), - id_ext(cx, "call_site"), - ~[]); + let e_sp = cx.expr_method_call(sp, + cx.expr_ident(sp, id_ext(cx, "ext_cx")), + id_ext(cx, "call_site"), + ~[]); - let stmt_let_sp = cx.mk_local(sp, false, - id_ext(cx, "sp"), - e_sp); + let stmt_let_sp = cx.stmt_let(sp, false, + id_ext(cx, "sp"), + e_sp); - let stmt_let_tt = cx.mk_local(sp, true, - id_ext(cx, "tt"), - cx.mk_uniq_vec_e(sp, ~[])); + let stmt_let_tt = cx.stmt_let(sp, true, + id_ext(cx, "tt"), + cx.expr_vec_uniq(sp, ~[])); - cx.mk_block(sp, uses, - ~[stmt_let_sp, - stmt_let_tt] + mk_tts(cx, sp, tts), - Some(cx.mk_path(sp, - ids_ext(cx, ~[~"tt"])))) + cx.expr_blk( + cx.blk_all(sp, uses, + ~[stmt_let_sp, + stmt_let_tt] + mk_tts(cx, sp, tts), + Some(cx.expr_ident(sp, id_ext(cx, "tt"))))) } fn expand_parse_call(cx: @ExtCtxt, @@ -736,27 +723,26 @@ fn expand_parse_call(cx: @ExtCtxt, tts: &[ast::token_tree]) -> @ast::expr { let tts_expr = expand_tts(cx, sp, tts); - let cfg_call = || cx.mk_method_call( - sp, cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), + let cfg_call = || cx.expr_method_call( + sp, cx.expr_ident(sp, id_ext(cx, "ext_cx")), id_ext(cx, "cfg"), ~[]); - let parse_sess_call = || cx.mk_method_call( - sp, cx.mk_path(sp, ids_ext(cx, ~[~"ext_cx"])), + let parse_sess_call = || cx.expr_method_call( + sp, cx.expr_ident(sp, id_ext(cx, "ext_cx")), id_ext(cx, "parse_sess"), ~[]); let new_parser_call = - cx.mk_call_global(sp, - ids_ext(cx, ~[~"syntax", - ~"ext", - ~"quote", - ~"rt", - ~"new_parser_from_tts"]), - ~[parse_sess_call(), - cfg_call(), - tts_expr]); - - cx.mk_method_call(sp, - new_parser_call, - id_ext(cx, parse_method), - arg_exprs) + cx.expr_call_global(sp, + ids_ext(cx, ~[~"syntax", + ~"ext", + ~"quote", + ~"rt", + ~"new_parser_from_tts"]), + ~[parse_sess_call(), + cfg_call(), + tts_expr]); + + cx.expr_method_call(sp, new_parser_call, + id_ext(cx, parse_method), + arg_exprs) } diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 40dc44ca99326..30e6b7cfc65c9 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -30,7 +30,7 @@ pub fn expand_line(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) let topmost = topmost_expn_info(cx.backtrace().get()); let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); - base::MRExpr(cx.mk_uint(topmost.call_site, loc.line)) + base::MRExpr(cx.expr_uint(topmost.call_site, loc.line)) } /* col!(): expands to the current column number */ @@ -40,7 +40,7 @@ pub fn expand_col(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) let topmost = topmost_expn_info(cx.backtrace().get()); let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo); - base::MRExpr(cx.mk_uint(topmost.call_site, loc.col.to_uint())) + base::MRExpr(cx.expr_uint(topmost.call_site, loc.col.to_uint())) } /* file!(): expands to the current filename */ @@ -53,19 +53,19 @@ pub fn expand_file(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) let topmost = topmost_expn_info(cx.backtrace().get()); let Loc { file: @FileMap { name: filename, _ }, _ } = cx.codemap().lookup_char_pos(topmost.call_site.lo); - base::MRExpr(cx.mk_base_str(topmost.call_site, filename)) + base::MRExpr(cx.expr_str(topmost.call_site, filename)) } pub fn expand_stringify(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { let s = pprust::tts_to_str(tts, cx.parse_sess().interner); - base::MRExpr(cx.mk_base_str(sp, s)) + base::MRExpr(cx.expr_str(sp, s)) } pub fn expand_mod(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) -> base::MacResult { base::check_zero_tts(cx, sp, tts, "module_path!"); - base::MRExpr(cx.mk_base_str(sp, + base::MRExpr(cx.expr_str(sp, str::connect(cx.mod_path().map( |x| cx.str_of(*x)), "::"))) } @@ -94,7 +94,7 @@ pub fn expand_include_str(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) } } - base::MRExpr(cx.mk_base_str(sp, result::unwrap(res))) + base::MRExpr(cx.expr_str(sp, result::unwrap(res))) } pub fn expand_include_bin(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) @@ -103,9 +103,9 @@ pub fn expand_include_bin(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree]) match io::read_whole_file(&res_rel_file(cx, sp, &Path(file))) { result::Ok(src) => { let u8_exprs = vec::map(src, |char| { - cx.mk_u8(sp, *char) + cx.expr_u8(sp, *char) }); - base::MRExpr(cx.mk_base_vec_e(sp, u8_exprs)) + base::MRExpr(cx.expr_vec(sp, u8_exprs)) } result::Err(ref e) => { cx.parse_sess().span_diagnostic.handler().fatal((*e)) From 6b525ecbda52bc890bdadf57e4c5b5ae10f47bd8 Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Wed, 22 May 2013 02:32:29 +0900 Subject: [PATCH 162/248] Take string slices --- src/libsyntax/print/pprust.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index a535e5d195f2a..3904d137faadf 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -656,10 +656,10 @@ pub fn visibility_to_str(vis: ast::visibility) -> ~str { } } -pub fn visibility_qualified(vis: ast::visibility, s: ~str) -> ~str { +pub fn visibility_qualified(vis: ast::visibility, s: &str) -> ~str { match vis { ast::private | ast::public => visibility_to_str(vis) + " " + s, - ast::inherited => copy s + ast::inherited => s.to_owned() } } From 743e4b044c0ed6e6b323eff7e4d07299fa59e1fb Mon Sep 17 00:00:00 2001 From: Seo Sanghyeon Date: Wed, 22 May 2013 02:48:56 +0900 Subject: [PATCH 163/248] Use static strings --- src/libsyntax/print/pprust.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 3904d137faadf..b5acdf8599c98 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -472,7 +472,7 @@ pub fn print_item(s: @ps, item: @ast::item) { (s.ann.pre)(ann_node); match item.node { ast::item_const(ty, expr) => { - head(s, visibility_qualified(item.vis, ~"static")); + head(s, visibility_qualified(item.vis, "static")); print_ident(s, item.ident); word_space(s, ":"); print_type(s, ty); @@ -500,7 +500,7 @@ pub fn print_item(s: @ps, item: @ast::item) { print_block_with_attrs(s, body, item.attrs); } ast::item_mod(ref _mod) => { - head(s, visibility_qualified(item.vis, ~"mod")); + head(s, visibility_qualified(item.vis, "mod")); print_ident(s, item.ident); nbsp(s); bopen(s); @@ -508,7 +508,7 @@ pub fn print_item(s: @ps, item: @ast::item) { bclose(s, item.span); } ast::item_foreign_mod(ref nmod) => { - head(s, visibility_qualified(item.vis, ~"extern")); + head(s, visibility_qualified(item.vis, "extern")); word_nbsp(s, nmod.abis.to_str()); match nmod.sort { ast::named => { @@ -525,7 +525,7 @@ pub fn print_item(s: @ps, item: @ast::item) { ast::item_ty(ty, ref params) => { ibox(s, indent_unit); ibox(s, 0u); - word_nbsp(s, visibility_qualified(item.vis, ~"type")); + word_nbsp(s, visibility_qualified(item.vis, "type")); print_ident(s, item.ident); print_generics(s, params); end(s); // end the inner ibox @@ -547,12 +547,12 @@ pub fn print_item(s: @ps, item: @ast::item) { ); } ast::item_struct(struct_def, ref generics) => { - head(s, visibility_qualified(item.vis, ~"struct")); + head(s, visibility_qualified(item.vis, "struct")); print_struct(s, struct_def, generics, item.ident, item.span); } ast::item_impl(ref generics, opt_trait, ty, ref methods) => { - head(s, visibility_qualified(item.vis, ~"impl")); + head(s, visibility_qualified(item.vis, "impl")); if generics.is_parameterized() { print_generics(s, generics); space(s.s); @@ -581,7 +581,7 @@ pub fn print_item(s: @ps, item: @ast::item) { } } ast::item_trait(ref generics, ref traits, ref methods) => { - head(s, visibility_qualified(item.vis, ~"trait")); + head(s, visibility_qualified(item.vis, "trait")); print_ident(s, item.ident); print_generics(s, generics); if traits.len() != 0u { @@ -624,7 +624,7 @@ fn print_trait_ref(s: @ps, t: &ast::trait_ref) { pub fn print_enum_def(s: @ps, enum_definition: &ast::enum_def, generics: &ast::Generics, ident: ast::ident, span: codemap::span, visibility: ast::visibility) { - head(s, visibility_qualified(visibility, ~"enum")); + head(s, visibility_qualified(visibility, "enum")); print_ident(s, ident); print_generics(s, generics); space(s.s); @@ -2169,7 +2169,7 @@ pub fn print_fn_header_info(s: @ps, onceness: ast::Onceness, opt_sigil: Option, vis: ast::visibility) { - word(s.s, visibility_qualified(vis, ~"")); + word(s.s, visibility_qualified(vis, "")); if abis != AbiSet::Rust() { word_nbsp(s, "extern"); From b6cf84f3e03cabc6a52b102b1178df319eb773b4 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Tue, 21 May 2013 12:55:54 -0700 Subject: [PATCH 164/248] testsuite: Test for #4780 --- src/test/run-pass/multibyte.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/test/run-pass/multibyte.rs diff --git a/src/test/run-pass/multibyte.rs b/src/test/run-pass/multibyte.rs new file mode 100644 index 0000000000000..7cb959b3437cc --- /dev/null +++ b/src/test/run-pass/multibyte.rs @@ -0,0 +1,14 @@ +// Copyright 2012 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. + +// Test that multibyte characters don't crash the compiler +fn main() { + io::println("마이너스 사인이 없으면"); +} From 1fadb97b68fa3b1f3e6fcc6198e4ac736bb85235 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Tue, 21 May 2013 12:58:27 -0700 Subject: [PATCH 165/248] testsuite: Update test for #2478. Still xfailed --- src/test/compile-fail/issue-2478.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/compile-fail/issue-2478.rs b/src/test/compile-fail/issue-2478.rs index d5663e57f4bf7..c6793e71ad97e 100644 --- a/src/test/compile-fail/issue-2478.rs +++ b/src/test/compile-fail/issue-2478.rs @@ -9,7 +9,7 @@ // except according to those terms. // xfail-test -fn foo() -> &'a int { +fn foo<'a>() -> &'a int { //~ ERROR unconstrained region return &x; } static x: int = 5; From 1df8a543f12b489b9cbd53fb72e768a68ff690d7 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Tue, 21 May 2013 13:12:31 -0700 Subject: [PATCH 166/248] testsuite: Add xfailed test cases --- src/test/run-pass/issue-3290.rs | 16 ++++++++++++++++ src/test/run-pass/issue-3796.rs | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 src/test/run-pass/issue-3290.rs create mode 100644 src/test/run-pass/issue-3796.rs diff --git a/src/test/run-pass/issue-3290.rs b/src/test/run-pass/issue-3290.rs new file mode 100644 index 0000000000000..3f8ce032d0d9e --- /dev/null +++ b/src/test/run-pass/issue-3290.rs @@ -0,0 +1,16 @@ +// 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. + +// xfail-test +fn main() { + let mut x = ~3; + x = x; + assert_eq!(*x, 3); +} diff --git a/src/test/run-pass/issue-3796.rs b/src/test/run-pass/issue-3796.rs new file mode 100644 index 0000000000000..0091c09625584 --- /dev/null +++ b/src/test/run-pass/issue-3796.rs @@ -0,0 +1,19 @@ +// 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. + +// xfail-test +#[deny(dead_assignment)]; +fn main() { + let mut x = 1; + let f: &fn() -> int = || { x + 20 }; + assert_eq!(f(), 21); + x += 1; + assert_eq!(f(), 22); +} From 8c68c4a52cc98608793bdab8188d76ce02649d68 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Tue, 21 May 2013 13:15:48 -0700 Subject: [PATCH 167/248] rustc: Don't generate code for unreachable expressions The way we deal with unreachable expressions in trans is pretty ad hoc, but this at least doesn't make it worse, and eliminates the LLVM assertion failure reported in #5741. --- src/librustc/middle/trans/expr.rs | 4 ++++ src/test/run-pass/issue-5741.rs | 14 ++++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 src/test/run-pass/issue-5741.rs diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index f457cc80da898..9349c2bcd26f3 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -499,6 +499,10 @@ fn trans_rvalue_stmt_unadjusted(bcx: block, expr: @ast::expr) -> block { let mut bcx = bcx; let _icx = bcx.insn_ctxt("trans_rvalue_stmt"); + if bcx.unreachable { + return bcx; + } + trace_span!(bcx, expr.span, @shorten(bcx.expr_to_str(expr))); match expr.node { diff --git a/src/test/run-pass/issue-5741.rs b/src/test/run-pass/issue-5741.rs new file mode 100644 index 0000000000000..b80e37a425b43 --- /dev/null +++ b/src/test/run-pass/issue-5741.rs @@ -0,0 +1,14 @@ +// 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. + +fn main() { + return; + while io::stdin().read_line() != ~"quit" { }; +} From 499b02213d7de83d301918d6068c75bd08941ac7 Mon Sep 17 00:00:00 2001 From: Jyun-Yan You Date: Wed, 22 May 2013 02:14:22 +0800 Subject: [PATCH 168/248] fix arm stack alignment --- src/libcore/rt/context.rs | 4 +++- src/rt/arch/arm/context.cpp | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/src/libcore/rt/context.rs b/src/libcore/rt/context.rs index f60ce3429579d..0d011ce42bab9 100644 --- a/src/libcore/rt/context.rs +++ b/src/libcore/rt/context.rs @@ -165,7 +165,9 @@ fn new_regs() -> ~Registers { ~([0, .. 32]) } #[cfg(target_arch = "arm")] fn initialize_call_frame(regs: &mut Registers, fptr: *c_void, arg: *c_void, sp: *mut uint) { - let sp = mut_offset(sp, -1); + let sp = align_down(sp); + // sp of arm eabi is 8-byte aligned + let sp = mut_offset(sp, -2); // The final return address. 0 indicates the bottom of the stack unsafe { *sp = 0; } diff --git a/src/rt/arch/arm/context.cpp b/src/rt/arch/arm/context.cpp index 2c735e410fa4a..7d90668aad53a 100644 --- a/src/rt/arch/arm/context.cpp +++ b/src/rt/arch/arm/context.cpp @@ -26,9 +26,11 @@ void context::call(void *f, void *arg, void *stack) // set up the stack uint32_t *sp = ( uint32_t *)stack; - //sp = align_down(sp); + sp = align_down(sp); // The final return address. 0 indicates the bottom of the stack - *--sp = 0; + // sp of arm eabi is 8-byte aligned + sp -= 2; + *sp = 0; regs.data[0] = ( uint32_t )arg; // r0 regs.data[13] = ( uint32_t )sp; //#52 sp, r13 From f8af2b50eee70ea912c18e5acb510789e59dd535 Mon Sep 17 00:00:00 2001 From: Jihyun Yu Date: Tue, 21 May 2013 18:04:55 +0900 Subject: [PATCH 169/248] fix issue #6209 --- src/librustc/middle/check_match.rs | 91 ++++++++++++++++++---- src/librustc/middle/const_eval.rs | 54 +++++++------ src/librustc/middle/trans/_match.rs | 77 +++++++++--------- src/librustc/middle/typeck/check/_match.rs | 16 +++- src/librustc/middle/typeck/check/mod.rs | 9 ++- src/test/compile-fail/match-ill-type1.rs | 6 ++ src/test/compile-fail/match-ill-type2.rs | 7 ++ 7 files changed, 181 insertions(+), 79 deletions(-) create mode 100644 src/test/compile-fail/match-ill-type1.rs create mode 100644 src/test/compile-fail/match-ill-type2.rs diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 7a81568117313..3717c6134726d 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -498,10 +498,27 @@ pub fn specialize(cx: @MatchCheckCtxt, lookup_const_by_id(cx.tcx, did).get(); let e_v = eval_const_expr(cx.tcx, const_expr); let match_ = match *ctor_id { - val(ref v) => compare_const_vals(&e_v, v) == 0, + val(ref v) => { + match compare_const_vals(&e_v, v) { + Some(val1) => (val1 == 0), + None => { + cx.tcx.sess.span_err(pat_span, + "mismatched types between arms"); + false + } + } + }, range(ref c_lo, ref c_hi) => { - compare_const_vals(c_lo, &e_v) >= 0 && - compare_const_vals(c_hi, &e_v) <= 0 + let m1 = compare_const_vals(c_lo, &e_v), + m2 = compare_const_vals(c_hi, &e_v); + match (m1, m2) { + (Some(val1), Some(val2)) => (val1 >= 0 && val2 <= 0), + _ => { + cx.tcx.sess.span_err(pat_span, + "mismatched types between ranges"); + false + } + } } single => true, _ => fail!("type error") @@ -529,10 +546,26 @@ pub fn specialize(cx: @MatchCheckCtxt, lookup_const_by_id(cx.tcx, did).get(); let e_v = eval_const_expr(cx.tcx, const_expr); let match_ = match *ctor_id { - val(ref v) => compare_const_vals(&e_v, v) == 0, + val(ref v) => + match compare_const_vals(&e_v, v) { + Some(val1) => (val1 == 0), + None => { + cx.tcx.sess.span_err(pat_span, + "mismatched types between arms"); + false + } + }, range(ref c_lo, ref c_hi) => { - compare_const_vals(c_lo, &e_v) >= 0 && - compare_const_vals(c_hi, &e_v) <= 0 + let m1 = compare_const_vals(c_lo, &e_v), + m2 = compare_const_vals(c_hi, &e_v); + match (m1, m2) { + (Some(val1), Some(val2)) => (val1 >= 0 && val2 <= 0), + _ => { + cx.tcx.sess.span_err(pat_span, + "mismatched types between ranges"); + false + } + } } single => true, _ => fail!("type error") @@ -619,10 +652,27 @@ pub fn specialize(cx: @MatchCheckCtxt, pat_lit(expr) => { let e_v = eval_const_expr(cx.tcx, expr); let match_ = match *ctor_id { - val(ref v) => compare_const_vals(&e_v, v) == 0, + val(ref v) => { + match compare_const_vals(&e_v, v) { + Some(val1) => val1 == 0, + None => { + cx.tcx.sess.span_err(pat_span, + "mismatched types between arms"); + false + } + } + }, range(ref c_lo, ref c_hi) => { - compare_const_vals(c_lo, &e_v) >= 0 && - compare_const_vals(c_hi, &e_v) <= 0 + let m1 = compare_const_vals(c_lo, &e_v), + m2 = compare_const_vals(c_hi, &e_v); + match (m1, m2) { + (Some(val1), Some(val2)) => (val1 >= 0 && val2 <= 0), + _ => { + cx.tcx.sess.span_err(pat_span, + "mismatched types between ranges"); + false + } + } } single => true, _ => fail!("type error") @@ -638,11 +688,22 @@ pub fn specialize(cx: @MatchCheckCtxt, _ => fail!("type error") }; let v_lo = eval_const_expr(cx.tcx, lo), - v_hi = eval_const_expr(cx.tcx, hi); - let match_ = compare_const_vals(&c_lo, &v_lo) >= 0 && - compare_const_vals(&c_hi, &v_hi) <= 0; - if match_ { Some(vec::to_owned(r.tail())) } else { None } - } + v_hi = eval_const_expr(cx.tcx, hi); + + let m1 = compare_const_vals(&c_lo, &v_lo), + m2 = compare_const_vals(&c_hi, &v_hi); + match (m1, m2) { + (Some(val1), Some(val2)) if val1 >= 0 && val2 <= 0 => { + Some(vec::to_owned(r.tail())) + }, + (Some(_), Some(_)) => None, + _ => { + cx.tcx.sess.span_err(pat_span, + "mismatched types between ranges"); + None + } + } + } pat_vec(before, slice, after) => { match *ctor_id { vec(_) => { diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 6cc4409aee660..751767fb58c14 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -420,65 +420,73 @@ pub fn lit_to_const(lit: @lit) -> const_val { } } -pub fn compare_const_vals(a: &const_val, b: &const_val) -> int { +pub fn compare_const_vals(a: &const_val, b: &const_val) -> Option { match (a, b) { (&const_int(a), &const_int(b)) => { if a == b { - 0 + Some(0) } else if a < b { - -1 + Some(-1) } else { - 1 + Some(1) } } (&const_uint(a), &const_uint(b)) => { if a == b { - 0 + Some(0) } else if a < b { - -1 + Some(-1) } else { - 1 + Some(1) } } (&const_float(a), &const_float(b)) => { if a == b { - 0 + Some(0) } else if a < b { - -1 + Some(-1) } else { - 1 + Some(1) } } (&const_str(ref a), &const_str(ref b)) => { if (*a) == (*b) { - 0 + Some(0) } else if (*a) < (*b) { - -1 + Some(-1) } else { - 1 + Some(1) } } (&const_bool(a), &const_bool(b)) => { if a == b { - 0 + Some(0) } else if a < b { - -1 + Some(-1) } else { - 1 + Some(1) } } - _ => fail!("compare_const_vals: ill-typed comparison") + _ => { + None + } } } -pub fn compare_lit_exprs(tcx: middle::ty::ctxt, a: @expr, b: @expr) -> int { - compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b)) +pub fn compare_lit_exprs(tcx: middle::ty::ctxt, a: @expr, b: @expr) -> Option { + compare_const_vals(&eval_const_expr(tcx, a), &eval_const_expr(tcx, b)) } -pub fn lit_expr_eq(tcx: middle::ty::ctxt, a: @expr, b: @expr) -> bool { - compare_lit_exprs(tcx, a, b) == 0 +pub fn lit_expr_eq(tcx: middle::ty::ctxt, a: @expr, b: @expr) -> Option { + match compare_lit_exprs(tcx, a, b) { + Some(val) => Some(val == 0), + None => None, + } } -pub fn lit_eq(a: @lit, b: @lit) -> bool { - compare_const_vals(&lit_to_const(a), &lit_to_const(b)) == 0 +pub fn lit_eq(a: @lit, b: @lit) -> Option { + match compare_const_vals(&lit_to_const(a), &lit_to_const(b)) { + Some(val) => Some(val == 0), + None => None, + } } diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index fa545f033a584..c7f2da9232961 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -193,48 +193,55 @@ pub enum Opt { pub fn opt_eq(tcx: ty::ctxt, a: &Opt, b: &Opt) -> bool { match (a, b) { - (&lit(a), &lit(b)) => { - match (a, b) { - (UnitLikeStructLit(a), UnitLikeStructLit(b)) => a == b, - _ => { - let a_expr; - match a { - ExprLit(existing_a_expr) => a_expr = existing_a_expr, - ConstLit(a_const) => { - let e = const_eval::lookup_const_by_id(tcx, a_const); - a_expr = e.get(); - } - UnitLikeStructLit(_) => { - fail!("UnitLikeStructLit should have been handled \ - above") + (&lit(a), &lit(b)) => { + match (a, b) { + (UnitLikeStructLit(a), UnitLikeStructLit(b)) => a == b, + _ => { + let a_expr; + match a { + ExprLit(existing_a_expr) => a_expr = existing_a_expr, + ConstLit(a_const) => { + let e = const_eval::lookup_const_by_id(tcx, a_const); + a_expr = e.get(); + } + UnitLikeStructLit(_) => { + fail!("UnitLikeStructLit should have been handled \ + above") + } } - } - let b_expr; - match b { - ExprLit(existing_b_expr) => b_expr = existing_b_expr, - ConstLit(b_const) => { - let e = const_eval::lookup_const_by_id(tcx, b_const); - b_expr = e.get(); + let b_expr; + match b { + ExprLit(existing_b_expr) => b_expr = existing_b_expr, + ConstLit(b_const) => { + let e = const_eval::lookup_const_by_id(tcx, b_const); + b_expr = e.get(); + } + UnitLikeStructLit(_) => { + fail!("UnitLikeStructLit should have been handled \ + above") + } } - UnitLikeStructLit(_) => { - fail!("UnitLikeStructLit should have been handled \ - above") + + match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) { + Some(val1) => val1 == 0, + None => fail!("compare_list_exprs: type mismatch"), } } - - const_eval::compare_lit_exprs(tcx, a_expr, b_expr) == 0 } } - } - (&range(a1, a2), &range(b1, b2)) => { - const_eval::compare_lit_exprs(tcx, a1, b1) == 0 && - const_eval::compare_lit_exprs(tcx, a2, b2) == 0 - } - (&var(a, _), &var(b, _)) => a == b, - (&vec_len_eq(a), &vec_len_eq(b)) => a == b, - (&vec_len_ge(a, _), &vec_len_ge(b, _)) => a == b, - _ => false + (&range(a1, a2), &range(b1, b2)) => { + let m1 = const_eval::compare_lit_exprs(tcx, a1, b1); + let m2 = const_eval::compare_lit_exprs(tcx, a2, b2); + match (m1, m2) { + (Some(val1), Some(val2)) => (val1 == 0 && val2 == 0), + _ => fail!("compare_list_exprs: type mismatch"), + } + } + (&var(a, _), &var(b, _)) => a == b, + (&vec_len_eq(a), &vec_len_eq(b)) => a == b, + (&vec_len_ge(a, _), &vec_len_ge(b, _)) => a == b, + _ => false } } diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index 07083459020b1..d6ef27ab7ff0c 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -408,8 +408,18 @@ pub fn check_pat(pcx: &pat_ctxt, pat: @ast::pat, expected: ty::t) { // no-op } else if !ty::type_is_numeric(b_ty) { tcx.sess.span_err(pat.span, "non-numeric type used in range"); - } else if !valid_range_bounds(fcx.ccx, begin, end) { - tcx.sess.span_err(begin.span, "lower range bound must be less than upper"); + } else { + match valid_range_bounds(fcx.ccx, begin, end) { + Some(false) => { + tcx.sess.span_err(begin.span, + "lower range bound must be less than upper"); + }, + None => { + tcx.sess.span_err(begin.span, + "mismatched types in range"); + }, + _ => { }, + } } fcx.write_ty(pat.id, b_ty); } diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index d45882cc17b05..cd58dc5fe48df 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -1044,8 +1044,11 @@ pub fn check_lit(fcx: @mut FnCtxt, lit: @ast::lit) -> ty::t { pub fn valid_range_bounds(ccx: @mut CrateCtxt, from: @ast::expr, to: @ast::expr) - -> bool { - const_eval::compare_lit_exprs(ccx.tcx, from, to) <= 0 + -> Option { + match const_eval::compare_lit_exprs(ccx.tcx, from, to) { + Some(val) => Some(val <= 0), + None => None + } } pub fn check_expr_has_type( diff --git a/src/test/compile-fail/match-ill-type1.rs b/src/test/compile-fail/match-ill-type1.rs new file mode 100644 index 0000000000000..4d2b95b61ea8d --- /dev/null +++ b/src/test/compile-fail/match-ill-type1.rs @@ -0,0 +1,6 @@ +fn main() { + match 1 { + 1..2u => 1, //~ ERROR mismatched types in range + _ => 2, + }; +} diff --git a/src/test/compile-fail/match-ill-type2.rs b/src/test/compile-fail/match-ill-type2.rs new file mode 100644 index 0000000000000..020ccde845246 --- /dev/null +++ b/src/test/compile-fail/match-ill-type2.rs @@ -0,0 +1,7 @@ +fn main() { + match 1 { + 1 => 1, //~ ERROR mismatched types between arms + 2u => 1, + _ => 2, + }; +} From da94580ddc605318a6bb7082a4b7907509d2dcc4 Mon Sep 17 00:00:00 2001 From: kud1ing Date: Wed, 22 May 2013 10:03:51 +0300 Subject: [PATCH 170/248] "Type :help for help", similar to ghci --- src/librusti/rusti.rc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librusti/rusti.rc b/src/librusti/rusti.rc index 3ec19ce1a1476..1671dfe11a309 100644 --- a/src/librusti/rusti.rc +++ b/src/librusti/rusti.rc @@ -389,7 +389,7 @@ pub fn main() { if istty { io::println("WARNING: The Rust REPL is experimental and may be"); io::println("unstable. If you encounter problems, please use the"); - io::println("compiler instead."); + io::println("compiler instead. Type :help for help."); unsafe { do rl::complete |line, suggest| { From 6c33f5044b0d7d0fe1cd0a726e37f3a915dcf8ef Mon Sep 17 00:00:00 2001 From: Jihyun Yu Date: Wed, 22 May 2013 16:11:48 +0900 Subject: [PATCH 171/248] Fix #6342 --- src/libsyntax/parse/parser.rs | 13 +++++++++---- src/test/compile-fail/extern-no-fn.rs | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 src/test/compile-fail/extern-no-fn.rs diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 9f11b059a9535..4f81194acd781 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -4186,10 +4186,10 @@ pub impl Parser { return iovi_foreign_item(item); } if (self.is_keyword("fn") || self.is_keyword("pure") || - self.is_keyword("unsafe")) { + self.is_keyword("unsafe")) { // FOREIGN FUNCTION ITEM - let item = self.parse_item_foreign_fn(attrs); - return iovi_foreign_item(item); + let item = self.parse_item_foreign_fn(attrs); + return iovi_foreign_item(item); } self.parse_macro_use_or_failure(attrs,macros_allowed,lo,visibility) } @@ -4504,7 +4504,12 @@ pub impl Parser { let mut foreign_items = ~[]; loop { match self.parse_foreign_item(/*bad*/ copy attrs, macros_allowed) { - iovi_none => break, + iovi_none => { + if *self.token == token::RBRACE { + break + } + self.unexpected(); + }, iovi_view_item(view_item) => { // I think this can't occur: self.span_err(view_item.span, diff --git a/src/test/compile-fail/extern-no-fn.rs b/src/test/compile-fail/extern-no-fn.rs new file mode 100644 index 0000000000000..164cbe5417402 --- /dev/null +++ b/src/test/compile-fail/extern-no-fn.rs @@ -0,0 +1,17 @@ +// Copyright 2012 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. + +// error-pattern:unexpected token +extern { + f(); +} + +fn main() { +} From 06685bacf8ba8cfbf1473ab46f0a1746bfbff58f Mon Sep 17 00:00:00 2001 From: Jihyun Yu Date: Wed, 22 May 2013 21:01:21 +0900 Subject: [PATCH 172/248] add smallintset --- src/libstd/smallintmap.rs | 243 +++++++++++++++++++++++++++++++++++++- 1 file changed, 242 insertions(+), 1 deletion(-) diff --git a/src/libstd/smallintmap.rs b/src/libstd/smallintmap.rs index 3c1f53b25f7f8..aa8372bab78d9 100644 --- a/src/libstd/smallintmap.rs +++ b/src/libstd/smallintmap.rs @@ -14,7 +14,8 @@ */ use core::container::{Container, Mutable, Map, Set}; -use core::old_iter::{BaseIter}; +use core::old_iter::BaseIter; +use core::old_iter; use core::option::{Some, None}; use core::util::replace; @@ -181,6 +182,87 @@ pub impl SmallIntMap { } } +pub struct SmallIntSet { + priv map: SmallIntMap<()> +} + +impl Container for SmallIntSet { + /// Return the number of elements in the map + fn len(&const self) -> uint { + self.map.len() + } + + /// Return true if the map contains no elements + fn is_empty(&const self) -> bool { self.len() == 0 } +} + +impl Mutable for SmallIntSet { + /// Clear the map, removing all key-value pairs. + fn clear(&mut self) { self.map.clear() } +} + +impl BaseIter for SmallIntSet { + /// Visit all values in order + fn each(&self, f: &fn(&uint) -> bool) -> bool { self.map.each_key(f) } + fn size_hint(&self) -> Option { Some(self.len()) } +} + +impl Set for SmallIntSet { + /// Return true if the set contains a value + fn contains(&self, value: &uint) -> bool { self.map.contains_key(value) } + + /// Add a value to the set. Return true if the value was not already + /// present in the set. + fn insert(&mut self, value: uint) -> bool { self.map.insert(value, ()) } + + /// Remove a value from the set. Return true if the value was + /// present in the set. + fn remove(&mut self, value: &uint) -> bool { self.map.remove(value) } + + /// Return true if the set has no elements in common with `other`. + /// This is equivalent to checking for an empty uintersection. + fn is_disjoint(&self, other: &SmallIntSet) -> bool { + old_iter::all(self, |v| !other.contains(v)) + } + + /// Return true if the set is a subset of another + fn is_subset(&self, other: &SmallIntSet) -> bool { + old_iter::all(self, |v| other.contains(v)) + } + + /// Return true if the set is a superset of another + fn is_superset(&self, other: &SmallIntSet) -> bool { + other.is_subset(self) + } + + /// Visit the values representing the difference + fn difference(&self, other: &SmallIntSet, f: &fn(&uint) -> bool) -> bool { + self.each(|v| other.contains(v) || f(v)) + } + + /// Visit the values representing the symmetric difference + fn symmetric_difference(&self, + other: &SmallIntSet, + f: &fn(&uint) -> bool) -> bool { + self.difference(other, f) && other.difference(self, f) + } + + /// Visit the values representing the uintersection + fn intersection(&self, other: &SmallIntSet, f: &fn(&uint) -> bool) -> bool { + self.each(|v| !other.contains(v) || f(v)) + } + + /// Visit the values representing the union + fn union(&self, other: &SmallIntSet, f: &fn(&uint) -> bool) -> bool { + self.each(f) && other.each(|v| self.contains(v) || f(v)) + } +} + +pub impl SmallIntSet { + /// Create an empty SmallIntSet + fn new() -> SmallIntSet { SmallIntSet{map: SmallIntMap::new()} } +} + #[cfg(test)] mod tests { use super::SmallIntMap; @@ -273,3 +355,162 @@ mod tests { assert_eq!(m.pop(&1), None); } } + +#[cfg(test)] +mod test_set { + use super::SmallIntSet; + + #[test] + fn test_disjoint() { + let mut xs = SmallIntSet::new(); + let mut ys = SmallIntSet::new(); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(5)); + assert!(ys.insert(11)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(xs.insert(7)); + assert!(xs.insert(19)); + assert!(xs.insert(4)); + assert!(ys.insert(2)); + assert!(xs.is_disjoint(&ys)); + assert!(ys.is_disjoint(&xs)); + assert!(ys.insert(7)); + assert!(!xs.is_disjoint(&ys)); + assert!(!ys.is_disjoint(&xs)); + } + + #[test] + fn test_subset_and_superset() { + let mut a = SmallIntSet::new(); + assert!(a.insert(0)); + assert!(a.insert(5)); + assert!(a.insert(11)); + assert!(a.insert(7)); + + let mut b = SmallIntSet::new(); + assert!(b.insert(0)); + assert!(b.insert(7)); + assert!(b.insert(19)); + assert!(b.insert(250)); + assert!(b.insert(11)); + assert!(b.insert(200)); + + assert!(!a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(!b.is_superset(&a)); + + assert!(b.insert(5)); + + assert!(a.is_subset(&b)); + assert!(!a.is_superset(&b)); + assert!(!b.is_subset(&a)); + assert!(b.is_superset(&a)); + } + + #[test] + fn test_intersection() { + let mut a = SmallIntSet::new(); + let mut b = SmallIntSet::new(); + + assert!(a.insert(11)); + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(77)); + assert!(a.insert(103)); + assert!(a.insert(5)); + + assert!(b.insert(2)); + assert!(b.insert(11)); + assert!(b.insert(77)); + assert!(b.insert(5)); + assert!(b.insert(3)); + + let mut i = 0; + let expected = [3, 5, 11, 77]; + for a.intersection(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert_eq!(i, expected.len()); + } + + #[test] + fn test_difference() { + let mut a = SmallIntSet::new(); + let mut b = SmallIntSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(3)); + assert!(b.insert(9)); + + let mut i = 0; + let expected = [1, 5, 11]; + for a.difference(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert_eq!(i, expected.len()); + } + + #[test] + fn test_symmetric_difference() { + let mut a = SmallIntSet::new(); + let mut b = SmallIntSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + + assert!(b.insert(3)); + assert!(b.insert(9)); + assert!(b.insert(14)); + assert!(b.insert(22)); + + let mut i = 0; + let expected = [1, 5, 11, 14, 22]; + for a.symmetric_difference(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert_eq!(i, expected.len()); + } + + #[test] + fn test_union() { + let mut a = SmallIntSet::new(); + let mut b = SmallIntSet::new(); + + assert!(a.insert(1)); + assert!(a.insert(3)); + assert!(a.insert(5)); + assert!(a.insert(9)); + assert!(a.insert(11)); + assert!(a.insert(16)); + assert!(a.insert(19)); + assert!(a.insert(24)); + + assert!(b.insert(1)); + assert!(b.insert(5)); + assert!(b.insert(9)); + assert!(b.insert(13)); + assert!(b.insert(19)); + + let mut i = 0; + let expected = [1, 3, 5, 9, 11, 13, 16, 19, 24]; + for a.union(&b) |x| { + assert!(vec::contains(expected, x)); + i += 1 + } + assert_eq!(i, expected.len()); + } +} From 5a424813667a27a0def860d96a5e79801718592b Mon Sep 17 00:00:00 2001 From: Benjamin Herr Date: Wed, 22 May 2013 15:53:26 +0200 Subject: [PATCH 173/248] declare that "///" is still a doc comment, just not "////+" (fixes #5838) --- src/libsyntax/parse/lexer.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index 5340293bb0249..6cd1ad9077f7d 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -247,7 +247,8 @@ fn consume_whitespace_and_comments(rdr: @mut StringReader) } pub fn is_line_non_doc_comment(s: &str) -> bool { - s.trim_right().all(|ch| ch == '/') + let s = s.trim_right(); + s.len() > 3 && s.all(|ch| ch == '/') } // PRECONDITION: rdr.curr is not whitespace @@ -268,7 +269,7 @@ fn consume_any_line_comment(rdr: @mut StringReader) str::push_char(&mut acc, rdr.curr); bump(rdr); } - // but comments with only "/"s are not + // but comments with only more "/"s are not if !is_line_non_doc_comment(acc) { return Some(TokenAndSpan{ tok: token::DOC_COMMENT(rdr.interner.intern(acc)), @@ -891,4 +892,10 @@ mod test { let id = env.interner.intern("abc"); assert_eq!(tok, token::LIFETIME(id)); } + + #[test] fn line_doc_comments() { + assert!(!is_line_non_doc_comment("///")); + assert!(!is_line_non_doc_comment("/// blah")); + assert!(is_line_non_doc_comment("////")); + } } From e64339645b675f3a1dbc21ae785fe9a754f0cb71 Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Tue, 21 May 2013 20:26:45 -0400 Subject: [PATCH 174/248] Implement static_assert attribute This verifies that a static item evaluates to true, at compile time. --- src/librustc/middle/trans/base.rs | 21 ++++++++++++++++++++- src/test/compile-fail/static-assert.rs | 5 +++++ src/test/compile-fail/static-assert2.rs | 4 ++++ src/test/run-pass/static-assert.rs | 14 ++++++++++++++ 4 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/test/compile-fail/static-assert.rs create mode 100644 src/test/compile-fail/static-assert2.rs create mode 100644 src/test/run-pass/static-assert.rs diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 94ca02b22554b..17d3e2c4dfefe 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -2147,7 +2147,26 @@ pub fn trans_item(ccx: @CrateContext, item: &ast::item) { trans_enum_def(ccx, enum_definition, item.id, vi, &mut i); } } - ast::item_const(_, expr) => consts::trans_const(ccx, expr, item.id), + ast::item_const(_, expr) => { + consts::trans_const(ccx, expr, item.id); + // Do static_assert checking. It can't really be done much earlier because we need to get + // the value of the bool out of LLVM + for item.attrs.each |attr| { + match attr.node.value.node { + ast::meta_word(x) => { + if x.slice(0, x.len()) == "static_assert" { + let v = ccx.const_values.get_copy(&item.id); + unsafe { + if !(llvm::LLVMConstIntGetZExtValue(v) as bool) { + ccx.sess.span_fatal(expr.span, "static assertion failed"); + } + } + } + }, + _ => () + } + } + }, ast::item_foreign_mod(ref foreign_mod) => { foreign::trans_foreign_mod(ccx, path, foreign_mod); } diff --git a/src/test/compile-fail/static-assert.rs b/src/test/compile-fail/static-assert.rs new file mode 100644 index 0000000000000..06f8c9f1a3257 --- /dev/null +++ b/src/test/compile-fail/static-assert.rs @@ -0,0 +1,5 @@ +#[static_assert] +static a: bool = false; //~ ERROR static assertion failed + +fn main() { +} diff --git a/src/test/compile-fail/static-assert2.rs b/src/test/compile-fail/static-assert2.rs new file mode 100644 index 0000000000000..de1c6427e14b2 --- /dev/null +++ b/src/test/compile-fail/static-assert2.rs @@ -0,0 +1,4 @@ +#[static_assert] +static e: bool = 1 == 2; //~ ERROR static assertion failed + +fn main() {} diff --git a/src/test/run-pass/static-assert.rs b/src/test/run-pass/static-assert.rs new file mode 100644 index 0000000000000..81b0c9ff28c3f --- /dev/null +++ b/src/test/run-pass/static-assert.rs @@ -0,0 +1,14 @@ +#[static_assert] +static b: bool = true; + +#[static_assert] +static c: bool = 1 == 1; + +#[static_assert] +static d: bool = 1 != 2; + +#[static_assert] +static f: bool = (4/2) == 2; + +fn main() { +} From acf920fe4bd521f92bea7add707fa029a9e4f0a7 Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Wed, 22 May 2013 01:27:39 -0400 Subject: [PATCH 175/248] Add static_assert doc blurb --- doc/rust.md | 1 + 1 file changed, 1 insertion(+) diff --git a/doc/rust.md b/doc/rust.md index a115f41ae864b..bb0438016b843 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -1426,6 +1426,7 @@ names are effectively reserved. Some significant attributes include: by the compiler can be found via `rustc -W help`. * The `deriving` attribute, for automatically generating implementations of certain traits. +* The `static_assert` attribute, for asserting that a static bool is true at compiletime Other attributes may be added or removed during development of the language. From fd94bd984e6e0772f501e57f9b2f36a3ac420640 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Tue, 14 May 2013 13:02:54 -0700 Subject: [PATCH 176/248] testsuite: Add passing test for #4107 --- src/test/run-pass/issue-4107.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/test/run-pass/issue-4107.rs diff --git a/src/test/run-pass/issue-4107.rs b/src/test/run-pass/issue-4107.rs new file mode 100644 index 0000000000000..94a42db047ef6 --- /dev/null +++ b/src/test/run-pass/issue-4107.rs @@ -0,0 +1,33 @@ +// 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. + +fn main() { + let id: &Mat2 = &Matrix::identity(); +} + +pub trait Index { } +pub trait Dimensional: Index { } + +pub struct Mat2 { x: () } +pub struct Vec2 { x: () } + +impl Dimensional> for Mat2 { } +impl Index> for Mat2 { } + +impl Dimensional for Vec2 { } +impl Index for Vec2 { } + +pub trait Matrix: Dimensional { + fn identity() -> Self; +} + +impl Matrix> for Mat2 { + fn identity() -> Mat2 { Mat2{ x: () } } +} From 1aae163d445d0074d893c4ab5c309449c1b6bd48 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 22 May 2013 14:13:04 -0700 Subject: [PATCH 177/248] testsuite: Make main fn public --- src/test/run-pass/issue-4107.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/test/run-pass/issue-4107.rs b/src/test/run-pass/issue-4107.rs index 94a42db047ef6..549d9cb734c00 100644 --- a/src/test/run-pass/issue-4107.rs +++ b/src/test/run-pass/issue-4107.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn main() { +pub fn main() { let id: &Mat2 = &Matrix::identity(); } From ee1b41981873805c69a122c0e6ed25d39e55b535 Mon Sep 17 00:00:00 2001 From: Graydon Hoare Date: Wed, 22 May 2013 15:35:25 -0700 Subject: [PATCH 178/248] revert no-longer-required workaround for mystery bug, close #3396 --- src/librustc/metadata/encoder.rs | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index d27bfd081bc65..09d48efe09716 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -1455,19 +1455,10 @@ pub fn encode_metadata(parms: EncodeParams, crate: &crate) -> ~[u8] { // remaining % 4 bytes. wr.write(&[0u8, 0u8, 0u8, 0u8]); - // FIXME #3396: weird bug here, for reasons unclear this emits random - // looking bytes (mostly 0x1) if we use the version byte-array constant - // above; so we use a string constant inline instead. - // - // Should be: - // - // vec::to_owned(metadata_encoding_version) + - let writer_bytes: &mut ~[u8] = wr.bytes; - (do str::as_bytes(&~"rust\x00\x00\x00\x01") |bytes| { - vec::slice(*bytes, 0, 8).to_vec() - }) + flate::deflate_bytes(*writer_bytes) + vec::to_owned(metadata_encoding_version) + + flate::deflate_bytes(*writer_bytes) } // Get the encoded string for a type From 7ccc97e5b4fb6a9a3fb76b806df4e22b9401a47c Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Wed, 22 May 2013 14:21:09 -0400 Subject: [PATCH 179/248] Fix ICE in macros --- src/libsyntax/ext/tt/transcribe.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index d806801b7d172..b13dc3f3c0fe7 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -118,10 +118,13 @@ fn lookup_cur_matched_by_matched(r: &mut TtReader, } fn lookup_cur_matched(r: &mut TtReader, name: ident) -> @named_match { - // FIXME (#3850): this looks a bit silly with an extra scope. - let start; - { start = *r.interpolations.get(&name); } - return lookup_cur_matched_by_matched(r, start); + match r.interpolations.find_copy(&name) { + Some(s) => lookup_cur_matched_by_matched(r, s), + None => { + r.sp_diag.span_fatal(r.cur_span, fmt!("unknown macro variable `%s`", + *r.interner.get(name))); + } + } } enum lis { lis_unconstrained, lis_constraint(uint, ident), lis_contradiction(~str) From 5118d2f84a4c4a8bf00d7fb9e06609877bf821e7 Mon Sep 17 00:00:00 2001 From: Corey Richardson Date: Wed, 22 May 2013 16:07:02 -0400 Subject: [PATCH 180/248] Add test --- src/test/compile-fail/issue-6596.rs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/test/compile-fail/issue-6596.rs diff --git a/src/test/compile-fail/issue-6596.rs b/src/test/compile-fail/issue-6596.rs new file mode 100644 index 0000000000000..3c952dbc59087 --- /dev/null +++ b/src/test/compile-fail/issue-6596.rs @@ -0,0 +1,9 @@ +macro_rules! e( //~ ERROR unknown macro variable `nonexistent` + ($inp:ident) => ( + $nonexistent + ); +) + +fn main() { + e!(foo); +} From ca9bb2d9ace2bf085dc276e241f6707e0402093f Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Mon, 13 May 2013 16:13:20 -0700 Subject: [PATCH 181/248] librustc: Disallow `use` from reaching into impls or traits. This can perhaps be restored in the future. For now this is a precursor to making typedefs work as expected. --- src/librustc/middle/resolve.rs | 192 +++++++++++++++------ src/librustpkg/rustpkg.rc | 21 ++- src/test/auxiliary/use_from_trait_xc.rs | 10 ++ src/test/compile-fail/use-from-trait-xc.rs | 12 ++ src/test/compile-fail/use-from-trait.rs | 17 ++ 5 files changed, 187 insertions(+), 65 deletions(-) create mode 100644 src/test/auxiliary/use_from_trait_xc.rs create mode 100644 src/test/compile-fail/use-from-trait-xc.rs create mode 100644 src/test/compile-fail/use-from-trait.rs diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 057b85730a0a6..bfa4862e0548e 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -255,8 +255,20 @@ pub enum AllowCapturingSelfFlag { #[deriving(Eq)] enum NameSearchType { - SearchItemsAndPublicImports, //< Search items and public imports. - SearchItemsAndAllImports, //< Search items and all imports. + /// We're doing a name search in order to resolve a `use` directive. + ImportSearch, + + /// We're doing a name search in order to resolve a path type, a path + /// expression, or a path pattern. We can select public or private + /// names. + /// + /// XXX: This should be ripped out of resolve and handled later, in + /// the privacy checking phase. + PathPublicOrPrivateSearch, + + /// We're doing a name search in order to resolve a path type, a path + /// expression, or a path pattern. Allow only public names to be selected. + PathPublicOnlySearch, } pub enum BareIdentifierPatternResolution { @@ -394,6 +406,7 @@ pub enum ModuleKind { NormalModuleKind, ExternModuleKind, TraitModuleKind, + ImplModuleKind, AnonymousModuleKind, } @@ -424,7 +437,6 @@ pub struct Module { // // There will be an anonymous module created around `g` with the ID of the // entry block for `f`. - anonymous_children: @mut HashMap, // The status of resolving each import in this module. @@ -514,6 +526,38 @@ pub impl NameBindings { } } + /// Sets the kind of the module, creating a new one if necessary. + fn set_module_kind(@mut self, + privacy: Privacy, + parent_link: ParentLink, + def_id: Option, + kind: ModuleKind, + sp: span) { + match self.type_def { + None => { + let module = @mut Module(parent_link, def_id, kind); + self.type_def = Some(TypeNsDef { + privacy: privacy, + module_def: Some(module), + type_def: None + }) + } + Some(type_def) => { + match type_def.module_def { + None => { + let module = @mut Module(parent_link, def_id, kind); + self.type_def = Some(TypeNsDef { + privacy: privacy, + module_def: Some(module), + type_def: type_def.type_def + }) + } + Some(module_def) => module_def.kind = kind, + } + } + } + } + /// Records a type definition. fn define_type(@mut self, privacy: Privacy, def: def, sp: span) { // Merges the type with the existing type def or creates a new one. @@ -1191,7 +1235,7 @@ pub impl Resolver { name_bindings.define_module(Public, parent_link, Some(def_id), - TraitModuleKind, + ImplModuleKind, sp); let new_parent = ModuleReducedGraphParent( @@ -1579,8 +1623,8 @@ pub impl Resolver { // If this is a trait, add all the method names // to the trait info. - let method_def_ids = get_trait_method_def_ids(self.session.cstore, - def_id); + let method_def_ids = + get_trait_method_def_ids(self.session.cstore, def_id); let mut interned_method_names = HashSet::new(); for method_def_ids.each |&method_def_id| { let (method_name, explicit_self) = @@ -1608,6 +1652,14 @@ pub impl Resolver { } child_name_bindings.define_type(Public, def, dummy_sp()); + + // Define a module if necessary. + let parent_link = self.get_parent_link(new_parent, ident); + child_name_bindings.set_module_kind(Public, + parent_link, + Some(def_id), + TraitModuleKind, + dummy_sp()) } def_ty(_) => { debug!("(building reduced graph for external \ @@ -1750,6 +1802,10 @@ pub impl Resolver { // We already have a module. This // is OK. type_module = module_def; + + // Mark it as an impl module if + // necessary. + type_module.kind = ImplModuleKind; } Some(_) | None => { let parent_link = @@ -1759,7 +1815,7 @@ pub impl Resolver { Public, parent_link, Some(def), - NormalModuleKind, + ImplModuleKind, dummy_sp()); type_module = child_name_bindings. @@ -1866,10 +1922,8 @@ pub impl Resolver { // remain or unsuccessfully when no forward progress in resolving imports // is made. - /** - * Resolves all imports for the crate. This method performs the fixed- - * point iteration. - */ + /// Resolves all imports for the crate. This method performs the fixed- + /// point iteration. fn resolve_imports(@mut self) { let mut i = 0; let mut prev_unresolved_imports = 0; @@ -1991,9 +2045,10 @@ pub impl Resolver { /// don't know whether the name exists at the moment due to other /// currently-unresolved imports, or success if we know the name exists. /// If successful, the resolved bindings are written into the module. - fn resolve_import_for_module(@mut self, module_: @mut Module, + fn resolve_import_for_module(@mut self, + module_: @mut Module, import_directive: @ImportDirective) - -> ResolveResult<()> { + -> ResolveResult<()> { let mut resolution_result = Failed; let module_path = &import_directive.module_path; @@ -2007,10 +2062,11 @@ pub impl Resolver { // Use the crate root. Some(self.graph_root.get_module()) } else { - match self.resolve_module_path_for_import(module_, - *module_path, - DontUseLexicalScope, - import_directive.span) { + match self.resolve_module_path(module_, + *module_path, + DontUseLexicalScope, + import_directive.span, + ImportSearch) { Failed => None, Indeterminate => { @@ -2097,7 +2153,7 @@ pub impl Resolver { target: ident, source: ident, span: span) - -> ResolveResult<()> { + -> ResolveResult<()> { debug!("(resolving single import) resolving `%s` = `%s::%s` from \ `%s`", *self.session.str_of(target), @@ -2134,9 +2190,7 @@ pub impl Resolver { // Unless we managed to find a result in both namespaces (unlikely), // search imports as well. match (value_result, type_result) { - (BoundResult(*), BoundResult(*)) => { - // Continue. - } + (BoundResult(*), BoundResult(*)) => {} // Continue. _ => { // If there is an unresolved glob at this point in the // containing module, bail out. We don't know enough to be @@ -2460,7 +2514,6 @@ pub impl Resolver { // Resolve the module part of the path. This does not involve looking // upward though scope chains; we simply resolve names directly in // modules as we go. - while index < module_path_len { let name = module_path[index]; match self.resolve_name_in_module(search_module, @@ -2470,12 +2523,17 @@ pub impl Resolver { Failed => { let segment_name = self.session.str_of(name); let module_name = self.module_to_str(search_module); - if module_name == ~"???" { - self.session.span_err(span {lo: span.lo, hi: span.lo + - BytePos(str::len(*segment_name)), expn_info: - span.expn_info}, fmt!("unresolved import. maybe \ - a missing `extern mod %s`?", - *segment_name)); + if "???" == module_name { + let span = span { + lo: span.lo, + hi: span.lo + BytePos(str::len(*segment_name)), + expn_info: span.expn_info, + }; + self.session.span_err(span, + fmt!("unresolved import. maybe \ + a missing `extern mod \ + %s`?", + *segment_name)); return Failed; } self.session.span_err(span, fmt!("unresolved import: could not find `%s` in \ @@ -2504,8 +2562,22 @@ pub impl Resolver { name))); return Failed; } - Some(copy module_def) => { - search_module = module_def; + Some(module_def) => { + // If we're doing the search for an + // import, do not allow traits and impls + // to be selected. + match (name_search_type, + module_def.kind) { + (ImportSearch, TraitModuleKind) | + (ImportSearch, ImplModuleKind) => { + self.session.span_err( + span, + ~"cannot import from a trait \ + or type implementation"); + return Failed; + } + (_, _) => search_module = module_def, + } } } } @@ -2523,18 +2595,13 @@ pub impl Resolver { index += 1; - // After the first element of the path, allow searching through - // items and imports unconditionally. This allows things like: - // - // pub mod core { - // pub use vec; - // } + // After the first element of the path, allow searching only + // through public identifiers. // - // pub mod something_else { - // use core::vec; - // } - - name_search_type = SearchItemsAndPublicImports; + // XXX: Rip this out and move it to the privacy checker. + if name_search_type == PathPublicOrPrivateSearch { + name_search_type = PathPublicOnlySearch + } } return Success(search_module); @@ -2542,12 +2609,13 @@ pub impl Resolver { /// Attempts to resolve the module part of an import directive or path /// rooted at the given module. - fn resolve_module_path_for_import(@mut self, - module_: @mut Module, - module_path: &[ident], - use_lexical_scope: UseLexicalScopeFlag, - span: span) - -> ResolveResult<@mut Module> { + fn resolve_module_path(@mut self, + module_: @mut Module, + module_path: &[ident], + use_lexical_scope: UseLexicalScopeFlag, + span: span, + name_search_type: NameSearchType) + -> ResolveResult<@mut Module> { let module_path_len = module_path.len(); assert!(module_path_len > 0); @@ -2630,7 +2698,7 @@ pub impl Resolver { module_path, start_index, span, - SearchItemsAndPublicImports) + name_search_type) } /// Invariant: This must only be called during main resolution, not during @@ -2722,6 +2790,7 @@ pub impl Resolver { } ExternModuleKind | TraitModuleKind | + ImplModuleKind | AnonymousModuleKind => { search_module = parent_module_node; } @@ -2741,7 +2810,7 @@ pub impl Resolver { match self.resolve_name_in_module(search_module, name, namespace, - SearchItemsAndAllImports) { + PathPublicOrPrivateSearch) { Failed => { // Continue up the search chain. } @@ -2822,6 +2891,7 @@ pub impl Resolver { NormalModuleKind => return Some(new_module), ExternModuleKind | TraitModuleKind | + ImplModuleKind | AnonymousModuleKind => module_ = new_module, } } @@ -2838,7 +2908,10 @@ pub impl Resolver { -> @mut Module { match module_.kind { NormalModuleKind => return module_, - ExternModuleKind | TraitModuleKind | AnonymousModuleKind => { + ExternModuleKind | + TraitModuleKind | + ImplModuleKind | + AnonymousModuleKind => { match self.get_nearest_normal_module_parent(module_) { None => module_, Some(new_module) => new_module @@ -2922,8 +2995,14 @@ pub impl Resolver { // If this is a search of all imports, we should be done with glob // resolution at this point. +<<<<<<< HEAD if name_search_type == SearchItemsAndAllImports { assert_eq!(module_.glob_count, 0); +======= + if name_search_type == PathPublicOrPrivateSearch || + name_search_type == PathPublicOnlySearch { + assert!(module_.glob_count == 0); +>>>>>>> librustc: Disallow `use` from reaching into impls or traits. } // Check the list of resolved imports. @@ -2944,7 +3023,7 @@ pub impl Resolver { } Some(target) if name_search_type == - SearchItemsAndAllImports || + PathPublicOrPrivateSearch || import_resolution.privacy == Public => { debug!("(resolving name in module) resolved to \ import"); @@ -4483,10 +4562,11 @@ pub impl Resolver { let module_path_idents = self.intern_module_part_of_path(path); let containing_module; - match self.resolve_module_path_for_import(self.current_module, - module_path_idents, - UseLexicalScope, - path.span) { + match self.resolve_module_path(self.current_module, + module_path_idents, + UseLexicalScope, + path.span, + PathPublicOnlySearch) { Failed => { self.session.span_err(path.span, fmt!("use of undeclared module `%s`", @@ -4535,7 +4615,7 @@ pub impl Resolver { module_path_idents, 0, path.span, - SearchItemsAndAllImports) { + PathPublicOrPrivateSearch) { Failed => { self.session.span_err(path.span, fmt!("use of undeclared module `::%s`", diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index 94fdcddfbb5b5..19dc973a4a150 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -602,7 +602,6 @@ impl PkgSrc { /// Infers crates to build. Called only in the case where there /// is no custom build logic fn find_crates(&mut self) { - use PkgSrc::push_crate; use conditions::missing_pkg_files::cond; let dir = self.check_dir(); @@ -610,14 +609,18 @@ impl PkgSrc { debug!("Matching against %?", self.id.local_path.filestem()); for os::walk_dir(&dir) |pth| { match pth.filename() { - Some(~"lib.rs") => push_crate(&mut self.libs, - prefix, pth), - Some(~"main.rs") => push_crate(&mut self.mains, - prefix, pth), - Some(~"test.rs") => push_crate(&mut self.tests, - prefix, pth), - Some(~"bench.rs") => push_crate(&mut self.benchs, - prefix, pth), + Some(~"lib.rs") => PkgSrc::push_crate(&mut self.libs, + prefix, + pth), + Some(~"main.rs") => PkgSrc::push_crate(&mut self.mains, + prefix, + pth), + Some(~"test.rs") => PkgSrc::push_crate(&mut self.tests, + prefix, + pth), + Some(~"bench.rs") => PkgSrc::push_crate(&mut self.benchs, + prefix, + pth), _ => () } } diff --git a/src/test/auxiliary/use_from_trait_xc.rs b/src/test/auxiliary/use_from_trait_xc.rs new file mode 100644 index 0000000000000..2ab95c271aec7 --- /dev/null +++ b/src/test/auxiliary/use_from_trait_xc.rs @@ -0,0 +1,10 @@ +pub trait Trait { + fn foo(); +} + +struct Foo; + +impl Foo { + pub fn new() {} +} + diff --git a/src/test/compile-fail/use-from-trait-xc.rs b/src/test/compile-fail/use-from-trait-xc.rs new file mode 100644 index 0000000000000..56805f58ad29a --- /dev/null +++ b/src/test/compile-fail/use-from-trait-xc.rs @@ -0,0 +1,12 @@ +// aux-build:use_from_trait_xc.rs + +extern mod use_from_trait_xc; + +use use_from_trait_xc::Trait::foo; //~ ERROR cannot import from a trait or type implementation +//~^ ERROR failed to resolve import +use use_from_trait_xc::Foo::new; //~ ERROR cannot import from a trait or type implementation +//~^ ERROR failed to resolve import + +fn main() { +} + diff --git a/src/test/compile-fail/use-from-trait.rs b/src/test/compile-fail/use-from-trait.rs new file mode 100644 index 0000000000000..10a30f0a266b3 --- /dev/null +++ b/src/test/compile-fail/use-from-trait.rs @@ -0,0 +1,17 @@ +use Trait::foo; //~ ERROR cannot import from a trait or type implementation +//~^ ERROR failed to resolve import +use Foo::new; //~ ERROR cannot import from a trait or type implementation +//~^ ERROR failed to resolve import + +pub trait Trait { + fn foo(); +} + +struct Foo; + +impl Foo { + fn new() {} +} + +fn main() {} + From 08e561ae70bc42b755b3831b3ce880745228892c Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Wed, 15 May 2013 14:01:54 -0700 Subject: [PATCH 182/248] librustc: Disable borrow check debugging even when rustc is compiled with -O0. This improves -O0 compile times dramatically. --- Makefile.in | 4 ++++ src/librustc/driver/session.rs | 13 ++++++++++--- src/librustc/middle/trans/write_guard.rs | 4 ++-- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Makefile.in b/Makefile.in index 8ab704ebe1719..9b59c46e5e831 100644 --- a/Makefile.in +++ b/Makefile.in @@ -122,6 +122,10 @@ endif ifdef TRACE CFG_RUSTC_FLAGS += -Z trace endif +ifndef DEBUG_BORROWS + RUSTFLAGS_STAGE1 += -Z no-debug-borrows + RUSTFLAGS_STAGE2 += -Z no-debug-borrows +endif # platform-specific auto-configuration include $(CFG_SRC_DIR)mk/platform.mk diff --git a/src/librustc/driver/session.rs b/src/librustc/driver/session.rs index e2cc285fb7afc..a340422d02311 100644 --- a/src/librustc/driver/session.rs +++ b/src/librustc/driver/session.rs @@ -66,6 +66,7 @@ pub static debug_info: uint = 1 << 20; pub static extra_debug_info: uint = 1 << 21; pub static statik: uint = 1 << 22; pub static print_link_args: uint = 1 << 23; +pub static no_debug_borrows: uint = 1 << 24; pub fn debugging_opts_map() -> ~[(~str, ~str, uint)] { ~[(~"verbose", ~"in general, enable more debug printouts", verbose), @@ -100,7 +101,10 @@ pub fn debugging_opts_map() -> ~[(~str, ~str, uint)] { extra_debug_info), (~"debug-info", ~"Produce debug info (experimental)", debug_info), (~"static", ~"Use or produce static libraries or binaries " + - "(experimental)", statik) + "(experimental)", statik), + (~"no-debug-borrows", + ~"do not show where borrow checks fail", + no_debug_borrows), ] } @@ -141,7 +145,7 @@ pub struct options { parse_only: bool, no_trans: bool, debugging_opts: uint, - android_cross_path: Option<~str> + android_cross_path: Option<~str>, } pub struct crate_metadata { @@ -271,6 +275,9 @@ pub impl Session_ { fn no_monomorphic_collapse(@self) -> bool { self.debugging_opt(no_monomorphic_collapse) } + fn debug_borrows(@self) -> bool { + self.opts.optimize == No && !self.debugging_opt(no_debug_borrows) + } fn str_of(@self, id: ast::ident) -> @~str { self.parse_sess.interner.get(id) @@ -308,7 +315,7 @@ pub fn basic_options() -> @options { parse_only: false, no_trans: false, debugging_opts: 0u, - android_cross_path: None + android_cross_path: None, } } diff --git a/src/librustc/middle/trans/write_guard.rs b/src/librustc/middle/trans/write_guard.rs index 9fd6204311253..0d13d27b65367 100644 --- a/src/librustc/middle/trans/write_guard.rs +++ b/src/librustc/middle/trans/write_guard.rs @@ -74,7 +74,7 @@ pub fn return_to_mut(mut bcx: block, let bits_val = Load(bcx, bits_val_ref); - if bcx.tcx().sess.opts.optimize == session::No { + if bcx.tcx().sess.debug_borrows() { bcx = callee::trans_lang_call( bcx, bcx.tcx().lang_items.unrecord_borrow_fn(), @@ -160,7 +160,7 @@ fn root(datum: &Datum, ], expr::SaveIn(scratch_bits.val)); - if bcx.tcx().sess.opts.optimize == session::No { + if bcx.tcx().sess.debug_borrows() { bcx = callee::trans_lang_call( bcx, bcx.tcx().lang_items.record_borrow_fn(), From db518ef68abdbf6ef05693dc492147ce5ec7219e Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Wed, 15 May 2013 14:10:42 -0700 Subject: [PATCH 183/248] test: Fix tests. --- src/test/auxiliary/extern-crosscrate-source.rs | 6 ++++-- src/test/run-pass/const-cast.rs | 2 +- src/test/run-pass/const-cross-crate-extern.rs | 2 +- src/test/run-pass/const-extern-function.rs | 2 +- src/test/run-pass/extern-call-deep.rs | 6 ++++-- src/test/run-pass/extern-call-deep2.rs | 6 ++++-- src/test/run-pass/extern-call-scrub.rs | 6 ++++-- src/test/run-pass/extern-call.rs | 4 +++- src/test/run-pass/extern-stress.rs | 6 ++++-- src/test/run-pass/extern-take-value.rs | 8 ++++---- src/test/run-pass/extern-yield.rs | 6 ++++-- src/test/run-pass/float-nan.rs | 10 ++++------ src/test/run-pass/foreign-call-no-runtime.rs | 3 ++- src/test/run-pass/static-method-xcrate.rs | 5 ++--- src/test/run-pass/trait-inheritance-num.rs | 6 +++--- src/test/run-pass/trait-inheritance-num0.rs | 4 ++-- src/test/run-pass/trait-inheritance-num1.rs | 4 ++-- src/test/run-pass/trait-inheritance-num2.rs | 1 - src/test/run-pass/trait-inheritance-num3.rs | 6 ++++-- src/test/run-pass/trait-inheritance-num5.rs | 4 ++-- 20 files changed, 55 insertions(+), 42 deletions(-) diff --git a/src/test/auxiliary/extern-crosscrate-source.rs b/src/test/auxiliary/extern-crosscrate-source.rs index d59057f01f2de..c7e8e89913595 100644 --- a/src/test/auxiliary/extern-crosscrate-source.rs +++ b/src/test/auxiliary/extern-crosscrate-source.rs @@ -15,8 +15,10 @@ pub mod rustrt { pub extern { - pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) - -> libc::uintptr_t; + pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) + -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } diff --git a/src/test/run-pass/const-cast.rs b/src/test/run-pass/const-cast.rs index 1c8e92b91cd1b..2f7ccfe2a3a23 100644 --- a/src/test/run-pass/const-cast.rs +++ b/src/test/run-pass/const-cast.rs @@ -10,7 +10,7 @@ extern fn foo() {} -static x: *u8 = foo; +static x: extern "C" fn() = foo; static y: *libc::c_void = x as *libc::c_void; static a: &'static int = &10; static b: *int = a as *int; diff --git a/src/test/run-pass/const-cross-crate-extern.rs b/src/test/run-pass/const-cross-crate-extern.rs index 5281c21762689..66db6c824bc01 100644 --- a/src/test/run-pass/const-cross-crate-extern.rs +++ b/src/test/run-pass/const-cross-crate-extern.rs @@ -13,7 +13,7 @@ extern mod cci_const; use cci_const::bar; -static foo: *u8 = bar; +static foo: extern "C" fn() = bar; pub fn main() { assert_eq!(foo, cci_const::bar); diff --git a/src/test/run-pass/const-extern-function.rs b/src/test/run-pass/const-extern-function.rs index 9a8104cb14f71..513f93a676056 100644 --- a/src/test/run-pass/const-extern-function.rs +++ b/src/test/run-pass/const-extern-function.rs @@ -10,7 +10,7 @@ extern fn foopy() {} -static f: *u8 = foopy; +static f: extern "C" fn() = foopy; static s: S = S { f: foopy }; struct S { diff --git a/src/test/run-pass/extern-call-deep.rs b/src/test/run-pass/extern-call-deep.rs index b8cdfcb0c4cfe..2e95873b60df4 100644 --- a/src/test/run-pass/extern-call-deep.rs +++ b/src/test/run-pass/extern-call-deep.rs @@ -10,8 +10,10 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) - -> libc::uintptr_t; + pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) + -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-call-deep2.rs b/src/test/run-pass/extern-call-deep2.rs index eb7ab055b07be..6ad1c531d9a19 100644 --- a/src/test/run-pass/extern-call-deep2.rs +++ b/src/test/run-pass/extern-call-deep2.rs @@ -10,8 +10,10 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) - -> libc::uintptr_t; + pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) + -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-call-scrub.rs b/src/test/run-pass/extern-call-scrub.rs index 4111f9eb00e21..2caf4cbf2bc74 100644 --- a/src/test/run-pass/extern-call-scrub.rs +++ b/src/test/run-pass/extern-call-scrub.rs @@ -14,8 +14,10 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) - -> libc::uintptr_t; + pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) + -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-call.rs b/src/test/run-pass/extern-call.rs index ec335cf8a82b8..6c36c4aa8f629 100644 --- a/src/test/run-pass/extern-call.rs +++ b/src/test/run-pass/extern-call.rs @@ -10,7 +10,9 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) + pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) + -> libc::uintptr_t, + data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-stress.rs b/src/test/run-pass/extern-stress.rs index 1a1e0ca7b6d9b..b12295ab57684 100644 --- a/src/test/run-pass/extern-stress.rs +++ b/src/test/run-pass/extern-stress.rs @@ -13,8 +13,10 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) - -> libc::uintptr_t; + pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) + -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-take-value.rs b/src/test/run-pass/extern-take-value.rs index 542686c9099f1..c3fe458802d4b 100644 --- a/src/test/run-pass/extern-take-value.rs +++ b/src/test/run-pass/extern-take-value.rs @@ -15,10 +15,10 @@ extern fn g() { } pub fn main() { - // extern functions are *u8 types - let a: *u8 = f; - let b: *u8 = f; - let c: *u8 = g; + // extern functions are extern function types + let a: extern "C" fn() = f; + let b: extern "C" fn() = f; + let c: extern "C" fn() = g; assert_eq!(a, b); assert!(a != c); diff --git a/src/test/run-pass/extern-yield.rs b/src/test/run-pass/extern-yield.rs index 067968ddb9f9e..16b1c7cd6f40f 100644 --- a/src/test/run-pass/extern-yield.rs +++ b/src/test/run-pass/extern-yield.rs @@ -10,8 +10,10 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) - -> libc::uintptr_t; + pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) + -> libc::uintptr_t, + data: libc::uintptr_t) + -> libc::uintptr_t; } } diff --git a/src/test/run-pass/float-nan.rs b/src/test/run-pass/float-nan.rs index de3ce4d8149be..4ea1604a18cbe 100644 --- a/src/test/run-pass/float-nan.rs +++ b/src/test/run-pass/float-nan.rs @@ -10,16 +10,14 @@ extern mod std; -use core::num::Float::{ - NaN, infinity, neg_infinity -}; +use core::num::Float; pub fn main() { - let nan = NaN::(); + let nan = Float::NaN::(); assert!((nan).is_NaN()); - let inf = infinity::(); - assert_eq!(-inf, neg_infinity::()); + let inf = Float::infinity::(); + assert_eq!(-inf, Float::neg_infinity::()); assert!( nan != nan); assert!( nan != -nan); diff --git a/src/test/run-pass/foreign-call-no-runtime.rs b/src/test/run-pass/foreign-call-no-runtime.rs index 3f61fca872616..6f94b16331532 100644 --- a/src/test/run-pass/foreign-call-no-runtime.rs +++ b/src/test/run-pass/foreign-call-no-runtime.rs @@ -1,7 +1,8 @@ use core::unstable::run_in_bare_thread; extern { - pub fn rust_dbg_call(cb: *u8, + pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) + -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } diff --git a/src/test/run-pass/static-method-xcrate.rs b/src/test/run-pass/static-method-xcrate.rs index c5d3b58276e5b..946c86ab298c6 100644 --- a/src/test/run-pass/static-method-xcrate.rs +++ b/src/test/run-pass/static-method-xcrate.rs @@ -13,11 +13,10 @@ extern mod static_methods_crate; use static_methods_crate::read; -use readMaybeRenamed = static_methods_crate::read::readMaybe; pub fn main() { let result: int = read(~"5"); assert_eq!(result, 5); - assert_eq!(readMaybeRenamed(~"false"), Some(false)); - assert_eq!(readMaybeRenamed(~"foo"), None::); + assert_eq!(read::readMaybe(~"false"), Some(false)); + assert_eq!(read::readMaybe(~"foo"), None::); } diff --git a/src/test/run-pass/trait-inheritance-num.rs b/src/test/run-pass/trait-inheritance-num.rs index 5179d13813cea..9135b458f95eb 100644 --- a/src/test/run-pass/trait-inheritance-num.rs +++ b/src/test/run-pass/trait-inheritance-num.rs @@ -13,13 +13,13 @@ extern mod std; use core::cmp::{Eq, Ord}; -use core::num::NumCast::from; +use core::num::NumCast; pub trait NumExt: Num + NumCast + Eq + Ord {} pub trait FloatExt: NumExt + ApproxEq {} -fn greater_than_one(n: &T) -> bool { *n > from(1) } -fn greater_than_one_float(n: &T) -> bool { *n > from(1) } +fn greater_than_one(n: &T) -> bool { *n > NumCast::from(1) } +fn greater_than_one_float(n: &T) -> bool { *n > NumCast::from(1) } pub fn main() {} diff --git a/src/test/run-pass/trait-inheritance-num0.rs b/src/test/run-pass/trait-inheritance-num0.rs index aae430dc4cdf9..3e31b8067f9c3 100644 --- a/src/test/run-pass/trait-inheritance-num0.rs +++ b/src/test/run-pass/trait-inheritance-num0.rs @@ -12,7 +12,7 @@ // Extending Num and using inherited static methods -use core::num::NumCast::from; +use core::num::NumCast; trait Num { fn from_int(i: int) -> Self; @@ -22,7 +22,7 @@ trait Num { pub trait NumExt: Num + NumCast { } fn greater_than_one(n: &T) -> bool { - n.gt(&from(1)) + n.gt(&NumCast::from(1)) } pub fn main() {} diff --git a/src/test/run-pass/trait-inheritance-num1.rs b/src/test/run-pass/trait-inheritance-num1.rs index d580b99012fa5..25741518f66eb 100644 --- a/src/test/run-pass/trait-inheritance-num1.rs +++ b/src/test/run-pass/trait-inheritance-num1.rs @@ -9,12 +9,12 @@ // except according to those terms. use core::cmp::Ord; -use core::num::NumCast::from; +use core::num::NumCast; pub trait NumExt: Num + NumCast + Ord { } fn greater_than_one(n: &T) -> bool { - *n > from(1) + *n > NumCast::from(1) } pub fn main() {} diff --git a/src/test/run-pass/trait-inheritance-num2.rs b/src/test/run-pass/trait-inheritance-num2.rs index f7edd2855a4cd..2963a815e0519 100644 --- a/src/test/run-pass/trait-inheritance-num2.rs +++ b/src/test/run-pass/trait-inheritance-num2.rs @@ -15,7 +15,6 @@ extern mod std; use core::cmp::{Eq, Ord}; -use core::num::NumCast::from; pub trait TypeExt {} diff --git a/src/test/run-pass/trait-inheritance-num3.rs b/src/test/run-pass/trait-inheritance-num3.rs index 5f1fef80ef201..667fd335ac4a4 100644 --- a/src/test/run-pass/trait-inheritance-num3.rs +++ b/src/test/run-pass/trait-inheritance-num3.rs @@ -9,13 +9,15 @@ // except according to those terms. use core::cmp::{Eq, Ord}; -use core::num::NumCast::from; +use core::num::NumCast; pub trait NumExt: Eq + Ord + Num + NumCast {} impl NumExt for f32 {} -fn num_eq_one(n: T) { io::println(fmt!("%?", n == from(1))) } +fn num_eq_one(n: T) { + io::println(fmt!("%?", n == NumCast::from(1))) +} pub fn main() { num_eq_one(1f32); // you need to actually use the function to trigger the ICE diff --git a/src/test/run-pass/trait-inheritance-num5.rs b/src/test/run-pass/trait-inheritance-num5.rs index 02cc9a3d221f8..f1897636c8aa6 100644 --- a/src/test/run-pass/trait-inheritance-num5.rs +++ b/src/test/run-pass/trait-inheritance-num5.rs @@ -9,7 +9,7 @@ // except according to those terms. use core::cmp::{Eq, Ord}; -use core::num::NumCast::from; +use core::num::NumCast; pub trait NumExt: Eq + Num + NumCast {} @@ -17,7 +17,7 @@ impl NumExt for f32 {} impl NumExt for int {} fn num_eq_one() -> T { - from(1) + NumCast::from(1) } pub fn main() { From 211d038abc05c77785f72a31840016517cf218c2 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Wed, 15 May 2013 17:38:52 -0700 Subject: [PATCH 184/248] librustc: Make `~Trait` two words by storing the type descriptor in the vtable. --- src/librustc/middle/trans/common.rs | 3 +- src/librustc/middle/trans/glue.rs | 15 +++- src/librustc/middle/trans/meth.rs | 107 +++++++++++++---------- src/librustc/middle/trans/write_guard.rs | 1 - 4 files changed, 73 insertions(+), 53 deletions(-) diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 115cf52056f40..5da664b696927 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -1089,8 +1089,7 @@ pub fn T_opaque_trait(cx: @CrateContext, store: ty::TraitStore) -> TypeRef { } ty::UniqTraitStore => { T_struct([T_ptr(cx.tydesc_type), - T_unique_ptr(T_unique(cx, T_i8())), - T_ptr(cx.tydesc_type)], + T_unique_ptr(T_unique(cx, T_i8()))], false) } ty::RegionTraitStore(_) => { diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index 048acdc07a120..b731d0f93b75d 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -545,9 +545,18 @@ pub fn make_drop_glue(bcx: block, v0: ValueRef, t: ty::t) { } ty::ty_trait(_, _, ty::UniqTraitStore, _) => { let lluniquevalue = GEPi(bcx, v0, [0, abi::trt_field_box]); - let lltydesc = Load(bcx, GEPi(bcx, v0, [0, abi::trt_field_tydesc])); - call_tydesc_glue_full(bcx, lluniquevalue, lltydesc, - abi::tydesc_field_free_glue, None); + let llvtable = Load(bcx, GEPi(bcx, v0, [0, abi::trt_field_vtable])); + + // Cast the vtable to a pointer to a pointer to a tydesc. + let llvtable = PointerCast(bcx, + llvtable, + T_ptr(T_ptr(ccx.tydesc_type))); + let lltydesc = Load(bcx, llvtable); + call_tydesc_glue_full(bcx, + lluniquevalue, + lltydesc, + abi::tydesc_field_free_glue, + None); bcx } ty::ty_opaque_closure_ptr(ck) => { diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index c6af3178d503d..7633c9069565c 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -39,9 +39,13 @@ for non-monomorphized methods only. Other methods will be generated once they are invoked with specific type parameters, see `trans::base::lval_static_fn()` or `trans::base::monomorphic_fn()`. */ -pub fn trans_impl(ccx: @CrateContext, path: path, name: ast::ident, - methods: &[@ast::method], generics: &ast::Generics, - self_ty: Option, id: ast::node_id) { +pub fn trans_impl(ccx: @CrateContext, + path: path, + name: ast::ident, + methods: &[@ast::method], + generics: &ast::Generics, + self_ty: Option, + id: ast::node_id) { let _icx = ccx.insn_ctxt("impl::trans_impl"); let tcx = ccx.tcx; @@ -718,7 +722,10 @@ pub fn trans_trait_callee_from_llval(bcx: block, // Load the function from the vtable and cast it to the expected type. debug!("(translating trait callee) loading method"); let llcallee_ty = type_of_fn_from_ty(ccx, callee_ty); - let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method])); + + // Plus one in order to skip past the type descriptor. + let mptr = Load(bcx, GEPi(bcx, llvtable, [0u, n_method + 1])); + let mptr = PointerCast(bcx, mptr, T_ptr(llcallee_ty)); return Callee { @@ -756,25 +763,40 @@ pub fn vtable_id(ccx: @CrateContext, } } +/// Creates a returns a dynamic vtable for the given type and vtable origin. +/// This is used only for objects. pub fn get_vtable(ccx: @CrateContext, + self_ty: ty::t, origin: typeck::vtable_origin) - -> ValueRef { + -> ValueRef { let hash_id = vtable_id(ccx, &origin); match ccx.vtables.find(&hash_id) { - Some(&val) => val, - None => match origin { - typeck::vtable_static(id, substs, sub_vtables) => { - make_impl_vtable(ccx, id, substs, sub_vtables) + Some(&val) => val, + None => { + match origin { + typeck::vtable_static(id, substs, sub_vtables) => { + make_impl_vtable(ccx, id, self_ty, substs, sub_vtables) + } + _ => fail!("get_vtable: expected a static origin"), + } } - _ => fail!("get_vtable: expected a static origin") - } } } -pub fn make_vtable(ccx: @CrateContext, ptrs: ~[ValueRef]) -> ValueRef { +/// Helper function to declare and initialize the vtable. +pub fn make_vtable(ccx: @CrateContext, + tydesc: @mut tydesc_info, + ptrs: &[ValueRef]) + -> ValueRef { unsafe { let _icx = ccx.insn_ctxt("impl::make_vtable"); - let tbl = C_struct(ptrs); + + let mut components = ~[ tydesc.tydesc ]; + for ptrs.each |&ptr| { + components.push(ptr) + } + + let tbl = C_struct(components); let vtable = ccx.sess.str_of((ccx.names)("vtable")); let vt_gvar = do str::as_c_str(*vtable) |buf| { llvm::LLVMAddGlobal(ccx.llmod, val_ty(tbl), buf) @@ -786,11 +808,13 @@ pub fn make_vtable(ccx: @CrateContext, ptrs: ~[ValueRef]) -> ValueRef { } } +/// Generates a dynamic vtable for objects. pub fn make_impl_vtable(ccx: @CrateContext, impl_id: ast::def_id, + self_ty: ty::t, substs: ~[ty::t], vtables: typeck::vtable_res) - -> ValueRef { + -> ValueRef { let _icx = ccx.insn_ctxt("impl::make_impl_vtable"); let tcx = ccx.tcx; @@ -802,9 +826,13 @@ pub fn make_impl_vtable(ccx: @CrateContext, let has_tps = !ty::lookup_item_type(ccx.tcx, impl_id).generics.type_param_defs.is_empty(); - make_vtable(ccx, ty::trait_method_def_ids(tcx, trt_id).map(|method_def_id| { + + let trait_method_def_ids = ty::trait_method_def_ids(tcx, trt_id); + let methods = do trait_method_def_ids.map |method_def_id| { let im = ty::method(tcx, *method_def_id); - let fty = ty::subst_tps(tcx, substs, None, + let fty = ty::subst_tps(tcx, + substs, + None, ty::mk_bare_fn(tcx, copy im.fty)); if im.generics.has_type_params() || ty::type_has_self(fty) { debug!("(making impl vtable) method has self or type params: %s", @@ -830,7 +858,13 @@ pub fn make_impl_vtable(ccx: @CrateContext, trans_external_path(ccx, m_id, fty) } } - })) + }; + + // Generate a type descriptor for the vtable. + let tydesc = get_tydesc(ccx, self_ty); + glue::lazily_emit_all_tydesc_glue(ccx, tydesc); + + make_vtable(ccx, tydesc, methods) } pub fn trans_trait_cast(bcx: block, @@ -852,40 +886,19 @@ pub fn trans_trait_cast(bcx: block, let ccx = bcx.ccx(); let v_ty = expr_ty(bcx, val); - match store { - ty::RegionTraitStore(_) | ty::BoxTraitStore => { - let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]); - // Just store the pointer into the pair. (Region/borrowed - // and boxed trait objects are represented as pairs, and - // have no type descriptor field.) - llboxdest = PointerCast(bcx, - llboxdest, - T_ptr(type_of(bcx.ccx(), v_ty))); - bcx = expr::trans_into(bcx, val, SaveIn(llboxdest)); - } - ty::UniqTraitStore => { - // Translate the uniquely-owned value in the - // triple. (Unique trait objects are represented as - // triples.) - let mut llvaldest = GEPi(bcx, lldest, [0, abi::trt_field_box]); - llvaldest = PointerCast(bcx, - llvaldest, - T_ptr(type_of(bcx.ccx(), v_ty))); - bcx = expr::trans_into(bcx, val, SaveIn(llvaldest)); - - // Get the type descriptor of the wrapped value and store - // it in the triple as well. - let tydesc = get_tydesc(bcx.ccx(), v_ty); - glue::lazily_emit_all_tydesc_glue(bcx.ccx(), tydesc); - let lltydescdest = GEPi(bcx, lldest, [0, abi::trt_field_tydesc]); - Store(bcx, tydesc.tydesc, lltydescdest); - } - } + let mut llboxdest = GEPi(bcx, lldest, [0u, abi::trt_field_box]); + // Just store the pointer into the pair. (Region/borrowed + // and boxed trait objects are represented as pairs, and + // have no type descriptor field.) + llboxdest = PointerCast(bcx, + llboxdest, + T_ptr(type_of(bcx.ccx(), v_ty))); + bcx = expr::trans_into(bcx, val, SaveIn(llboxdest)); // Store the vtable into the pair or triple. let orig = /*bad*/copy ccx.maps.vtable_map.get(&id)[0]; let orig = resolve_vtable_in_fn_ctxt(bcx.fcx, orig); - let vtable = get_vtable(bcx.ccx(), orig); + let vtable = get_vtable(bcx.ccx(), v_ty, orig); Store(bcx, vtable, PointerCast(bcx, GEPi(bcx, lldest, [0u, abi::trt_field_vtable]), T_ptr(val_ty(vtable)))); diff --git a/src/librustc/middle/trans/write_guard.rs b/src/librustc/middle/trans/write_guard.rs index 0d13d27b65367..281e592f31e59 100644 --- a/src/librustc/middle/trans/write_guard.rs +++ b/src/librustc/middle/trans/write_guard.rs @@ -23,7 +23,6 @@ use middle::trans::common::*; use middle::trans::datum::*; use middle::trans::expr; use middle::ty; -use driver::session; use syntax::codemap::span; use syntax::ast; From 565942b145efbf6c1d1f66db46423d721b55d32c Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Thu, 16 May 2013 15:37:52 -0700 Subject: [PATCH 185/248] librustc: Fix privacy checking for cross-crate variants --- src/librustc/metadata/csearch.rs | 15 +++++- src/librustc/metadata/decoder.rs | 31 ++++++++---- src/librustc/metadata/encoder.rs | 1 + src/librustc/middle/resolve.rs | 52 ++++++++++++--------- src/librustc/middle/typeck/coherence.rs | 2 +- src/test/auxiliary/private_variant_xc.rs | 5 ++ src/test/compile-fail/private-variant-xc.rs | 9 ++++ 7 files changed, 81 insertions(+), 34 deletions(-) create mode 100644 src/test/auxiliary/private_variant_xc.rs create mode 100644 src/test/compile-fail/private-variant-xc.rs diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 9e0021831372c..b21417f5100c6 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -52,9 +52,22 @@ pub fn each_lang_item(cstore: @mut cstore::CStore, } /// Iterates over all the paths in the given crate. +#[cfg(stage0)] pub fn each_path(cstore: @mut cstore::CStore, cnum: ast::crate_num, - f: &fn(&str, decoder::def_like) -> bool) -> bool { + f: &fn(&str, decoder::def_like, ast::visibility) -> bool) { + let crate_data = cstore::get_crate_data(cstore, cnum); + let get_crate_data: decoder::GetCrateDataCb = |cnum| { + cstore::get_crate_data(cstore, cnum) + }; + decoder::each_path(cstore.intr, crate_data, get_crate_data, f) +} +/// Iterates over all the paths in the given crate. +#[cfg(not(stage0))] +pub fn each_path(cstore: @mut cstore::CStore, + cnum: ast::crate_num, + f: &fn(&str, decoder::def_like, ast::visibility) -> bool) + -> bool { let crate_data = cstore::get_crate_data(cstore, cnum); let get_crate_data: decoder::GetCrateDataCb = |cnum| { cstore::get_crate_data(cstore, cnum) diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index de440632b1fdb..d6e7e64e4f801 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -319,8 +319,7 @@ fn item_name(intr: @ident_interner, item: ebml::Doc) -> ast::ident { } fn item_to_def_like(item: ebml::Doc, did: ast::def_id, cnum: ast::crate_num) - -> def_like -{ + -> def_like { let fam = item_family(item); match fam { Const => dl_def(ast::def_const(did)), @@ -474,9 +473,11 @@ pub fn each_lang_item(cdata: cmd, f: &fn(ast::node_id, uint) -> bool) -> bool { } /// Iterates over all the paths in the given crate. -pub fn _each_path(intr: @ident_interner, cdata: cmd, +pub fn _each_path(intr: @ident_interner, + cdata: cmd, get_crate_data: GetCrateDataCb, - f: &fn(&str, def_like) -> bool) -> bool { + f: &fn(&str, def_like, ast::visibility) -> bool) + -> bool { let root = reader::Doc(cdata.data); let items = reader::get_doc(root, tag_items); let items_data = reader::get_doc(items, tag_items_data); @@ -497,8 +498,10 @@ pub fn _each_path(intr: @ident_interner, cdata: cmd, debug!("(each_path) yielding explicit item: %s", path); let def_like = item_to_def_like(item_doc, def_id, cdata.cnum); + let vis = item_visibility(item_doc); + // Hand the information off to the iteratee. - if !f(path, def_like) { + if !f(path, def_like, vis) { broken = true; // FIXME #4572: This is awful. } } @@ -548,7 +551,7 @@ pub fn _each_path(intr: @ident_interner, cdata: cmd, debug!("(each_path) yielding reexported \ item: %s", reexport_path); - if (!f(reexport_path, def_like)) { + if (!f(reexport_path, def_like, ast::public)) { broken = true; // FIXME #4572: This is awful. } } @@ -561,9 +564,19 @@ pub fn _each_path(intr: @ident_interner, cdata: cmd, return broken; } -pub fn each_path(intr: @ident_interner, cdata: cmd, +#[cfg(stage0)] +pub fn each_path(intr: @ident_interner, + cdata: cmd, + get_crate_data: GetCrateDataCb, + f: &fn(&str, def_like, ast::visibility) -> bool) { + _each_path(intr, cdata, get_crate_data, f); +} +#[cfg(not(stage0))] +pub fn each_path(intr: @ident_interner, + cdata: cmd, get_crate_data: GetCrateDataCb, - f: &fn(&str, def_like) -> bool) -> bool { + f: &fn(&str, def_like, ast::visibility) -> bool) + -> bool { _each_path(intr, cdata, get_crate_data, f) } @@ -1127,7 +1140,7 @@ pub fn get_crate_vers(data: @~[u8]) -> @~str { fn iter_crate_items(intr: @ident_interner, cdata: cmd, get_crate_data: GetCrateDataCb, proc: &fn(path: &str, ast::def_id)) { - for each_path(intr, cdata, get_crate_data) |path_string, def_like| { + for each_path(intr, cdata, get_crate_data) |path_string, def_like, _| { match def_like { dl_impl(*) | dl_field => {} dl_def(def) => { diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 5fc05fe79209c..297b0408dc524 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -316,6 +316,7 @@ fn encode_enum_variant_info(ecx: @EncodeContext, encode_family(ebml_w, 'v'); encode_name(ecx, ebml_w, variant.node.name); encode_parent_item(ebml_w, local_def(id)); + encode_visibility(ebml_w, variant.node.vis); encode_type(ecx, ebml_w, node_id_to_type(ecx.tcx, variant.node.id)); match variant.node.kind { diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index bfa4862e0548e..306671641a384 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -539,7 +539,8 @@ pub impl NameBindings { self.type_def = Some(TypeNsDef { privacy: privacy, module_def: Some(module), - type_def: None + type_def: None, + type_span: None, }) } Some(type_def) => { @@ -549,7 +550,8 @@ pub impl NameBindings { self.type_def = Some(TypeNsDef { privacy: privacy, module_def: Some(module), - type_def: type_def.type_def + type_def: type_def.type_def, + type_span: None, }) } Some(module_def) => module_def.kind = kind, @@ -1392,10 +1394,8 @@ pub impl Resolver { } } - /** - * Constructs the reduced graph for one 'view item'. View items consist - * of imports and use directives. - */ + /// Constructs the reduced graph for one 'view item'. View items consist + /// of imports and use directives. fn build_reduced_graph_for_view_item(@mut self, view_item: @view_item, parent: ReducedGraphParent, @@ -1551,11 +1551,13 @@ pub impl Resolver { fn handle_external_def(@mut self, def: def, + visibility: ast::visibility, modules: &mut HashMap, child_name_bindings: @mut NameBindings, final_ident: &str, ident: ident, new_parent: ReducedGraphParent) { + let privacy = visibility_to_privacy(visibility); match def { def_mod(def_id) | def_foreign_mod(def_id) => { match child_name_bindings.type_def { @@ -1573,7 +1575,7 @@ pub impl Resolver { // FIXME (#5074): this should be a match on find if !modules.contains_key(&def_id) { - child_name_bindings.define_module(Public, + child_name_bindings.define_module(privacy, parent_link, Some(def_id), NormalModuleKind, @@ -1582,9 +1584,9 @@ pub impl Resolver { child_name_bindings.get_module()); } else { let existing_module = *modules.get(&def_id); - // Create an import resolution to - // avoid creating cycles in the - // module graph. + + // Create an import resolution to avoid creating cycles in + // the module graph. let resolution = @mut ImportResolution(Public, 0); resolution.outstanding_references = 0; @@ -1610,11 +1612,19 @@ pub impl Resolver { } } } - def_fn(*) | def_static_method(*) | def_const(*) | def_variant(*) => { + debug!("(building reduced graph for external crate) building \ + variant %s", + final_ident); + // We assume the parent is visible, or else we wouldn't have seen + // it. + let privacy = variant_visibility_to_privacy(visibility, true); + child_name_bindings.define_value(privacy, def, dummy_sp()); + } + def_fn(*) | def_static_method(*) | def_const(*) => { debug!("(building reduced graph for external \ crate) building value %s", final_ident); - child_name_bindings.define_value(Public, def, dummy_sp()); + child_name_bindings.define_value(privacy, def, dummy_sp()); } def_trait(def_id) => { debug!("(building reduced graph for external \ @@ -1651,11 +1661,11 @@ pub impl Resolver { } } - child_name_bindings.define_type(Public, def, dummy_sp()); + child_name_bindings.define_type(privacy, def, dummy_sp()); // Define a module if necessary. let parent_link = self.get_parent_link(new_parent, ident); - child_name_bindings.set_module_kind(Public, + child_name_bindings.set_module_kind(privacy, parent_link, Some(def_id), TraitModuleKind, @@ -1665,13 +1675,13 @@ pub impl Resolver { debug!("(building reduced graph for external \ crate) building type %s", final_ident); - child_name_bindings.define_type(Public, def, dummy_sp()); + child_name_bindings.define_type(privacy, def, dummy_sp()); } def_struct(def_id) => { debug!("(building reduced graph for external \ crate) building type %s", final_ident); - child_name_bindings.define_type(Public, def, dummy_sp()); + child_name_bindings.define_type(privacy, def, dummy_sp()); self.structs.insert(def_id); } def_self(*) | def_arg(*) | def_local(*) | @@ -1692,7 +1702,7 @@ pub impl Resolver { // Create all the items reachable by paths. for each_path(self.session.cstore, root.def_id.get().crate) - |path_string, def_like| { + |path_string, def_like, visibility| { debug!("(building reduced graph for external crate) found path \ entry: %s (%?)", @@ -1760,6 +1770,7 @@ pub impl Resolver { dummy_sp()); self.handle_external_def(def, + visibility, &mut modules, child_name_bindings, *self.session.str_of( @@ -2995,14 +3006,9 @@ pub impl Resolver { // If this is a search of all imports, we should be done with glob // resolution at this point. -<<<<<<< HEAD - if name_search_type == SearchItemsAndAllImports { - assert_eq!(module_.glob_count, 0); -======= if name_search_type == PathPublicOrPrivateSearch || name_search_type == PathPublicOnlySearch { - assert!(module_.glob_count == 0); ->>>>>>> librustc: Disallow `use` from reaching into impls or traits. + assert_eq!(module_.glob_count, 0); } // Check the list of resolved imports. diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index f133a010f83ab..8870f0fdc57f0 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -975,7 +975,7 @@ pub impl CoherenceChecker { def_id { crate: crate_number, node: 0 }); - for each_path(crate_store, crate_number) |_p, def_like| { + for each_path(crate_store, crate_number) |_, def_like, _| { match def_like { dl_def(def_mod(def_id)) => { self.add_impls_for_module(&mut impls_seen, diff --git a/src/test/auxiliary/private_variant_xc.rs b/src/test/auxiliary/private_variant_xc.rs new file mode 100644 index 0000000000000..d7d55c691b683 --- /dev/null +++ b/src/test/auxiliary/private_variant_xc.rs @@ -0,0 +1,5 @@ +pub enum Foo { + pub Bar, + priv Baz, +} + diff --git a/src/test/compile-fail/private-variant-xc.rs b/src/test/compile-fail/private-variant-xc.rs new file mode 100644 index 0000000000000..c7838b9885508 --- /dev/null +++ b/src/test/compile-fail/private-variant-xc.rs @@ -0,0 +1,9 @@ +// aux-build:private_variant_xc.rs + +extern mod private_variant_xc; + +pub fn main() { + let _ = private_variant_xc::Bar; + let _ = private_variant_xc::Baz; //~ ERROR unresolved name +} + From 0c820d4123c754522b0655e9e74f692c55685bfa Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Fri, 17 May 2013 10:45:09 -0700 Subject: [PATCH 186/248] libstd: Rename libcore to libstd and libstd to libextra; update makefiles. This only changes the directory names; it does not change the "real" metadata names. --- Makefile.in | 52 +- configure | 2 +- mk/clean.mk | 8 +- mk/dist.mk | 4 +- mk/docs.mk | 4 +- mk/host.mk | 42 +- mk/install.mk | 16 +- mk/pp.mk | 4 +- mk/stage0.mk | 14 +- mk/target.mk | 14 +- mk/tests.mk | 16 +- mk/tools.mk | 14 +- src/libcore/comm.rs | 810 ----- src/libcore/unicode.rs | 2642 --------------- src/{libstd => libextra}/arc.rs | 0 src/{libstd => libextra}/arena.rs | 0 src/{libstd => libextra}/base64.rs | 0 src/{libstd => libextra}/bitv.rs | 0 src/{libstd => libextra}/c_vec.rs | 0 src/libextra/comm.rs | 110 + src/{libstd => libextra}/dbg.rs | 0 src/{libstd => libextra}/deque.rs | 0 src/{libstd => libextra}/dlist.rs | 0 src/{libstd => libextra}/ebml.rs | 0 src/{libstd => libextra}/fileinput.rs | 0 src/{libstd => libextra}/flate.rs | 0 src/{libstd => libextra}/flatpipes.rs | 0 src/{libstd => libextra}/fun_treemap.rs | 0 src/{libstd => libextra}/future.rs | 0 src/{libstd => libextra}/getopts.rs | 0 src/{libstd => libextra}/io_util.rs | 0 src/{libstd => libextra}/json.rs | 0 src/{libstd => libextra}/list.rs | 0 src/{libstd => libextra}/md4.rs | 0 src/{libstd => libextra}/net.rs | 0 src/{libstd => libextra}/net_ip.rs | 0 src/{libstd => libextra}/net_tcp.rs | 0 src/{libstd => libextra}/net_url.rs | 0 src/{libstd => libextra}/num/bigint.rs | 0 src/{libstd => libextra}/num/complex.rs | 0 src/{libstd => libextra}/num/rational.rs | 0 src/{libstd => libextra}/par.rs | 0 src/{libstd => libextra}/priority_queue.rs | 0 src/{libstd => libextra}/rc.rs | 0 src/{libstd => libextra}/rl.rs | 0 src/{libstd => libextra}/rope.rs | 0 src/{libstd => libextra}/semver.rs | 0 src/{libstd => libextra}/serialize.rs | 0 src/{libstd => libextra}/sha1.rs | 0 src/{libstd => libextra}/smallintmap.rs | 0 src/{libstd => libextra}/sort.rs | 0 src/{libstd => libextra}/stats.rs | 0 src/{libstd => libextra}/std.rc | 0 src/{libstd => libextra}/sync.rs | 0 src/{libstd => libextra}/task_pool.rs | 0 src/{libstd => libextra}/tempfile.rs | 0 src/{libstd => libextra}/term.rs | 0 src/{libstd => libextra}/test.rs | 0 src/{libstd => libextra}/time.rs | 0 src/{libstd => libextra}/timer.rs | 0 src/{libstd => libextra}/treemap.rs | 0 src/libextra/unicode.rs | 248 ++ src/{libstd => libextra}/uv.rs | 0 src/{libstd => libextra}/uv_global_loop.rs | 0 src/{libstd => libextra}/uv_iotask.rs | 0 src/{libstd => libextra}/uv_ll.rs | 0 src/{libstd => libextra}/workcache.rs | 0 src/{libcore => libstd}/at_vec.rs | 0 src/{libcore => libstd}/bool.rs | 0 src/{libcore => libstd}/cast.rs | 0 src/{libcore => libstd}/cell.rs | 0 src/{libcore => libstd}/char.rs | 0 src/{libcore => libstd}/cleanup.rs | 0 src/{libcore => libstd}/clone.rs | 0 src/{libcore => libstd}/cmp.rs | 0 src/libstd/comm.rs | 808 ++++- src/{libcore => libstd}/condition.rs | 0 src/{libcore => libstd}/container.rs | 0 src/{libcore => libstd}/core.rc | 0 src/{libcore => libstd}/either.rs | 0 src/{libcore => libstd}/from_str.rs | 0 src/{libcore => libstd}/gc.rs | 0 src/{libcore => libstd}/hash.rs | 0 src/{libcore => libstd}/hashmap.rs | 0 src/{libcore => libstd}/io.rs | 0 src/{libcore => libstd}/iter.rs | 0 src/{libcore => libstd}/iterator.rs | 0 src/{libcore => libstd}/kinds.rs | 0 src/{libcore => libstd}/libc.rs | 0 src/{libcore => libstd}/local_data.rs | 0 src/{libcore => libstd}/logging.rs | 0 src/{libcore => libstd}/macros.rs | 0 src/{libcore => libstd}/managed.rs | 0 src/{libcore => libstd}/nil.rs | 0 src/{libcore => libstd}/num/cmath.rs | 0 src/{libcore => libstd}/num/f32.rs | 0 src/{libcore => libstd}/num/f64.rs | 0 src/{libcore => libstd}/num/float.rs | 0 src/{libcore => libstd}/num/int-template.rs | 0 .../num/int-template/i16.rs | 0 .../num/int-template/i32.rs | 0 .../num/int-template/i64.rs | 0 .../num/int-template/i8.rs | 0 .../num/int-template/int.rs | 0 src/{libcore => libstd}/num/num.rs | 0 src/{libcore => libstd}/num/strconv.rs | 0 src/{libcore => libstd}/num/uint-template.rs | 0 .../num/uint-template/u16.rs | 0 .../num/uint-template/u32.rs | 0 .../num/uint-template/u64.rs | 0 .../num/uint-template/u8.rs | 0 .../num/uint-template/uint.rs | 0 src/{libcore => libstd}/old_iter.rs | 0 src/{libcore => libstd}/ops.rs | 0 src/{libcore => libstd}/option.rs | 0 src/{libcore => libstd}/os.rs | 0 src/{libcore => libstd}/owned.rs | 0 src/{libcore => libstd}/path.rs | 0 src/{libcore => libstd}/pipes.rs | 0 src/{libcore => libstd}/prelude.rs | 0 src/{libcore => libstd}/ptr.rs | 0 src/{libcore => libstd}/rand.rs | 0 src/{libcore => libstd}/rand/distributions.rs | 0 .../rand/ziggurat_tables.rs | 0 src/{libcore => libstd}/reflect.rs | 0 src/{libcore => libstd}/repr.rs | 0 src/{libcore => libstd}/result.rs | 0 src/{libcore => libstd}/rt/context.rs | 0 src/{libcore => libstd}/rt/env.rs | 0 .../rt/io/comm_adapters.rs | 0 src/{libcore => libstd}/rt/io/extensions.rs | 0 src/{libcore => libstd}/rt/io/file.rs | 0 src/{libcore => libstd}/rt/io/flate.rs | 0 src/{libcore => libstd}/rt/io/mem.rs | 0 src/{libcore => libstd}/rt/io/mod.rs | 0 src/{libcore => libstd}/rt/io/native/file.rs | 0 src/{libcore => libstd}/rt/io/net/http.rs | 0 src/{libcore => libstd}/rt/io/net/ip.rs | 0 src/{libcore => libstd}/rt/io/net/tcp.rs | 0 src/{libcore => libstd}/rt/io/net/udp.rs | 0 src/{libcore => libstd}/rt/io/net/unix.rs | 0 src/{libcore => libstd}/rt/io/option.rs | 0 src/{libcore => libstd}/rt/io/stdio.rs | 0 src/{libcore => libstd}/rt/io/support.rs | 0 src/{libcore => libstd}/rt/local_heap.rs | 0 src/{libcore => libstd}/rt/mod.rs | 0 src/{libcore => libstd}/rt/rtio.rs | 0 src/{libcore => libstd}/rt/stack.rs | 0 src/{libcore => libstd}/rt/task.rs | 0 src/{libcore => libstd}/rt/test.rs | 0 src/{libcore => libstd}/rt/thread.rs | 0 .../rt/thread_local_storage.rs | 0 src/{libcore => libstd}/rt/uv/file.rs | 0 src/{libcore => libstd}/rt/uv/mod.rs | 0 src/{libcore => libstd}/rt/uv/net.rs | 0 src/{libcore/rt/uv => libstd/rt}/uvio.rs | 327 +- src/{libcore/rt/uv => libstd/rt}/uvll.rs | 23 +- src/{libcore => libstd}/rt/work_queue.rs | 0 src/{libcore => libstd}/run.rs | 0 src/{libcore => libstd}/stackwalk.rs | 0 src/{libcore => libstd}/str.rs | 0 src/{libcore => libstd}/str/ascii.rs | 0 src/{libcore => libstd}/sys.rs | 0 .../task/local_data_priv.rs | 0 src/{libcore => libstd}/task/mod.rs | 0 src/{libcore => libstd}/task/rt.rs | 0 src/{libcore => libstd}/task/spawn.rs | 0 src/{libcore => libstd}/to_bytes.rs | 0 src/{libcore => libstd}/to_str.rs | 0 src/{libcore => libstd}/trie.rs | 0 src/{libcore => libstd}/tuple.rs | 0 src/libstd/unicode.rs | 2830 +++++++++++++++-- src/{libcore => libstd}/unstable/at_exit.rs | 0 .../unstable/exchange_alloc.rs} | 14 +- src/{libcore => libstd}/unstable/extfmt.rs | 0 src/{libcore => libstd}/unstable/finally.rs | 0 src/{libcore => libstd}/unstable/global.rs | 0 .../unstable/intrinsics.rs | 0 src/{libcore => libstd}/unstable/lang.rs | 0 src/{libcore => libstd}/unstable/mod.rs | 0 src/{libcore => libstd}/unstable/simd.rs | 0 src/{libcore => libstd}/unstable/sync.rs | 0 src/{libcore => libstd}/unstable/weak_task.rs | 0 src/{libcore => libstd}/util.rs | 0 src/{libcore => libstd}/vec.rs | 0 src/libuv | 2 +- 186 files changed, 3980 insertions(+), 4024 deletions(-) delete mode 100644 src/libcore/comm.rs delete mode 100644 src/libcore/unicode.rs rename src/{libstd => libextra}/arc.rs (100%) rename src/{libstd => libextra}/arena.rs (100%) rename src/{libstd => libextra}/base64.rs (100%) rename src/{libstd => libextra}/bitv.rs (100%) rename src/{libstd => libextra}/c_vec.rs (100%) create mode 100644 src/libextra/comm.rs rename src/{libstd => libextra}/dbg.rs (100%) rename src/{libstd => libextra}/deque.rs (100%) rename src/{libstd => libextra}/dlist.rs (100%) rename src/{libstd => libextra}/ebml.rs (100%) rename src/{libstd => libextra}/fileinput.rs (100%) rename src/{libstd => libextra}/flate.rs (100%) rename src/{libstd => libextra}/flatpipes.rs (100%) rename src/{libstd => libextra}/fun_treemap.rs (100%) rename src/{libstd => libextra}/future.rs (100%) rename src/{libstd => libextra}/getopts.rs (100%) rename src/{libstd => libextra}/io_util.rs (100%) rename src/{libstd => libextra}/json.rs (100%) rename src/{libstd => libextra}/list.rs (100%) rename src/{libstd => libextra}/md4.rs (100%) rename src/{libstd => libextra}/net.rs (100%) rename src/{libstd => libextra}/net_ip.rs (100%) rename src/{libstd => libextra}/net_tcp.rs (100%) rename src/{libstd => libextra}/net_url.rs (100%) rename src/{libstd => libextra}/num/bigint.rs (100%) rename src/{libstd => libextra}/num/complex.rs (100%) rename src/{libstd => libextra}/num/rational.rs (100%) rename src/{libstd => libextra}/par.rs (100%) rename src/{libstd => libextra}/priority_queue.rs (100%) rename src/{libstd => libextra}/rc.rs (100%) rename src/{libstd => libextra}/rl.rs (100%) rename src/{libstd => libextra}/rope.rs (100%) rename src/{libstd => libextra}/semver.rs (100%) rename src/{libstd => libextra}/serialize.rs (100%) rename src/{libstd => libextra}/sha1.rs (100%) rename src/{libstd => libextra}/smallintmap.rs (100%) rename src/{libstd => libextra}/sort.rs (100%) rename src/{libstd => libextra}/stats.rs (100%) rename src/{libstd => libextra}/std.rc (100%) rename src/{libstd => libextra}/sync.rs (100%) rename src/{libstd => libextra}/task_pool.rs (100%) rename src/{libstd => libextra}/tempfile.rs (100%) rename src/{libstd => libextra}/term.rs (100%) rename src/{libstd => libextra}/test.rs (100%) rename src/{libstd => libextra}/time.rs (100%) rename src/{libstd => libextra}/timer.rs (100%) rename src/{libstd => libextra}/treemap.rs (100%) create mode 100644 src/libextra/unicode.rs rename src/{libstd => libextra}/uv.rs (100%) rename src/{libstd => libextra}/uv_global_loop.rs (100%) rename src/{libstd => libextra}/uv_iotask.rs (100%) rename src/{libstd => libextra}/uv_ll.rs (100%) rename src/{libstd => libextra}/workcache.rs (100%) rename src/{libcore => libstd}/at_vec.rs (100%) rename src/{libcore => libstd}/bool.rs (100%) rename src/{libcore => libstd}/cast.rs (100%) rename src/{libcore => libstd}/cell.rs (100%) rename src/{libcore => libstd}/char.rs (100%) rename src/{libcore => libstd}/cleanup.rs (100%) rename src/{libcore => libstd}/clone.rs (100%) rename src/{libcore => libstd}/cmp.rs (100%) rename src/{libcore => libstd}/condition.rs (100%) rename src/{libcore => libstd}/container.rs (100%) rename src/{libcore => libstd}/core.rc (100%) rename src/{libcore => libstd}/either.rs (100%) rename src/{libcore => libstd}/from_str.rs (100%) rename src/{libcore => libstd}/gc.rs (100%) rename src/{libcore => libstd}/hash.rs (100%) rename src/{libcore => libstd}/hashmap.rs (100%) rename src/{libcore => libstd}/io.rs (100%) rename src/{libcore => libstd}/iter.rs (100%) rename src/{libcore => libstd}/iterator.rs (100%) rename src/{libcore => libstd}/kinds.rs (100%) rename src/{libcore => libstd}/libc.rs (100%) rename src/{libcore => libstd}/local_data.rs (100%) rename src/{libcore => libstd}/logging.rs (100%) rename src/{libcore => libstd}/macros.rs (100%) rename src/{libcore => libstd}/managed.rs (100%) rename src/{libcore => libstd}/nil.rs (100%) rename src/{libcore => libstd}/num/cmath.rs (100%) rename src/{libcore => libstd}/num/f32.rs (100%) rename src/{libcore => libstd}/num/f64.rs (100%) rename src/{libcore => libstd}/num/float.rs (100%) rename src/{libcore => libstd}/num/int-template.rs (100%) rename src/{libcore => libstd}/num/int-template/i16.rs (100%) rename src/{libcore => libstd}/num/int-template/i32.rs (100%) rename src/{libcore => libstd}/num/int-template/i64.rs (100%) rename src/{libcore => libstd}/num/int-template/i8.rs (100%) rename src/{libcore => libstd}/num/int-template/int.rs (100%) rename src/{libcore => libstd}/num/num.rs (100%) rename src/{libcore => libstd}/num/strconv.rs (100%) rename src/{libcore => libstd}/num/uint-template.rs (100%) rename src/{libcore => libstd}/num/uint-template/u16.rs (100%) rename src/{libcore => libstd}/num/uint-template/u32.rs (100%) rename src/{libcore => libstd}/num/uint-template/u64.rs (100%) rename src/{libcore => libstd}/num/uint-template/u8.rs (100%) rename src/{libcore => libstd}/num/uint-template/uint.rs (100%) rename src/{libcore => libstd}/old_iter.rs (100%) rename src/{libcore => libstd}/ops.rs (100%) rename src/{libcore => libstd}/option.rs (100%) rename src/{libcore => libstd}/os.rs (100%) rename src/{libcore => libstd}/owned.rs (100%) rename src/{libcore => libstd}/path.rs (100%) rename src/{libcore => libstd}/pipes.rs (100%) rename src/{libcore => libstd}/prelude.rs (100%) rename src/{libcore => libstd}/ptr.rs (100%) rename src/{libcore => libstd}/rand.rs (100%) rename src/{libcore => libstd}/rand/distributions.rs (100%) rename src/{libcore => libstd}/rand/ziggurat_tables.rs (100%) rename src/{libcore => libstd}/reflect.rs (100%) rename src/{libcore => libstd}/repr.rs (100%) rename src/{libcore => libstd}/result.rs (100%) rename src/{libcore => libstd}/rt/context.rs (100%) rename src/{libcore => libstd}/rt/env.rs (100%) rename src/{libcore => libstd}/rt/io/comm_adapters.rs (100%) rename src/{libcore => libstd}/rt/io/extensions.rs (100%) rename src/{libcore => libstd}/rt/io/file.rs (100%) rename src/{libcore => libstd}/rt/io/flate.rs (100%) rename src/{libcore => libstd}/rt/io/mem.rs (100%) rename src/{libcore => libstd}/rt/io/mod.rs (100%) rename src/{libcore => libstd}/rt/io/native/file.rs (100%) rename src/{libcore => libstd}/rt/io/net/http.rs (100%) rename src/{libcore => libstd}/rt/io/net/ip.rs (100%) rename src/{libcore => libstd}/rt/io/net/tcp.rs (100%) rename src/{libcore => libstd}/rt/io/net/udp.rs (100%) rename src/{libcore => libstd}/rt/io/net/unix.rs (100%) rename src/{libcore => libstd}/rt/io/option.rs (100%) rename src/{libcore => libstd}/rt/io/stdio.rs (100%) rename src/{libcore => libstd}/rt/io/support.rs (100%) rename src/{libcore => libstd}/rt/local_heap.rs (100%) rename src/{libcore => libstd}/rt/mod.rs (100%) rename src/{libcore => libstd}/rt/rtio.rs (100%) rename src/{libcore => libstd}/rt/stack.rs (100%) rename src/{libcore => libstd}/rt/task.rs (100%) rename src/{libcore => libstd}/rt/test.rs (100%) rename src/{libcore => libstd}/rt/thread.rs (100%) rename src/{libcore => libstd}/rt/thread_local_storage.rs (100%) rename src/{libcore => libstd}/rt/uv/file.rs (100%) rename src/{libcore => libstd}/rt/uv/mod.rs (100%) rename src/{libcore => libstd}/rt/uv/net.rs (100%) rename src/{libcore/rt/uv => libstd/rt}/uvio.rs (51%) rename src/{libcore/rt/uv => libstd/rt}/uvll.rs (95%) rename src/{libcore => libstd}/rt/work_queue.rs (100%) rename src/{libcore => libstd}/run.rs (100%) rename src/{libcore => libstd}/stackwalk.rs (100%) rename src/{libcore => libstd}/str.rs (100%) rename src/{libcore => libstd}/str/ascii.rs (100%) rename src/{libcore => libstd}/sys.rs (100%) rename src/{libcore => libstd}/task/local_data_priv.rs (100%) rename src/{libcore => libstd}/task/mod.rs (100%) rename src/{libcore => libstd}/task/rt.rs (100%) rename src/{libcore => libstd}/task/spawn.rs (100%) rename src/{libcore => libstd}/to_bytes.rs (100%) rename src/{libcore => libstd}/to_str.rs (100%) rename src/{libcore => libstd}/trie.rs (100%) rename src/{libcore => libstd}/tuple.rs (100%) rename src/{libcore => libstd}/unstable/at_exit.rs (100%) rename src/{libcore/rt/global_heap.rs => libstd/unstable/exchange_alloc.rs} (88%) rename src/{libcore => libstd}/unstable/extfmt.rs (100%) rename src/{libcore => libstd}/unstable/finally.rs (100%) rename src/{libcore => libstd}/unstable/global.rs (100%) rename src/{libcore => libstd}/unstable/intrinsics.rs (100%) rename src/{libcore => libstd}/unstable/lang.rs (100%) rename src/{libcore => libstd}/unstable/mod.rs (100%) rename src/{libcore => libstd}/unstable/simd.rs (100%) rename src/{libcore => libstd}/unstable/sync.rs (100%) rename src/{libcore => libstd}/unstable/weak_task.rs (100%) rename src/{libcore => libstd}/util.rs (100%) rename src/{libcore => libstd}/vec.rs (100%) diff --git a/Makefile.in b/Makefile.in index 9b59c46e5e831..0a652c0f35017 100644 --- a/Makefile.in +++ b/Makefile.in @@ -205,8 +205,8 @@ define DEF_LIBS CFG_RUNTIME_$(1) :=$(call CFG_LIB_NAME_$(1),rustrt) CFG_RUSTLLVM_$(1) :=$(call CFG_LIB_NAME_$(1),rustllvm) -CFG_CORELIB_$(1) :=$(call CFG_LIB_NAME_$(1),core) CFG_STDLIB_$(1) :=$(call CFG_LIB_NAME_$(1),std) +CFG_EXTRALIB_$(1) :=$(call CFG_LIB_NAME_$(1),extra) CFG_LIBRUSTC_$(1) :=$(call CFG_LIB_NAME_$(1),rustc) CFG_LIBSYNTAX_$(1) :=$(call CFG_LIB_NAME_$(1),syntax) CFG_LIBFUZZER_$(1) :=$(call CFG_LIB_NAME_$(1),fuzzer) @@ -215,8 +215,8 @@ CFG_LIBRUSTDOC_$(1) :=$(call CFG_LIB_NAME_$(1),rustdoc) CFG_LIBRUSTI_$(1) :=$(call CFG_LIB_NAME_$(1),rusti) CFG_LIBRUST_$(1) :=$(call CFG_LIB_NAME_$(1),rust) -STDLIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),std) -CORELIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),core) +EXTRALIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),std) +STDLIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),core) LIBRUSTC_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),rustc) LIBSYNTAX_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),syntax) LIBFUZZER_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),fuzzer) @@ -224,8 +224,8 @@ LIBRUSTPKG_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),rustpkg) LIBRUSTDOC_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),rustdoc) LIBRUSTI_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),rusti) LIBRUST_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),rust) +EXTRALIB_DSYM_GLOB_$(1) :=$(call CFG_LIB_DSYM_GLOB_$(1),extra) STDLIB_DSYM_GLOB_$(1) :=$(call CFG_LIB_DSYM_GLOB_$(1),std) -CORELIB_DSYM_GLOB_$(1) :=$(call CFG_LIB_DSYM_GLOB_$(1),core) LIBRUSTC_DSYM_GLOB_$(1) :=$(call CFG_LIB_DSYM_GLOB_$(1),rustc) LIBSYNTAX_DSYM_GLOB_$(1) :=$(call CFG_LIB_DSYM_GLOB_$(1),syntax) LIBFUZZER_DSYM_GLOB_$(1) :=$(call CFG_LIB_DSYM_GLOB_$(1),fuzzer) @@ -240,19 +240,19 @@ $(foreach target,$(CFG_TARGET_TRIPLES),\ $(eval $(call DEF_LIBS,$(target)))) ###################################################################### -# Core library variables +# Standard library variables ###################################################################### -CORELIB_CRATE := $(S)src/libcore/core.rc -CORELIB_INPUTS := $(wildcard $(addprefix $(S)src/libcore/, \ +STDLIB_CRATE := $(S)src/libstd/core.rc +STDLIB_INPUTS := $(wildcard $(addprefix $(S)src/libstd/, \ core.rc *.rs */*.rs */*/*rs */*/*/*rs)) ###################################################################### -# Standard library variables +# Extra library variables ###################################################################### -STDLIB_CRATE := $(S)src/libstd/std.rc -STDLIB_INPUTS := $(wildcard $(addprefix $(S)src/libstd/, \ +EXTRALIB_CRATE := $(S)src/libextra/std.rc +EXTRALIB_INPUTS := $(wildcard $(addprefix $(S)src/libextra/, \ std.rc *.rs */*.rs)) ###################################################################### @@ -344,33 +344,33 @@ TROOT$(1)_T_$(2)_H_$(3) = $$(HLIB$(1)_H_$(3))/rustc/$(2) TBIN$(1)_T_$(2)_H_$(3) = $$(TROOT$(1)_T_$(2)_H_$(3))/bin TLIB$(1)_T_$(2)_H_$(3) = $$(TROOT$(1)_T_$(2)_H_$(3))/$$(CFG_LIBDIR) -# The name of the core and standard libraries used by rustc +# The name of the standard and extra libraries used by rustc ifdef CFG_DISABLE_SHAREDSTD - HCORELIB_DEFAULT$(1)_H_$(3) = \ - $$(HLIB$(1)_H_$(3))/libcore.rlib - TCORELIB_DEFAULT$(1)_T_$(2)_H_$(3) = \ - $$(TLIB$(1)_T_$(2)_H_$(3))/libcore.rlib - HSTDLIB_DEFAULT$(1)_H_$(3) = \ $$(HLIB$(1)_H_$(3))/libstd.rlib TSTDLIB_DEFAULT$(1)_T_$(2)_H_$(3) = \ $$(TLIB$(1)_T_$(2)_H_$(3))/libstd.rlib + HEXTRALIB_DEFAULT$(1)_H_$(3) = \ + $$(HLIB$(1)_H_$(3))/libextra.rlib + TEXTRALIB_DEFAULT$(1)_T_$(2)_H_$(3) = \ + $$(TLIB$(1)_T_$(2)_H_$(3))/libextra.rlib + HLIBRUSTC_DEFAULT$(1)_H_$(3) = \ $$(HLIB$(1)_H_$(3))/librustc.rlib TLIBRUSTC_DEFAULT$(1)_T_$(2)_H_$(3) = \ $$(TLIB$(1)_T_$(2)_H_$(3))/librustc.rlib else - HCORELIB_DEFAULT$(1)_H_$(3) = \ - $$(HLIB$(1)_H_$(3))/$(CFG_CORELIB_$(3)) - TCORELIB_DEFAULT$(1)_T_$(2)_H_$(3) = \ - $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_CORELIB_$(2)) - HSTDLIB_DEFAULT$(1)_H_$(3) = \ $$(HLIB$(1)_H_$(3))/$(CFG_STDLIB_$(3)) TSTDLIB_DEFAULT$(1)_T_$(2)_H_$(3) = \ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)) + HEXTRALIB_DEFAULT$(1)_H_$(3) = \ + $$(HLIB$(1)_H_$(3))/$(CFG_EXTRALIB_$(3)) + TEXTRALIB_DEFAULT$(1)_T_$(2)_H_$(3) = \ + $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_EXTRALIB_$(2)) + HLIBRUSTC_DEFAULT$(1)_H_$(3) = \ $$(HLIB$(1)_H_$(3))/$(CFG_LIBRUSTC_$(3)) TLIBRUSTC_DEFAULT$(1)_T_$(2)_H_$(3) = \ @@ -382,8 +382,8 @@ HSREQ$(1)_H_$(3) = \ $$(HBIN$(1)_H_$(3))/rustc$$(X_$(3)) \ $$(HLIB$(1)_H_$(3))/$(CFG_RUNTIME_$(3)) \ $$(HLIB$(1)_H_$(3))/$(CFG_RUSTLLVM_$(3)) \ - $$(HCORELIB_DEFAULT$(1)_H_$(3)) \ $$(HSTDLIB_DEFAULT$(1)_H_$(3)) \ + $$(HEXTRALIB_DEFAULT$(1)_H_$(3)) \ $$(HLIBSYNTAX_DEFAULT$(1)_H_$(3)) \ $$(HLIBRUSTC_DEFAULT$(1)_H_$(3)) \ $$(MKFILE_DEPS) @@ -397,8 +397,8 @@ TSREQ$(1)_T_$(2)_H_$(3) = \ # Prerequisites for a working stageN compiler and libraries, for a specific target SREQ$(1)_T_$(2)_H_$(3) = \ $$(TSREQ$(1)_T_$(2)_H_$(3)) \ - $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_CORELIB_$(2)) \ - $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)) + $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)) \ + $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_EXTRALIB_$(2)) # Prerequisites for a working stageN compiler and libraries, for a specific target CSREQ$(1)_T_$(2)_H_$(3) = \ @@ -413,8 +413,8 @@ CSREQ$(1)_T_$(2)_H_$(3) = \ $$(HLIB$(1)_H_$(3))/$(CFG_LIBRUSTDOC_$(3)) \ $$(HLIB$(1)_H_$(3))/$(CFG_LIBRUSTI_$(3)) \ $$(HLIB$(1)_H_$(3))/$(CFG_LIBRUST_$(3)) \ - $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_CORELIB_$(2)) \ - $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)) \ + $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)) \ + $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_EXTRALIB_$(2)) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBSYNTAX_$(2)) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUSTC_$(2)) \ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBFUZZER_$(2)) \ diff --git a/configure b/configure index e4ca72737db9e..0b8189416bb0b 100755 --- a/configure +++ b/configure @@ -643,7 +643,7 @@ fi step_msg "making directories" for i in \ - doc doc/core doc/std \ + doc doc/std doc/extra \ dl tmp do make_dir $i diff --git a/mk/clean.mk b/mk/clean.mk index 660793b1c347e..9a074b29d8b1c 100644 --- a/mk/clean.mk +++ b/mk/clean.mk @@ -73,14 +73,14 @@ clean$(1)_H_$(2): $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBRUSTPKG_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBRUSTDOC_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_RUNTIME_$(2)) - $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_CORELIB_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_STDLIB_$(2)) + $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_EXTRALIB_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBRUSTC_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBSYNTAX_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBRUSTI_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CFG_LIBRUST_$(2)) - $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(CORELIB_GLOB_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(STDLIB_GLOB_$(2)) + $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(EXTRALIB_GLOB_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBRUSTC_GLOB_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBSYNTAX_GLOB_$(2)) $(Q)rm -f $$(HLIB$(1)_H_$(2))/$(LIBFUZZER_GLOB_$(2)) @@ -111,14 +111,14 @@ clean$(1)_T_$(2)_H_$(3): $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUSTPKG_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUSTDOC_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_RUNTIME_$(2)) - $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_CORELIB_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)) + $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_EXTRALIB_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUSTC_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBSYNTAX_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUSTI_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBRUST_$(2)) - $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(CORELIB_GLOB_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(STDLIB_GLOB_$(2)) + $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(EXTRALIB_GLOB_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBRUSTC_GLOB_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBSYNTAX_GLOB_$(2)) $(Q)rm -f $$(TLIB$(1)_T_$(2)_H_$(3))/$(LIBFUZZER_GLOB_$(2)) diff --git a/mk/dist.mk b/mk/dist.mk index f71abc48620d1..96f35031de930 100644 --- a/mk/dist.mk +++ b/mk/dist.mk @@ -33,9 +33,9 @@ PKG_FILES := \ compiletest \ etc \ libfuzzer \ - libcore \ - libsyntax \ + libextra \ libstd \ + libsyntax \ rt \ librustdoc \ rustllvm \ diff --git a/mk/docs.mk b/mk/docs.mk index f49c75d6acb01..8470da7c07b2c 100644 --- a/mk/docs.mk +++ b/mk/docs.mk @@ -173,7 +173,7 @@ endif ###################################################################### -# Rustdoc (libcore/std) +# Rustdoc (libstd/extra) ###################################################################### ifeq ($(CFG_PANDOC),) @@ -199,8 +199,8 @@ doc/$(1)/rust.css: rust.css DOCS += doc/$(1)/index.html endef -$(eval $(call libdoc,core,$(CORELIB_CRATE),$(CORELIB_INPUTS))) $(eval $(call libdoc,std,$(STDLIB_CRATE),$(STDLIB_INPUTS))) +$(eval $(call libdoc,extra,$(EXTRALIB_CRATE),$(EXTRALIB_INPUTS))) endif diff --git a/mk/host.mk b/mk/host.mk index 92c6ffbbe172f..ac3bc8ad8cbf9 100644 --- a/mk/host.mk +++ b/mk/host.mk @@ -28,8 +28,8 @@ $$(HBIN$(2)_H_$(4))/rustc$$(X_$(4)): \ $$(HLIB$(2)_H_$(4))/$(CFG_RUNTIME_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_RUSTLLVM_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_LIBRUSTC_$(4)) \ - $$(HCORELIB_DEFAULT$(2)_H_$(4)) \ $$(HSTDLIB_DEFAULT$(2)_H_$(4)) \ + $$(HEXTRALIB_DEFAULT$(2)_H_$(4)) \ | $$(HBIN$(2)_H_$(4))/ @$$(call E, cp: $$@) @@ -40,8 +40,8 @@ $$(HLIB$(2)_H_$(4))/$(CFG_LIBRUSTC_$(4)): \ $$(HLIB$(2)_H_$(4))/$(CFG_LIBSYNTAX_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_RUNTIME_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_RUSTLLVM_$(4)) \ - $$(HCORELIB_DEFAULT$(2)_H_$(4)) \ $$(HSTDLIB_DEFAULT$(2)_H_$(4)) \ + $$(HEXTRALIB_DEFAULT$(2)_H_$(4)) \ | $$(HLIB$(2)_H_$(4))/ @$$(call E, cp: $$@) @@ -54,8 +54,8 @@ $$(HLIB$(2)_H_$(4))/$(CFG_LIBSYNTAX_$(4)): \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBSYNTAX_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_RUNTIME_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_RUSTLLVM_$(4)) \ - $$(HCORELIB_DEFAULT$(2)_H_$(4)) \ $$(HSTDLIB_DEFAULT$(2)_H_$(4)) \ + $$(HEXTRALIB_DEFAULT$(2)_H_$(4)) \ | $$(HLIB$(2)_H_$(4))/ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ @@ -69,44 +69,44 @@ $$(HLIB$(2)_H_$(4))/$(CFG_RUNTIME_$(4)): \ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ -$$(HLIB$(2)_H_$(4))/$(CFG_CORELIB_$(4)): \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_CORELIB_$(4)) \ +$$(HLIB$(2)_H_$(4))/$(CFG_STDLIB_$(4)): \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_RUNTIME_$(4)) \ | $$(HLIB$(2)_H_$(4))/ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ -# Subtle: We do not let the shell expand $(CORELIB_DSYM_GLOB) directly rather +# Subtle: We do not let the shell expand $(STDLIB_DSYM_GLOB) directly rather # we use Make's $$(wildcard) facility. The reason is that, on mac, when using -# USE_SNAPSHOT_CORELIB, we copy the core.dylib file out of the snapshot. +# USE_SNAPSHOT_STDLIB, we copy the std.dylib file out of the snapshot. # In that case, there is no .dSYM file. Annoyingly, bash then refuses to expand -# glob, and cp reports an error because libcore-*.dylib.dsym does not exist. +# glob, and cp reports an error because libstd-*.dylib.dsym does not exist. # Make instead expands the glob to nothing, which gives us the correct behavior. # (Copy .dsym file if it exists, but do nothing otherwise) - $$(Q)cp -R $$(TLIB$(1)_T_$(4)_H_$(3))/$(CORELIB_GLOB_$(4)) \ - $$(wildcard $$(TLIB$(1)_T_$(4)_H_$(3))/$(CORELIB_DSYM_GLOB_$(4))) \ + $$(Q)cp -R $$(TLIB$(1)_T_$(4)_H_$(3))/$(STDLIB_GLOB_$(4)) \ + $$(wildcard $$(TLIB$(1)_T_$(4)_H_$(3))/$(STDLIB_DSYM_GLOB_$(4))) \ $$(HLIB$(2)_H_$(4)) -$$(HLIB$(2)_H_$(4))/$(CFG_STDLIB_$(4)): \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ - $$(HLIB$(2)_H_$(4))/$(CFG_CORELIB_$(4)) \ +$$(HLIB$(2)_H_$(4))/$(CFG_EXTRALIB_$(4)): \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_EXTRALIB_$(4)) \ + $$(HLIB$(2)_H_$(4))/$(CFG_STDLIB_$(4)) \ $$(HLIB$(2)_H_$(4))/$(CFG_RUNTIME_$(4)) \ | $$(HLIB$(2)_H_$(4))/ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ - $$(Q)cp -R $$(TLIB$(1)_T_$(4)_H_$(3))/$(STDLIB_GLOB_$(4)) \ - $$(wildcard $$(TLIB$(1)_T_$(4)_H_$(3))/$(STDLIB_DSYM_GLOB_$(4))) \ + $$(Q)cp -R $$(TLIB$(1)_T_$(4)_H_$(3))/$(EXTRALIB_GLOB_$(4)) \ + $$(wildcard $$(TLIB$(1)_T_$(4)_H_$(3))/$(EXTRALIB_DSYM_GLOB_$(4))) \ $$(HLIB$(2)_H_$(4)) -$$(HLIB$(2)_H_$(4))/libcore.rlib: \ - $$(TLIB$(1)_T_$(4)_H_$(3))/libcore.rlib \ +$$(HLIB$(2)_H_$(4))/libstd.rlib: \ + $$(TLIB$(1)_T_$(4)_H_$(3))/libstd.rlib \ $$(HLIB$(2)_H_$(4))/$$(CFG_RUNTIME_$(4)) \ | $$(HLIB$(2)_H_$(4))/ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ -$$(HLIB$(2)_H_$(4))/libstd.rlib: \ - $$(TLIB$(1)_T_$(4)_H_$(3))/libstd.rlib \ - $$(HLIB$(2)_H_$(4))/libcore.rlib \ +$$(HLIB$(2)_H_$(4))/libextra.rlib: \ + $$(TLIB$(1)_T_$(4)_H_$(3))/libextra.rlib \ + $$(HLIB$(2)_H_$(4))/libstd.rlib \ $$(HLIB$(2)_H_$(4))/$$(CFG_RUNTIME_$(4)) \ | $$(HLIB$(2)_H_$(4))/ @$$(call E, cp: $$@) @@ -114,8 +114,8 @@ $$(HLIB$(2)_H_$(4))/libstd.rlib: \ $$(HLIB$(2)_H_$(4))/librustc.rlib: \ $$(TLIB$(1)_T_$(4)_H_$(3))/librustc.rlib \ - $$(HLIB$(2)_H_$(4))/libcore.rlib \ $$(HLIB$(2)_H_$(4))/libstd.rlib \ + $$(HLIB$(2)_H_$(4))/libextra.rlib \ $$(HLIB$(2)_H_$(4))/$$(CFG_RUNTIME_$(4)) \ | $$(HLIB$(2)_H_$(4))/ @$$(call E, cp: $$@) diff --git a/mk/install.mk b/mk/install.mk index 47fcb224a7348..ae6bd29228f0b 100644 --- a/mk/install.mk +++ b/mk/install.mk @@ -52,10 +52,10 @@ define INSTALL_TARGET_N install-target-$(1)-host-$(2): $$(TSREQ$$(ISTAGE)_T_$(1)_H_$(2)) $$(SREQ$$(ISTAGE)_T_$(1)_H_$(2)) $$(Q)mkdir -p $$(PTL$(1)$(2)) $$(Q)$$(call INSTALL_LIB,$$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(CFG_RUNTIME_$(1))) - $$(Q)$$(call INSTALL_LIB, \ - $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(CORELIB_GLOB_$(1))) $$(Q)$$(call INSTALL_LIB, \ $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(STDLIB_GLOB_$(1))) + $$(Q)$$(call INSTALL_LIB, \ + $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(EXTRALIB_GLOB_$(1))) $$(Q)$$(call INSTALL_LIB,$$(TL$(1)$(2)),$$(PTL$(1)$(2)),libmorestack.a) endef @@ -64,10 +64,10 @@ define INSTALL_HOST_N install-target-$(1)-host-$(2): $$(CSREQ$$(ISTAGE)_T_$(1)_H_$(2)) $$(Q)mkdir -p $$(PTL$(1)$(2)) $$(Q)$$(call INSTALL_LIB,$$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(CFG_RUNTIME_$(1))) - $$(Q)$$(call INSTALL_LIB, \ - $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(CORELIB_GLOB_$(1))) $$(Q)$$(call INSTALL_LIB, \ $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(STDLIB_GLOB_$(1))) + $$(Q)$$(call INSTALL_LIB, \ + $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(EXTRALIB_GLOB_$(1))) $$(Q)$$(call INSTALL_LIB, \ $$(TL$(1)$(2)),$$(PTL$(1)$(2)),$$(LIBRUSTC_GLOB_$(1))) $$(Q)$$(call INSTALL_LIB, \ @@ -113,8 +113,8 @@ install-host: $(CSREQ$(ISTAGE)_T_$(CFG_BUILD_TRIPLE)_H_$(CFG_BUILD_TRIPLE)) $(Q)$(call INSTALL,$(HB2),$(PHB),rustdoc$(X_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL,$(HB2),$(PHB),rusti$(X_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL,$(HB2),$(PHB),rust$(X_$(CFG_BUILD_TRIPLE))) - $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(CORELIB_GLOB_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(STDLIB_GLOB_$(CFG_BUILD_TRIPLE))) + $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(EXTRALIB_GLOB_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTC_GLOB_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBSYNTAX_GLOB_$(CFG_BUILD_TRIPLE))) $(Q)$(call INSTALL_LIB,$(HL),$(PHL),$(LIBRUSTI_GLOB_$(CFG_BUILD_TRIPLE))) @@ -141,8 +141,8 @@ uninstall: $(Q)rm -f $(PHL)/$(CFG_RUSTLLVM_$(CFG_BUILD_TRIPLE)) $(Q)rm -f $(PHL)/$(CFG_RUNTIME_$(CFG_BUILD_TRIPLE)) $(Q)for i in \ - $(call HOST_LIB_FROM_HL_GLOB,$(CORELIB_GLOB_$(CFG_BUILD_TRIPLE))) \ $(call HOST_LIB_FROM_HL_GLOB,$(STDLIB_GLOB_$(CFG_BUILD_TRIPLE))) \ + $(call HOST_LIB_FROM_HL_GLOB,$(EXTRALIB_GLOB_$(CFG_BUILD_TRIPLE))) \ $(call HOST_LIB_FROM_HL_GLOB,$(LIBRUSTC_GLOB_$(CFG_BUILD_TRIPLE))) \ $(call HOST_LIB_FROM_HL_GLOB,$(LIBSYNTAX_GLOB_$(CFG_BUILD_TRIPLE))) \ $(call HOST_LIB_FROM_HL_GLOB,$(LIBRUSTPKG_GLOB_$(CFG_BUILD_TRIPLE))) \ @@ -203,16 +203,16 @@ define INSTALL_RUNTIME_TARGET_N install-runtime-target-$(1)-host-$(2): $$(TSREQ$$(ISTAGE)_T_$(1)_H_$(2)) $$(SREQ$$(ISTAGE)_T_$(1)_H_$(2)) $(Q)$(call ADB_SHELL,mkdir,$(CFG_RUNTIME_PUSH_DIR)) $(Q)$(call ADB_PUSH,$$(TL$(1)$(2))/$$(CFG_RUNTIME_$(1)),$(CFG_RUNTIME_PUSH_DIR)) - $(Q)$(call ADB_PUSH,$$(TL$(1)$(2))/$$(CORELIB_GLOB_$(1)),$(CFG_RUNTIME_PUSH_DIR)) $(Q)$(call ADB_PUSH,$$(TL$(1)$(2))/$$(STDLIB_GLOB_$(1)),$(CFG_RUNTIME_PUSH_DIR)) + $(Q)$(call ADB_PUSH,$$(TL$(1)$(2))/$$(EXTRALIB_GLOB_$(1)),$(CFG_RUNTIME_PUSH_DIR)) endef define INSTALL_RUNTIME_TARGET_CLEANUP_N install-runtime-target-$(1)-cleanup: $(Q)$(call ADB,remount) $(Q)$(call ADB_SHELL,rm,$(CFG_RUNTIME_PUSH_DIR)/$(CFG_RUNTIME_$(1))) - $(Q)$(call ADB_SHELL,rm,$(CFG_RUNTIME_PUSH_DIR)/$(CORELIB_GLOB_$(1))) $(Q)$(call ADB_SHELL,rm,$(CFG_RUNTIME_PUSH_DIR)/$(STDLIB_GLOB_$(1))) + $(Q)$(call ADB_SHELL,rm,$(CFG_RUNTIME_PUSH_DIR)/$(EXTRALIB_GLOB_$(1))) endef $(eval $(call INSTALL_RUNTIME_TARGET_N,arm-linux-androideabi,$(CFG_BUILD_TRIPLE))) diff --git a/mk/pp.mk b/mk/pp.mk index c7f316bcfc72d..0a24d9e87979d 100644 --- a/mk/pp.mk +++ b/mk/pp.mk @@ -12,8 +12,8 @@ ifdef PPFILES PP_INPUTS_FILTERED := $(wildcard $(PPFILES)) else - PP_INPUTS = $(wildcard $(addprefix $(S)src/libcore/,*.rs */*.rs)) \ - $(wildcard $(addprefix $(S)src/libstd/,*.rs */*.rs)) \ + PP_INPUTS = $(wildcard $(addprefix $(S)src/libstd/,*.rs */*.rs)) \ + $(wildcard $(addprefix $(S)src/libextra/,*.rs */*.rs)) \ $(wildcard $(addprefix $(S)src/rustc/,*.rs */*.rs */*/*.rs)) \ $(wildcard $(S)src/test/*/*.rs \ $(S)src/test/*/*/*.rs) \ diff --git a/mk/stage0.mk b/mk/stage0.mk index ac1b3e86ac918..a1aaef4d554ad 100644 --- a/mk/stage0.mk +++ b/mk/stage0.mk @@ -25,11 +25,11 @@ $(HLIB0_H_$(CFG_BUILD_TRIPLE))/$(CFG_RUNTIME_$(CFG_BUILD_TRIPLE)): \ $(HBIN0_H_$(CFG_BUILD_TRIPLE))/rustc$(X_$(CFG_BUILD_TRIPLE)) $(Q)touch $@ -$(HLIB0_H_$(CFG_BUILD_TRIPLE))/$(CFG_CORELIB_$(CFG_BUILD_TRIPLE)): \ +$(HLIB0_H_$(CFG_BUILD_TRIPLE))/$(CFG_STDLIB_$(CFG_BUILD_TRIPLE)): \ $(HBIN0_H_$(CFG_BUILD_TRIPLE))/rustc$(X_$(CFG_BUILD_TRIPLE)) $(Q)touch $@ -$(HLIB0_H_$(CFG_BUILD_TRIPLE))/$(CFG_STDLIB_$(CFG_BUILD_TRIPLE)): \ +$(HLIB0_H_$(CFG_BUILD_TRIPLE))/$(CFG_EXTRALIB_$(CFG_BUILD_TRIPLE)): \ $(HBIN0_H_$(CFG_BUILD_TRIPLE))/rustc$(X_$(CFG_BUILD_TRIPLE)) $(Q)touch $@ @@ -58,16 +58,16 @@ $$(HLIB0_H_$(1))/$(CFG_RUNTIME_$(1)): \ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ -$$(HLIB0_H_$(1))/$(CFG_CORELIB_$(1)): \ - $$(TLIB$(2)_T_$(1)_H_$(3))/$(CFG_CORELIB_$(1)) - @$$(call E, cp: $$@) - $$(Q)cp $$(TLIB$(2)_T_$(1)_H_$(3))/$(CORELIB_GLOB_$(1)) $$@ - $$(HLIB0_H_$(1))/$(CFG_STDLIB_$(1)): \ $$(TLIB$(2)_T_$(1)_H_$(3))/$(CFG_STDLIB_$(1)) @$$(call E, cp: $$@) $$(Q)cp $$(TLIB$(2)_T_$(1)_H_$(3))/$(STDLIB_GLOB_$(1)) $$@ +$$(HLIB0_H_$(1))/$(CFG_EXTRALIB_$(1)): \ + $$(TLIB$(2)_T_$(1)_H_$(3))/$(CFG_EXTRALIB_$(1)) + @$$(call E, cp: $$@) + $$(Q)cp $$(TLIB$(2)_T_$(1)_H_$(3))/$(EXTRALIB_GLOB_$(1)) $$@ + $$(HLIB0_H_$(1))/$(CFG_LIBRUSTC_$(1)): \ $$(TLIB$(2)_T_$(1)_H_$(3))/$(CFG_LIBRUSTC_$(1)) @$$(call E, cp: $$@) diff --git a/mk/target.mk b/mk/target.mk index 3cecc3940e62f..9b4153d7ed50d 100644 --- a/mk/target.mk +++ b/mk/target.mk @@ -29,16 +29,16 @@ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_RUNTIME_$(2)): \ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ -$$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_CORELIB_$(2)): \ - $$(CORELIB_CRATE) $$(CORELIB_INPUTS) \ +$$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)): \ + $$(STDLIB_CRATE) $$(STDLIB_INPUTS) \ $$(TSREQ$(1)_T_$(2)_H_$(3)) \ | $$(TLIB$(1)_T_$(2)_H_$(3))/ @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(2)_H_$(3)) -o $$@ $$< && touch $$@ -$$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)): \ - $$(STDLIB_CRATE) $$(STDLIB_INPUTS) \ - $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_CORELIB_$(2)) \ +$$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_EXTRALIB_$(2)): \ + $$(EXTRALIB_CRATE) $$(EXTRALIB_INPUTS) \ + $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)) \ $$(TSREQ$(1)_T_$(2)_H_$(3)) \ | $$(TLIB$(1)_T_$(2)_H_$(3))/ @$$(call E, compile_and_link: $$@) @@ -47,8 +47,8 @@ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_STDLIB_$(2)): \ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_LIBSYNTAX_$(3)): \ $$(LIBSYNTAX_CRATE) $$(LIBSYNTAX_INPUTS) \ $$(TSREQ$(1)_T_$(2)_H_$(3)) \ - $$(TCORELIB_DEFAULT$(1)_T_$(2)_H_$(3)) \ - $$(TSTDLIB_DEFAULT$(1)_T_$(2)_H_$(3)) \ + $$(TSTDLIB_DEFAULT$(1)_T_$(2)_H_$(3)) \ + $$(TEXTRALIB_DEFAULT$(1)_T_$(2)_H_$(3)) \ | $$(TLIB$(1)_T_$(2)_H_$(3))/ @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(2)_H_$(3)) $(BORROWCK) -o $$@ $$< && touch $$@ diff --git a/mk/tests.mk b/mk/tests.mk index 5cdd900d65f9c..6e84aa49a88ed 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -14,7 +14,7 @@ ###################################################################### # The names of crates that must be tested -TEST_TARGET_CRATES = core std +TEST_TARGET_CRATES = std extra TEST_HOST_CRATES = syntax rustc rustdoc rusti rust rustpkg TEST_CRATES = $(TEST_TARGET_CRATES) $(TEST_HOST_CRATES) @@ -148,7 +148,7 @@ check-test: cleantestlibs cleantmptestlogs all check-stage2-rfail $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log check-lite: cleantestlibs cleantmptestlogs \ - check-stage2-core check-stage2-std check-stage2-rpass \ + check-stage2-std check-stage2-extra check-stage2-rpass \ check-stage2-rfail check-stage2-cfail $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log @@ -281,22 +281,22 @@ $(foreach host,$(CFG_HOST_TRIPLES), \ define TEST_RUNNER -# If NO_REBUILD is set then break the dependencies on std so we can -# test crates without rebuilding core and std first +# If NO_REBUILD is set then break the dependencies on extra so we can +# test crates without rebuilding std and extra first ifeq ($(NO_REBUILD),) STDTESTDEP_$(1)_$(2)_$(3) = $$(TLIB$(1)_T_$(2)_H_$(3))/$$(CFG_STDLIB_$(2)) else STDTESTDEP_$(1)_$(2)_$(3) = endif -$(3)/stage$(1)/test/coretest-$(2)$$(X_$(2)): \ - $$(CORELIB_CRATE) $$(CORELIB_INPUTS) \ +$(3)/stage$(1)/test/stdtest-$(2)$$(X_$(2)): \ + $$(STDLIB_CRATE) $$(STDLIB_INPUTS) \ $$(STDTESTDEP_$(1)_$(2)_$(3)) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(2)_H_$(3)) -o $$@ $$< --test -$(3)/stage$(1)/test/stdtest-$(2)$$(X_$(2)): \ - $$(STDLIB_CRATE) $$(STDLIB_INPUTS) \ +$(3)/stage$(1)/test/extratest-$(2)$$(X_$(2)): \ + $$(EXTRALIB_CRATE) $$(EXTRALIB_INPUTS) \ $$(STDTESTDEP_$(1)_$(2)_$(3)) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(2)_H_$(3)) -o $$@ $$< --test diff --git a/mk/tools.mk b/mk/tools.mk index 2900aa711dc6d..018da2a640169 100644 --- a/mk/tools.mk +++ b/mk/tools.mk @@ -41,8 +41,8 @@ define TOOLS_STAGE_N_TARGET $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBFUZZER_$(4)): \ $$(FUZZER_LIB) $$(FUZZER_INPUTS) \ $$(TSREQ$(1)_T_$(4)_H_$(3)) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_CORELIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_EXTRALIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTC_$(4)) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(4)_H_$(3)) -o $$@ $$< && touch $$@ @@ -56,16 +56,16 @@ $$(TBIN$(1)_T_$(4)_H_$(3))/fuzzer$$(X_$(4)): \ $$(TBIN$(1)_T_$(4)_H_$(3))/compiletest$$(X_$(4)): \ $$(COMPILETEST_CRATE) $$(COMPILETEST_INPUTS) \ $$(TSREQ$(1)_T_$(4)_H_$(3)) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_CORELIB_$(4)) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_EXTRALIB_$(4)) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(4)_H_$(3)) -o $$@ $$< $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTPKG_$(4)): \ $$(RUSTPKG_LIB) $$(RUSTPKG_INPUTS) \ $$(TSREQ$(1)_T_$(4)_H_$(3)) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_CORELIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_EXTRALIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTC_$(4)) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(4)_H_$(3)) -o $$@ $$< && touch $$@ @@ -79,8 +79,8 @@ $$(TBIN$(1)_T_$(4)_H_$(3))/rustpkg$$(X_$(4)): \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTDOC_$(4)): \ $$(RUSTDOC_LIB) $$(RUSTDOC_INPUTS) \ $$(TSREQ$(1)_T_$(4)_H_$(3)) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_CORELIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_EXTRALIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTC_$(4)) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(4)_H_$(3)) -o $$@ $$< && touch $$@ @@ -94,8 +94,8 @@ $$(TBIN$(1)_T_$(4)_H_$(3))/rustdoc$$(X_$(4)): \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTI_$(4)): \ $$(RUSTI_LIB) $$(RUSTI_INPUTS) \ $$(TSREQ$(1)_T_$(4)_H_$(3)) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_CORELIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_EXTRALIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTC_$(4)) @$$(call E, compile_and_link: $$@) $$(STAGE$(1)_T_$(4)_H_$(3)) -o $$@ $$< && touch $$@ @@ -109,8 +109,8 @@ $$(TBIN$(1)_T_$(4)_H_$(3))/rusti$$(X_$(4)): \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUST_$(4)): \ $$(RUST_LIB) $$(RUST_INPUTS) \ $$(TSREQ$(1)_T_$(4)_H_$(3)) \ - $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_CORELIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_STDLIB_$(4)) \ + $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_EXTRALIB_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTPKG_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTI_$(4)) \ $$(TLIB$(1)_T_$(4)_H_$(3))/$(CFG_LIBRUSTDOC_$(4)) \ diff --git a/src/libcore/comm.rs b/src/libcore/comm.rs deleted file mode 100644 index 59eb915c239fe..0000000000000 --- a/src/libcore/comm.rs +++ /dev/null @@ -1,810 +0,0 @@ -// Copyright 2012 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. - -/*! -Message passing -*/ - -use cast::{transmute, transmute_mut}; -use container::Container; -use either::{Either, Left, Right}; -use kinds::Owned; -use option::{Option, Some, None}; -use uint; -use vec; -use vec::OwnedVector; -use util::replace; -use unstable::sync::{Exclusive, exclusive}; -use rtcomm = rt::comm; -use rt; - -use pipes::{wait_many, PacketHeader}; - -// FIXME #5160: Making this public exposes some plumbing from -// pipes. Needs some refactoring -pub use pipes::Selectable; - -/// A trait for things that can send multiple messages. -pub trait GenericChan { - /// Sends a message. - fn send(&self, x: T); -} - -/// Things that can send multiple messages and can detect when the receiver -/// is closed -pub trait GenericSmartChan { - /// Sends a message, or report if the receiver has closed the connection. - fn try_send(&self, x: T) -> bool; -} - -/// A trait for things that can receive multiple messages. -pub trait GenericPort { - /// Receives a message, or fails if the connection closes. - fn recv(&self) -> T; - - /** Receives a message, or returns `none` if - the connection is closed or closes. - */ - fn try_recv(&self) -> Option; -} - -/// Ports that can `peek` -pub trait Peekable { - /// Returns true if a message is available - fn peek(&self) -> bool; -} - -/// An endpoint that can send many messages. -pub struct Chan { - inner: Either, rtcomm::Chan> -} - -/// An endpoint that can receive many messages. -pub struct Port { - inner: Either, rtcomm::Port> -} - -/** Creates a `(Port, Chan)` pair. - -These allow sending or receiving an unlimited number of messages. - -*/ -pub fn stream() -> (Port, Chan) { - let (port, chan) = match rt::context() { - rt::OldTaskContext => match pipesy::stream() { - (p, c) => (Left(p), Left(c)) - }, - _ => match rtcomm::stream() { - (p, c) => (Right(p), Right(c)) - } - }; - let port = Port { inner: port }; - let chan = Chan { inner: chan }; - return (port, chan); -} - -impl GenericChan for Chan { - fn send(&self, x: T) { - match self.inner { - Left(ref chan) => chan.send(x), - Right(ref chan) => chan.send(x) - } - } -} - -impl GenericSmartChan for Chan { - fn try_send(&self, x: T) -> bool { - match self.inner { - Left(ref chan) => chan.try_send(x), - Right(ref chan) => chan.try_send(x) - } - } -} - -impl GenericPort for Port { - fn recv(&self) -> T { - match self.inner { - Left(ref port) => port.recv(), - Right(ref port) => port.recv() - } - } - - fn try_recv(&self) -> Option { - match self.inner { - Left(ref port) => port.try_recv(), - Right(ref port) => port.try_recv() - } - } -} - -impl Peekable for Port { - fn peek(&self) -> bool { - match self.inner { - Left(ref port) => port.peek(), - Right(ref port) => port.peek() - } - } -} - -impl Selectable for Port { - fn header(&mut self) -> *mut PacketHeader { - match self.inner { - Left(ref mut port) => port.header(), - Right(_) => fail!("can't select on newsched ports") - } - } -} - -/// Treat many ports as one. -#[unsafe_mut_field(ports)] -pub struct PortSet { - ports: ~[pipesy::Port], -} - -pub impl PortSet { - fn new() -> PortSet { - PortSet { - ports: ~[] - } - } - - fn add(&self, port: Port) { - let Port { inner } = port; - let port = match inner { - Left(p) => p, - Right(_) => fail!("PortSet not implemented") - }; - unsafe { - let self_ports = transmute_mut(&self.ports); - self_ports.push(port) - } - } - - fn chan(&self) -> Chan { - let (po, ch) = stream(); - self.add(po); - ch - } -} - -impl GenericPort for PortSet { - fn try_recv(&self) -> Option { - unsafe { - let self_ports = transmute_mut(&self.ports); - let mut result = None; - // we have to swap the ports array so we aren't borrowing - // aliasable mutable memory. - let mut ports = replace(self_ports, ~[]); - while result.is_none() && ports.len() > 0 { - let i = wait_many(ports); - match ports[i].try_recv() { - Some(m) => { - result = Some(m); - } - None => { - // Remove this port. - let _ = ports.swap_remove(i); - } - } - } - *self_ports = ports; - result - } - } - fn recv(&self) -> T { - self.try_recv().expect("port_set: endpoints closed") - } -} - -impl Peekable for PortSet { - fn peek(&self) -> bool { - // It'd be nice to use self.port.each, but that version isn't - // pure. - for uint::range(0, vec::uniq_len(&const self.ports)) |i| { - let port: &pipesy::Port = &self.ports[i]; - if port.peek() { - return true; - } - } - false - } -} - -/// A channel that can be shared between many senders. -pub struct SharedChan { - ch: Exclusive> -} - -impl SharedChan { - /// Converts a `chan` into a `shared_chan`. - pub fn new(c: Chan) -> SharedChan { - let Chan { inner } = c; - let c = match inner { - Left(c) => c, - Right(_) => fail!("SharedChan not implemented") - }; - SharedChan { ch: exclusive(c) } - } -} - -impl GenericChan for SharedChan { - fn send(&self, x: T) { - let mut xx = Some(x); - do self.ch.with_imm |chan| { - let x = replace(&mut xx, None); - chan.send(x.unwrap()) - } - } -} - -impl GenericSmartChan for SharedChan { - fn try_send(&self, x: T) -> bool { - let mut xx = Some(x); - do self.ch.with_imm |chan| { - let x = replace(&mut xx, None); - chan.try_send(x.unwrap()) - } - } -} - -impl ::clone::Clone for SharedChan { - fn clone(&self) -> SharedChan { - SharedChan { ch: self.ch.clone() } - } -} - -pub struct PortOne { - inner: Either, rtcomm::PortOne> -} - -pub struct ChanOne { - inner: Either, rtcomm::ChanOne> -} - -pub fn oneshot() -> (PortOne, ChanOne) { - let (port, chan) = match rt::context() { - rt::OldTaskContext => match pipesy::oneshot() { - (p, c) => (Left(p), Left(c)), - }, - _ => match rtcomm::oneshot() { - (p, c) => (Right(p), Right(c)) - } - }; - let port = PortOne { inner: port }; - let chan = ChanOne { inner: chan }; - return (port, chan); -} - -impl PortOne { - pub fn recv(self) -> T { - let PortOne { inner } = self; - match inner { - Left(p) => p.recv(), - Right(p) => p.recv() - } - } - - pub fn try_recv(self) -> Option { - let PortOne { inner } = self; - match inner { - Left(p) => p.try_recv(), - Right(p) => p.try_recv() - } - } -} - -impl ChanOne { - pub fn send(self, data: T) { - let ChanOne { inner } = self; - match inner { - Left(p) => p.send(data), - Right(p) => p.send(data) - } - } - - pub fn try_send(self, data: T) -> bool { - let ChanOne { inner } = self; - match inner { - Left(p) => p.try_send(data), - Right(p) => p.try_send(data) - } - } -} - -pub fn recv_one(port: PortOne) -> T { - let PortOne { inner } = port; - match inner { - Left(p) => pipesy::recv_one(p), - Right(p) => p.recv() - } -} - -pub fn try_recv_one(port: PortOne) -> Option { - let PortOne { inner } = port; - match inner { - Left(p) => pipesy::try_recv_one(p), - Right(p) => p.try_recv() - } -} - -pub fn send_one(chan: ChanOne, data: T) { - let ChanOne { inner } = chan; - match inner { - Left(c) => pipesy::send_one(c, data), - Right(c) => c.send(data) - } -} - -pub fn try_send_one(chan: ChanOne, data: T) -> bool { - let ChanOne { inner } = chan; - match inner { - Left(c) => pipesy::try_send_one(c, data), - Right(c) => c.try_send(data) - } -} - -mod pipesy { - - use kinds::Owned; - use option::{Option, Some, None}; - use pipes::{recv, try_recv, peek, PacketHeader}; - use super::{GenericChan, GenericSmartChan, GenericPort, Peekable, Selectable}; - use cast::transmute_mut; - use util::replace; - - /*proto! oneshot ( - Oneshot:send { - send(T) -> ! - } - )*/ - - #[allow(non_camel_case_types)] - pub mod oneshot { - priv use core::kinds::Owned; - use ptr::to_mut_unsafe_ptr; - - pub fn init() -> (client::Oneshot, server::Oneshot) { - pub use core::pipes::HasBuffer; - - let buffer = ~::core::pipes::Buffer { - header: ::core::pipes::BufferHeader(), - data: __Buffer { - Oneshot: ::core::pipes::mk_packet::>() - }, - }; - do ::core::pipes::entangle_buffer(buffer) |buffer, data| { - data.Oneshot.set_buffer(buffer); - to_mut_unsafe_ptr(&mut data.Oneshot) - } - } - #[allow(non_camel_case_types)] - pub enum Oneshot { pub send(T), } - #[allow(non_camel_case_types)] - pub struct __Buffer { - Oneshot: ::core::pipes::Packet>, - } - - #[allow(non_camel_case_types)] - pub mod client { - - priv use core::kinds::Owned; - - #[allow(non_camel_case_types)] - pub fn try_send(pipe: Oneshot, x_0: T) -> - ::core::option::Option<()> { - { - use super::send; - let message = send(x_0); - if ::core::pipes::send(pipe, message) { - ::core::pipes::rt::make_some(()) - } else { ::core::pipes::rt::make_none() } - } - } - - #[allow(non_camel_case_types)] - pub fn send(pipe: Oneshot, x_0: T) { - { - use super::send; - let message = send(x_0); - ::core::pipes::send(pipe, message); - } - } - - #[allow(non_camel_case_types)] - pub type Oneshot = - ::core::pipes::SendPacketBuffered, - super::__Buffer>; - } - - #[allow(non_camel_case_types)] - pub mod server { - #[allow(non_camel_case_types)] - pub type Oneshot = - ::core::pipes::RecvPacketBuffered, - super::__Buffer>; - } - } - - /// The send end of a oneshot pipe. - pub struct ChanOne { - contents: oneshot::client::Oneshot - } - - impl ChanOne { - pub fn new(contents: oneshot::client::Oneshot) -> ChanOne { - ChanOne { - contents: contents - } - } - } - - /// The receive end of a oneshot pipe. - pub struct PortOne { - contents: oneshot::server::Oneshot - } - - impl PortOne { - pub fn new(contents: oneshot::server::Oneshot) -> PortOne { - PortOne { - contents: contents - } - } - } - - /// Initialiase a (send-endpoint, recv-endpoint) oneshot pipe pair. - pub fn oneshot() -> (PortOne, ChanOne) { - let (chan, port) = oneshot::init(); - (PortOne::new(port), ChanOne::new(chan)) - } - - pub impl PortOne { - fn recv(self) -> T { recv_one(self) } - fn try_recv(self) -> Option { try_recv_one(self) } - fn unwrap(self) -> oneshot::server::Oneshot { - match self { - PortOne { contents: s } => s - } - } - } - - pub impl ChanOne { - fn send(self, data: T) { send_one(self, data) } - fn try_send(self, data: T) -> bool { try_send_one(self, data) } - fn unwrap(self) -> oneshot::client::Oneshot { - match self { - ChanOne { contents: s } => s - } - } - } - - /** - * Receive a message from a oneshot pipe, failing if the connection was - * closed. - */ - pub fn recv_one(port: PortOne) -> T { - match port { - PortOne { contents: port } => { - let oneshot::send(message) = recv(port); - message - } - } - } - - /// Receive a message from a oneshot pipe unless the connection was closed. - pub fn try_recv_one (port: PortOne) -> Option { - match port { - PortOne { contents: port } => { - let message = try_recv(port); - - if message.is_none() { - None - } else { - let oneshot::send(message) = message.unwrap(); - Some(message) - } - } - } - } - - /// Send a message on a oneshot pipe, failing if the connection was closed. - pub fn send_one(chan: ChanOne, data: T) { - match chan { - ChanOne { contents: chan } => oneshot::client::send(chan, data), - } - } - - /** - * Send a message on a oneshot pipe, or return false if the connection was - * closed. - */ - pub fn try_send_one(chan: ChanOne, data: T) -> bool { - match chan { - ChanOne { contents: chan } => { - oneshot::client::try_send(chan, data).is_some() - } - } - } - - // Streams - Make pipes a little easier in general. - - /*proto! streamp ( - Open:send { - data(T) -> Open - } - )*/ - - #[allow(non_camel_case_types)] - pub mod streamp { - priv use core::kinds::Owned; - - pub fn init() -> (client::Open, server::Open) { - pub use core::pipes::HasBuffer; - ::core::pipes::entangle() - } - - #[allow(non_camel_case_types)] - pub enum Open { pub data(T, server::Open), } - - #[allow(non_camel_case_types)] - pub mod client { - priv use core::kinds::Owned; - - #[allow(non_camel_case_types)] - pub fn try_data(pipe: Open, x_0: T) -> - ::core::option::Option> { - { - use super::data; - let (c, s) = ::core::pipes::entangle(); - let message = data(x_0, s); - if ::core::pipes::send(pipe, message) { - ::core::pipes::rt::make_some(c) - } else { ::core::pipes::rt::make_none() } - } - } - - #[allow(non_camel_case_types)] - pub fn data(pipe: Open, x_0: T) -> Open { - { - use super::data; - let (c, s) = ::core::pipes::entangle(); - let message = data(x_0, s); - ::core::pipes::send(pipe, message); - c - } - } - - #[allow(non_camel_case_types)] - pub type Open = ::core::pipes::SendPacket>; - } - - #[allow(non_camel_case_types)] - pub mod server { - #[allow(non_camel_case_types)] - pub type Open = ::core::pipes::RecvPacket>; - } - } - - /// An endpoint that can send many messages. - #[unsafe_mut_field(endp)] - pub struct Chan { - endp: Option> - } - - /// An endpoint that can receive many messages. - #[unsafe_mut_field(endp)] - pub struct Port { - endp: Option>, - } - - /** Creates a `(Port, Chan)` pair. - - These allow sending or receiving an unlimited number of messages. - - */ - pub fn stream() -> (Port, Chan) { - let (c, s) = streamp::init(); - - (Port { - endp: Some(s) - }, Chan { - endp: Some(c) - }) - } - - impl GenericChan for Chan { - #[inline(always)] - fn send(&self, x: T) { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - *self_endp = Some(streamp::client::data(endp.unwrap(), x)) - } - } - } - - impl GenericSmartChan for Chan { - #[inline(always)] - fn try_send(&self, x: T) -> bool { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - match streamp::client::try_data(endp.unwrap(), x) { - Some(next) => { - *self_endp = Some(next); - true - } - None => false - } - } - } - } - - impl GenericPort for Port { - #[inline(always)] - fn recv(&self) -> T { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - let streamp::data(x, endp) = recv(endp.unwrap()); - *self_endp = Some(endp); - x - } - } - - #[inline(always)] - fn try_recv(&self) -> Option { - unsafe { - let self_endp = transmute_mut(&self.endp); - let endp = replace(self_endp, None); - match try_recv(endp.unwrap()) { - Some(streamp::data(x, endp)) => { - *self_endp = Some(endp); - Some(x) - } - None => None - } - } - } - } - - impl Peekable for Port { - #[inline(always)] - fn peek(&self) -> bool { - unsafe { - let self_endp = transmute_mut(&self.endp); - let mut endp = replace(self_endp, None); - let peek = match endp { - Some(ref mut endp) => peek(endp), - None => fail!("peeking empty stream") - }; - *self_endp = endp; - peek - } - } - } - - impl Selectable for Port { - fn header(&mut self) -> *mut PacketHeader { - match self.endp { - Some(ref mut endp) => endp.header(), - None => fail!("peeking empty stream") - } - } -} - -} - -/// Returns the index of an endpoint that is ready to receive. -pub fn selecti(endpoints: &mut [T]) -> uint { - wait_many(endpoints) -} - -/// Returns 0 or 1 depending on which endpoint is ready to receive -pub fn select2i(a: &mut A, b: &mut B) - -> Either<(), ()> { - let mut endpoints = [ a.header(), b.header() ]; - match wait_many(endpoints) { - 0 => Left(()), - 1 => Right(()), - _ => fail!("wait returned unexpected index"), - } -} - -/// Receive a message from one of two endpoints. -pub trait Select2 { - /// Receive a message or return `None` if a connection closes. - fn try_select(&mut self) -> Either, Option>; - /// Receive a message or fail if a connection closes. - fn select(&mut self) -> Either; -} - -impl, - Right:Selectable + GenericPort> - Select2 - for (Left, Right) { - fn select(&mut self) -> Either { - // XXX: Bad borrow check workaround. - unsafe { - let this: &(Left, Right) = transmute(self); - match *this { - (ref lp, ref rp) => { - let lp: &mut Left = transmute(lp); - let rp: &mut Right = transmute(rp); - match select2i(lp, rp) { - Left(()) => Left(lp.recv()), - Right(()) => Right(rp.recv()), - } - } - } - } - } - - fn try_select(&mut self) -> Either, Option> { - // XXX: Bad borrow check workaround. - unsafe { - let this: &(Left, Right) = transmute(self); - match *this { - (ref lp, ref rp) => { - let lp: &mut Left = transmute(lp); - let rp: &mut Right = transmute(rp); - match select2i(lp, rp) { - Left(()) => Left (lp.try_recv()), - Right(()) => Right(rp.try_recv()), - } - } - } - } - } -} - -#[cfg(test)] -mod test { - use either::Right; - use super::{Chan, Port, oneshot, stream}; - - #[test] - fn test_select2() { - let (p1, c1) = stream(); - let (p2, c2) = stream(); - - c1.send(~"abc"); - - let mut tuple = (p1, p2); - match tuple.select() { - Right(_) => fail!(), - _ => (), - } - - c2.send(123); - } - - #[test] - fn test_oneshot() { - let (p, c) = oneshot(); - - c.send(()); - - p.recv() - } - - #[test] - fn test_peek_terminated() { - let (port, chan): (Port, Chan) = stream(); - - { - // Destroy the channel - let _chan = chan; - } - - assert!(!port.peek()); - } -} diff --git a/src/libcore/unicode.rs b/src/libcore/unicode.rs deleted file mode 100644 index d76da6fcc664f..0000000000000 --- a/src/libcore/unicode.rs +++ /dev/null @@ -1,2642 +0,0 @@ -// Copyright 2012-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. - -#[doc(hidden)]; // FIXME #3538 - -// The following code was generated by "src/etc/unicode.py" - -pub mod general_category { - - fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { - use cmp::{Equal, Less, Greater}; - use vec::bsearch; - use option::None; - (do bsearch(r) |&(lo,hi)| { cond!( - (lo <= c && c <= hi) { Equal } - (hi < c) { Less } - _ { Greater } - )}) != None - } - - - static Cc_table : &'static [(char,char)] = &[ - ('\x00', '\x1f'), ('\x7f', '\x9f') - ]; - - pub fn Cc(c: char) -> bool { - bsearch_range_table(c, Cc_table) - } - - static Cf_table : &'static [(char,char)] = &[ - ('\xad', '\xad'), ('\u0600', '\u0604'), - ('\u06dd', '\u06dd'), ('\u070f', '\u070f'), - ('\u200b', '\u200f'), ('\u202a', '\u202e'), - ('\u2060', '\u206f'), ('\ufeff', '\ufeff'), - ('\ufff9', '\ufffb'), ('\U000110bd', '\U000110bd'), - ('\U0001d173', '\U0001d17a'), ('\U000e0001', '\U000e007f') - ]; - - pub fn Cf(c: char) -> bool { - bsearch_range_table(c, Cf_table) - } - - static Co_table : &'static [(char,char)] = &[ - ('\ue000', '\uf8ff') - ]; - - pub fn Co(c: char) -> bool { - bsearch_range_table(c, Co_table) - } - - static Cs_table : &'static [(char,char)] = &[ - ('\ud800', '\udfff') - ]; - - pub fn Cs(c: char) -> bool { - bsearch_range_table(c, Cs_table) - } - - static Ll_table : &'static [(char,char)] = &[ - ('\x61', '\x7a'), ('\xb5', '\xb5'), - ('\xdf', '\xf6'), ('\xf8', '\xff'), - ('\u0101', '\u0101'), ('\u0103', '\u0103'), - ('\u0105', '\u0105'), ('\u0107', '\u0107'), - ('\u0109', '\u0109'), ('\u010b', '\u010b'), - ('\u010d', '\u010d'), ('\u010f', '\u010f'), - ('\u0111', '\u0111'), ('\u0113', '\u0113'), - ('\u0115', '\u0115'), ('\u0117', '\u0117'), - ('\u0119', '\u0119'), ('\u011b', '\u011b'), - ('\u011d', '\u011d'), ('\u011f', '\u011f'), - ('\u0121', '\u0121'), ('\u0123', '\u0123'), - ('\u0125', '\u0125'), ('\u0127', '\u0127'), - ('\u0129', '\u0129'), ('\u012b', '\u012b'), - ('\u012d', '\u012d'), ('\u012f', '\u012f'), - ('\u0131', '\u0131'), ('\u0133', '\u0133'), - ('\u0135', '\u0135'), ('\u0137', '\u0138'), - ('\u013a', '\u013a'), ('\u013c', '\u013c'), - ('\u013e', '\u013e'), ('\u0140', '\u0140'), - ('\u0142', '\u0142'), ('\u0144', '\u0144'), - ('\u0146', '\u0146'), ('\u0148', '\u0149'), - ('\u014b', '\u014b'), ('\u014d', '\u014d'), - ('\u014f', '\u014f'), ('\u0151', '\u0151'), - ('\u0153', '\u0153'), ('\u0155', '\u0155'), - ('\u0157', '\u0157'), ('\u0159', '\u0159'), - ('\u015b', '\u015b'), ('\u015d', '\u015d'), - ('\u015f', '\u015f'), ('\u0161', '\u0161'), - ('\u0163', '\u0163'), ('\u0165', '\u0165'), - ('\u0167', '\u0167'), ('\u0169', '\u0169'), - ('\u016b', '\u016b'), ('\u016d', '\u016d'), - ('\u016f', '\u016f'), ('\u0171', '\u0171'), - ('\u0173', '\u0173'), ('\u0175', '\u0175'), - ('\u0177', '\u0177'), ('\u017a', '\u017a'), - ('\u017c', '\u017c'), ('\u017e', '\u0180'), - ('\u0183', '\u0183'), ('\u0185', '\u0185'), - ('\u0188', '\u0188'), ('\u018c', '\u018d'), - ('\u0192', '\u0192'), ('\u0195', '\u0195'), - ('\u0199', '\u019b'), ('\u019e', '\u019e'), - ('\u01a1', '\u01a1'), ('\u01a3', '\u01a3'), - ('\u01a5', '\u01a5'), ('\u01a8', '\u01a8'), - ('\u01aa', '\u01ab'), ('\u01ad', '\u01ad'), - ('\u01b0', '\u01b0'), ('\u01b4', '\u01b4'), - ('\u01b6', '\u01b6'), ('\u01b9', '\u01ba'), - ('\u01bd', '\u01bf'), ('\u01c6', '\u01c6'), - ('\u01c9', '\u01c9'), ('\u01cc', '\u01cc'), - ('\u01ce', '\u01ce'), ('\u01d0', '\u01d0'), - ('\u01d2', '\u01d2'), ('\u01d4', '\u01d4'), - ('\u01d6', '\u01d6'), ('\u01d8', '\u01d8'), - ('\u01da', '\u01da'), ('\u01dc', '\u01dd'), - ('\u01df', '\u01df'), ('\u01e1', '\u01e1'), - ('\u01e3', '\u01e3'), ('\u01e5', '\u01e5'), - ('\u01e7', '\u01e7'), ('\u01e9', '\u01e9'), - ('\u01eb', '\u01eb'), ('\u01ed', '\u01ed'), - ('\u01ef', '\u01f0'), ('\u01f3', '\u01f3'), - ('\u01f5', '\u01f5'), ('\u01f9', '\u01f9'), - ('\u01fb', '\u01fb'), ('\u01fd', '\u01fd'), - ('\u01ff', '\u01ff'), ('\u0201', '\u0201'), - ('\u0203', '\u0203'), ('\u0205', '\u0205'), - ('\u0207', '\u0207'), ('\u0209', '\u0209'), - ('\u020b', '\u020b'), ('\u020d', '\u020d'), - ('\u020f', '\u020f'), ('\u0211', '\u0211'), - ('\u0213', '\u0213'), ('\u0215', '\u0215'), - ('\u0217', '\u0217'), ('\u0219', '\u0219'), - ('\u021b', '\u021b'), ('\u021d', '\u021d'), - ('\u021f', '\u021f'), ('\u0221', '\u0221'), - ('\u0223', '\u0223'), ('\u0225', '\u0225'), - ('\u0227', '\u0227'), ('\u0229', '\u0229'), - ('\u022b', '\u022b'), ('\u022d', '\u022d'), - ('\u022f', '\u022f'), ('\u0231', '\u0231'), - ('\u0233', '\u0239'), ('\u023c', '\u023c'), - ('\u023f', '\u0240'), ('\u0242', '\u0242'), - ('\u0247', '\u0247'), ('\u0249', '\u0249'), - ('\u024b', '\u024b'), ('\u024d', '\u024d'), - ('\u024f', '\u0293'), ('\u0295', '\u02af'), - ('\u0371', '\u0371'), ('\u0373', '\u0373'), - ('\u0377', '\u0377'), ('\u037b', '\u037d'), - ('\u0390', '\u0390'), ('\u03ac', '\u03ce'), - ('\u03d0', '\u03d1'), ('\u03d5', '\u03d7'), - ('\u03d9', '\u03d9'), ('\u03db', '\u03db'), - ('\u03dd', '\u03dd'), ('\u03df', '\u03df'), - ('\u03e1', '\u03e1'), ('\u03e3', '\u03e3'), - ('\u03e5', '\u03e5'), ('\u03e7', '\u03e7'), - ('\u03e9', '\u03e9'), ('\u03eb', '\u03eb'), - ('\u03ed', '\u03ed'), ('\u03ef', '\u03f3'), - ('\u03f5', '\u03f5'), ('\u03f8', '\u03f8'), - ('\u03fb', '\u03fc'), ('\u0430', '\u045f'), - ('\u0461', '\u0461'), ('\u0463', '\u0463'), - ('\u0465', '\u0465'), ('\u0467', '\u0467'), - ('\u0469', '\u0469'), ('\u046b', '\u046b'), - ('\u046d', '\u046d'), ('\u046f', '\u046f'), - ('\u0471', '\u0471'), ('\u0473', '\u0473'), - ('\u0475', '\u0475'), ('\u0477', '\u0477'), - ('\u0479', '\u0479'), ('\u047b', '\u047b'), - ('\u047d', '\u047d'), ('\u047f', '\u047f'), - ('\u0481', '\u0481'), ('\u048b', '\u048b'), - ('\u048d', '\u048d'), ('\u048f', '\u048f'), - ('\u0491', '\u0491'), ('\u0493', '\u0493'), - ('\u0495', '\u0495'), ('\u0497', '\u0497'), - ('\u0499', '\u0499'), ('\u049b', '\u049b'), - ('\u049d', '\u049d'), ('\u049f', '\u049f'), - ('\u04a1', '\u04a1'), ('\u04a3', '\u04a3'), - ('\u04a5', '\u04a5'), ('\u04a7', '\u04a7'), - ('\u04a9', '\u04a9'), ('\u04ab', '\u04ab'), - ('\u04ad', '\u04ad'), ('\u04af', '\u04af'), - ('\u04b1', '\u04b1'), ('\u04b3', '\u04b3'), - ('\u04b5', '\u04b5'), ('\u04b7', '\u04b7'), - ('\u04b9', '\u04b9'), ('\u04bb', '\u04bb'), - ('\u04bd', '\u04bd'), ('\u04bf', '\u04bf'), - ('\u04c2', '\u04c2'), ('\u04c4', '\u04c4'), - ('\u04c6', '\u04c6'), ('\u04c8', '\u04c8'), - ('\u04ca', '\u04ca'), ('\u04cc', '\u04cc'), - ('\u04ce', '\u04cf'), ('\u04d1', '\u04d1'), - ('\u04d3', '\u04d3'), ('\u04d5', '\u04d5'), - ('\u04d7', '\u04d7'), ('\u04d9', '\u04d9'), - ('\u04db', '\u04db'), ('\u04dd', '\u04dd'), - ('\u04df', '\u04df'), ('\u04e1', '\u04e1'), - ('\u04e3', '\u04e3'), ('\u04e5', '\u04e5'), - ('\u04e7', '\u04e7'), ('\u04e9', '\u04e9'), - ('\u04eb', '\u04eb'), ('\u04ed', '\u04ed'), - ('\u04ef', '\u04ef'), ('\u04f1', '\u04f1'), - ('\u04f3', '\u04f3'), ('\u04f5', '\u04f5'), - ('\u04f7', '\u04f7'), ('\u04f9', '\u04f9'), - ('\u04fb', '\u04fb'), ('\u04fd', '\u04fd'), - ('\u04ff', '\u04ff'), ('\u0501', '\u0501'), - ('\u0503', '\u0503'), ('\u0505', '\u0505'), - ('\u0507', '\u0507'), ('\u0509', '\u0509'), - ('\u050b', '\u050b'), ('\u050d', '\u050d'), - ('\u050f', '\u050f'), ('\u0511', '\u0511'), - ('\u0513', '\u0513'), ('\u0515', '\u0515'), - ('\u0517', '\u0517'), ('\u0519', '\u0519'), - ('\u051b', '\u051b'), ('\u051d', '\u051d'), - ('\u051f', '\u051f'), ('\u0521', '\u0521'), - ('\u0523', '\u0523'), ('\u0525', '\u0525'), - ('\u0527', '\u0527'), ('\u0561', '\u0587'), - ('\u1d00', '\u1d2b'), ('\u1d6b', '\u1d77'), - ('\u1d79', '\u1d9a'), ('\u1e01', '\u1e01'), - ('\u1e03', '\u1e03'), ('\u1e05', '\u1e05'), - ('\u1e07', '\u1e07'), ('\u1e09', '\u1e09'), - ('\u1e0b', '\u1e0b'), ('\u1e0d', '\u1e0d'), - ('\u1e0f', '\u1e0f'), ('\u1e11', '\u1e11'), - ('\u1e13', '\u1e13'), ('\u1e15', '\u1e15'), - ('\u1e17', '\u1e17'), ('\u1e19', '\u1e19'), - ('\u1e1b', '\u1e1b'), ('\u1e1d', '\u1e1d'), - ('\u1e1f', '\u1e1f'), ('\u1e21', '\u1e21'), - ('\u1e23', '\u1e23'), ('\u1e25', '\u1e25'), - ('\u1e27', '\u1e27'), ('\u1e29', '\u1e29'), - ('\u1e2b', '\u1e2b'), ('\u1e2d', '\u1e2d'), - ('\u1e2f', '\u1e2f'), ('\u1e31', '\u1e31'), - ('\u1e33', '\u1e33'), ('\u1e35', '\u1e35'), - ('\u1e37', '\u1e37'), ('\u1e39', '\u1e39'), - ('\u1e3b', '\u1e3b'), ('\u1e3d', '\u1e3d'), - ('\u1e3f', '\u1e3f'), ('\u1e41', '\u1e41'), - ('\u1e43', '\u1e43'), ('\u1e45', '\u1e45'), - ('\u1e47', '\u1e47'), ('\u1e49', '\u1e49'), - ('\u1e4b', '\u1e4b'), ('\u1e4d', '\u1e4d'), - ('\u1e4f', '\u1e4f'), ('\u1e51', '\u1e51'), - ('\u1e53', '\u1e53'), ('\u1e55', '\u1e55'), - ('\u1e57', '\u1e57'), ('\u1e59', '\u1e59'), - ('\u1e5b', '\u1e5b'), ('\u1e5d', '\u1e5d'), - ('\u1e5f', '\u1e5f'), ('\u1e61', '\u1e61'), - ('\u1e63', '\u1e63'), ('\u1e65', '\u1e65'), - ('\u1e67', '\u1e67'), ('\u1e69', '\u1e69'), - ('\u1e6b', '\u1e6b'), ('\u1e6d', '\u1e6d'), - ('\u1e6f', '\u1e6f'), ('\u1e71', '\u1e71'), - ('\u1e73', '\u1e73'), ('\u1e75', '\u1e75'), - ('\u1e77', '\u1e77'), ('\u1e79', '\u1e79'), - ('\u1e7b', '\u1e7b'), ('\u1e7d', '\u1e7d'), - ('\u1e7f', '\u1e7f'), ('\u1e81', '\u1e81'), - ('\u1e83', '\u1e83'), ('\u1e85', '\u1e85'), - ('\u1e87', '\u1e87'), ('\u1e89', '\u1e89'), - ('\u1e8b', '\u1e8b'), ('\u1e8d', '\u1e8d'), - ('\u1e8f', '\u1e8f'), ('\u1e91', '\u1e91'), - ('\u1e93', '\u1e93'), ('\u1e95', '\u1e9d'), - ('\u1e9f', '\u1e9f'), ('\u1ea1', '\u1ea1'), - ('\u1ea3', '\u1ea3'), ('\u1ea5', '\u1ea5'), - ('\u1ea7', '\u1ea7'), ('\u1ea9', '\u1ea9'), - ('\u1eab', '\u1eab'), ('\u1ead', '\u1ead'), - ('\u1eaf', '\u1eaf'), ('\u1eb1', '\u1eb1'), - ('\u1eb3', '\u1eb3'), ('\u1eb5', '\u1eb5'), - ('\u1eb7', '\u1eb7'), ('\u1eb9', '\u1eb9'), - ('\u1ebb', '\u1ebb'), ('\u1ebd', '\u1ebd'), - ('\u1ebf', '\u1ebf'), ('\u1ec1', '\u1ec1'), - ('\u1ec3', '\u1ec3'), ('\u1ec5', '\u1ec5'), - ('\u1ec7', '\u1ec7'), ('\u1ec9', '\u1ec9'), - ('\u1ecb', '\u1ecb'), ('\u1ecd', '\u1ecd'), - ('\u1ecf', '\u1ecf'), ('\u1ed1', '\u1ed1'), - ('\u1ed3', '\u1ed3'), ('\u1ed5', '\u1ed5'), - ('\u1ed7', '\u1ed7'), ('\u1ed9', '\u1ed9'), - ('\u1edb', '\u1edb'), ('\u1edd', '\u1edd'), - ('\u1edf', '\u1edf'), ('\u1ee1', '\u1ee1'), - ('\u1ee3', '\u1ee3'), ('\u1ee5', '\u1ee5'), - ('\u1ee7', '\u1ee7'), ('\u1ee9', '\u1ee9'), - ('\u1eeb', '\u1eeb'), ('\u1eed', '\u1eed'), - ('\u1eef', '\u1eef'), ('\u1ef1', '\u1ef1'), - ('\u1ef3', '\u1ef3'), ('\u1ef5', '\u1ef5'), - ('\u1ef7', '\u1ef7'), ('\u1ef9', '\u1ef9'), - ('\u1efb', '\u1efb'), ('\u1efd', '\u1efd'), - ('\u1eff', '\u1f07'), ('\u1f10', '\u1f15'), - ('\u1f20', '\u1f27'), ('\u1f30', '\u1f37'), - ('\u1f40', '\u1f45'), ('\u1f50', '\u1f57'), - ('\u1f60', '\u1f67'), ('\u1f70', '\u1f87'), - ('\u1f90', '\u1f97'), ('\u1fa0', '\u1fa7'), - ('\u1fb0', '\u1fb7'), ('\u1fbe', '\u1fbe'), - ('\u1fc2', '\u1fc7'), ('\u1fd0', '\u1fd7'), - ('\u1fe0', '\u1fe7'), ('\u1ff2', '\u1ff7'), - ('\u210a', '\u210a'), ('\u210e', '\u210f'), - ('\u2113', '\u2113'), ('\u212f', '\u212f'), - ('\u2134', '\u2134'), ('\u2139', '\u2139'), - ('\u213c', '\u213d'), ('\u2146', '\u2149'), - ('\u214e', '\u214e'), ('\u2184', '\u2184'), - ('\u2c30', '\u2c5e'), ('\u2c61', '\u2c61'), - ('\u2c65', '\u2c66'), ('\u2c68', '\u2c68'), - ('\u2c6a', '\u2c6a'), ('\u2c6c', '\u2c6c'), - ('\u2c71', '\u2c71'), ('\u2c73', '\u2c74'), - ('\u2c76', '\u2c7b'), ('\u2c81', '\u2c81'), - ('\u2c83', '\u2c83'), ('\u2c85', '\u2c85'), - ('\u2c87', '\u2c87'), ('\u2c89', '\u2c89'), - ('\u2c8b', '\u2c8b'), ('\u2c8d', '\u2c8d'), - ('\u2c8f', '\u2c8f'), ('\u2c91', '\u2c91'), - ('\u2c93', '\u2c93'), ('\u2c95', '\u2c95'), - ('\u2c97', '\u2c97'), ('\u2c99', '\u2c99'), - ('\u2c9b', '\u2c9b'), ('\u2c9d', '\u2c9d'), - ('\u2c9f', '\u2c9f'), ('\u2ca1', '\u2ca1'), - ('\u2ca3', '\u2ca3'), ('\u2ca5', '\u2ca5'), - ('\u2ca7', '\u2ca7'), ('\u2ca9', '\u2ca9'), - ('\u2cab', '\u2cab'), ('\u2cad', '\u2cad'), - ('\u2caf', '\u2caf'), ('\u2cb1', '\u2cb1'), - ('\u2cb3', '\u2cb3'), ('\u2cb5', '\u2cb5'), - ('\u2cb7', '\u2cb7'), ('\u2cb9', '\u2cb9'), - ('\u2cbb', '\u2cbb'), ('\u2cbd', '\u2cbd'), - ('\u2cbf', '\u2cbf'), ('\u2cc1', '\u2cc1'), - ('\u2cc3', '\u2cc3'), ('\u2cc5', '\u2cc5'), - ('\u2cc7', '\u2cc7'), ('\u2cc9', '\u2cc9'), - ('\u2ccb', '\u2ccb'), ('\u2ccd', '\u2ccd'), - ('\u2ccf', '\u2ccf'), ('\u2cd1', '\u2cd1'), - ('\u2cd3', '\u2cd3'), ('\u2cd5', '\u2cd5'), - ('\u2cd7', '\u2cd7'), ('\u2cd9', '\u2cd9'), - ('\u2cdb', '\u2cdb'), ('\u2cdd', '\u2cdd'), - ('\u2cdf', '\u2cdf'), ('\u2ce1', '\u2ce1'), - ('\u2ce3', '\u2ce4'), ('\u2cec', '\u2cec'), - ('\u2cee', '\u2cee'), ('\u2cf3', '\u2cf3'), - ('\u2d00', '\u2d2d'), ('\ua641', '\ua641'), - ('\ua643', '\ua643'), ('\ua645', '\ua645'), - ('\ua647', '\ua647'), ('\ua649', '\ua649'), - ('\ua64b', '\ua64b'), ('\ua64d', '\ua64d'), - ('\ua64f', '\ua64f'), ('\ua651', '\ua651'), - ('\ua653', '\ua653'), ('\ua655', '\ua655'), - ('\ua657', '\ua657'), ('\ua659', '\ua659'), - ('\ua65b', '\ua65b'), ('\ua65d', '\ua65d'), - ('\ua65f', '\ua65f'), ('\ua661', '\ua661'), - ('\ua663', '\ua663'), ('\ua665', '\ua665'), - ('\ua667', '\ua667'), ('\ua669', '\ua669'), - ('\ua66b', '\ua66b'), ('\ua66d', '\ua66d'), - ('\ua681', '\ua681'), ('\ua683', '\ua683'), - ('\ua685', '\ua685'), ('\ua687', '\ua687'), - ('\ua689', '\ua689'), ('\ua68b', '\ua68b'), - ('\ua68d', '\ua68d'), ('\ua68f', '\ua68f'), - ('\ua691', '\ua691'), ('\ua693', '\ua693'), - ('\ua695', '\ua695'), ('\ua697', '\ua697'), - ('\ua723', '\ua723'), ('\ua725', '\ua725'), - ('\ua727', '\ua727'), ('\ua729', '\ua729'), - ('\ua72b', '\ua72b'), ('\ua72d', '\ua72d'), - ('\ua72f', '\ua731'), ('\ua733', '\ua733'), - ('\ua735', '\ua735'), ('\ua737', '\ua737'), - ('\ua739', '\ua739'), ('\ua73b', '\ua73b'), - ('\ua73d', '\ua73d'), ('\ua73f', '\ua73f'), - ('\ua741', '\ua741'), ('\ua743', '\ua743'), - ('\ua745', '\ua745'), ('\ua747', '\ua747'), - ('\ua749', '\ua749'), ('\ua74b', '\ua74b'), - ('\ua74d', '\ua74d'), ('\ua74f', '\ua74f'), - ('\ua751', '\ua751'), ('\ua753', '\ua753'), - ('\ua755', '\ua755'), ('\ua757', '\ua757'), - ('\ua759', '\ua759'), ('\ua75b', '\ua75b'), - ('\ua75d', '\ua75d'), ('\ua75f', '\ua75f'), - ('\ua761', '\ua761'), ('\ua763', '\ua763'), - ('\ua765', '\ua765'), ('\ua767', '\ua767'), - ('\ua769', '\ua769'), ('\ua76b', '\ua76b'), - ('\ua76d', '\ua76d'), ('\ua76f', '\ua76f'), - ('\ua771', '\ua778'), ('\ua77a', '\ua77a'), - ('\ua77c', '\ua77c'), ('\ua77f', '\ua77f'), - ('\ua781', '\ua781'), ('\ua783', '\ua783'), - ('\ua785', '\ua785'), ('\ua787', '\ua787'), - ('\ua78c', '\ua78c'), ('\ua78e', '\ua78e'), - ('\ua791', '\ua791'), ('\ua793', '\ua793'), - ('\ua7a1', '\ua7a1'), ('\ua7a3', '\ua7a3'), - ('\ua7a5', '\ua7a5'), ('\ua7a7', '\ua7a7'), - ('\ua7a9', '\ua7a9'), ('\ua7fa', '\ua7fa'), - ('\ufb00', '\ufb17'), ('\uff41', '\uff5a'), - ('\U00010428', '\U0001044f'), ('\U0001d41a', '\U0001d433'), - ('\U0001d44e', '\U0001d467'), ('\U0001d482', '\U0001d49b'), - ('\U0001d4b6', '\U0001d4cf'), ('\U0001d4ea', '\U0001d503'), - ('\U0001d51e', '\U0001d537'), ('\U0001d552', '\U0001d56b'), - ('\U0001d586', '\U0001d59f'), ('\U0001d5ba', '\U0001d5d3'), - ('\U0001d5ee', '\U0001d607'), ('\U0001d622', '\U0001d63b'), - ('\U0001d656', '\U0001d66f'), ('\U0001d68a', '\U0001d6a5'), - ('\U0001d6c2', '\U0001d6da'), ('\U0001d6dc', '\U0001d6e1'), - ('\U0001d6fc', '\U0001d714'), ('\U0001d716', '\U0001d71b'), - ('\U0001d736', '\U0001d74e'), ('\U0001d750', '\U0001d755'), - ('\U0001d770', '\U0001d788'), ('\U0001d78a', '\U0001d78f'), - ('\U0001d7aa', '\U0001d7c2'), ('\U0001d7c4', '\U0001d7c9'), - ('\U0001d7cb', '\U0001d7cb') - ]; - - pub fn Ll(c: char) -> bool { - bsearch_range_table(c, Ll_table) - } - - static Lm_table : &'static [(char,char)] = &[ - ('\u02b0', '\u02c1'), ('\u02c6', '\u02d1'), - ('\u02e0', '\u02e4'), ('\u02ec', '\u02ec'), - ('\u02ee', '\u02ee'), ('\u0374', '\u0374'), - ('\u037a', '\u037a'), ('\u0559', '\u0559'), - ('\u0640', '\u0640'), ('\u06e5', '\u06e6'), - ('\u07f4', '\u07f5'), ('\u07fa', '\u07fa'), - ('\u081a', '\u081a'), ('\u0824', '\u0824'), - ('\u0828', '\u0828'), ('\u0971', '\u0971'), - ('\u0e46', '\u0e46'), ('\u0ec6', '\u0ec6'), - ('\u10fc', '\u10fc'), ('\u17d7', '\u17d7'), - ('\u1843', '\u1843'), ('\u1aa7', '\u1aa7'), - ('\u1c78', '\u1c7d'), ('\u1d2c', '\u1d6a'), - ('\u1d78', '\u1d78'), ('\u1d9b', '\u1dbf'), - ('\u2071', '\u2071'), ('\u207f', '\u207f'), - ('\u2090', '\u209c'), ('\u2c7c', '\u2c7d'), - ('\u2d6f', '\u2d6f'), ('\u2e2f', '\u2e2f'), - ('\u3005', '\u3005'), ('\u3031', '\u3035'), - ('\u303b', '\u303b'), ('\u309d', '\u309e'), - ('\u30fc', '\u30fe'), ('\ua015', '\ua015'), - ('\ua4f8', '\ua4fd'), ('\ua60c', '\ua60c'), - ('\ua67f', '\ua67f'), ('\ua717', '\ua71f'), - ('\ua770', '\ua770'), ('\ua788', '\ua788'), - ('\ua7f8', '\ua7f9'), ('\ua9cf', '\ua9cf'), - ('\uaa70', '\uaa70'), ('\uaadd', '\uaadd'), - ('\uaaf3', '\uaaf4'), ('\uff70', '\uff70'), - ('\uff9e', '\uff9f'), ('\U00016f93', '\U00016f9f') - ]; - - pub fn Lm(c: char) -> bool { - bsearch_range_table(c, Lm_table) - } - - static Lo_table : &'static [(char,char)] = &[ - ('\xaa', '\xaa'), ('\xba', '\xba'), - ('\u01bb', '\u01bb'), ('\u01c0', '\u01c3'), - ('\u0294', '\u0294'), ('\u05d0', '\u05f2'), - ('\u0620', '\u063f'), ('\u0641', '\u064a'), - ('\u066e', '\u066f'), ('\u0671', '\u06d3'), - ('\u06d5', '\u06d5'), ('\u06ee', '\u06ef'), - ('\u06fa', '\u06fc'), ('\u06ff', '\u06ff'), - ('\u0710', '\u0710'), ('\u0712', '\u072f'), - ('\u074d', '\u07a5'), ('\u07b1', '\u07b1'), - ('\u07ca', '\u07ea'), ('\u0800', '\u0815'), - ('\u0840', '\u0858'), ('\u08a0', '\u08ac'), - ('\u0904', '\u0939'), ('\u093d', '\u093d'), - ('\u0950', '\u0950'), ('\u0958', '\u0961'), - ('\u0972', '\u097f'), ('\u0985', '\u09b9'), - ('\u09bd', '\u09bd'), ('\u09ce', '\u09ce'), - ('\u09dc', '\u09e1'), ('\u09f0', '\u09f1'), - ('\u0a05', '\u0a39'), ('\u0a59', '\u0a5e'), - ('\u0a72', '\u0a74'), ('\u0a85', '\u0ab9'), - ('\u0abd', '\u0abd'), ('\u0ad0', '\u0ae1'), - ('\u0b05', '\u0b39'), ('\u0b3d', '\u0b3d'), - ('\u0b5c', '\u0b61'), ('\u0b71', '\u0b71'), - ('\u0b83', '\u0bb9'), ('\u0bd0', '\u0bd0'), - ('\u0c05', '\u0c3d'), ('\u0c58', '\u0c61'), - ('\u0c85', '\u0cb9'), ('\u0cbd', '\u0cbd'), - ('\u0cde', '\u0ce1'), ('\u0cf1', '\u0cf2'), - ('\u0d05', '\u0d3d'), ('\u0d4e', '\u0d4e'), - ('\u0d60', '\u0d61'), ('\u0d7a', '\u0d7f'), - ('\u0d85', '\u0dc6'), ('\u0e01', '\u0e30'), - ('\u0e32', '\u0e33'), ('\u0e40', '\u0e45'), - ('\u0e81', '\u0eb0'), ('\u0eb2', '\u0eb3'), - ('\u0ebd', '\u0ec4'), ('\u0edc', '\u0f00'), - ('\u0f40', '\u0f6c'), ('\u0f88', '\u0f8c'), - ('\u1000', '\u102a'), ('\u103f', '\u103f'), - ('\u1050', '\u1055'), ('\u105a', '\u105d'), - ('\u1061', '\u1061'), ('\u1065', '\u1066'), - ('\u106e', '\u1070'), ('\u1075', '\u1081'), - ('\u108e', '\u108e'), ('\u10d0', '\u10fa'), - ('\u10fd', '\u135a'), ('\u1380', '\u138f'), - ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), - ('\u166f', '\u167f'), ('\u1681', '\u169a'), - ('\u16a0', '\u16ea'), ('\u1700', '\u1711'), - ('\u1720', '\u1731'), ('\u1740', '\u1751'), - ('\u1760', '\u1770'), ('\u1780', '\u17b3'), - ('\u17dc', '\u17dc'), ('\u1820', '\u1842'), - ('\u1844', '\u18a8'), ('\u18aa', '\u191c'), - ('\u1950', '\u19ab'), ('\u19c1', '\u19c7'), - ('\u1a00', '\u1a16'), ('\u1a20', '\u1a54'), - ('\u1b05', '\u1b33'), ('\u1b45', '\u1b4b'), - ('\u1b83', '\u1ba0'), ('\u1bae', '\u1baf'), - ('\u1bba', '\u1be5'), ('\u1c00', '\u1c23'), - ('\u1c4d', '\u1c4f'), ('\u1c5a', '\u1c77'), - ('\u1ce9', '\u1cec'), ('\u1cee', '\u1cf1'), - ('\u1cf5', '\u1cf6'), ('\u2135', '\u2138'), - ('\u2d30', '\u2d67'), ('\u2d80', '\u2dde'), - ('\u3006', '\u3006'), ('\u303c', '\u303c'), - ('\u3041', '\u3096'), ('\u309f', '\u309f'), - ('\u30a1', '\u30fa'), ('\u30ff', '\u318e'), - ('\u31a0', '\u31ba'), ('\u31f0', '\u31ff'), - ('\u3400', '\u4db5'), ('\u4e00', '\ua014'), - ('\ua016', '\ua48c'), ('\ua4d0', '\ua4f7'), - ('\ua500', '\ua60b'), ('\ua610', '\ua61f'), - ('\ua62a', '\ua62b'), ('\ua66e', '\ua66e'), - ('\ua6a0', '\ua6e5'), ('\ua7fb', '\ua801'), - ('\ua803', '\ua805'), ('\ua807', '\ua80a'), - ('\ua80c', '\ua822'), ('\ua840', '\ua873'), - ('\ua882', '\ua8b3'), ('\ua8f2', '\ua8f7'), - ('\ua8fb', '\ua8fb'), ('\ua90a', '\ua925'), - ('\ua930', '\ua946'), ('\ua960', '\ua97c'), - ('\ua984', '\ua9b2'), ('\uaa00', '\uaa28'), - ('\uaa40', '\uaa42'), ('\uaa44', '\uaa4b'), - ('\uaa60', '\uaa6f'), ('\uaa71', '\uaa76'), - ('\uaa7a', '\uaa7a'), ('\uaa80', '\uaaaf'), - ('\uaab1', '\uaab1'), ('\uaab5', '\uaab6'), - ('\uaab9', '\uaabd'), ('\uaac0', '\uaac0'), - ('\uaac2', '\uaadc'), ('\uaae0', '\uaaea'), - ('\uaaf2', '\uaaf2'), ('\uab01', '\uabe2'), - ('\uac00', '\ud7fb'), ('\uf900', '\ufad9'), - ('\ufb1d', '\ufb1d'), ('\ufb1f', '\ufb28'), - ('\ufb2a', '\ufbb1'), ('\ufbd3', '\ufd3d'), - ('\ufd50', '\ufdfb'), ('\ufe70', '\ufefc'), - ('\uff66', '\uff6f'), ('\uff71', '\uff9d'), - ('\uffa0', '\uffdc'), ('\U00010000', '\U000100fa'), - ('\U00010280', '\U0001031e'), ('\U00010330', '\U00010340'), - ('\U00010342', '\U00010349'), ('\U00010380', '\U0001039d'), - ('\U000103a0', '\U000103cf'), ('\U00010450', '\U0001049d'), - ('\U00010800', '\U00010855'), ('\U00010900', '\U00010915'), - ('\U00010920', '\U00010939'), ('\U00010980', '\U00010a00'), - ('\U00010a10', '\U00010a33'), ('\U00010a60', '\U00010a7c'), - ('\U00010b00', '\U00010b35'), ('\U00010b40', '\U00010b55'), - ('\U00010b60', '\U00010b72'), ('\U00010c00', '\U00010c48'), - ('\U00011003', '\U00011037'), ('\U00011083', '\U000110af'), - ('\U000110d0', '\U000110e8'), ('\U00011103', '\U00011126'), - ('\U00011183', '\U000111b2'), ('\U000111c1', '\U000111c4'), - ('\U00011680', '\U000116aa'), ('\U00012000', '\U0001236e'), - ('\U00013000', '\U00016f50'), ('\U0001b000', '\U0001b001'), - ('\U0001ee00', '\U0001eebb'), ('\U00020000', '\U0002fa1d') - ]; - - pub fn Lo(c: char) -> bool { - bsearch_range_table(c, Lo_table) - } - - static Lt_table : &'static [(char,char)] = &[ - ('\u01c5', '\u01c5'), ('\u01c8', '\u01c8'), - ('\u01cb', '\u01cb'), ('\u01f2', '\u01f2'), - ('\u1f88', '\u1f8f'), ('\u1f98', '\u1f9f'), - ('\u1fa8', '\u1faf'), ('\u1fbc', '\u1fbc'), - ('\u1fcc', '\u1fcc'), ('\u1ffc', '\u1ffc') - ]; - - pub fn Lt(c: char) -> bool { - bsearch_range_table(c, Lt_table) - } - - static Lu_table : &'static [(char,char)] = &[ - ('\x41', '\x5a'), ('\xc0', '\xd6'), - ('\xd8', '\xde'), ('\u0100', '\u0100'), - ('\u0102', '\u0102'), ('\u0104', '\u0104'), - ('\u0106', '\u0106'), ('\u0108', '\u0108'), - ('\u010a', '\u010a'), ('\u010c', '\u010c'), - ('\u010e', '\u010e'), ('\u0110', '\u0110'), - ('\u0112', '\u0112'), ('\u0114', '\u0114'), - ('\u0116', '\u0116'), ('\u0118', '\u0118'), - ('\u011a', '\u011a'), ('\u011c', '\u011c'), - ('\u011e', '\u011e'), ('\u0120', '\u0120'), - ('\u0122', '\u0122'), ('\u0124', '\u0124'), - ('\u0126', '\u0126'), ('\u0128', '\u0128'), - ('\u012a', '\u012a'), ('\u012c', '\u012c'), - ('\u012e', '\u012e'), ('\u0130', '\u0130'), - ('\u0132', '\u0132'), ('\u0134', '\u0134'), - ('\u0136', '\u0136'), ('\u0139', '\u0139'), - ('\u013b', '\u013b'), ('\u013d', '\u013d'), - ('\u013f', '\u013f'), ('\u0141', '\u0141'), - ('\u0143', '\u0143'), ('\u0145', '\u0145'), - ('\u0147', '\u0147'), ('\u014a', '\u014a'), - ('\u014c', '\u014c'), ('\u014e', '\u014e'), - ('\u0150', '\u0150'), ('\u0152', '\u0152'), - ('\u0154', '\u0154'), ('\u0156', '\u0156'), - ('\u0158', '\u0158'), ('\u015a', '\u015a'), - ('\u015c', '\u015c'), ('\u015e', '\u015e'), - ('\u0160', '\u0160'), ('\u0162', '\u0162'), - ('\u0164', '\u0164'), ('\u0166', '\u0166'), - ('\u0168', '\u0168'), ('\u016a', '\u016a'), - ('\u016c', '\u016c'), ('\u016e', '\u016e'), - ('\u0170', '\u0170'), ('\u0172', '\u0172'), - ('\u0174', '\u0174'), ('\u0176', '\u0176'), - ('\u0178', '\u0179'), ('\u017b', '\u017b'), - ('\u017d', '\u017d'), ('\u0181', '\u0182'), - ('\u0184', '\u0184'), ('\u0186', '\u0187'), - ('\u0189', '\u018b'), ('\u018e', '\u0191'), - ('\u0193', '\u0194'), ('\u0196', '\u0198'), - ('\u019c', '\u019d'), ('\u019f', '\u01a0'), - ('\u01a2', '\u01a2'), ('\u01a4', '\u01a4'), - ('\u01a6', '\u01a7'), ('\u01a9', '\u01a9'), - ('\u01ac', '\u01ac'), ('\u01ae', '\u01af'), - ('\u01b1', '\u01b3'), ('\u01b5', '\u01b5'), - ('\u01b7', '\u01b8'), ('\u01bc', '\u01bc'), - ('\u01c4', '\u01c4'), ('\u01c7', '\u01c7'), - ('\u01ca', '\u01ca'), ('\u01cd', '\u01cd'), - ('\u01cf', '\u01cf'), ('\u01d1', '\u01d1'), - ('\u01d3', '\u01d3'), ('\u01d5', '\u01d5'), - ('\u01d7', '\u01d7'), ('\u01d9', '\u01d9'), - ('\u01db', '\u01db'), ('\u01de', '\u01de'), - ('\u01e0', '\u01e0'), ('\u01e2', '\u01e2'), - ('\u01e4', '\u01e4'), ('\u01e6', '\u01e6'), - ('\u01e8', '\u01e8'), ('\u01ea', '\u01ea'), - ('\u01ec', '\u01ec'), ('\u01ee', '\u01ee'), - ('\u01f1', '\u01f1'), ('\u01f4', '\u01f4'), - ('\u01f6', '\u01f8'), ('\u01fa', '\u01fa'), - ('\u01fc', '\u01fc'), ('\u01fe', '\u01fe'), - ('\u0200', '\u0200'), ('\u0202', '\u0202'), - ('\u0204', '\u0204'), ('\u0206', '\u0206'), - ('\u0208', '\u0208'), ('\u020a', '\u020a'), - ('\u020c', '\u020c'), ('\u020e', '\u020e'), - ('\u0210', '\u0210'), ('\u0212', '\u0212'), - ('\u0214', '\u0214'), ('\u0216', '\u0216'), - ('\u0218', '\u0218'), ('\u021a', '\u021a'), - ('\u021c', '\u021c'), ('\u021e', '\u021e'), - ('\u0220', '\u0220'), ('\u0222', '\u0222'), - ('\u0224', '\u0224'), ('\u0226', '\u0226'), - ('\u0228', '\u0228'), ('\u022a', '\u022a'), - ('\u022c', '\u022c'), ('\u022e', '\u022e'), - ('\u0230', '\u0230'), ('\u0232', '\u0232'), - ('\u023a', '\u023b'), ('\u023d', '\u023e'), - ('\u0241', '\u0241'), ('\u0243', '\u0246'), - ('\u0248', '\u0248'), ('\u024a', '\u024a'), - ('\u024c', '\u024c'), ('\u024e', '\u024e'), - ('\u0370', '\u0370'), ('\u0372', '\u0372'), - ('\u0376', '\u0376'), ('\u0386', '\u0386'), - ('\u0388', '\u038f'), ('\u0391', '\u03ab'), - ('\u03cf', '\u03cf'), ('\u03d2', '\u03d4'), - ('\u03d8', '\u03d8'), ('\u03da', '\u03da'), - ('\u03dc', '\u03dc'), ('\u03de', '\u03de'), - ('\u03e0', '\u03e0'), ('\u03e2', '\u03e2'), - ('\u03e4', '\u03e4'), ('\u03e6', '\u03e6'), - ('\u03e8', '\u03e8'), ('\u03ea', '\u03ea'), - ('\u03ec', '\u03ec'), ('\u03ee', '\u03ee'), - ('\u03f4', '\u03f4'), ('\u03f7', '\u03f7'), - ('\u03f9', '\u03fa'), ('\u03fd', '\u042f'), - ('\u0460', '\u0460'), ('\u0462', '\u0462'), - ('\u0464', '\u0464'), ('\u0466', '\u0466'), - ('\u0468', '\u0468'), ('\u046a', '\u046a'), - ('\u046c', '\u046c'), ('\u046e', '\u046e'), - ('\u0470', '\u0470'), ('\u0472', '\u0472'), - ('\u0474', '\u0474'), ('\u0476', '\u0476'), - ('\u0478', '\u0478'), ('\u047a', '\u047a'), - ('\u047c', '\u047c'), ('\u047e', '\u047e'), - ('\u0480', '\u0480'), ('\u048a', '\u048a'), - ('\u048c', '\u048c'), ('\u048e', '\u048e'), - ('\u0490', '\u0490'), ('\u0492', '\u0492'), - ('\u0494', '\u0494'), ('\u0496', '\u0496'), - ('\u0498', '\u0498'), ('\u049a', '\u049a'), - ('\u049c', '\u049c'), ('\u049e', '\u049e'), - ('\u04a0', '\u04a0'), ('\u04a2', '\u04a2'), - ('\u04a4', '\u04a4'), ('\u04a6', '\u04a6'), - ('\u04a8', '\u04a8'), ('\u04aa', '\u04aa'), - ('\u04ac', '\u04ac'), ('\u04ae', '\u04ae'), - ('\u04b0', '\u04b0'), ('\u04b2', '\u04b2'), - ('\u04b4', '\u04b4'), ('\u04b6', '\u04b6'), - ('\u04b8', '\u04b8'), ('\u04ba', '\u04ba'), - ('\u04bc', '\u04bc'), ('\u04be', '\u04be'), - ('\u04c0', '\u04c1'), ('\u04c3', '\u04c3'), - ('\u04c5', '\u04c5'), ('\u04c7', '\u04c7'), - ('\u04c9', '\u04c9'), ('\u04cb', '\u04cb'), - ('\u04cd', '\u04cd'), ('\u04d0', '\u04d0'), - ('\u04d2', '\u04d2'), ('\u04d4', '\u04d4'), - ('\u04d6', '\u04d6'), ('\u04d8', '\u04d8'), - ('\u04da', '\u04da'), ('\u04dc', '\u04dc'), - ('\u04de', '\u04de'), ('\u04e0', '\u04e0'), - ('\u04e2', '\u04e2'), ('\u04e4', '\u04e4'), - ('\u04e6', '\u04e6'), ('\u04e8', '\u04e8'), - ('\u04ea', '\u04ea'), ('\u04ec', '\u04ec'), - ('\u04ee', '\u04ee'), ('\u04f0', '\u04f0'), - ('\u04f2', '\u04f2'), ('\u04f4', '\u04f4'), - ('\u04f6', '\u04f6'), ('\u04f8', '\u04f8'), - ('\u04fa', '\u04fa'), ('\u04fc', '\u04fc'), - ('\u04fe', '\u04fe'), ('\u0500', '\u0500'), - ('\u0502', '\u0502'), ('\u0504', '\u0504'), - ('\u0506', '\u0506'), ('\u0508', '\u0508'), - ('\u050a', '\u050a'), ('\u050c', '\u050c'), - ('\u050e', '\u050e'), ('\u0510', '\u0510'), - ('\u0512', '\u0512'), ('\u0514', '\u0514'), - ('\u0516', '\u0516'), ('\u0518', '\u0518'), - ('\u051a', '\u051a'), ('\u051c', '\u051c'), - ('\u051e', '\u051e'), ('\u0520', '\u0520'), - ('\u0522', '\u0522'), ('\u0524', '\u0524'), - ('\u0526', '\u0526'), ('\u0531', '\u0556'), - ('\u10a0', '\u10cd'), ('\u1e00', '\u1e00'), - ('\u1e02', '\u1e02'), ('\u1e04', '\u1e04'), - ('\u1e06', '\u1e06'), ('\u1e08', '\u1e08'), - ('\u1e0a', '\u1e0a'), ('\u1e0c', '\u1e0c'), - ('\u1e0e', '\u1e0e'), ('\u1e10', '\u1e10'), - ('\u1e12', '\u1e12'), ('\u1e14', '\u1e14'), - ('\u1e16', '\u1e16'), ('\u1e18', '\u1e18'), - ('\u1e1a', '\u1e1a'), ('\u1e1c', '\u1e1c'), - ('\u1e1e', '\u1e1e'), ('\u1e20', '\u1e20'), - ('\u1e22', '\u1e22'), ('\u1e24', '\u1e24'), - ('\u1e26', '\u1e26'), ('\u1e28', '\u1e28'), - ('\u1e2a', '\u1e2a'), ('\u1e2c', '\u1e2c'), - ('\u1e2e', '\u1e2e'), ('\u1e30', '\u1e30'), - ('\u1e32', '\u1e32'), ('\u1e34', '\u1e34'), - ('\u1e36', '\u1e36'), ('\u1e38', '\u1e38'), - ('\u1e3a', '\u1e3a'), ('\u1e3c', '\u1e3c'), - ('\u1e3e', '\u1e3e'), ('\u1e40', '\u1e40'), - ('\u1e42', '\u1e42'), ('\u1e44', '\u1e44'), - ('\u1e46', '\u1e46'), ('\u1e48', '\u1e48'), - ('\u1e4a', '\u1e4a'), ('\u1e4c', '\u1e4c'), - ('\u1e4e', '\u1e4e'), ('\u1e50', '\u1e50'), - ('\u1e52', '\u1e52'), ('\u1e54', '\u1e54'), - ('\u1e56', '\u1e56'), ('\u1e58', '\u1e58'), - ('\u1e5a', '\u1e5a'), ('\u1e5c', '\u1e5c'), - ('\u1e5e', '\u1e5e'), ('\u1e60', '\u1e60'), - ('\u1e62', '\u1e62'), ('\u1e64', '\u1e64'), - ('\u1e66', '\u1e66'), ('\u1e68', '\u1e68'), - ('\u1e6a', '\u1e6a'), ('\u1e6c', '\u1e6c'), - ('\u1e6e', '\u1e6e'), ('\u1e70', '\u1e70'), - ('\u1e72', '\u1e72'), ('\u1e74', '\u1e74'), - ('\u1e76', '\u1e76'), ('\u1e78', '\u1e78'), - ('\u1e7a', '\u1e7a'), ('\u1e7c', '\u1e7c'), - ('\u1e7e', '\u1e7e'), ('\u1e80', '\u1e80'), - ('\u1e82', '\u1e82'), ('\u1e84', '\u1e84'), - ('\u1e86', '\u1e86'), ('\u1e88', '\u1e88'), - ('\u1e8a', '\u1e8a'), ('\u1e8c', '\u1e8c'), - ('\u1e8e', '\u1e8e'), ('\u1e90', '\u1e90'), - ('\u1e92', '\u1e92'), ('\u1e94', '\u1e94'), - ('\u1e9e', '\u1e9e'), ('\u1ea0', '\u1ea0'), - ('\u1ea2', '\u1ea2'), ('\u1ea4', '\u1ea4'), - ('\u1ea6', '\u1ea6'), ('\u1ea8', '\u1ea8'), - ('\u1eaa', '\u1eaa'), ('\u1eac', '\u1eac'), - ('\u1eae', '\u1eae'), ('\u1eb0', '\u1eb0'), - ('\u1eb2', '\u1eb2'), ('\u1eb4', '\u1eb4'), - ('\u1eb6', '\u1eb6'), ('\u1eb8', '\u1eb8'), - ('\u1eba', '\u1eba'), ('\u1ebc', '\u1ebc'), - ('\u1ebe', '\u1ebe'), ('\u1ec0', '\u1ec0'), - ('\u1ec2', '\u1ec2'), ('\u1ec4', '\u1ec4'), - ('\u1ec6', '\u1ec6'), ('\u1ec8', '\u1ec8'), - ('\u1eca', '\u1eca'), ('\u1ecc', '\u1ecc'), - ('\u1ece', '\u1ece'), ('\u1ed0', '\u1ed0'), - ('\u1ed2', '\u1ed2'), ('\u1ed4', '\u1ed4'), - ('\u1ed6', '\u1ed6'), ('\u1ed8', '\u1ed8'), - ('\u1eda', '\u1eda'), ('\u1edc', '\u1edc'), - ('\u1ede', '\u1ede'), ('\u1ee0', '\u1ee0'), - ('\u1ee2', '\u1ee2'), ('\u1ee4', '\u1ee4'), - ('\u1ee6', '\u1ee6'), ('\u1ee8', '\u1ee8'), - ('\u1eea', '\u1eea'), ('\u1eec', '\u1eec'), - ('\u1eee', '\u1eee'), ('\u1ef0', '\u1ef0'), - ('\u1ef2', '\u1ef2'), ('\u1ef4', '\u1ef4'), - ('\u1ef6', '\u1ef6'), ('\u1ef8', '\u1ef8'), - ('\u1efa', '\u1efa'), ('\u1efc', '\u1efc'), - ('\u1efe', '\u1efe'), ('\u1f08', '\u1f0f'), - ('\u1f18', '\u1f1d'), ('\u1f28', '\u1f2f'), - ('\u1f38', '\u1f3f'), ('\u1f48', '\u1f4d'), - ('\u1f59', '\u1f5f'), ('\u1f68', '\u1f6f'), - ('\u1fb8', '\u1fbb'), ('\u1fc8', '\u1fcb'), - ('\u1fd8', '\u1fdb'), ('\u1fe8', '\u1fec'), - ('\u1ff8', '\u1ffb'), ('\u2102', '\u2102'), - ('\u2107', '\u2107'), ('\u210b', '\u210d'), - ('\u2110', '\u2112'), ('\u2115', '\u2115'), - ('\u2119', '\u211d'), ('\u2124', '\u2124'), - ('\u2126', '\u2126'), ('\u2128', '\u2128'), - ('\u212a', '\u212d'), ('\u2130', '\u2133'), - ('\u213e', '\u213f'), ('\u2145', '\u2145'), - ('\u2183', '\u2183'), ('\u2c00', '\u2c2e'), - ('\u2c60', '\u2c60'), ('\u2c62', '\u2c64'), - ('\u2c67', '\u2c67'), ('\u2c69', '\u2c69'), - ('\u2c6b', '\u2c6b'), ('\u2c6d', '\u2c70'), - ('\u2c72', '\u2c72'), ('\u2c75', '\u2c75'), - ('\u2c7e', '\u2c80'), ('\u2c82', '\u2c82'), - ('\u2c84', '\u2c84'), ('\u2c86', '\u2c86'), - ('\u2c88', '\u2c88'), ('\u2c8a', '\u2c8a'), - ('\u2c8c', '\u2c8c'), ('\u2c8e', '\u2c8e'), - ('\u2c90', '\u2c90'), ('\u2c92', '\u2c92'), - ('\u2c94', '\u2c94'), ('\u2c96', '\u2c96'), - ('\u2c98', '\u2c98'), ('\u2c9a', '\u2c9a'), - ('\u2c9c', '\u2c9c'), ('\u2c9e', '\u2c9e'), - ('\u2ca0', '\u2ca0'), ('\u2ca2', '\u2ca2'), - ('\u2ca4', '\u2ca4'), ('\u2ca6', '\u2ca6'), - ('\u2ca8', '\u2ca8'), ('\u2caa', '\u2caa'), - ('\u2cac', '\u2cac'), ('\u2cae', '\u2cae'), - ('\u2cb0', '\u2cb0'), ('\u2cb2', '\u2cb2'), - ('\u2cb4', '\u2cb4'), ('\u2cb6', '\u2cb6'), - ('\u2cb8', '\u2cb8'), ('\u2cba', '\u2cba'), - ('\u2cbc', '\u2cbc'), ('\u2cbe', '\u2cbe'), - ('\u2cc0', '\u2cc0'), ('\u2cc2', '\u2cc2'), - ('\u2cc4', '\u2cc4'), ('\u2cc6', '\u2cc6'), - ('\u2cc8', '\u2cc8'), ('\u2cca', '\u2cca'), - ('\u2ccc', '\u2ccc'), ('\u2cce', '\u2cce'), - ('\u2cd0', '\u2cd0'), ('\u2cd2', '\u2cd2'), - ('\u2cd4', '\u2cd4'), ('\u2cd6', '\u2cd6'), - ('\u2cd8', '\u2cd8'), ('\u2cda', '\u2cda'), - ('\u2cdc', '\u2cdc'), ('\u2cde', '\u2cde'), - ('\u2ce0', '\u2ce0'), ('\u2ce2', '\u2ce2'), - ('\u2ceb', '\u2ceb'), ('\u2ced', '\u2ced'), - ('\u2cf2', '\u2cf2'), ('\ua640', '\ua640'), - ('\ua642', '\ua642'), ('\ua644', '\ua644'), - ('\ua646', '\ua646'), ('\ua648', '\ua648'), - ('\ua64a', '\ua64a'), ('\ua64c', '\ua64c'), - ('\ua64e', '\ua64e'), ('\ua650', '\ua650'), - ('\ua652', '\ua652'), ('\ua654', '\ua654'), - ('\ua656', '\ua656'), ('\ua658', '\ua658'), - ('\ua65a', '\ua65a'), ('\ua65c', '\ua65c'), - ('\ua65e', '\ua65e'), ('\ua660', '\ua660'), - ('\ua662', '\ua662'), ('\ua664', '\ua664'), - ('\ua666', '\ua666'), ('\ua668', '\ua668'), - ('\ua66a', '\ua66a'), ('\ua66c', '\ua66c'), - ('\ua680', '\ua680'), ('\ua682', '\ua682'), - ('\ua684', '\ua684'), ('\ua686', '\ua686'), - ('\ua688', '\ua688'), ('\ua68a', '\ua68a'), - ('\ua68c', '\ua68c'), ('\ua68e', '\ua68e'), - ('\ua690', '\ua690'), ('\ua692', '\ua692'), - ('\ua694', '\ua694'), ('\ua696', '\ua696'), - ('\ua722', '\ua722'), ('\ua724', '\ua724'), - ('\ua726', '\ua726'), ('\ua728', '\ua728'), - ('\ua72a', '\ua72a'), ('\ua72c', '\ua72c'), - ('\ua72e', '\ua72e'), ('\ua732', '\ua732'), - ('\ua734', '\ua734'), ('\ua736', '\ua736'), - ('\ua738', '\ua738'), ('\ua73a', '\ua73a'), - ('\ua73c', '\ua73c'), ('\ua73e', '\ua73e'), - ('\ua740', '\ua740'), ('\ua742', '\ua742'), - ('\ua744', '\ua744'), ('\ua746', '\ua746'), - ('\ua748', '\ua748'), ('\ua74a', '\ua74a'), - ('\ua74c', '\ua74c'), ('\ua74e', '\ua74e'), - ('\ua750', '\ua750'), ('\ua752', '\ua752'), - ('\ua754', '\ua754'), ('\ua756', '\ua756'), - ('\ua758', '\ua758'), ('\ua75a', '\ua75a'), - ('\ua75c', '\ua75c'), ('\ua75e', '\ua75e'), - ('\ua760', '\ua760'), ('\ua762', '\ua762'), - ('\ua764', '\ua764'), ('\ua766', '\ua766'), - ('\ua768', '\ua768'), ('\ua76a', '\ua76a'), - ('\ua76c', '\ua76c'), ('\ua76e', '\ua76e'), - ('\ua779', '\ua779'), ('\ua77b', '\ua77b'), - ('\ua77d', '\ua77e'), ('\ua780', '\ua780'), - ('\ua782', '\ua782'), ('\ua784', '\ua784'), - ('\ua786', '\ua786'), ('\ua78b', '\ua78b'), - ('\ua78d', '\ua78d'), ('\ua790', '\ua790'), - ('\ua792', '\ua792'), ('\ua7a0', '\ua7a0'), - ('\ua7a2', '\ua7a2'), ('\ua7a4', '\ua7a4'), - ('\ua7a6', '\ua7a6'), ('\ua7a8', '\ua7a8'), - ('\ua7aa', '\ua7aa'), ('\uff21', '\uff3a'), - ('\U00010400', '\U00010427'), ('\U0001d400', '\U0001d419'), - ('\U0001d434', '\U0001d44d'), ('\U0001d468', '\U0001d481'), - ('\U0001d49c', '\U0001d4b5'), ('\U0001d4d0', '\U0001d4e9'), - ('\U0001d504', '\U0001d51c'), ('\U0001d538', '\U0001d550'), - ('\U0001d56c', '\U0001d585'), ('\U0001d5a0', '\U0001d5b9'), - ('\U0001d5d4', '\U0001d5ed'), ('\U0001d608', '\U0001d621'), - ('\U0001d63c', '\U0001d655'), ('\U0001d670', '\U0001d689'), - ('\U0001d6a8', '\U0001d6c0'), ('\U0001d6e2', '\U0001d6fa'), - ('\U0001d71c', '\U0001d734'), ('\U0001d756', '\U0001d76e'), - ('\U0001d790', '\U0001d7a8'), ('\U0001d7ca', '\U0001d7ca') - ]; - - pub fn Lu(c: char) -> bool { - bsearch_range_table(c, Lu_table) - } - - static Mc_table : &'static [(char,char)] = &[ - ('\u0903', '\u0903'), ('\u093b', '\u093b'), - ('\u093e', '\u0940'), ('\u0949', '\u094c'), - ('\u094e', '\u094f'), ('\u0982', '\u0983'), - ('\u09be', '\u09c0'), ('\u09c7', '\u09cc'), - ('\u09d7', '\u09d7'), ('\u0a03', '\u0a03'), - ('\u0a3e', '\u0a40'), ('\u0a83', '\u0a83'), - ('\u0abe', '\u0ac0'), ('\u0ac9', '\u0acc'), - ('\u0b02', '\u0b03'), ('\u0b3e', '\u0b3e'), - ('\u0b40', '\u0b40'), ('\u0b47', '\u0b4c'), - ('\u0b57', '\u0b57'), ('\u0bbe', '\u0bbf'), - ('\u0bc1', '\u0bcc'), ('\u0bd7', '\u0bd7'), - ('\u0c01', '\u0c03'), ('\u0c41', '\u0c44'), - ('\u0c82', '\u0c83'), ('\u0cbe', '\u0cbe'), - ('\u0cc0', '\u0cc4'), ('\u0cc7', '\u0ccb'), - ('\u0cd5', '\u0cd6'), ('\u0d02', '\u0d03'), - ('\u0d3e', '\u0d40'), ('\u0d46', '\u0d4c'), - ('\u0d57', '\u0d57'), ('\u0d82', '\u0d83'), - ('\u0dcf', '\u0dd1'), ('\u0dd8', '\u0df3'), - ('\u0f3e', '\u0f3f'), ('\u0f7f', '\u0f7f'), - ('\u102b', '\u102c'), ('\u1031', '\u1031'), - ('\u1038', '\u1038'), ('\u103b', '\u103c'), - ('\u1056', '\u1057'), ('\u1062', '\u1064'), - ('\u1067', '\u106d'), ('\u1083', '\u1084'), - ('\u1087', '\u108c'), ('\u108f', '\u108f'), - ('\u109a', '\u109c'), ('\u17b6', '\u17b6'), - ('\u17be', '\u17c5'), ('\u17c7', '\u17c8'), - ('\u1923', '\u1926'), ('\u1929', '\u1931'), - ('\u1933', '\u1938'), ('\u19b0', '\u19c0'), - ('\u19c8', '\u19c9'), ('\u1a19', '\u1a1b'), - ('\u1a55', '\u1a55'), ('\u1a57', '\u1a57'), - ('\u1a61', '\u1a61'), ('\u1a63', '\u1a64'), - ('\u1a6d', '\u1a72'), ('\u1b04', '\u1b04'), - ('\u1b35', '\u1b35'), ('\u1b3b', '\u1b3b'), - ('\u1b3d', '\u1b41'), ('\u1b43', '\u1b44'), - ('\u1b82', '\u1b82'), ('\u1ba1', '\u1ba1'), - ('\u1ba6', '\u1ba7'), ('\u1baa', '\u1baa'), - ('\u1bac', '\u1bad'), ('\u1be7', '\u1be7'), - ('\u1bea', '\u1bec'), ('\u1bee', '\u1bee'), - ('\u1bf2', '\u1bf3'), ('\u1c24', '\u1c2b'), - ('\u1c34', '\u1c35'), ('\u1ce1', '\u1ce1'), - ('\u1cf2', '\u1cf3'), ('\u302e', '\u302f'), - ('\ua823', '\ua824'), ('\ua827', '\ua827'), - ('\ua880', '\ua881'), ('\ua8b4', '\ua8c3'), - ('\ua952', '\ua953'), ('\ua983', '\ua983'), - ('\ua9b4', '\ua9b5'), ('\ua9ba', '\ua9bb'), - ('\ua9bd', '\ua9c0'), ('\uaa2f', '\uaa30'), - ('\uaa33', '\uaa34'), ('\uaa4d', '\uaa4d'), - ('\uaa7b', '\uaa7b'), ('\uaaeb', '\uaaeb'), - ('\uaaee', '\uaaef'), ('\uaaf5', '\uaaf5'), - ('\uabe3', '\uabe4'), ('\uabe6', '\uabe7'), - ('\uabe9', '\uabea'), ('\uabec', '\uabec'), - ('\U00011000', '\U00011000'), ('\U00011002', '\U00011002'), - ('\U00011082', '\U00011082'), ('\U000110b0', '\U000110b2'), - ('\U000110b7', '\U000110b8'), ('\U0001112c', '\U0001112c'), - ('\U00011182', '\U00011182'), ('\U000111b3', '\U000111b5'), - ('\U000111bf', '\U000111c0'), ('\U000116ac', '\U000116ac'), - ('\U000116ae', '\U000116af'), ('\U000116b6', '\U000116b6'), - ('\U00016f51', '\U00016f7e'), ('\U0001d165', '\U0001d166'), - ('\U0001d16d', '\U0001d172') - ]; - - pub fn Mc(c: char) -> bool { - bsearch_range_table(c, Mc_table) - } - - static Me_table : &'static [(char,char)] = &[ - ('\u0488', '\u0489'), ('\u20dd', '\u20e0'), - ('\u20e2', '\u20e4'), ('\ua670', '\ua672') - ]; - - pub fn Me(c: char) -> bool { - bsearch_range_table(c, Me_table) - } - - static Mn_table : &'static [(char,char)] = &[ - ('\u0300', '\u036f'), ('\u0483', '\u0487'), - ('\u0591', '\u05bd'), ('\u05bf', '\u05bf'), - ('\u05c1', '\u05c2'), ('\u05c4', '\u05c5'), - ('\u05c7', '\u05c7'), ('\u0610', '\u061a'), - ('\u064b', '\u065f'), ('\u0670', '\u0670'), - ('\u06d6', '\u06dc'), ('\u06df', '\u06e4'), - ('\u06e7', '\u06e8'), ('\u06ea', '\u06ed'), - ('\u0711', '\u0711'), ('\u0730', '\u074a'), - ('\u07a6', '\u07b0'), ('\u07eb', '\u07f3'), - ('\u0816', '\u0819'), ('\u081b', '\u0823'), - ('\u0825', '\u0827'), ('\u0829', '\u082d'), - ('\u0859', '\u085b'), ('\u08e4', '\u0902'), - ('\u093a', '\u093a'), ('\u093c', '\u093c'), - ('\u0941', '\u0948'), ('\u094d', '\u094d'), - ('\u0951', '\u0957'), ('\u0962', '\u0963'), - ('\u0981', '\u0981'), ('\u09bc', '\u09bc'), - ('\u09c1', '\u09c4'), ('\u09cd', '\u09cd'), - ('\u09e2', '\u09e3'), ('\u0a01', '\u0a02'), - ('\u0a3c', '\u0a3c'), ('\u0a41', '\u0a51'), - ('\u0a70', '\u0a71'), ('\u0a75', '\u0a82'), - ('\u0abc', '\u0abc'), ('\u0ac1', '\u0ac8'), - ('\u0acd', '\u0acd'), ('\u0ae2', '\u0ae3'), - ('\u0b01', '\u0b01'), ('\u0b3c', '\u0b3c'), - ('\u0b3f', '\u0b3f'), ('\u0b41', '\u0b44'), - ('\u0b4d', '\u0b56'), ('\u0b62', '\u0b63'), - ('\u0b82', '\u0b82'), ('\u0bc0', '\u0bc0'), - ('\u0bcd', '\u0bcd'), ('\u0c3e', '\u0c40'), - ('\u0c46', '\u0c56'), ('\u0c62', '\u0c63'), - ('\u0cbc', '\u0cbc'), ('\u0cbf', '\u0cbf'), - ('\u0cc6', '\u0cc6'), ('\u0ccc', '\u0ccd'), - ('\u0ce2', '\u0ce3'), ('\u0d41', '\u0d44'), - ('\u0d4d', '\u0d4d'), ('\u0d62', '\u0d63'), - ('\u0dca', '\u0dca'), ('\u0dd2', '\u0dd6'), - ('\u0e31', '\u0e31'), ('\u0e34', '\u0e3a'), - ('\u0e47', '\u0e4e'), ('\u0eb1', '\u0eb1'), - ('\u0eb4', '\u0ebc'), ('\u0ec8', '\u0ecd'), - ('\u0f18', '\u0f19'), ('\u0f35', '\u0f35'), - ('\u0f37', '\u0f37'), ('\u0f39', '\u0f39'), - ('\u0f71', '\u0f7e'), ('\u0f80', '\u0f84'), - ('\u0f86', '\u0f87'), ('\u0f8d', '\u0fbc'), - ('\u0fc6', '\u0fc6'), ('\u102d', '\u1030'), - ('\u1032', '\u1037'), ('\u1039', '\u103a'), - ('\u103d', '\u103e'), ('\u1058', '\u1059'), - ('\u105e', '\u1060'), ('\u1071', '\u1074'), - ('\u1082', '\u1082'), ('\u1085', '\u1086'), - ('\u108d', '\u108d'), ('\u109d', '\u109d'), - ('\u135d', '\u135f'), ('\u1712', '\u1714'), - ('\u1732', '\u1734'), ('\u1752', '\u1753'), - ('\u1772', '\u1773'), ('\u17b4', '\u17b5'), - ('\u17b7', '\u17bd'), ('\u17c6', '\u17c6'), - ('\u17c9', '\u17d3'), ('\u17dd', '\u17dd'), - ('\u180b', '\u180d'), ('\u18a9', '\u18a9'), - ('\u1920', '\u1922'), ('\u1927', '\u1928'), - ('\u1932', '\u1932'), ('\u1939', '\u193b'), - ('\u1a17', '\u1a18'), ('\u1a56', '\u1a56'), - ('\u1a58', '\u1a60'), ('\u1a62', '\u1a62'), - ('\u1a65', '\u1a6c'), ('\u1a73', '\u1a7f'), - ('\u1b00', '\u1b03'), ('\u1b34', '\u1b34'), - ('\u1b36', '\u1b3a'), ('\u1b3c', '\u1b3c'), - ('\u1b42', '\u1b42'), ('\u1b6b', '\u1b73'), - ('\u1b80', '\u1b81'), ('\u1ba2', '\u1ba5'), - ('\u1ba8', '\u1ba9'), ('\u1bab', '\u1bab'), - ('\u1be6', '\u1be6'), ('\u1be8', '\u1be9'), - ('\u1bed', '\u1bed'), ('\u1bef', '\u1bf1'), - ('\u1c2c', '\u1c33'), ('\u1c36', '\u1c37'), - ('\u1cd0', '\u1cd2'), ('\u1cd4', '\u1ce0'), - ('\u1ce2', '\u1ce8'), ('\u1ced', '\u1ced'), - ('\u1cf4', '\u1cf4'), ('\u1dc0', '\u1dff'), - ('\u20d0', '\u20dc'), ('\u20e1', '\u20e1'), - ('\u20e5', '\u20f0'), ('\u2cef', '\u2cf1'), - ('\u2d7f', '\u2d7f'), ('\u2de0', '\u2dff'), - ('\u302a', '\u302d'), ('\u3099', '\u309a'), - ('\ua66f', '\ua66f'), ('\ua674', '\ua67d'), - ('\ua69f', '\ua69f'), ('\ua6f0', '\ua6f1'), - ('\ua802', '\ua802'), ('\ua806', '\ua806'), - ('\ua80b', '\ua80b'), ('\ua825', '\ua826'), - ('\ua8c4', '\ua8c4'), ('\ua8e0', '\ua8f1'), - ('\ua926', '\ua92d'), ('\ua947', '\ua951'), - ('\ua980', '\ua982'), ('\ua9b3', '\ua9b3'), - ('\ua9b6', '\ua9b9'), ('\ua9bc', '\ua9bc'), - ('\uaa29', '\uaa2e'), ('\uaa31', '\uaa32'), - ('\uaa35', '\uaa36'), ('\uaa43', '\uaa43'), - ('\uaa4c', '\uaa4c'), ('\uaab0', '\uaab0'), - ('\uaab2', '\uaab4'), ('\uaab7', '\uaab8'), - ('\uaabe', '\uaabf'), ('\uaac1', '\uaac1'), - ('\uaaec', '\uaaed'), ('\uaaf6', '\uaaf6'), - ('\uabe5', '\uabe5'), ('\uabe8', '\uabe8'), - ('\uabed', '\uabed'), ('\ufb1e', '\ufb1e'), - ('\ufe00', '\ufe0f'), ('\ufe20', '\ufe26'), - ('\U000101fd', '\U000101fd'), ('\U00010a01', '\U00010a0f'), - ('\U00010a38', '\U00010a3f'), ('\U00011001', '\U00011001'), - ('\U00011038', '\U00011046'), ('\U00011080', '\U00011081'), - ('\U000110b3', '\U000110b6'), ('\U000110b9', '\U000110ba'), - ('\U00011100', '\U00011102'), ('\U00011127', '\U0001112b'), - ('\U0001112d', '\U00011134'), ('\U00011180', '\U00011181'), - ('\U000111b6', '\U000111be'), ('\U000116ab', '\U000116ab'), - ('\U000116ad', '\U000116ad'), ('\U000116b0', '\U000116b5'), - ('\U000116b7', '\U000116b7'), ('\U00016f8f', '\U00016f92'), - ('\U0001d167', '\U0001d169'), ('\U0001d17b', '\U0001d182'), - ('\U0001d185', '\U0001d18b'), ('\U0001d1aa', '\U0001d1ad'), - ('\U0001d242', '\U0001d244'), ('\U000e0100', '\U000e01ef') - ]; - - pub fn Mn(c: char) -> bool { - bsearch_range_table(c, Mn_table) - } - - static Nd_table : &'static [(char,char)] = &[ - ('\x30', '\x39'), ('\u0660', '\u0669'), - ('\u06f0', '\u06f9'), ('\u07c0', '\u07c9'), - ('\u0966', '\u096f'), ('\u09e6', '\u09ef'), - ('\u0a66', '\u0a6f'), ('\u0ae6', '\u0aef'), - ('\u0b66', '\u0b6f'), ('\u0be6', '\u0bef'), - ('\u0c66', '\u0c6f'), ('\u0ce6', '\u0cef'), - ('\u0d66', '\u0d6f'), ('\u0e50', '\u0e59'), - ('\u0ed0', '\u0ed9'), ('\u0f20', '\u0f29'), - ('\u1040', '\u1049'), ('\u1090', '\u1099'), - ('\u17e0', '\u17e9'), ('\u1810', '\u1819'), - ('\u1946', '\u194f'), ('\u19d0', '\u19d9'), - ('\u1a80', '\u1a99'), ('\u1b50', '\u1b59'), - ('\u1bb0', '\u1bb9'), ('\u1c40', '\u1c49'), - ('\u1c50', '\u1c59'), ('\ua620', '\ua629'), - ('\ua8d0', '\ua8d9'), ('\ua900', '\ua909'), - ('\ua9d0', '\ua9d9'), ('\uaa50', '\uaa59'), - ('\uabf0', '\uabf9'), ('\uff10', '\uff19'), - ('\U000104a0', '\U000104a9'), ('\U00011066', '\U0001106f'), - ('\U000110f0', '\U000110f9'), ('\U00011136', '\U0001113f'), - ('\U000111d0', '\U000111d9'), ('\U000116c0', '\U000116c9'), - ('\U0001d7ce', '\U0001d7ff') - ]; - - pub fn Nd(c: char) -> bool { - bsearch_range_table(c, Nd_table) - } - - static Nl_table : &'static [(char,char)] = &[ - ('\u16ee', '\u16f0'), ('\u2160', '\u2182'), - ('\u2185', '\u2188'), ('\u3007', '\u3007'), - ('\u3021', '\u3029'), ('\u3038', '\u303a'), - ('\ua6e6', '\ua6ef'), ('\U00010140', '\U00010174'), - ('\U00010341', '\U00010341'), ('\U0001034a', '\U0001034a'), - ('\U000103d1', '\U000103d5'), ('\U00012400', '\U00012462') - ]; - - pub fn Nl(c: char) -> bool { - bsearch_range_table(c, Nl_table) - } - - static No_table : &'static [(char,char)] = &[ - ('\xb2', '\xb3'), ('\xb9', '\xb9'), - ('\xbc', '\xbe'), ('\u09f4', '\u09f9'), - ('\u0b72', '\u0b77'), ('\u0bf0', '\u0bf2'), - ('\u0c78', '\u0c7e'), ('\u0d70', '\u0d75'), - ('\u0f2a', '\u0f33'), ('\u1369', '\u137c'), - ('\u17f0', '\u17f9'), ('\u19da', '\u19da'), - ('\u2070', '\u2070'), ('\u2074', '\u2079'), - ('\u2080', '\u2089'), ('\u2150', '\u215f'), - ('\u2189', '\u2189'), ('\u2460', '\u249b'), - ('\u24ea', '\u24ff'), ('\u2776', '\u2793'), - ('\u2cfd', '\u2cfd'), ('\u3192', '\u3195'), - ('\u3220', '\u3229'), ('\u3248', '\u324f'), - ('\u3251', '\u325f'), ('\u3280', '\u3289'), - ('\u32b1', '\u32bf'), ('\ua830', '\ua835'), - ('\U00010107', '\U00010133'), ('\U00010175', '\U00010178'), - ('\U0001018a', '\U0001018a'), ('\U00010320', '\U00010323'), - ('\U00010858', '\U0001085f'), ('\U00010916', '\U0001091b'), - ('\U00010a40', '\U00010a47'), ('\U00010a7d', '\U00010a7e'), - ('\U00010b58', '\U00010b5f'), ('\U00010b78', '\U00010b7f'), - ('\U00010e60', '\U00010e7e'), ('\U00011052', '\U00011065'), - ('\U0001d360', '\U0001d371'), ('\U0001f100', '\U0001f10a') - ]; - - pub fn No(c: char) -> bool { - bsearch_range_table(c, No_table) - } - - static Pc_table : &'static [(char,char)] = &[ - ('\x5f', '\x5f'), ('\u203f', '\u2040'), - ('\u2054', '\u2054'), ('\ufe33', '\ufe34'), - ('\ufe4d', '\ufe4f'), ('\uff3f', '\uff3f') - ]; - - pub fn Pc(c: char) -> bool { - bsearch_range_table(c, Pc_table) - } - - static Pd_table : &'static [(char,char)] = &[ - ('\x2d', '\x2d'), ('\u058a', '\u058a'), - ('\u05be', '\u05be'), ('\u1400', '\u1400'), - ('\u1806', '\u1806'), ('\u2010', '\u2015'), - ('\u2e17', '\u2e17'), ('\u2e1a', '\u2e1a'), - ('\u2e3a', '\u2e3b'), ('\u301c', '\u301c'), - ('\u3030', '\u3030'), ('\u30a0', '\u30a0'), - ('\ufe31', '\ufe32'), ('\ufe58', '\ufe58'), - ('\ufe63', '\ufe63'), ('\uff0d', '\uff0d') - ]; - - pub fn Pd(c: char) -> bool { - bsearch_range_table(c, Pd_table) - } - - static Pe_table : &'static [(char,char)] = &[ - ('\x29', '\x29'), ('\x5d', '\x5d'), - ('\x7d', '\x7d'), ('\u0f3b', '\u0f3b'), - ('\u0f3d', '\u0f3d'), ('\u169c', '\u169c'), - ('\u2046', '\u2046'), ('\u207e', '\u207e'), - ('\u208e', '\u208e'), ('\u232a', '\u232a'), - ('\u2769', '\u2769'), ('\u276b', '\u276b'), - ('\u276d', '\u276d'), ('\u276f', '\u276f'), - ('\u2771', '\u2771'), ('\u2773', '\u2773'), - ('\u2775', '\u2775'), ('\u27c6', '\u27c6'), - ('\u27e7', '\u27e7'), ('\u27e9', '\u27e9'), - ('\u27eb', '\u27eb'), ('\u27ed', '\u27ed'), - ('\u27ef', '\u27ef'), ('\u2984', '\u2984'), - ('\u2986', '\u2986'), ('\u2988', '\u2988'), - ('\u298a', '\u298a'), ('\u298c', '\u298c'), - ('\u298e', '\u298e'), ('\u2990', '\u2990'), - ('\u2992', '\u2992'), ('\u2994', '\u2994'), - ('\u2996', '\u2996'), ('\u2998', '\u2998'), - ('\u29d9', '\u29d9'), ('\u29db', '\u29db'), - ('\u29fd', '\u29fd'), ('\u2e23', '\u2e23'), - ('\u2e25', '\u2e25'), ('\u2e27', '\u2e27'), - ('\u2e29', '\u2e29'), ('\u3009', '\u3009'), - ('\u300b', '\u300b'), ('\u300d', '\u300d'), - ('\u300f', '\u300f'), ('\u3011', '\u3011'), - ('\u3015', '\u3015'), ('\u3017', '\u3017'), - ('\u3019', '\u3019'), ('\u301b', '\u301b'), - ('\u301e', '\u301f'), ('\ufd3f', '\ufd3f'), - ('\ufe18', '\ufe18'), ('\ufe36', '\ufe36'), - ('\ufe38', '\ufe38'), ('\ufe3a', '\ufe3a'), - ('\ufe3c', '\ufe3c'), ('\ufe3e', '\ufe3e'), - ('\ufe40', '\ufe40'), ('\ufe42', '\ufe42'), - ('\ufe44', '\ufe44'), ('\ufe48', '\ufe48'), - ('\ufe5a', '\ufe5a'), ('\ufe5c', '\ufe5c'), - ('\ufe5e', '\ufe5e'), ('\uff09', '\uff09'), - ('\uff3d', '\uff3d'), ('\uff5d', '\uff5d'), - ('\uff60', '\uff60'), ('\uff63', '\uff63') - ]; - - pub fn Pe(c: char) -> bool { - bsearch_range_table(c, Pe_table) - } - - static Pf_table : &'static [(char,char)] = &[ - ('\xbb', '\xbb'), ('\u2019', '\u2019'), - ('\u201d', '\u201d'), ('\u203a', '\u203a'), - ('\u2e03', '\u2e03'), ('\u2e05', '\u2e05'), - ('\u2e0a', '\u2e0a'), ('\u2e0d', '\u2e0d'), - ('\u2e1d', '\u2e1d'), ('\u2e21', '\u2e21') - ]; - - pub fn Pf(c: char) -> bool { - bsearch_range_table(c, Pf_table) - } - - static Pi_table : &'static [(char,char)] = &[ - ('\xab', '\xab'), ('\u2018', '\u2018'), - ('\u201b', '\u201c'), ('\u201f', '\u201f'), - ('\u2039', '\u2039'), ('\u2e02', '\u2e02'), - ('\u2e04', '\u2e04'), ('\u2e09', '\u2e09'), - ('\u2e0c', '\u2e0c'), ('\u2e1c', '\u2e1c'), - ('\u2e20', '\u2e20') - ]; - - pub fn Pi(c: char) -> bool { - bsearch_range_table(c, Pi_table) - } - - static Po_table : &'static [(char,char)] = &[ - ('\x21', '\x23'), ('\x25', '\x27'), - ('\x2a', '\x2a'), ('\x2c', '\x2c'), - ('\x2e', '\x2f'), ('\x3a', '\x3b'), - ('\x3f', '\x40'), ('\x5c', '\x5c'), - ('\xa1', '\xa1'), ('\xa7', '\xa7'), - ('\xb6', '\xb7'), ('\xbf', '\xbf'), - ('\u037e', '\u037e'), ('\u0387', '\u0387'), - ('\u055a', '\u055f'), ('\u0589', '\u0589'), - ('\u05c0', '\u05c0'), ('\u05c3', '\u05c3'), - ('\u05c6', '\u05c6'), ('\u05f3', '\u05f4'), - ('\u0609', '\u060a'), ('\u060c', '\u060d'), - ('\u061b', '\u061f'), ('\u066a', '\u066d'), - ('\u06d4', '\u06d4'), ('\u0700', '\u070d'), - ('\u07f7', '\u07f9'), ('\u0830', '\u083e'), - ('\u085e', '\u085e'), ('\u0964', '\u0965'), - ('\u0970', '\u0970'), ('\u0af0', '\u0af0'), - ('\u0df4', '\u0df4'), ('\u0e4f', '\u0e4f'), - ('\u0e5a', '\u0e5b'), ('\u0f04', '\u0f12'), - ('\u0f14', '\u0f14'), ('\u0f85', '\u0f85'), - ('\u0fd0', '\u0fd4'), ('\u0fd9', '\u0fda'), - ('\u104a', '\u104f'), ('\u10fb', '\u10fb'), - ('\u1360', '\u1368'), ('\u166d', '\u166e'), - ('\u16eb', '\u16ed'), ('\u1735', '\u1736'), - ('\u17d4', '\u17d6'), ('\u17d8', '\u17da'), - ('\u1800', '\u1805'), ('\u1807', '\u180a'), - ('\u1944', '\u1945'), ('\u1a1e', '\u1a1f'), - ('\u1aa0', '\u1aa6'), ('\u1aa8', '\u1aad'), - ('\u1b5a', '\u1b60'), ('\u1bfc', '\u1bff'), - ('\u1c3b', '\u1c3f'), ('\u1c7e', '\u1cc7'), - ('\u1cd3', '\u1cd3'), ('\u2016', '\u2017'), - ('\u2020', '\u2027'), ('\u2030', '\u2038'), - ('\u203b', '\u203e'), ('\u2041', '\u2043'), - ('\u2047', '\u2051'), ('\u2053', '\u2053'), - ('\u2055', '\u205e'), ('\u2cf9', '\u2cfc'), - ('\u2cfe', '\u2cff'), ('\u2d70', '\u2d70'), - ('\u2e00', '\u2e01'), ('\u2e06', '\u2e08'), - ('\u2e0b', '\u2e0b'), ('\u2e0e', '\u2e16'), - ('\u2e18', '\u2e19'), ('\u2e1b', '\u2e1b'), - ('\u2e1e', '\u2e1f'), ('\u2e2a', '\u2e2e'), - ('\u2e30', '\u2e39'), ('\u3001', '\u3003'), - ('\u303d', '\u303d'), ('\u30fb', '\u30fb'), - ('\ua4fe', '\ua4ff'), ('\ua60d', '\ua60f'), - ('\ua673', '\ua673'), ('\ua67e', '\ua67e'), - ('\ua6f2', '\ua6f7'), ('\ua874', '\ua877'), - ('\ua8ce', '\ua8cf'), ('\ua8f8', '\ua8fa'), - ('\ua92e', '\ua92f'), ('\ua95f', '\ua95f'), - ('\ua9c1', '\ua9cd'), ('\ua9de', '\ua9df'), - ('\uaa5c', '\uaa5f'), ('\uaade', '\uaadf'), - ('\uaaf0', '\uaaf1'), ('\uabeb', '\uabeb'), - ('\ufe10', '\ufe16'), ('\ufe19', '\ufe19'), - ('\ufe30', '\ufe30'), ('\ufe45', '\ufe46'), - ('\ufe49', '\ufe4c'), ('\ufe50', '\ufe57'), - ('\ufe5f', '\ufe61'), ('\ufe68', '\ufe68'), - ('\ufe6a', '\ufe6b'), ('\uff01', '\uff03'), - ('\uff05', '\uff07'), ('\uff0a', '\uff0a'), - ('\uff0c', '\uff0c'), ('\uff0e', '\uff0f'), - ('\uff1a', '\uff1b'), ('\uff1f', '\uff20'), - ('\uff3c', '\uff3c'), ('\uff61', '\uff61'), - ('\uff64', '\uff65'), ('\U00010100', '\U00010102'), - ('\U0001039f', '\U0001039f'), ('\U000103d0', '\U000103d0'), - ('\U00010857', '\U00010857'), ('\U0001091f', '\U0001091f'), - ('\U0001093f', '\U0001093f'), ('\U00010a50', '\U00010a58'), - ('\U00010a7f', '\U00010a7f'), ('\U00010b39', '\U00010b3f'), - ('\U00011047', '\U0001104d'), ('\U000110bb', '\U000110bc'), - ('\U000110be', '\U000110c1'), ('\U00011140', '\U00011143'), - ('\U000111c5', '\U000111c8'), ('\U00012470', '\U00012473') - ]; - - pub fn Po(c: char) -> bool { - bsearch_range_table(c, Po_table) - } - - static Ps_table : &'static [(char,char)] = &[ - ('\x28', '\x28'), ('\x5b', '\x5b'), - ('\x7b', '\x7b'), ('\u0f3a', '\u0f3a'), - ('\u0f3c', '\u0f3c'), ('\u169b', '\u169b'), - ('\u201a', '\u201a'), ('\u201e', '\u201e'), - ('\u2045', '\u2045'), ('\u207d', '\u207d'), - ('\u208d', '\u208d'), ('\u2329', '\u2329'), - ('\u2768', '\u2768'), ('\u276a', '\u276a'), - ('\u276c', '\u276c'), ('\u276e', '\u276e'), - ('\u2770', '\u2770'), ('\u2772', '\u2772'), - ('\u2774', '\u2774'), ('\u27c5', '\u27c5'), - ('\u27e6', '\u27e6'), ('\u27e8', '\u27e8'), - ('\u27ea', '\u27ea'), ('\u27ec', '\u27ec'), - ('\u27ee', '\u27ee'), ('\u2983', '\u2983'), - ('\u2985', '\u2985'), ('\u2987', '\u2987'), - ('\u2989', '\u2989'), ('\u298b', '\u298b'), - ('\u298d', '\u298d'), ('\u298f', '\u298f'), - ('\u2991', '\u2991'), ('\u2993', '\u2993'), - ('\u2995', '\u2995'), ('\u2997', '\u2997'), - ('\u29d8', '\u29d8'), ('\u29da', '\u29da'), - ('\u29fc', '\u29fc'), ('\u2e22', '\u2e22'), - ('\u2e24', '\u2e24'), ('\u2e26', '\u2e26'), - ('\u2e28', '\u2e28'), ('\u3008', '\u3008'), - ('\u300a', '\u300a'), ('\u300c', '\u300c'), - ('\u300e', '\u300e'), ('\u3010', '\u3010'), - ('\u3014', '\u3014'), ('\u3016', '\u3016'), - ('\u3018', '\u3018'), ('\u301a', '\u301a'), - ('\u301d', '\u301d'), ('\ufd3e', '\ufd3e'), - ('\ufe17', '\ufe17'), ('\ufe35', '\ufe35'), - ('\ufe37', '\ufe37'), ('\ufe39', '\ufe39'), - ('\ufe3b', '\ufe3b'), ('\ufe3d', '\ufe3d'), - ('\ufe3f', '\ufe3f'), ('\ufe41', '\ufe41'), - ('\ufe43', '\ufe43'), ('\ufe47', '\ufe47'), - ('\ufe59', '\ufe59'), ('\ufe5b', '\ufe5b'), - ('\ufe5d', '\ufe5d'), ('\uff08', '\uff08'), - ('\uff3b', '\uff3b'), ('\uff5b', '\uff5b'), - ('\uff5f', '\uff5f'), ('\uff62', '\uff62') - ]; - - pub fn Ps(c: char) -> bool { - bsearch_range_table(c, Ps_table) - } - - static Sc_table : &'static [(char,char)] = &[ - ('\x24', '\x24'), ('\xa2', '\xa5'), - ('\u058f', '\u058f'), ('\u060b', '\u060b'), - ('\u09f2', '\u09f3'), ('\u09fb', '\u09fb'), - ('\u0af1', '\u0af1'), ('\u0bf9', '\u0bf9'), - ('\u0e3f', '\u0e3f'), ('\u17db', '\u17db'), - ('\u20a0', '\u20ba'), ('\ua838', '\ua838'), - ('\ufdfc', '\ufdfc'), ('\ufe69', '\ufe69'), - ('\uff04', '\uff04'), ('\uffe0', '\uffe1'), - ('\uffe5', '\uffe6') - ]; - - pub fn Sc(c: char) -> bool { - bsearch_range_table(c, Sc_table) - } - - static Sk_table : &'static [(char,char)] = &[ - ('\x5e', '\x5e'), ('\x60', '\x60'), - ('\xa8', '\xa8'), ('\xaf', '\xaf'), - ('\xb4', '\xb4'), ('\xb8', '\xb8'), - ('\u02c2', '\u02c5'), ('\u02d2', '\u02df'), - ('\u02e5', '\u02eb'), ('\u02ed', '\u02ed'), - ('\u02ef', '\u02ff'), ('\u0375', '\u0375'), - ('\u0384', '\u0385'), ('\u1fbd', '\u1fbd'), - ('\u1fbf', '\u1fc1'), ('\u1fcd', '\u1fcf'), - ('\u1fdd', '\u1fdf'), ('\u1fed', '\u1fef'), - ('\u1ffd', '\u1ffe'), ('\u309b', '\u309c'), - ('\ua700', '\ua716'), ('\ua720', '\ua721'), - ('\ua789', '\ua78a'), ('\ufbb2', '\ufbc1'), - ('\uff3e', '\uff3e'), ('\uff40', '\uff40'), - ('\uffe3', '\uffe3') - ]; - - pub fn Sk(c: char) -> bool { - bsearch_range_table(c, Sk_table) - } - - static Sm_table : &'static [(char,char)] = &[ - ('\x2b', '\x2b'), ('\x3c', '\x3e'), - ('\x7c', '\x7c'), ('\x7e', '\x7e'), - ('\xac', '\xac'), ('\xb1', '\xb1'), - ('\xd7', '\xd7'), ('\xf7', '\xf7'), - ('\u03f6', '\u03f6'), ('\u0606', '\u0608'), - ('\u2044', '\u2044'), ('\u2052', '\u2052'), - ('\u207a', '\u207c'), ('\u208a', '\u208c'), - ('\u2118', '\u2118'), ('\u2140', '\u2144'), - ('\u214b', '\u214b'), ('\u2190', '\u2194'), - ('\u219a', '\u219b'), ('\u21a0', '\u21a0'), - ('\u21a3', '\u21a3'), ('\u21a6', '\u21a6'), - ('\u21ae', '\u21ae'), ('\u21ce', '\u21cf'), - ('\u21d2', '\u21d2'), ('\u21d4', '\u21d4'), - ('\u21f4', '\u22ff'), ('\u2308', '\u230b'), - ('\u2320', '\u2321'), ('\u237c', '\u237c'), - ('\u239b', '\u23b3'), ('\u23dc', '\u23e1'), - ('\u25b7', '\u25b7'), ('\u25c1', '\u25c1'), - ('\u25f8', '\u25ff'), ('\u266f', '\u266f'), - ('\u27c0', '\u27c4'), ('\u27c7', '\u27e5'), - ('\u27f0', '\u27ff'), ('\u2900', '\u2982'), - ('\u2999', '\u29d7'), ('\u29dc', '\u29fb'), - ('\u29fe', '\u2aff'), ('\u2b30', '\u2b44'), - ('\u2b47', '\u2b4c'), ('\ufb29', '\ufb29'), - ('\ufe62', '\ufe62'), ('\ufe64', '\ufe66'), - ('\uff0b', '\uff0b'), ('\uff1c', '\uff1e'), - ('\uff5c', '\uff5c'), ('\uff5e', '\uff5e'), - ('\uffe2', '\uffe2'), ('\uffe9', '\uffec'), - ('\U0001d6c1', '\U0001d6c1'), ('\U0001d6db', '\U0001d6db'), - ('\U0001d6fb', '\U0001d6fb'), ('\U0001d715', '\U0001d715'), - ('\U0001d735', '\U0001d735'), ('\U0001d74f', '\U0001d74f'), - ('\U0001d76f', '\U0001d76f'), ('\U0001d789', '\U0001d789'), - ('\U0001d7a9', '\U0001d7a9'), ('\U0001d7c3', '\U0001d7c3'), - ('\U0001eef0', '\U0001eef1') - ]; - - pub fn Sm(c: char) -> bool { - bsearch_range_table(c, Sm_table) - } - - static So_table : &'static [(char,char)] = &[ - ('\xa6', '\xa6'), ('\xa9', '\xa9'), - ('\xae', '\xae'), ('\xb0', '\xb0'), - ('\u0482', '\u0482'), ('\u060e', '\u060f'), - ('\u06de', '\u06de'), ('\u06e9', '\u06e9'), - ('\u06fd', '\u06fe'), ('\u07f6', '\u07f6'), - ('\u09fa', '\u09fa'), ('\u0b70', '\u0b70'), - ('\u0bf3', '\u0bf8'), ('\u0bfa', '\u0bfa'), - ('\u0c7f', '\u0c7f'), ('\u0d79', '\u0d79'), - ('\u0f01', '\u0f03'), ('\u0f13', '\u0f13'), - ('\u0f15', '\u0f17'), ('\u0f1a', '\u0f1f'), - ('\u0f34', '\u0f34'), ('\u0f36', '\u0f36'), - ('\u0f38', '\u0f38'), ('\u0fbe', '\u0fc5'), - ('\u0fc7', '\u0fcf'), ('\u0fd5', '\u0fd8'), - ('\u109e', '\u109f'), ('\u1390', '\u1399'), - ('\u1940', '\u1940'), ('\u19de', '\u19ff'), - ('\u1b61', '\u1b6a'), ('\u1b74', '\u1b7c'), - ('\u2100', '\u2101'), ('\u2103', '\u2106'), - ('\u2108', '\u2109'), ('\u2114', '\u2114'), - ('\u2116', '\u2117'), ('\u211e', '\u2123'), - ('\u2125', '\u2125'), ('\u2127', '\u2127'), - ('\u2129', '\u2129'), ('\u212e', '\u212e'), - ('\u213a', '\u213b'), ('\u214a', '\u214a'), - ('\u214c', '\u214d'), ('\u214f', '\u214f'), - ('\u2195', '\u2199'), ('\u219c', '\u219f'), - ('\u21a1', '\u21a2'), ('\u21a4', '\u21a5'), - ('\u21a7', '\u21ad'), ('\u21af', '\u21cd'), - ('\u21d0', '\u21d1'), ('\u21d3', '\u21d3'), - ('\u21d5', '\u21f3'), ('\u2300', '\u2307'), - ('\u230c', '\u231f'), ('\u2322', '\u2328'), - ('\u232b', '\u237b'), ('\u237d', '\u239a'), - ('\u23b4', '\u23db'), ('\u23e2', '\u244a'), - ('\u249c', '\u24e9'), ('\u2500', '\u25b6'), - ('\u25b8', '\u25c0'), ('\u25c2', '\u25f7'), - ('\u2600', '\u266e'), ('\u2670', '\u2767'), - ('\u2794', '\u27bf'), ('\u2800', '\u28ff'), - ('\u2b00', '\u2b2f'), ('\u2b45', '\u2b46'), - ('\u2b50', '\u2b59'), ('\u2ce5', '\u2cea'), - ('\u2e80', '\u2ffb'), ('\u3004', '\u3004'), - ('\u3012', '\u3013'), ('\u3020', '\u3020'), - ('\u3036', '\u3037'), ('\u303e', '\u303f'), - ('\u3190', '\u3191'), ('\u3196', '\u319f'), - ('\u31c0', '\u31e3'), ('\u3200', '\u321e'), - ('\u322a', '\u3247'), ('\u3250', '\u3250'), - ('\u3260', '\u327f'), ('\u328a', '\u32b0'), - ('\u32c0', '\u33ff'), ('\u4dc0', '\u4dff'), - ('\ua490', '\ua4c6'), ('\ua828', '\ua82b'), - ('\ua836', '\ua837'), ('\ua839', '\ua839'), - ('\uaa77', '\uaa79'), ('\ufdfd', '\ufdfd'), - ('\uffe4', '\uffe4'), ('\uffe8', '\uffe8'), - ('\uffed', '\uffee'), ('\ufffc', '\ufffd'), - ('\U00010137', '\U0001013f'), ('\U00010179', '\U00010189'), - ('\U00010190', '\U000101fc'), ('\U0001d000', '\U0001d164'), - ('\U0001d16a', '\U0001d16c'), ('\U0001d183', '\U0001d184'), - ('\U0001d18c', '\U0001d1a9'), ('\U0001d1ae', '\U0001d241'), - ('\U0001d245', '\U0001d356'), ('\U0001f000', '\U0001f0df'), - ('\U0001f110', '\U0001f773') - ]; - - pub fn So(c: char) -> bool { - bsearch_range_table(c, So_table) - } - - static Zl_table : &'static [(char,char)] = &[ - ('\u2028', '\u2028') - ]; - - pub fn Zl(c: char) -> bool { - bsearch_range_table(c, Zl_table) - } - - static Zp_table : &'static [(char,char)] = &[ - ('\u2029', '\u2029') - ]; - - pub fn Zp(c: char) -> bool { - bsearch_range_table(c, Zp_table) - } - - static Zs_table : &'static [(char,char)] = &[ - ('\x20', '\x20'), ('\xa0', '\xa0'), - ('\u1680', '\u1680'), ('\u180e', '\u180e'), - ('\u2000', '\u200a'), ('\u202f', '\u202f'), - ('\u205f', '\u205f'), ('\u3000', '\u3000') - ]; - - pub fn Zs(c: char) -> bool { - bsearch_range_table(c, Zs_table) - } - -} - -pub mod derived_property { - fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { - use cmp::{Equal, Less, Greater}; - use vec::bsearch; - use option::None; - (do bsearch(r) |&(lo,hi)| { cond!( - (lo <= c && c <= hi) { Equal } - (hi < c) { Less } - _ { Greater } - )}) != None - } - - - static Alphabetic_table : &'static [(char,char)] = &[ - ('\x41', '\x5a'), ('\x61', '\x7a'), - ('\xaa', '\xaa'), ('\xb5', '\xb5'), - ('\xba', '\xba'), ('\xc0', '\xd6'), - ('\xd8', '\xf6'), ('\xf8', '\u01ba'), - ('\u01bb', '\u01bb'), ('\u01bc', '\u01bf'), - ('\u01c0', '\u01c3'), ('\u01c4', '\u0293'), - ('\u0294', '\u0294'), ('\u0295', '\u02af'), - ('\u02b0', '\u02c1'), ('\u02c6', '\u02d1'), - ('\u02e0', '\u02e4'), ('\u02ec', '\u02ec'), - ('\u02ee', '\u02ee'), ('\u0345', '\u0345'), - ('\u0370', '\u0373'), ('\u0374', '\u0374'), - ('\u0376', '\u0377'), ('\u037a', '\u037a'), - ('\u037b', '\u037d'), ('\u0386', '\u0386'), - ('\u0388', '\u038a'), ('\u038c', '\u038c'), - ('\u038e', '\u03a1'), ('\u03a3', '\u03f5'), - ('\u03f7', '\u0481'), ('\u048a', '\u0527'), - ('\u0531', '\u0556'), ('\u0559', '\u0559'), - ('\u0561', '\u0587'), ('\u05b0', '\u05bd'), - ('\u05bf', '\u05bf'), ('\u05c1', '\u05c2'), - ('\u05c4', '\u05c5'), ('\u05c7', '\u05c7'), - ('\u05d0', '\u05ea'), ('\u05f0', '\u05f2'), - ('\u0610', '\u061a'), ('\u0620', '\u063f'), - ('\u0640', '\u0640'), ('\u0641', '\u064a'), - ('\u064b', '\u0657'), ('\u0659', '\u065f'), - ('\u066e', '\u066f'), ('\u0670', '\u0670'), - ('\u0671', '\u06d3'), ('\u06d5', '\u06d5'), - ('\u06d6', '\u06dc'), ('\u06e1', '\u06e4'), - ('\u06e5', '\u06e6'), ('\u06e7', '\u06e8'), - ('\u06ed', '\u06ed'), ('\u06ee', '\u06ef'), - ('\u06fa', '\u06fc'), ('\u06ff', '\u06ff'), - ('\u0710', '\u0710'), ('\u0711', '\u0711'), - ('\u0712', '\u072f'), ('\u0730', '\u073f'), - ('\u074d', '\u07a5'), ('\u07a6', '\u07b0'), - ('\u07b1', '\u07b1'), ('\u07ca', '\u07ea'), - ('\u07f4', '\u07f5'), ('\u07fa', '\u07fa'), - ('\u0800', '\u0815'), ('\u0816', '\u0817'), - ('\u081a', '\u081a'), ('\u081b', '\u0823'), - ('\u0824', '\u0824'), ('\u0825', '\u0827'), - ('\u0828', '\u0828'), ('\u0829', '\u082c'), - ('\u0840', '\u0858'), ('\u08a0', '\u08a0'), - ('\u08a2', '\u08ac'), ('\u08e4', '\u08e9'), - ('\u08f0', '\u08fe'), ('\u0900', '\u0902'), - ('\u0903', '\u0903'), ('\u0904', '\u0939'), - ('\u093a', '\u093a'), ('\u093b', '\u093b'), - ('\u093d', '\u093d'), ('\u093e', '\u0940'), - ('\u0941', '\u0948'), ('\u0949', '\u094c'), - ('\u094e', '\u094f'), ('\u0950', '\u0950'), - ('\u0955', '\u0957'), ('\u0958', '\u0961'), - ('\u0962', '\u0963'), ('\u0971', '\u0971'), - ('\u0972', '\u0977'), ('\u0979', '\u097f'), - ('\u0981', '\u0981'), ('\u0982', '\u0983'), - ('\u0985', '\u098c'), ('\u098f', '\u0990'), - ('\u0993', '\u09a8'), ('\u09aa', '\u09b0'), - ('\u09b2', '\u09b2'), ('\u09b6', '\u09b9'), - ('\u09bd', '\u09bd'), ('\u09be', '\u09c0'), - ('\u09c1', '\u09c4'), ('\u09c7', '\u09c8'), - ('\u09cb', '\u09cc'), ('\u09ce', '\u09ce'), - ('\u09d7', '\u09d7'), ('\u09dc', '\u09dd'), - ('\u09df', '\u09e1'), ('\u09e2', '\u09e3'), - ('\u09f0', '\u09f1'), ('\u0a01', '\u0a02'), - ('\u0a03', '\u0a03'), ('\u0a05', '\u0a0a'), - ('\u0a0f', '\u0a10'), ('\u0a13', '\u0a28'), - ('\u0a2a', '\u0a30'), ('\u0a32', '\u0a33'), - ('\u0a35', '\u0a36'), ('\u0a38', '\u0a39'), - ('\u0a3e', '\u0a40'), ('\u0a41', '\u0a42'), - ('\u0a47', '\u0a48'), ('\u0a4b', '\u0a4c'), - ('\u0a51', '\u0a51'), ('\u0a59', '\u0a5c'), - ('\u0a5e', '\u0a5e'), ('\u0a70', '\u0a71'), - ('\u0a72', '\u0a74'), ('\u0a75', '\u0a75'), - ('\u0a81', '\u0a82'), ('\u0a83', '\u0a83'), - ('\u0a85', '\u0a8d'), ('\u0a8f', '\u0a91'), - ('\u0a93', '\u0aa8'), ('\u0aaa', '\u0ab0'), - ('\u0ab2', '\u0ab3'), ('\u0ab5', '\u0ab9'), - ('\u0abd', '\u0abd'), ('\u0abe', '\u0ac0'), - ('\u0ac1', '\u0ac5'), ('\u0ac7', '\u0ac8'), - ('\u0ac9', '\u0ac9'), ('\u0acb', '\u0acc'), - ('\u0ad0', '\u0ad0'), ('\u0ae0', '\u0ae1'), - ('\u0ae2', '\u0ae3'), ('\u0b01', '\u0b01'), - ('\u0b02', '\u0b03'), ('\u0b05', '\u0b0c'), - ('\u0b0f', '\u0b10'), ('\u0b13', '\u0b28'), - ('\u0b2a', '\u0b30'), ('\u0b32', '\u0b33'), - ('\u0b35', '\u0b39'), ('\u0b3d', '\u0b3d'), - ('\u0b3e', '\u0b3e'), ('\u0b3f', '\u0b3f'), - ('\u0b40', '\u0b40'), ('\u0b41', '\u0b44'), - ('\u0b47', '\u0b48'), ('\u0b4b', '\u0b4c'), - ('\u0b56', '\u0b56'), ('\u0b57', '\u0b57'), - ('\u0b5c', '\u0b5d'), ('\u0b5f', '\u0b61'), - ('\u0b62', '\u0b63'), ('\u0b71', '\u0b71'), - ('\u0b82', '\u0b82'), ('\u0b83', '\u0b83'), - ('\u0b85', '\u0b8a'), ('\u0b8e', '\u0b90'), - ('\u0b92', '\u0b95'), ('\u0b99', '\u0b9a'), - ('\u0b9c', '\u0b9c'), ('\u0b9e', '\u0b9f'), - ('\u0ba3', '\u0ba4'), ('\u0ba8', '\u0baa'), - ('\u0bae', '\u0bb9'), ('\u0bbe', '\u0bbf'), - ('\u0bc0', '\u0bc0'), ('\u0bc1', '\u0bc2'), - ('\u0bc6', '\u0bc8'), ('\u0bca', '\u0bcc'), - ('\u0bd0', '\u0bd0'), ('\u0bd7', '\u0bd7'), - ('\u0c01', '\u0c03'), ('\u0c05', '\u0c0c'), - ('\u0c0e', '\u0c10'), ('\u0c12', '\u0c28'), - ('\u0c2a', '\u0c33'), ('\u0c35', '\u0c39'), - ('\u0c3d', '\u0c3d'), ('\u0c3e', '\u0c40'), - ('\u0c41', '\u0c44'), ('\u0c46', '\u0c48'), - ('\u0c4a', '\u0c4c'), ('\u0c55', '\u0c56'), - ('\u0c58', '\u0c59'), ('\u0c60', '\u0c61'), - ('\u0c62', '\u0c63'), ('\u0c82', '\u0c83'), - ('\u0c85', '\u0c8c'), ('\u0c8e', '\u0c90'), - ('\u0c92', '\u0ca8'), ('\u0caa', '\u0cb3'), - ('\u0cb5', '\u0cb9'), ('\u0cbd', '\u0cbd'), - ('\u0cbe', '\u0cbe'), ('\u0cbf', '\u0cbf'), - ('\u0cc0', '\u0cc4'), ('\u0cc6', '\u0cc6'), - ('\u0cc7', '\u0cc8'), ('\u0cca', '\u0ccb'), - ('\u0ccc', '\u0ccc'), ('\u0cd5', '\u0cd6'), - ('\u0cde', '\u0cde'), ('\u0ce0', '\u0ce1'), - ('\u0ce2', '\u0ce3'), ('\u0cf1', '\u0cf2'), - ('\u0d02', '\u0d03'), ('\u0d05', '\u0d0c'), - ('\u0d0e', '\u0d10'), ('\u0d12', '\u0d3a'), - ('\u0d3d', '\u0d3d'), ('\u0d3e', '\u0d40'), - ('\u0d41', '\u0d44'), ('\u0d46', '\u0d48'), - ('\u0d4a', '\u0d4c'), ('\u0d4e', '\u0d4e'), - ('\u0d57', '\u0d57'), ('\u0d60', '\u0d61'), - ('\u0d62', '\u0d63'), ('\u0d7a', '\u0d7f'), - ('\u0d82', '\u0d83'), ('\u0d85', '\u0d96'), - ('\u0d9a', '\u0db1'), ('\u0db3', '\u0dbb'), - ('\u0dbd', '\u0dbd'), ('\u0dc0', '\u0dc6'), - ('\u0dcf', '\u0dd1'), ('\u0dd2', '\u0dd4'), - ('\u0dd6', '\u0dd6'), ('\u0dd8', '\u0ddf'), - ('\u0df2', '\u0df3'), ('\u0e01', '\u0e30'), - ('\u0e31', '\u0e31'), ('\u0e32', '\u0e33'), - ('\u0e34', '\u0e3a'), ('\u0e40', '\u0e45'), - ('\u0e46', '\u0e46'), ('\u0e4d', '\u0e4d'), - ('\u0e81', '\u0e82'), ('\u0e84', '\u0e84'), - ('\u0e87', '\u0e88'), ('\u0e8a', '\u0e8a'), - ('\u0e8d', '\u0e8d'), ('\u0e94', '\u0e97'), - ('\u0e99', '\u0e9f'), ('\u0ea1', '\u0ea3'), - ('\u0ea5', '\u0ea5'), ('\u0ea7', '\u0ea7'), - ('\u0eaa', '\u0eab'), ('\u0ead', '\u0eb0'), - ('\u0eb1', '\u0eb1'), ('\u0eb2', '\u0eb3'), - ('\u0eb4', '\u0eb9'), ('\u0ebb', '\u0ebc'), - ('\u0ebd', '\u0ebd'), ('\u0ec0', '\u0ec4'), - ('\u0ec6', '\u0ec6'), ('\u0ecd', '\u0ecd'), - ('\u0edc', '\u0edf'), ('\u0f00', '\u0f00'), - ('\u0f40', '\u0f47'), ('\u0f49', '\u0f6c'), - ('\u0f71', '\u0f7e'), ('\u0f7f', '\u0f7f'), - ('\u0f80', '\u0f81'), ('\u0f88', '\u0f8c'), - ('\u0f8d', '\u0f97'), ('\u0f99', '\u0fbc'), - ('\u1000', '\u102a'), ('\u102b', '\u102c'), - ('\u102d', '\u1030'), ('\u1031', '\u1031'), - ('\u1032', '\u1036'), ('\u1038', '\u1038'), - ('\u103b', '\u103c'), ('\u103d', '\u103e'), - ('\u103f', '\u103f'), ('\u1050', '\u1055'), - ('\u1056', '\u1057'), ('\u1058', '\u1059'), - ('\u105a', '\u105d'), ('\u105e', '\u1060'), - ('\u1061', '\u1061'), ('\u1062', '\u1062'), - ('\u1065', '\u1066'), ('\u1067', '\u1068'), - ('\u106e', '\u1070'), ('\u1071', '\u1074'), - ('\u1075', '\u1081'), ('\u1082', '\u1082'), - ('\u1083', '\u1084'), ('\u1085', '\u1086'), - ('\u108e', '\u108e'), ('\u109c', '\u109c'), - ('\u109d', '\u109d'), ('\u10a0', '\u10c5'), - ('\u10c7', '\u10c7'), ('\u10cd', '\u10cd'), - ('\u10d0', '\u10fa'), ('\u10fc', '\u10fc'), - ('\u10fd', '\u1248'), ('\u124a', '\u124d'), - ('\u1250', '\u1256'), ('\u1258', '\u1258'), - ('\u125a', '\u125d'), ('\u1260', '\u1288'), - ('\u128a', '\u128d'), ('\u1290', '\u12b0'), - ('\u12b2', '\u12b5'), ('\u12b8', '\u12be'), - ('\u12c0', '\u12c0'), ('\u12c2', '\u12c5'), - ('\u12c8', '\u12d6'), ('\u12d8', '\u1310'), - ('\u1312', '\u1315'), ('\u1318', '\u135a'), - ('\u135f', '\u135f'), ('\u1380', '\u138f'), - ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), - ('\u166f', '\u167f'), ('\u1681', '\u169a'), - ('\u16a0', '\u16ea'), ('\u16ee', '\u16f0'), - ('\u1700', '\u170c'), ('\u170e', '\u1711'), - ('\u1712', '\u1713'), ('\u1720', '\u1731'), - ('\u1732', '\u1733'), ('\u1740', '\u1751'), - ('\u1752', '\u1753'), ('\u1760', '\u176c'), - ('\u176e', '\u1770'), ('\u1772', '\u1773'), - ('\u1780', '\u17b3'), ('\u17b6', '\u17b6'), - ('\u17b7', '\u17bd'), ('\u17be', '\u17c5'), - ('\u17c6', '\u17c6'), ('\u17c7', '\u17c8'), - ('\u17d7', '\u17d7'), ('\u17dc', '\u17dc'), - ('\u1820', '\u1842'), ('\u1843', '\u1843'), - ('\u1844', '\u1877'), ('\u1880', '\u18a8'), - ('\u18a9', '\u18a9'), ('\u18aa', '\u18aa'), - ('\u18b0', '\u18f5'), ('\u1900', '\u191c'), - ('\u1920', '\u1922'), ('\u1923', '\u1926'), - ('\u1927', '\u1928'), ('\u1929', '\u192b'), - ('\u1930', '\u1931'), ('\u1932', '\u1932'), - ('\u1933', '\u1938'), ('\u1950', '\u196d'), - ('\u1970', '\u1974'), ('\u1980', '\u19ab'), - ('\u19b0', '\u19c0'), ('\u19c1', '\u19c7'), - ('\u19c8', '\u19c9'), ('\u1a00', '\u1a16'), - ('\u1a17', '\u1a18'), ('\u1a19', '\u1a1b'), - ('\u1a20', '\u1a54'), ('\u1a55', '\u1a55'), - ('\u1a56', '\u1a56'), ('\u1a57', '\u1a57'), - ('\u1a58', '\u1a5e'), ('\u1a61', '\u1a61'), - ('\u1a62', '\u1a62'), ('\u1a63', '\u1a64'), - ('\u1a65', '\u1a6c'), ('\u1a6d', '\u1a72'), - ('\u1a73', '\u1a74'), ('\u1aa7', '\u1aa7'), - ('\u1b00', '\u1b03'), ('\u1b04', '\u1b04'), - ('\u1b05', '\u1b33'), ('\u1b35', '\u1b35'), - ('\u1b36', '\u1b3a'), ('\u1b3b', '\u1b3b'), - ('\u1b3c', '\u1b3c'), ('\u1b3d', '\u1b41'), - ('\u1b42', '\u1b42'), ('\u1b43', '\u1b43'), - ('\u1b45', '\u1b4b'), ('\u1b80', '\u1b81'), - ('\u1b82', '\u1b82'), ('\u1b83', '\u1ba0'), - ('\u1ba1', '\u1ba1'), ('\u1ba2', '\u1ba5'), - ('\u1ba6', '\u1ba7'), ('\u1ba8', '\u1ba9'), - ('\u1bac', '\u1bad'), ('\u1bae', '\u1baf'), - ('\u1bba', '\u1be5'), ('\u1be7', '\u1be7'), - ('\u1be8', '\u1be9'), ('\u1bea', '\u1bec'), - ('\u1bed', '\u1bed'), ('\u1bee', '\u1bee'), - ('\u1bef', '\u1bf1'), ('\u1c00', '\u1c23'), - ('\u1c24', '\u1c2b'), ('\u1c2c', '\u1c33'), - ('\u1c34', '\u1c35'), ('\u1c4d', '\u1c4f'), - ('\u1c5a', '\u1c77'), ('\u1c78', '\u1c7d'), - ('\u1ce9', '\u1cec'), ('\u1cee', '\u1cf1'), - ('\u1cf2', '\u1cf3'), ('\u1cf5', '\u1cf6'), - ('\u1d00', '\u1d2b'), ('\u1d2c', '\u1d6a'), - ('\u1d6b', '\u1d77'), ('\u1d78', '\u1d78'), - ('\u1d79', '\u1d9a'), ('\u1d9b', '\u1dbf'), - ('\u1e00', '\u1f15'), ('\u1f18', '\u1f1d'), - ('\u1f20', '\u1f45'), ('\u1f48', '\u1f4d'), - ('\u1f50', '\u1f57'), ('\u1f59', '\u1f59'), - ('\u1f5b', '\u1f5b'), ('\u1f5d', '\u1f5d'), - ('\u1f5f', '\u1f7d'), ('\u1f80', '\u1fb4'), - ('\u1fb6', '\u1fbc'), ('\u1fbe', '\u1fbe'), - ('\u1fc2', '\u1fc4'), ('\u1fc6', '\u1fcc'), - ('\u1fd0', '\u1fd3'), ('\u1fd6', '\u1fdb'), - ('\u1fe0', '\u1fec'), ('\u1ff2', '\u1ff4'), - ('\u1ff6', '\u1ffc'), ('\u2071', '\u2071'), - ('\u207f', '\u207f'), ('\u2090', '\u209c'), - ('\u2102', '\u2102'), ('\u2107', '\u2107'), - ('\u210a', '\u2113'), ('\u2115', '\u2115'), - ('\u2119', '\u211d'), ('\u2124', '\u2124'), - ('\u2126', '\u2126'), ('\u2128', '\u2128'), - ('\u212a', '\u212d'), ('\u212f', '\u2134'), - ('\u2135', '\u2138'), ('\u2139', '\u2139'), - ('\u213c', '\u213f'), ('\u2145', '\u2149'), - ('\u214e', '\u214e'), ('\u2160', '\u2182'), - ('\u2183', '\u2184'), ('\u2185', '\u2188'), - ('\u24b6', '\u24e9'), ('\u2c00', '\u2c2e'), - ('\u2c30', '\u2c5e'), ('\u2c60', '\u2c7b'), - ('\u2c7c', '\u2c7d'), ('\u2c7e', '\u2ce4'), - ('\u2ceb', '\u2cee'), ('\u2cf2', '\u2cf3'), - ('\u2d00', '\u2d25'), ('\u2d27', '\u2d27'), - ('\u2d2d', '\u2d2d'), ('\u2d30', '\u2d67'), - ('\u2d6f', '\u2d6f'), ('\u2d80', '\u2d96'), - ('\u2da0', '\u2da6'), ('\u2da8', '\u2dae'), - ('\u2db0', '\u2db6'), ('\u2db8', '\u2dbe'), - ('\u2dc0', '\u2dc6'), ('\u2dc8', '\u2dce'), - ('\u2dd0', '\u2dd6'), ('\u2dd8', '\u2dde'), - ('\u2de0', '\u2dff'), ('\u2e2f', '\u2e2f'), - ('\u3005', '\u3005'), ('\u3006', '\u3006'), - ('\u3007', '\u3007'), ('\u3021', '\u3029'), - ('\u3031', '\u3035'), ('\u3038', '\u303a'), - ('\u303b', '\u303b'), ('\u303c', '\u303c'), - ('\u3041', '\u3096'), ('\u309d', '\u309e'), - ('\u309f', '\u309f'), ('\u30a1', '\u30fa'), - ('\u30fc', '\u30fe'), ('\u30ff', '\u30ff'), - ('\u3105', '\u312d'), ('\u3131', '\u318e'), - ('\u31a0', '\u31ba'), ('\u31f0', '\u31ff'), - ('\u3400', '\u4db5'), ('\u4e00', '\u9fcc'), - ('\ua000', '\ua014'), ('\ua015', '\ua015'), - ('\ua016', '\ua48c'), ('\ua4d0', '\ua4f7'), - ('\ua4f8', '\ua4fd'), ('\ua500', '\ua60b'), - ('\ua60c', '\ua60c'), ('\ua610', '\ua61f'), - ('\ua62a', '\ua62b'), ('\ua640', '\ua66d'), - ('\ua66e', '\ua66e'), ('\ua674', '\ua67b'), - ('\ua67f', '\ua67f'), ('\ua680', '\ua697'), - ('\ua69f', '\ua69f'), ('\ua6a0', '\ua6e5'), - ('\ua6e6', '\ua6ef'), ('\ua717', '\ua71f'), - ('\ua722', '\ua76f'), ('\ua770', '\ua770'), - ('\ua771', '\ua787'), ('\ua788', '\ua788'), - ('\ua78b', '\ua78e'), ('\ua790', '\ua793'), - ('\ua7a0', '\ua7aa'), ('\ua7f8', '\ua7f9'), - ('\ua7fa', '\ua7fa'), ('\ua7fb', '\ua801'), - ('\ua803', '\ua805'), ('\ua807', '\ua80a'), - ('\ua80c', '\ua822'), ('\ua823', '\ua824'), - ('\ua825', '\ua826'), ('\ua827', '\ua827'), - ('\ua840', '\ua873'), ('\ua880', '\ua881'), - ('\ua882', '\ua8b3'), ('\ua8b4', '\ua8c3'), - ('\ua8f2', '\ua8f7'), ('\ua8fb', '\ua8fb'), - ('\ua90a', '\ua925'), ('\ua926', '\ua92a'), - ('\ua930', '\ua946'), ('\ua947', '\ua951'), - ('\ua952', '\ua952'), ('\ua960', '\ua97c'), - ('\ua980', '\ua982'), ('\ua983', '\ua983'), - ('\ua984', '\ua9b2'), ('\ua9b4', '\ua9b5'), - ('\ua9b6', '\ua9b9'), ('\ua9ba', '\ua9bb'), - ('\ua9bc', '\ua9bc'), ('\ua9bd', '\ua9bf'), - ('\ua9cf', '\ua9cf'), ('\uaa00', '\uaa28'), - ('\uaa29', '\uaa2e'), ('\uaa2f', '\uaa30'), - ('\uaa31', '\uaa32'), ('\uaa33', '\uaa34'), - ('\uaa35', '\uaa36'), ('\uaa40', '\uaa42'), - ('\uaa43', '\uaa43'), ('\uaa44', '\uaa4b'), - ('\uaa4c', '\uaa4c'), ('\uaa4d', '\uaa4d'), - ('\uaa60', '\uaa6f'), ('\uaa70', '\uaa70'), - ('\uaa71', '\uaa76'), ('\uaa7a', '\uaa7a'), - ('\uaa80', '\uaaaf'), ('\uaab0', '\uaab0'), - ('\uaab1', '\uaab1'), ('\uaab2', '\uaab4'), - ('\uaab5', '\uaab6'), ('\uaab7', '\uaab8'), - ('\uaab9', '\uaabd'), ('\uaabe', '\uaabe'), - ('\uaac0', '\uaac0'), ('\uaac2', '\uaac2'), - ('\uaadb', '\uaadc'), ('\uaadd', '\uaadd'), - ('\uaae0', '\uaaea'), ('\uaaeb', '\uaaeb'), - ('\uaaec', '\uaaed'), ('\uaaee', '\uaaef'), - ('\uaaf2', '\uaaf2'), ('\uaaf3', '\uaaf4'), - ('\uaaf5', '\uaaf5'), ('\uab01', '\uab06'), - ('\uab09', '\uab0e'), ('\uab11', '\uab16'), - ('\uab20', '\uab26'), ('\uab28', '\uab2e'), - ('\uabc0', '\uabe2'), ('\uabe3', '\uabe4'), - ('\uabe5', '\uabe5'), ('\uabe6', '\uabe7'), - ('\uabe8', '\uabe8'), ('\uabe9', '\uabea'), - ('\uac00', '\ud7a3'), ('\ud7b0', '\ud7c6'), - ('\ud7cb', '\ud7fb'), ('\uf900', '\ufa6d'), - ('\ufa70', '\ufad9'), ('\ufb00', '\ufb06'), - ('\ufb13', '\ufb17'), ('\ufb1d', '\ufb1d'), - ('\ufb1e', '\ufb1e'), ('\ufb1f', '\ufb28'), - ('\ufb2a', '\ufb36'), ('\ufb38', '\ufb3c'), - ('\ufb3e', '\ufb3e'), ('\ufb40', '\ufb41'), - ('\ufb43', '\ufb44'), ('\ufb46', '\ufbb1'), - ('\ufbd3', '\ufd3d'), ('\ufd50', '\ufd8f'), - ('\ufd92', '\ufdc7'), ('\ufdf0', '\ufdfb'), - ('\ufe70', '\ufe74'), ('\ufe76', '\ufefc'), - ('\uff21', '\uff3a'), ('\uff41', '\uff5a'), - ('\uff66', '\uff6f'), ('\uff70', '\uff70'), - ('\uff71', '\uff9d'), ('\uff9e', '\uff9f'), - ('\uffa0', '\uffbe'), ('\uffc2', '\uffc7'), - ('\uffca', '\uffcf'), ('\uffd2', '\uffd7'), - ('\uffda', '\uffdc'), ('\U00010000', '\U0001000b'), - ('\U0001000d', '\U00010026'), ('\U00010028', '\U0001003a'), - ('\U0001003c', '\U0001003d'), ('\U0001003f', '\U0001004d'), - ('\U00010050', '\U0001005d'), ('\U00010080', '\U000100fa'), - ('\U00010140', '\U00010174'), ('\U00010280', '\U0001029c'), - ('\U000102a0', '\U000102d0'), ('\U00010300', '\U0001031e'), - ('\U00010330', '\U00010340'), ('\U00010341', '\U00010341'), - ('\U00010342', '\U00010349'), ('\U0001034a', '\U0001034a'), - ('\U00010380', '\U0001039d'), ('\U000103a0', '\U000103c3'), - ('\U000103c8', '\U000103cf'), ('\U000103d1', '\U000103d5'), - ('\U00010400', '\U0001044f'), ('\U00010450', '\U0001049d'), - ('\U00010800', '\U00010805'), ('\U00010808', '\U00010808'), - ('\U0001080a', '\U00010835'), ('\U00010837', '\U00010838'), - ('\U0001083c', '\U0001083c'), ('\U0001083f', '\U00010855'), - ('\U00010900', '\U00010915'), ('\U00010920', '\U00010939'), - ('\U00010980', '\U000109b7'), ('\U000109be', '\U000109bf'), - ('\U00010a00', '\U00010a00'), ('\U00010a01', '\U00010a03'), - ('\U00010a05', '\U00010a06'), ('\U00010a0c', '\U00010a0f'), - ('\U00010a10', '\U00010a13'), ('\U00010a15', '\U00010a17'), - ('\U00010a19', '\U00010a33'), ('\U00010a60', '\U00010a7c'), - ('\U00010b00', '\U00010b35'), ('\U00010b40', '\U00010b55'), - ('\U00010b60', '\U00010b72'), ('\U00010c00', '\U00010c48'), - ('\U00011000', '\U00011000'), ('\U00011001', '\U00011001'), - ('\U00011002', '\U00011002'), ('\U00011003', '\U00011037'), - ('\U00011038', '\U00011045'), ('\U00011082', '\U00011082'), - ('\U00011083', '\U000110af'), ('\U000110b0', '\U000110b2'), - ('\U000110b3', '\U000110b6'), ('\U000110b7', '\U000110b8'), - ('\U000110d0', '\U000110e8'), ('\U00011100', '\U00011102'), - ('\U00011103', '\U00011126'), ('\U00011127', '\U0001112b'), - ('\U0001112c', '\U0001112c'), ('\U0001112d', '\U00011132'), - ('\U00011180', '\U00011181'), ('\U00011182', '\U00011182'), - ('\U00011183', '\U000111b2'), ('\U000111b3', '\U000111b5'), - ('\U000111b6', '\U000111be'), ('\U000111bf', '\U000111bf'), - ('\U000111c1', '\U000111c4'), ('\U00011680', '\U000116aa'), - ('\U000116ab', '\U000116ab'), ('\U000116ac', '\U000116ac'), - ('\U000116ad', '\U000116ad'), ('\U000116ae', '\U000116af'), - ('\U000116b0', '\U000116b5'), ('\U00012000', '\U0001236e'), - ('\U00012400', '\U00012462'), ('\U00013000', '\U0001342e'), - ('\U00016800', '\U00016a38'), ('\U00016f00', '\U00016f44'), - ('\U00016f50', '\U00016f50'), ('\U00016f51', '\U00016f7e'), - ('\U00016f93', '\U00016f9f'), ('\U0001b000', '\U0001b001'), - ('\U0001d400', '\U0001d454'), ('\U0001d456', '\U0001d49c'), - ('\U0001d49e', '\U0001d49f'), ('\U0001d4a2', '\U0001d4a2'), - ('\U0001d4a5', '\U0001d4a6'), ('\U0001d4a9', '\U0001d4ac'), - ('\U0001d4ae', '\U0001d4b9'), ('\U0001d4bb', '\U0001d4bb'), - ('\U0001d4bd', '\U0001d4c3'), ('\U0001d4c5', '\U0001d505'), - ('\U0001d507', '\U0001d50a'), ('\U0001d50d', '\U0001d514'), - ('\U0001d516', '\U0001d51c'), ('\U0001d51e', '\U0001d539'), - ('\U0001d53b', '\U0001d53e'), ('\U0001d540', '\U0001d544'), - ('\U0001d546', '\U0001d546'), ('\U0001d54a', '\U0001d550'), - ('\U0001d552', '\U0001d6a5'), ('\U0001d6a8', '\U0001d6c0'), - ('\U0001d6c2', '\U0001d6da'), ('\U0001d6dc', '\U0001d6fa'), - ('\U0001d6fc', '\U0001d714'), ('\U0001d716', '\U0001d734'), - ('\U0001d736', '\U0001d74e'), ('\U0001d750', '\U0001d76e'), - ('\U0001d770', '\U0001d788'), ('\U0001d78a', '\U0001d7a8'), - ('\U0001d7aa', '\U0001d7c2'), ('\U0001d7c4', '\U0001d7cb'), - ('\U0001ee00', '\U0001ee03'), ('\U0001ee05', '\U0001ee1f'), - ('\U0001ee21', '\U0001ee22'), ('\U0001ee24', '\U0001ee24'), - ('\U0001ee27', '\U0001ee27'), ('\U0001ee29', '\U0001ee32'), - ('\U0001ee34', '\U0001ee37'), ('\U0001ee39', '\U0001ee39'), - ('\U0001ee3b', '\U0001ee3b'), ('\U0001ee42', '\U0001ee42'), - ('\U0001ee47', '\U0001ee47'), ('\U0001ee49', '\U0001ee49'), - ('\U0001ee4b', '\U0001ee4b'), ('\U0001ee4d', '\U0001ee4f'), - ('\U0001ee51', '\U0001ee52'), ('\U0001ee54', '\U0001ee54'), - ('\U0001ee57', '\U0001ee57'), ('\U0001ee59', '\U0001ee59'), - ('\U0001ee5b', '\U0001ee5b'), ('\U0001ee5d', '\U0001ee5d'), - ('\U0001ee5f', '\U0001ee5f'), ('\U0001ee61', '\U0001ee62'), - ('\U0001ee64', '\U0001ee64'), ('\U0001ee67', '\U0001ee6a'), - ('\U0001ee6c', '\U0001ee72'), ('\U0001ee74', '\U0001ee77'), - ('\U0001ee79', '\U0001ee7c'), ('\U0001ee7e', '\U0001ee7e'), - ('\U0001ee80', '\U0001ee89'), ('\U0001ee8b', '\U0001ee9b'), - ('\U0001eea1', '\U0001eea3'), ('\U0001eea5', '\U0001eea9'), - ('\U0001eeab', '\U0001eebb'), ('\U00020000', '\U0002a6d6'), - ('\U0002a700', '\U0002b734'), ('\U0002b740', '\U0002b81d'), - ('\U0002f800', '\U0002fa1d') - ]; - - pub fn Alphabetic(c: char) -> bool { - bsearch_range_table(c, Alphabetic_table) - } - - static XID_Continue_table : &'static [(char,char)] = &[ - ('\x30', '\x39'), ('\x41', '\x5a'), - ('\x5f', '\x5f'), ('\x61', '\x7a'), - ('\xaa', '\xaa'), ('\xb5', '\xb5'), - ('\xb7', '\xb7'), ('\xba', '\xba'), - ('\xc0', '\xd6'), ('\xd8', '\xf6'), - ('\xf8', '\u01ba'), ('\u01bb', '\u01bb'), - ('\u01bc', '\u01bf'), ('\u01c0', '\u01c3'), - ('\u01c4', '\u0293'), ('\u0294', '\u0294'), - ('\u0295', '\u02af'), ('\u02b0', '\u02c1'), - ('\u02c6', '\u02d1'), ('\u02e0', '\u02e4'), - ('\u02ec', '\u02ec'), ('\u02ee', '\u02ee'), - ('\u0300', '\u036f'), ('\u0370', '\u0373'), - ('\u0374', '\u0374'), ('\u0376', '\u0377'), - ('\u037b', '\u037d'), ('\u0386', '\u0386'), - ('\u0387', '\u0387'), ('\u0388', '\u038a'), - ('\u038c', '\u038c'), ('\u038e', '\u03a1'), - ('\u03a3', '\u03f5'), ('\u03f7', '\u0481'), - ('\u0483', '\u0487'), ('\u048a', '\u0527'), - ('\u0531', '\u0556'), ('\u0559', '\u0559'), - ('\u0561', '\u0587'), ('\u0591', '\u05bd'), - ('\u05bf', '\u05bf'), ('\u05c1', '\u05c2'), - ('\u05c4', '\u05c5'), ('\u05c7', '\u05c7'), - ('\u05d0', '\u05ea'), ('\u05f0', '\u05f2'), - ('\u0610', '\u061a'), ('\u0620', '\u063f'), - ('\u0640', '\u0640'), ('\u0641', '\u064a'), - ('\u064b', '\u065f'), ('\u0660', '\u0669'), - ('\u066e', '\u066f'), ('\u0670', '\u0670'), - ('\u0671', '\u06d3'), ('\u06d5', '\u06d5'), - ('\u06d6', '\u06dc'), ('\u06df', '\u06e4'), - ('\u06e5', '\u06e6'), ('\u06e7', '\u06e8'), - ('\u06ea', '\u06ed'), ('\u06ee', '\u06ef'), - ('\u06f0', '\u06f9'), ('\u06fa', '\u06fc'), - ('\u06ff', '\u06ff'), ('\u0710', '\u0710'), - ('\u0711', '\u0711'), ('\u0712', '\u072f'), - ('\u0730', '\u074a'), ('\u074d', '\u07a5'), - ('\u07a6', '\u07b0'), ('\u07b1', '\u07b1'), - ('\u07c0', '\u07c9'), ('\u07ca', '\u07ea'), - ('\u07eb', '\u07f3'), ('\u07f4', '\u07f5'), - ('\u07fa', '\u07fa'), ('\u0800', '\u0815'), - ('\u0816', '\u0819'), ('\u081a', '\u081a'), - ('\u081b', '\u0823'), ('\u0824', '\u0824'), - ('\u0825', '\u0827'), ('\u0828', '\u0828'), - ('\u0829', '\u082d'), ('\u0840', '\u0858'), - ('\u0859', '\u085b'), ('\u08a0', '\u08a0'), - ('\u08a2', '\u08ac'), ('\u08e4', '\u08fe'), - ('\u0900', '\u0902'), ('\u0903', '\u0903'), - ('\u0904', '\u0939'), ('\u093a', '\u093a'), - ('\u093b', '\u093b'), ('\u093c', '\u093c'), - ('\u093d', '\u093d'), ('\u093e', '\u0940'), - ('\u0941', '\u0948'), ('\u0949', '\u094c'), - ('\u094d', '\u094d'), ('\u094e', '\u094f'), - ('\u0950', '\u0950'), ('\u0951', '\u0957'), - ('\u0958', '\u0961'), ('\u0962', '\u0963'), - ('\u0966', '\u096f'), ('\u0971', '\u0971'), - ('\u0972', '\u0977'), ('\u0979', '\u097f'), - ('\u0981', '\u0981'), ('\u0982', '\u0983'), - ('\u0985', '\u098c'), ('\u098f', '\u0990'), - ('\u0993', '\u09a8'), ('\u09aa', '\u09b0'), - ('\u09b2', '\u09b2'), ('\u09b6', '\u09b9'), - ('\u09bc', '\u09bc'), ('\u09bd', '\u09bd'), - ('\u09be', '\u09c0'), ('\u09c1', '\u09c4'), - ('\u09c7', '\u09c8'), ('\u09cb', '\u09cc'), - ('\u09cd', '\u09cd'), ('\u09ce', '\u09ce'), - ('\u09d7', '\u09d7'), ('\u09dc', '\u09dd'), - ('\u09df', '\u09e1'), ('\u09e2', '\u09e3'), - ('\u09e6', '\u09ef'), ('\u09f0', '\u09f1'), - ('\u0a01', '\u0a02'), ('\u0a03', '\u0a03'), - ('\u0a05', '\u0a0a'), ('\u0a0f', '\u0a10'), - ('\u0a13', '\u0a28'), ('\u0a2a', '\u0a30'), - ('\u0a32', '\u0a33'), ('\u0a35', '\u0a36'), - ('\u0a38', '\u0a39'), ('\u0a3c', '\u0a3c'), - ('\u0a3e', '\u0a40'), ('\u0a41', '\u0a42'), - ('\u0a47', '\u0a48'), ('\u0a4b', '\u0a4d'), - ('\u0a51', '\u0a51'), ('\u0a59', '\u0a5c'), - ('\u0a5e', '\u0a5e'), ('\u0a66', '\u0a6f'), - ('\u0a70', '\u0a71'), ('\u0a72', '\u0a74'), - ('\u0a75', '\u0a75'), ('\u0a81', '\u0a82'), - ('\u0a83', '\u0a83'), ('\u0a85', '\u0a8d'), - ('\u0a8f', '\u0a91'), ('\u0a93', '\u0aa8'), - ('\u0aaa', '\u0ab0'), ('\u0ab2', '\u0ab3'), - ('\u0ab5', '\u0ab9'), ('\u0abc', '\u0abc'), - ('\u0abd', '\u0abd'), ('\u0abe', '\u0ac0'), - ('\u0ac1', '\u0ac5'), ('\u0ac7', '\u0ac8'), - ('\u0ac9', '\u0ac9'), ('\u0acb', '\u0acc'), - ('\u0acd', '\u0acd'), ('\u0ad0', '\u0ad0'), - ('\u0ae0', '\u0ae1'), ('\u0ae2', '\u0ae3'), - ('\u0ae6', '\u0aef'), ('\u0b01', '\u0b01'), - ('\u0b02', '\u0b03'), ('\u0b05', '\u0b0c'), - ('\u0b0f', '\u0b10'), ('\u0b13', '\u0b28'), - ('\u0b2a', '\u0b30'), ('\u0b32', '\u0b33'), - ('\u0b35', '\u0b39'), ('\u0b3c', '\u0b3c'), - ('\u0b3d', '\u0b3d'), ('\u0b3e', '\u0b3e'), - ('\u0b3f', '\u0b3f'), ('\u0b40', '\u0b40'), - ('\u0b41', '\u0b44'), ('\u0b47', '\u0b48'), - ('\u0b4b', '\u0b4c'), ('\u0b4d', '\u0b4d'), - ('\u0b56', '\u0b56'), ('\u0b57', '\u0b57'), - ('\u0b5c', '\u0b5d'), ('\u0b5f', '\u0b61'), - ('\u0b62', '\u0b63'), ('\u0b66', '\u0b6f'), - ('\u0b71', '\u0b71'), ('\u0b82', '\u0b82'), - ('\u0b83', '\u0b83'), ('\u0b85', '\u0b8a'), - ('\u0b8e', '\u0b90'), ('\u0b92', '\u0b95'), - ('\u0b99', '\u0b9a'), ('\u0b9c', '\u0b9c'), - ('\u0b9e', '\u0b9f'), ('\u0ba3', '\u0ba4'), - ('\u0ba8', '\u0baa'), ('\u0bae', '\u0bb9'), - ('\u0bbe', '\u0bbf'), ('\u0bc0', '\u0bc0'), - ('\u0bc1', '\u0bc2'), ('\u0bc6', '\u0bc8'), - ('\u0bca', '\u0bcc'), ('\u0bcd', '\u0bcd'), - ('\u0bd0', '\u0bd0'), ('\u0bd7', '\u0bd7'), - ('\u0be6', '\u0bef'), ('\u0c01', '\u0c03'), - ('\u0c05', '\u0c0c'), ('\u0c0e', '\u0c10'), - ('\u0c12', '\u0c28'), ('\u0c2a', '\u0c33'), - ('\u0c35', '\u0c39'), ('\u0c3d', '\u0c3d'), - ('\u0c3e', '\u0c40'), ('\u0c41', '\u0c44'), - ('\u0c46', '\u0c48'), ('\u0c4a', '\u0c4d'), - ('\u0c55', '\u0c56'), ('\u0c58', '\u0c59'), - ('\u0c60', '\u0c61'), ('\u0c62', '\u0c63'), - ('\u0c66', '\u0c6f'), ('\u0c82', '\u0c83'), - ('\u0c85', '\u0c8c'), ('\u0c8e', '\u0c90'), - ('\u0c92', '\u0ca8'), ('\u0caa', '\u0cb3'), - ('\u0cb5', '\u0cb9'), ('\u0cbc', '\u0cbc'), - ('\u0cbd', '\u0cbd'), ('\u0cbe', '\u0cbe'), - ('\u0cbf', '\u0cbf'), ('\u0cc0', '\u0cc4'), - ('\u0cc6', '\u0cc6'), ('\u0cc7', '\u0cc8'), - ('\u0cca', '\u0ccb'), ('\u0ccc', '\u0ccd'), - ('\u0cd5', '\u0cd6'), ('\u0cde', '\u0cde'), - ('\u0ce0', '\u0ce1'), ('\u0ce2', '\u0ce3'), - ('\u0ce6', '\u0cef'), ('\u0cf1', '\u0cf2'), - ('\u0d02', '\u0d03'), ('\u0d05', '\u0d0c'), - ('\u0d0e', '\u0d10'), ('\u0d12', '\u0d3a'), - ('\u0d3d', '\u0d3d'), ('\u0d3e', '\u0d40'), - ('\u0d41', '\u0d44'), ('\u0d46', '\u0d48'), - ('\u0d4a', '\u0d4c'), ('\u0d4d', '\u0d4d'), - ('\u0d4e', '\u0d4e'), ('\u0d57', '\u0d57'), - ('\u0d60', '\u0d61'), ('\u0d62', '\u0d63'), - ('\u0d66', '\u0d6f'), ('\u0d7a', '\u0d7f'), - ('\u0d82', '\u0d83'), ('\u0d85', '\u0d96'), - ('\u0d9a', '\u0db1'), ('\u0db3', '\u0dbb'), - ('\u0dbd', '\u0dbd'), ('\u0dc0', '\u0dc6'), - ('\u0dca', '\u0dca'), ('\u0dcf', '\u0dd1'), - ('\u0dd2', '\u0dd4'), ('\u0dd6', '\u0dd6'), - ('\u0dd8', '\u0ddf'), ('\u0df2', '\u0df3'), - ('\u0e01', '\u0e30'), ('\u0e31', '\u0e31'), - ('\u0e32', '\u0e33'), ('\u0e34', '\u0e3a'), - ('\u0e40', '\u0e45'), ('\u0e46', '\u0e46'), - ('\u0e47', '\u0e4e'), ('\u0e50', '\u0e59'), - ('\u0e81', '\u0e82'), ('\u0e84', '\u0e84'), - ('\u0e87', '\u0e88'), ('\u0e8a', '\u0e8a'), - ('\u0e8d', '\u0e8d'), ('\u0e94', '\u0e97'), - ('\u0e99', '\u0e9f'), ('\u0ea1', '\u0ea3'), - ('\u0ea5', '\u0ea5'), ('\u0ea7', '\u0ea7'), - ('\u0eaa', '\u0eab'), ('\u0ead', '\u0eb0'), - ('\u0eb1', '\u0eb1'), ('\u0eb2', '\u0eb3'), - ('\u0eb4', '\u0eb9'), ('\u0ebb', '\u0ebc'), - ('\u0ebd', '\u0ebd'), ('\u0ec0', '\u0ec4'), - ('\u0ec6', '\u0ec6'), ('\u0ec8', '\u0ecd'), - ('\u0ed0', '\u0ed9'), ('\u0edc', '\u0edf'), - ('\u0f00', '\u0f00'), ('\u0f18', '\u0f19'), - ('\u0f20', '\u0f29'), ('\u0f35', '\u0f35'), - ('\u0f37', '\u0f37'), ('\u0f39', '\u0f39'), - ('\u0f3e', '\u0f3f'), ('\u0f40', '\u0f47'), - ('\u0f49', '\u0f6c'), ('\u0f71', '\u0f7e'), - ('\u0f7f', '\u0f7f'), ('\u0f80', '\u0f84'), - ('\u0f86', '\u0f87'), ('\u0f88', '\u0f8c'), - ('\u0f8d', '\u0f97'), ('\u0f99', '\u0fbc'), - ('\u0fc6', '\u0fc6'), ('\u1000', '\u102a'), - ('\u102b', '\u102c'), ('\u102d', '\u1030'), - ('\u1031', '\u1031'), ('\u1032', '\u1037'), - ('\u1038', '\u1038'), ('\u1039', '\u103a'), - ('\u103b', '\u103c'), ('\u103d', '\u103e'), - ('\u103f', '\u103f'), ('\u1040', '\u1049'), - ('\u1050', '\u1055'), ('\u1056', '\u1057'), - ('\u1058', '\u1059'), ('\u105a', '\u105d'), - ('\u105e', '\u1060'), ('\u1061', '\u1061'), - ('\u1062', '\u1064'), ('\u1065', '\u1066'), - ('\u1067', '\u106d'), ('\u106e', '\u1070'), - ('\u1071', '\u1074'), ('\u1075', '\u1081'), - ('\u1082', '\u1082'), ('\u1083', '\u1084'), - ('\u1085', '\u1086'), ('\u1087', '\u108c'), - ('\u108d', '\u108d'), ('\u108e', '\u108e'), - ('\u108f', '\u108f'), ('\u1090', '\u1099'), - ('\u109a', '\u109c'), ('\u109d', '\u109d'), - ('\u10a0', '\u10c5'), ('\u10c7', '\u10c7'), - ('\u10cd', '\u10cd'), ('\u10d0', '\u10fa'), - ('\u10fc', '\u10fc'), ('\u10fd', '\u1248'), - ('\u124a', '\u124d'), ('\u1250', '\u1256'), - ('\u1258', '\u1258'), ('\u125a', '\u125d'), - ('\u1260', '\u1288'), ('\u128a', '\u128d'), - ('\u1290', '\u12b0'), ('\u12b2', '\u12b5'), - ('\u12b8', '\u12be'), ('\u12c0', '\u12c0'), - ('\u12c2', '\u12c5'), ('\u12c8', '\u12d6'), - ('\u12d8', '\u1310'), ('\u1312', '\u1315'), - ('\u1318', '\u135a'), ('\u135d', '\u135f'), - ('\u1369', '\u1371'), ('\u1380', '\u138f'), - ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), - ('\u166f', '\u167f'), ('\u1681', '\u169a'), - ('\u16a0', '\u16ea'), ('\u16ee', '\u16f0'), - ('\u1700', '\u170c'), ('\u170e', '\u1711'), - ('\u1712', '\u1714'), ('\u1720', '\u1731'), - ('\u1732', '\u1734'), ('\u1740', '\u1751'), - ('\u1752', '\u1753'), ('\u1760', '\u176c'), - ('\u176e', '\u1770'), ('\u1772', '\u1773'), - ('\u1780', '\u17b3'), ('\u17b4', '\u17b5'), - ('\u17b6', '\u17b6'), ('\u17b7', '\u17bd'), - ('\u17be', '\u17c5'), ('\u17c6', '\u17c6'), - ('\u17c7', '\u17c8'), ('\u17c9', '\u17d3'), - ('\u17d7', '\u17d7'), ('\u17dc', '\u17dc'), - ('\u17dd', '\u17dd'), ('\u17e0', '\u17e9'), - ('\u180b', '\u180d'), ('\u1810', '\u1819'), - ('\u1820', '\u1842'), ('\u1843', '\u1843'), - ('\u1844', '\u1877'), ('\u1880', '\u18a8'), - ('\u18a9', '\u18a9'), ('\u18aa', '\u18aa'), - ('\u18b0', '\u18f5'), ('\u1900', '\u191c'), - ('\u1920', '\u1922'), ('\u1923', '\u1926'), - ('\u1927', '\u1928'), ('\u1929', '\u192b'), - ('\u1930', '\u1931'), ('\u1932', '\u1932'), - ('\u1933', '\u1938'), ('\u1939', '\u193b'), - ('\u1946', '\u194f'), ('\u1950', '\u196d'), - ('\u1970', '\u1974'), ('\u1980', '\u19ab'), - ('\u19b0', '\u19c0'), ('\u19c1', '\u19c7'), - ('\u19c8', '\u19c9'), ('\u19d0', '\u19d9'), - ('\u19da', '\u19da'), ('\u1a00', '\u1a16'), - ('\u1a17', '\u1a18'), ('\u1a19', '\u1a1b'), - ('\u1a20', '\u1a54'), ('\u1a55', '\u1a55'), - ('\u1a56', '\u1a56'), ('\u1a57', '\u1a57'), - ('\u1a58', '\u1a5e'), ('\u1a60', '\u1a60'), - ('\u1a61', '\u1a61'), ('\u1a62', '\u1a62'), - ('\u1a63', '\u1a64'), ('\u1a65', '\u1a6c'), - ('\u1a6d', '\u1a72'), ('\u1a73', '\u1a7c'), - ('\u1a7f', '\u1a7f'), ('\u1a80', '\u1a89'), - ('\u1a90', '\u1a99'), ('\u1aa7', '\u1aa7'), - ('\u1b00', '\u1b03'), ('\u1b04', '\u1b04'), - ('\u1b05', '\u1b33'), ('\u1b34', '\u1b34'), - ('\u1b35', '\u1b35'), ('\u1b36', '\u1b3a'), - ('\u1b3b', '\u1b3b'), ('\u1b3c', '\u1b3c'), - ('\u1b3d', '\u1b41'), ('\u1b42', '\u1b42'), - ('\u1b43', '\u1b44'), ('\u1b45', '\u1b4b'), - ('\u1b50', '\u1b59'), ('\u1b6b', '\u1b73'), - ('\u1b80', '\u1b81'), ('\u1b82', '\u1b82'), - ('\u1b83', '\u1ba0'), ('\u1ba1', '\u1ba1'), - ('\u1ba2', '\u1ba5'), ('\u1ba6', '\u1ba7'), - ('\u1ba8', '\u1ba9'), ('\u1baa', '\u1baa'), - ('\u1bab', '\u1bab'), ('\u1bac', '\u1bad'), - ('\u1bae', '\u1baf'), ('\u1bb0', '\u1bb9'), - ('\u1bba', '\u1be5'), ('\u1be6', '\u1be6'), - ('\u1be7', '\u1be7'), ('\u1be8', '\u1be9'), - ('\u1bea', '\u1bec'), ('\u1bed', '\u1bed'), - ('\u1bee', '\u1bee'), ('\u1bef', '\u1bf1'), - ('\u1bf2', '\u1bf3'), ('\u1c00', '\u1c23'), - ('\u1c24', '\u1c2b'), ('\u1c2c', '\u1c33'), - ('\u1c34', '\u1c35'), ('\u1c36', '\u1c37'), - ('\u1c40', '\u1c49'), ('\u1c4d', '\u1c4f'), - ('\u1c50', '\u1c59'), ('\u1c5a', '\u1c77'), - ('\u1c78', '\u1c7d'), ('\u1cd0', '\u1cd2'), - ('\u1cd4', '\u1ce0'), ('\u1ce1', '\u1ce1'), - ('\u1ce2', '\u1ce8'), ('\u1ce9', '\u1cec'), - ('\u1ced', '\u1ced'), ('\u1cee', '\u1cf1'), - ('\u1cf2', '\u1cf3'), ('\u1cf4', '\u1cf4'), - ('\u1cf5', '\u1cf6'), ('\u1d00', '\u1d2b'), - ('\u1d2c', '\u1d6a'), ('\u1d6b', '\u1d77'), - ('\u1d78', '\u1d78'), ('\u1d79', '\u1d9a'), - ('\u1d9b', '\u1dbf'), ('\u1dc0', '\u1de6'), - ('\u1dfc', '\u1dff'), ('\u1e00', '\u1f15'), - ('\u1f18', '\u1f1d'), ('\u1f20', '\u1f45'), - ('\u1f48', '\u1f4d'), ('\u1f50', '\u1f57'), - ('\u1f59', '\u1f59'), ('\u1f5b', '\u1f5b'), - ('\u1f5d', '\u1f5d'), ('\u1f5f', '\u1f7d'), - ('\u1f80', '\u1fb4'), ('\u1fb6', '\u1fbc'), - ('\u1fbe', '\u1fbe'), ('\u1fc2', '\u1fc4'), - ('\u1fc6', '\u1fcc'), ('\u1fd0', '\u1fd3'), - ('\u1fd6', '\u1fdb'), ('\u1fe0', '\u1fec'), - ('\u1ff2', '\u1ff4'), ('\u1ff6', '\u1ffc'), - ('\u203f', '\u2040'), ('\u2054', '\u2054'), - ('\u2071', '\u2071'), ('\u207f', '\u207f'), - ('\u2090', '\u209c'), ('\u20d0', '\u20dc'), - ('\u20e1', '\u20e1'), ('\u20e5', '\u20f0'), - ('\u2102', '\u2102'), ('\u2107', '\u2107'), - ('\u210a', '\u2113'), ('\u2115', '\u2115'), - ('\u2118', '\u2118'), ('\u2119', '\u211d'), - ('\u2124', '\u2124'), ('\u2126', '\u2126'), - ('\u2128', '\u2128'), ('\u212a', '\u212d'), - ('\u212e', '\u212e'), ('\u212f', '\u2134'), - ('\u2135', '\u2138'), ('\u2139', '\u2139'), - ('\u213c', '\u213f'), ('\u2145', '\u2149'), - ('\u214e', '\u214e'), ('\u2160', '\u2182'), - ('\u2183', '\u2184'), ('\u2185', '\u2188'), - ('\u2c00', '\u2c2e'), ('\u2c30', '\u2c5e'), - ('\u2c60', '\u2c7b'), ('\u2c7c', '\u2c7d'), - ('\u2c7e', '\u2ce4'), ('\u2ceb', '\u2cee'), - ('\u2cef', '\u2cf1'), ('\u2cf2', '\u2cf3'), - ('\u2d00', '\u2d25'), ('\u2d27', '\u2d27'), - ('\u2d2d', '\u2d2d'), ('\u2d30', '\u2d67'), - ('\u2d6f', '\u2d6f'), ('\u2d7f', '\u2d7f'), - ('\u2d80', '\u2d96'), ('\u2da0', '\u2da6'), - ('\u2da8', '\u2dae'), ('\u2db0', '\u2db6'), - ('\u2db8', '\u2dbe'), ('\u2dc0', '\u2dc6'), - ('\u2dc8', '\u2dce'), ('\u2dd0', '\u2dd6'), - ('\u2dd8', '\u2dde'), ('\u2de0', '\u2dff'), - ('\u3005', '\u3005'), ('\u3006', '\u3006'), - ('\u3007', '\u3007'), ('\u3021', '\u3029'), - ('\u302a', '\u302d'), ('\u302e', '\u302f'), - ('\u3031', '\u3035'), ('\u3038', '\u303a'), - ('\u303b', '\u303b'), ('\u303c', '\u303c'), - ('\u3041', '\u3096'), ('\u3099', '\u309a'), - ('\u309d', '\u309e'), ('\u309f', '\u309f'), - ('\u30a1', '\u30fa'), ('\u30fc', '\u30fe'), - ('\u30ff', '\u30ff'), ('\u3105', '\u312d'), - ('\u3131', '\u318e'), ('\u31a0', '\u31ba'), - ('\u31f0', '\u31ff'), ('\u3400', '\u4db5'), - ('\u4e00', '\u9fcc'), ('\ua000', '\ua014'), - ('\ua015', '\ua015'), ('\ua016', '\ua48c'), - ('\ua4d0', '\ua4f7'), ('\ua4f8', '\ua4fd'), - ('\ua500', '\ua60b'), ('\ua60c', '\ua60c'), - ('\ua610', '\ua61f'), ('\ua620', '\ua629'), - ('\ua62a', '\ua62b'), ('\ua640', '\ua66d'), - ('\ua66e', '\ua66e'), ('\ua66f', '\ua66f'), - ('\ua674', '\ua67d'), ('\ua67f', '\ua67f'), - ('\ua680', '\ua697'), ('\ua69f', '\ua69f'), - ('\ua6a0', '\ua6e5'), ('\ua6e6', '\ua6ef'), - ('\ua6f0', '\ua6f1'), ('\ua717', '\ua71f'), - ('\ua722', '\ua76f'), ('\ua770', '\ua770'), - ('\ua771', '\ua787'), ('\ua788', '\ua788'), - ('\ua78b', '\ua78e'), ('\ua790', '\ua793'), - ('\ua7a0', '\ua7aa'), ('\ua7f8', '\ua7f9'), - ('\ua7fa', '\ua7fa'), ('\ua7fb', '\ua801'), - ('\ua802', '\ua802'), ('\ua803', '\ua805'), - ('\ua806', '\ua806'), ('\ua807', '\ua80a'), - ('\ua80b', '\ua80b'), ('\ua80c', '\ua822'), - ('\ua823', '\ua824'), ('\ua825', '\ua826'), - ('\ua827', '\ua827'), ('\ua840', '\ua873'), - ('\ua880', '\ua881'), ('\ua882', '\ua8b3'), - ('\ua8b4', '\ua8c3'), ('\ua8c4', '\ua8c4'), - ('\ua8d0', '\ua8d9'), ('\ua8e0', '\ua8f1'), - ('\ua8f2', '\ua8f7'), ('\ua8fb', '\ua8fb'), - ('\ua900', '\ua909'), ('\ua90a', '\ua925'), - ('\ua926', '\ua92d'), ('\ua930', '\ua946'), - ('\ua947', '\ua951'), ('\ua952', '\ua953'), - ('\ua960', '\ua97c'), ('\ua980', '\ua982'), - ('\ua983', '\ua983'), ('\ua984', '\ua9b2'), - ('\ua9b3', '\ua9b3'), ('\ua9b4', '\ua9b5'), - ('\ua9b6', '\ua9b9'), ('\ua9ba', '\ua9bb'), - ('\ua9bc', '\ua9bc'), ('\ua9bd', '\ua9c0'), - ('\ua9cf', '\ua9cf'), ('\ua9d0', '\ua9d9'), - ('\uaa00', '\uaa28'), ('\uaa29', '\uaa2e'), - ('\uaa2f', '\uaa30'), ('\uaa31', '\uaa32'), - ('\uaa33', '\uaa34'), ('\uaa35', '\uaa36'), - ('\uaa40', '\uaa42'), ('\uaa43', '\uaa43'), - ('\uaa44', '\uaa4b'), ('\uaa4c', '\uaa4c'), - ('\uaa4d', '\uaa4d'), ('\uaa50', '\uaa59'), - ('\uaa60', '\uaa6f'), ('\uaa70', '\uaa70'), - ('\uaa71', '\uaa76'), ('\uaa7a', '\uaa7a'), - ('\uaa7b', '\uaa7b'), ('\uaa80', '\uaaaf'), - ('\uaab0', '\uaab0'), ('\uaab1', '\uaab1'), - ('\uaab2', '\uaab4'), ('\uaab5', '\uaab6'), - ('\uaab7', '\uaab8'), ('\uaab9', '\uaabd'), - ('\uaabe', '\uaabf'), ('\uaac0', '\uaac0'), - ('\uaac1', '\uaac1'), ('\uaac2', '\uaac2'), - ('\uaadb', '\uaadc'), ('\uaadd', '\uaadd'), - ('\uaae0', '\uaaea'), ('\uaaeb', '\uaaeb'), - ('\uaaec', '\uaaed'), ('\uaaee', '\uaaef'), - ('\uaaf2', '\uaaf2'), ('\uaaf3', '\uaaf4'), - ('\uaaf5', '\uaaf5'), ('\uaaf6', '\uaaf6'), - ('\uab01', '\uab06'), ('\uab09', '\uab0e'), - ('\uab11', '\uab16'), ('\uab20', '\uab26'), - ('\uab28', '\uab2e'), ('\uabc0', '\uabe2'), - ('\uabe3', '\uabe4'), ('\uabe5', '\uabe5'), - ('\uabe6', '\uabe7'), ('\uabe8', '\uabe8'), - ('\uabe9', '\uabea'), ('\uabec', '\uabec'), - ('\uabed', '\uabed'), ('\uabf0', '\uabf9'), - ('\uac00', '\ud7a3'), ('\ud7b0', '\ud7c6'), - ('\ud7cb', '\ud7fb'), ('\uf900', '\ufa6d'), - ('\ufa70', '\ufad9'), ('\ufb00', '\ufb06'), - ('\ufb13', '\ufb17'), ('\ufb1d', '\ufb1d'), - ('\ufb1e', '\ufb1e'), ('\ufb1f', '\ufb28'), - ('\ufb2a', '\ufb36'), ('\ufb38', '\ufb3c'), - ('\ufb3e', '\ufb3e'), ('\ufb40', '\ufb41'), - ('\ufb43', '\ufb44'), ('\ufb46', '\ufbb1'), - ('\ufbd3', '\ufc5d'), ('\ufc64', '\ufd3d'), - ('\ufd50', '\ufd8f'), ('\ufd92', '\ufdc7'), - ('\ufdf0', '\ufdf9'), ('\ufe00', '\ufe0f'), - ('\ufe20', '\ufe26'), ('\ufe33', '\ufe34'), - ('\ufe4d', '\ufe4f'), ('\ufe71', '\ufe71'), - ('\ufe73', '\ufe73'), ('\ufe77', '\ufe77'), - ('\ufe79', '\ufe79'), ('\ufe7b', '\ufe7b'), - ('\ufe7d', '\ufe7d'), ('\ufe7f', '\ufefc'), - ('\uff10', '\uff19'), ('\uff21', '\uff3a'), - ('\uff3f', '\uff3f'), ('\uff41', '\uff5a'), - ('\uff66', '\uff6f'), ('\uff70', '\uff70'), - ('\uff71', '\uff9d'), ('\uff9e', '\uff9f'), - ('\uffa0', '\uffbe'), ('\uffc2', '\uffc7'), - ('\uffca', '\uffcf'), ('\uffd2', '\uffd7'), - ('\uffda', '\uffdc'), ('\U00010000', '\U0001000b'), - ('\U0001000d', '\U00010026'), ('\U00010028', '\U0001003a'), - ('\U0001003c', '\U0001003d'), ('\U0001003f', '\U0001004d'), - ('\U00010050', '\U0001005d'), ('\U00010080', '\U000100fa'), - ('\U00010140', '\U00010174'), ('\U000101fd', '\U000101fd'), - ('\U00010280', '\U0001029c'), ('\U000102a0', '\U000102d0'), - ('\U00010300', '\U0001031e'), ('\U00010330', '\U00010340'), - ('\U00010341', '\U00010341'), ('\U00010342', '\U00010349'), - ('\U0001034a', '\U0001034a'), ('\U00010380', '\U0001039d'), - ('\U000103a0', '\U000103c3'), ('\U000103c8', '\U000103cf'), - ('\U000103d1', '\U000103d5'), ('\U00010400', '\U0001044f'), - ('\U00010450', '\U0001049d'), ('\U000104a0', '\U000104a9'), - ('\U00010800', '\U00010805'), ('\U00010808', '\U00010808'), - ('\U0001080a', '\U00010835'), ('\U00010837', '\U00010838'), - ('\U0001083c', '\U0001083c'), ('\U0001083f', '\U00010855'), - ('\U00010900', '\U00010915'), ('\U00010920', '\U00010939'), - ('\U00010980', '\U000109b7'), ('\U000109be', '\U000109bf'), - ('\U00010a00', '\U00010a00'), ('\U00010a01', '\U00010a03'), - ('\U00010a05', '\U00010a06'), ('\U00010a0c', '\U00010a0f'), - ('\U00010a10', '\U00010a13'), ('\U00010a15', '\U00010a17'), - ('\U00010a19', '\U00010a33'), ('\U00010a38', '\U00010a3a'), - ('\U00010a3f', '\U00010a3f'), ('\U00010a60', '\U00010a7c'), - ('\U00010b00', '\U00010b35'), ('\U00010b40', '\U00010b55'), - ('\U00010b60', '\U00010b72'), ('\U00010c00', '\U00010c48'), - ('\U00011000', '\U00011000'), ('\U00011001', '\U00011001'), - ('\U00011002', '\U00011002'), ('\U00011003', '\U00011037'), - ('\U00011038', '\U00011046'), ('\U00011066', '\U0001106f'), - ('\U00011080', '\U00011081'), ('\U00011082', '\U00011082'), - ('\U00011083', '\U000110af'), ('\U000110b0', '\U000110b2'), - ('\U000110b3', '\U000110b6'), ('\U000110b7', '\U000110b8'), - ('\U000110b9', '\U000110ba'), ('\U000110d0', '\U000110e8'), - ('\U000110f0', '\U000110f9'), ('\U00011100', '\U00011102'), - ('\U00011103', '\U00011126'), ('\U00011127', '\U0001112b'), - ('\U0001112c', '\U0001112c'), ('\U0001112d', '\U00011134'), - ('\U00011136', '\U0001113f'), ('\U00011180', '\U00011181'), - ('\U00011182', '\U00011182'), ('\U00011183', '\U000111b2'), - ('\U000111b3', '\U000111b5'), ('\U000111b6', '\U000111be'), - ('\U000111bf', '\U000111c0'), ('\U000111c1', '\U000111c4'), - ('\U000111d0', '\U000111d9'), ('\U00011680', '\U000116aa'), - ('\U000116ab', '\U000116ab'), ('\U000116ac', '\U000116ac'), - ('\U000116ad', '\U000116ad'), ('\U000116ae', '\U000116af'), - ('\U000116b0', '\U000116b5'), ('\U000116b6', '\U000116b6'), - ('\U000116b7', '\U000116b7'), ('\U000116c0', '\U000116c9'), - ('\U00012000', '\U0001236e'), ('\U00012400', '\U00012462'), - ('\U00013000', '\U0001342e'), ('\U00016800', '\U00016a38'), - ('\U00016f00', '\U00016f44'), ('\U00016f50', '\U00016f50'), - ('\U00016f51', '\U00016f7e'), ('\U00016f8f', '\U00016f92'), - ('\U00016f93', '\U00016f9f'), ('\U0001b000', '\U0001b001'), - ('\U0001d165', '\U0001d166'), ('\U0001d167', '\U0001d169'), - ('\U0001d16d', '\U0001d172'), ('\U0001d17b', '\U0001d182'), - ('\U0001d185', '\U0001d18b'), ('\U0001d1aa', '\U0001d1ad'), - ('\U0001d242', '\U0001d244'), ('\U0001d400', '\U0001d454'), - ('\U0001d456', '\U0001d49c'), ('\U0001d49e', '\U0001d49f'), - ('\U0001d4a2', '\U0001d4a2'), ('\U0001d4a5', '\U0001d4a6'), - ('\U0001d4a9', '\U0001d4ac'), ('\U0001d4ae', '\U0001d4b9'), - ('\U0001d4bb', '\U0001d4bb'), ('\U0001d4bd', '\U0001d4c3'), - ('\U0001d4c5', '\U0001d505'), ('\U0001d507', '\U0001d50a'), - ('\U0001d50d', '\U0001d514'), ('\U0001d516', '\U0001d51c'), - ('\U0001d51e', '\U0001d539'), ('\U0001d53b', '\U0001d53e'), - ('\U0001d540', '\U0001d544'), ('\U0001d546', '\U0001d546'), - ('\U0001d54a', '\U0001d550'), ('\U0001d552', '\U0001d6a5'), - ('\U0001d6a8', '\U0001d6c0'), ('\U0001d6c2', '\U0001d6da'), - ('\U0001d6dc', '\U0001d6fa'), ('\U0001d6fc', '\U0001d714'), - ('\U0001d716', '\U0001d734'), ('\U0001d736', '\U0001d74e'), - ('\U0001d750', '\U0001d76e'), ('\U0001d770', '\U0001d788'), - ('\U0001d78a', '\U0001d7a8'), ('\U0001d7aa', '\U0001d7c2'), - ('\U0001d7c4', '\U0001d7cb'), ('\U0001d7ce', '\U0001d7ff'), - ('\U0001ee00', '\U0001ee03'), ('\U0001ee05', '\U0001ee1f'), - ('\U0001ee21', '\U0001ee22'), ('\U0001ee24', '\U0001ee24'), - ('\U0001ee27', '\U0001ee27'), ('\U0001ee29', '\U0001ee32'), - ('\U0001ee34', '\U0001ee37'), ('\U0001ee39', '\U0001ee39'), - ('\U0001ee3b', '\U0001ee3b'), ('\U0001ee42', '\U0001ee42'), - ('\U0001ee47', '\U0001ee47'), ('\U0001ee49', '\U0001ee49'), - ('\U0001ee4b', '\U0001ee4b'), ('\U0001ee4d', '\U0001ee4f'), - ('\U0001ee51', '\U0001ee52'), ('\U0001ee54', '\U0001ee54'), - ('\U0001ee57', '\U0001ee57'), ('\U0001ee59', '\U0001ee59'), - ('\U0001ee5b', '\U0001ee5b'), ('\U0001ee5d', '\U0001ee5d'), - ('\U0001ee5f', '\U0001ee5f'), ('\U0001ee61', '\U0001ee62'), - ('\U0001ee64', '\U0001ee64'), ('\U0001ee67', '\U0001ee6a'), - ('\U0001ee6c', '\U0001ee72'), ('\U0001ee74', '\U0001ee77'), - ('\U0001ee79', '\U0001ee7c'), ('\U0001ee7e', '\U0001ee7e'), - ('\U0001ee80', '\U0001ee89'), ('\U0001ee8b', '\U0001ee9b'), - ('\U0001eea1', '\U0001eea3'), ('\U0001eea5', '\U0001eea9'), - ('\U0001eeab', '\U0001eebb'), ('\U00020000', '\U0002a6d6'), - ('\U0002a700', '\U0002b734'), ('\U0002b740', '\U0002b81d'), - ('\U0002f800', '\U0002fa1d'), ('\U000e0100', '\U000e01ef') - ]; - - pub fn XID_Continue(c: char) -> bool { - bsearch_range_table(c, XID_Continue_table) - } - - static XID_Start_table : &'static [(char,char)] = &[ - ('\x41', '\x5a'), ('\x61', '\x7a'), - ('\xaa', '\xaa'), ('\xb5', '\xb5'), - ('\xba', '\xba'), ('\xc0', '\xd6'), - ('\xd8', '\xf6'), ('\xf8', '\u01ba'), - ('\u01bb', '\u01bb'), ('\u01bc', '\u01bf'), - ('\u01c0', '\u01c3'), ('\u01c4', '\u0293'), - ('\u0294', '\u0294'), ('\u0295', '\u02af'), - ('\u02b0', '\u02c1'), ('\u02c6', '\u02d1'), - ('\u02e0', '\u02e4'), ('\u02ec', '\u02ec'), - ('\u02ee', '\u02ee'), ('\u0370', '\u0373'), - ('\u0374', '\u0374'), ('\u0376', '\u0377'), - ('\u037b', '\u037d'), ('\u0386', '\u0386'), - ('\u0388', '\u038a'), ('\u038c', '\u038c'), - ('\u038e', '\u03a1'), ('\u03a3', '\u03f5'), - ('\u03f7', '\u0481'), ('\u048a', '\u0527'), - ('\u0531', '\u0556'), ('\u0559', '\u0559'), - ('\u0561', '\u0587'), ('\u05d0', '\u05ea'), - ('\u05f0', '\u05f2'), ('\u0620', '\u063f'), - ('\u0640', '\u0640'), ('\u0641', '\u064a'), - ('\u066e', '\u066f'), ('\u0671', '\u06d3'), - ('\u06d5', '\u06d5'), ('\u06e5', '\u06e6'), - ('\u06ee', '\u06ef'), ('\u06fa', '\u06fc'), - ('\u06ff', '\u06ff'), ('\u0710', '\u0710'), - ('\u0712', '\u072f'), ('\u074d', '\u07a5'), - ('\u07b1', '\u07b1'), ('\u07ca', '\u07ea'), - ('\u07f4', '\u07f5'), ('\u07fa', '\u07fa'), - ('\u0800', '\u0815'), ('\u081a', '\u081a'), - ('\u0824', '\u0824'), ('\u0828', '\u0828'), - ('\u0840', '\u0858'), ('\u08a0', '\u08a0'), - ('\u08a2', '\u08ac'), ('\u0904', '\u0939'), - ('\u093d', '\u093d'), ('\u0950', '\u0950'), - ('\u0958', '\u0961'), ('\u0971', '\u0971'), - ('\u0972', '\u0977'), ('\u0979', '\u097f'), - ('\u0985', '\u098c'), ('\u098f', '\u0990'), - ('\u0993', '\u09a8'), ('\u09aa', '\u09b0'), - ('\u09b2', '\u09b2'), ('\u09b6', '\u09b9'), - ('\u09bd', '\u09bd'), ('\u09ce', '\u09ce'), - ('\u09dc', '\u09dd'), ('\u09df', '\u09e1'), - ('\u09f0', '\u09f1'), ('\u0a05', '\u0a0a'), - ('\u0a0f', '\u0a10'), ('\u0a13', '\u0a28'), - ('\u0a2a', '\u0a30'), ('\u0a32', '\u0a33'), - ('\u0a35', '\u0a36'), ('\u0a38', '\u0a39'), - ('\u0a59', '\u0a5c'), ('\u0a5e', '\u0a5e'), - ('\u0a72', '\u0a74'), ('\u0a85', '\u0a8d'), - ('\u0a8f', '\u0a91'), ('\u0a93', '\u0aa8'), - ('\u0aaa', '\u0ab0'), ('\u0ab2', '\u0ab3'), - ('\u0ab5', '\u0ab9'), ('\u0abd', '\u0abd'), - ('\u0ad0', '\u0ad0'), ('\u0ae0', '\u0ae1'), - ('\u0b05', '\u0b0c'), ('\u0b0f', '\u0b10'), - ('\u0b13', '\u0b28'), ('\u0b2a', '\u0b30'), - ('\u0b32', '\u0b33'), ('\u0b35', '\u0b39'), - ('\u0b3d', '\u0b3d'), ('\u0b5c', '\u0b5d'), - ('\u0b5f', '\u0b61'), ('\u0b71', '\u0b71'), - ('\u0b83', '\u0b83'), ('\u0b85', '\u0b8a'), - ('\u0b8e', '\u0b90'), ('\u0b92', '\u0b95'), - ('\u0b99', '\u0b9a'), ('\u0b9c', '\u0b9c'), - ('\u0b9e', '\u0b9f'), ('\u0ba3', '\u0ba4'), - ('\u0ba8', '\u0baa'), ('\u0bae', '\u0bb9'), - ('\u0bd0', '\u0bd0'), ('\u0c05', '\u0c0c'), - ('\u0c0e', '\u0c10'), ('\u0c12', '\u0c28'), - ('\u0c2a', '\u0c33'), ('\u0c35', '\u0c39'), - ('\u0c3d', '\u0c3d'), ('\u0c58', '\u0c59'), - ('\u0c60', '\u0c61'), ('\u0c85', '\u0c8c'), - ('\u0c8e', '\u0c90'), ('\u0c92', '\u0ca8'), - ('\u0caa', '\u0cb3'), ('\u0cb5', '\u0cb9'), - ('\u0cbd', '\u0cbd'), ('\u0cde', '\u0cde'), - ('\u0ce0', '\u0ce1'), ('\u0cf1', '\u0cf2'), - ('\u0d05', '\u0d0c'), ('\u0d0e', '\u0d10'), - ('\u0d12', '\u0d3a'), ('\u0d3d', '\u0d3d'), - ('\u0d4e', '\u0d4e'), ('\u0d60', '\u0d61'), - ('\u0d7a', '\u0d7f'), ('\u0d85', '\u0d96'), - ('\u0d9a', '\u0db1'), ('\u0db3', '\u0dbb'), - ('\u0dbd', '\u0dbd'), ('\u0dc0', '\u0dc6'), - ('\u0e01', '\u0e30'), ('\u0e32', '\u0e32'), - ('\u0e40', '\u0e45'), ('\u0e46', '\u0e46'), - ('\u0e81', '\u0e82'), ('\u0e84', '\u0e84'), - ('\u0e87', '\u0e88'), ('\u0e8a', '\u0e8a'), - ('\u0e8d', '\u0e8d'), ('\u0e94', '\u0e97'), - ('\u0e99', '\u0e9f'), ('\u0ea1', '\u0ea3'), - ('\u0ea5', '\u0ea5'), ('\u0ea7', '\u0ea7'), - ('\u0eaa', '\u0eab'), ('\u0ead', '\u0eb0'), - ('\u0eb2', '\u0eb2'), ('\u0ebd', '\u0ebd'), - ('\u0ec0', '\u0ec4'), ('\u0ec6', '\u0ec6'), - ('\u0edc', '\u0edf'), ('\u0f00', '\u0f00'), - ('\u0f40', '\u0f47'), ('\u0f49', '\u0f6c'), - ('\u0f88', '\u0f8c'), ('\u1000', '\u102a'), - ('\u103f', '\u103f'), ('\u1050', '\u1055'), - ('\u105a', '\u105d'), ('\u1061', '\u1061'), - ('\u1065', '\u1066'), ('\u106e', '\u1070'), - ('\u1075', '\u1081'), ('\u108e', '\u108e'), - ('\u10a0', '\u10c5'), ('\u10c7', '\u10c7'), - ('\u10cd', '\u10cd'), ('\u10d0', '\u10fa'), - ('\u10fc', '\u10fc'), ('\u10fd', '\u1248'), - ('\u124a', '\u124d'), ('\u1250', '\u1256'), - ('\u1258', '\u1258'), ('\u125a', '\u125d'), - ('\u1260', '\u1288'), ('\u128a', '\u128d'), - ('\u1290', '\u12b0'), ('\u12b2', '\u12b5'), - ('\u12b8', '\u12be'), ('\u12c0', '\u12c0'), - ('\u12c2', '\u12c5'), ('\u12c8', '\u12d6'), - ('\u12d8', '\u1310'), ('\u1312', '\u1315'), - ('\u1318', '\u135a'), ('\u1380', '\u138f'), - ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), - ('\u166f', '\u167f'), ('\u1681', '\u169a'), - ('\u16a0', '\u16ea'), ('\u16ee', '\u16f0'), - ('\u1700', '\u170c'), ('\u170e', '\u1711'), - ('\u1720', '\u1731'), ('\u1740', '\u1751'), - ('\u1760', '\u176c'), ('\u176e', '\u1770'), - ('\u1780', '\u17b3'), ('\u17d7', '\u17d7'), - ('\u17dc', '\u17dc'), ('\u1820', '\u1842'), - ('\u1843', '\u1843'), ('\u1844', '\u1877'), - ('\u1880', '\u18a8'), ('\u18aa', '\u18aa'), - ('\u18b0', '\u18f5'), ('\u1900', '\u191c'), - ('\u1950', '\u196d'), ('\u1970', '\u1974'), - ('\u1980', '\u19ab'), ('\u19c1', '\u19c7'), - ('\u1a00', '\u1a16'), ('\u1a20', '\u1a54'), - ('\u1aa7', '\u1aa7'), ('\u1b05', '\u1b33'), - ('\u1b45', '\u1b4b'), ('\u1b83', '\u1ba0'), - ('\u1bae', '\u1baf'), ('\u1bba', '\u1be5'), - ('\u1c00', '\u1c23'), ('\u1c4d', '\u1c4f'), - ('\u1c5a', '\u1c77'), ('\u1c78', '\u1c7d'), - ('\u1ce9', '\u1cec'), ('\u1cee', '\u1cf1'), - ('\u1cf5', '\u1cf6'), ('\u1d00', '\u1d2b'), - ('\u1d2c', '\u1d6a'), ('\u1d6b', '\u1d77'), - ('\u1d78', '\u1d78'), ('\u1d79', '\u1d9a'), - ('\u1d9b', '\u1dbf'), ('\u1e00', '\u1f15'), - ('\u1f18', '\u1f1d'), ('\u1f20', '\u1f45'), - ('\u1f48', '\u1f4d'), ('\u1f50', '\u1f57'), - ('\u1f59', '\u1f59'), ('\u1f5b', '\u1f5b'), - ('\u1f5d', '\u1f5d'), ('\u1f5f', '\u1f7d'), - ('\u1f80', '\u1fb4'), ('\u1fb6', '\u1fbc'), - ('\u1fbe', '\u1fbe'), ('\u1fc2', '\u1fc4'), - ('\u1fc6', '\u1fcc'), ('\u1fd0', '\u1fd3'), - ('\u1fd6', '\u1fdb'), ('\u1fe0', '\u1fec'), - ('\u1ff2', '\u1ff4'), ('\u1ff6', '\u1ffc'), - ('\u2071', '\u2071'), ('\u207f', '\u207f'), - ('\u2090', '\u209c'), ('\u2102', '\u2102'), - ('\u2107', '\u2107'), ('\u210a', '\u2113'), - ('\u2115', '\u2115'), ('\u2118', '\u2118'), - ('\u2119', '\u211d'), ('\u2124', '\u2124'), - ('\u2126', '\u2126'), ('\u2128', '\u2128'), - ('\u212a', '\u212d'), ('\u212e', '\u212e'), - ('\u212f', '\u2134'), ('\u2135', '\u2138'), - ('\u2139', '\u2139'), ('\u213c', '\u213f'), - ('\u2145', '\u2149'), ('\u214e', '\u214e'), - ('\u2160', '\u2182'), ('\u2183', '\u2184'), - ('\u2185', '\u2188'), ('\u2c00', '\u2c2e'), - ('\u2c30', '\u2c5e'), ('\u2c60', '\u2c7b'), - ('\u2c7c', '\u2c7d'), ('\u2c7e', '\u2ce4'), - ('\u2ceb', '\u2cee'), ('\u2cf2', '\u2cf3'), - ('\u2d00', '\u2d25'), ('\u2d27', '\u2d27'), - ('\u2d2d', '\u2d2d'), ('\u2d30', '\u2d67'), - ('\u2d6f', '\u2d6f'), ('\u2d80', '\u2d96'), - ('\u2da0', '\u2da6'), ('\u2da8', '\u2dae'), - ('\u2db0', '\u2db6'), ('\u2db8', '\u2dbe'), - ('\u2dc0', '\u2dc6'), ('\u2dc8', '\u2dce'), - ('\u2dd0', '\u2dd6'), ('\u2dd8', '\u2dde'), - ('\u3005', '\u3005'), ('\u3006', '\u3006'), - ('\u3007', '\u3007'), ('\u3021', '\u3029'), - ('\u3031', '\u3035'), ('\u3038', '\u303a'), - ('\u303b', '\u303b'), ('\u303c', '\u303c'), - ('\u3041', '\u3096'), ('\u309d', '\u309e'), - ('\u309f', '\u309f'), ('\u30a1', '\u30fa'), - ('\u30fc', '\u30fe'), ('\u30ff', '\u30ff'), - ('\u3105', '\u312d'), ('\u3131', '\u318e'), - ('\u31a0', '\u31ba'), ('\u31f0', '\u31ff'), - ('\u3400', '\u4db5'), ('\u4e00', '\u9fcc'), - ('\ua000', '\ua014'), ('\ua015', '\ua015'), - ('\ua016', '\ua48c'), ('\ua4d0', '\ua4f7'), - ('\ua4f8', '\ua4fd'), ('\ua500', '\ua60b'), - ('\ua60c', '\ua60c'), ('\ua610', '\ua61f'), - ('\ua62a', '\ua62b'), ('\ua640', '\ua66d'), - ('\ua66e', '\ua66e'), ('\ua67f', '\ua67f'), - ('\ua680', '\ua697'), ('\ua6a0', '\ua6e5'), - ('\ua6e6', '\ua6ef'), ('\ua717', '\ua71f'), - ('\ua722', '\ua76f'), ('\ua770', '\ua770'), - ('\ua771', '\ua787'), ('\ua788', '\ua788'), - ('\ua78b', '\ua78e'), ('\ua790', '\ua793'), - ('\ua7a0', '\ua7aa'), ('\ua7f8', '\ua7f9'), - ('\ua7fa', '\ua7fa'), ('\ua7fb', '\ua801'), - ('\ua803', '\ua805'), ('\ua807', '\ua80a'), - ('\ua80c', '\ua822'), ('\ua840', '\ua873'), - ('\ua882', '\ua8b3'), ('\ua8f2', '\ua8f7'), - ('\ua8fb', '\ua8fb'), ('\ua90a', '\ua925'), - ('\ua930', '\ua946'), ('\ua960', '\ua97c'), - ('\ua984', '\ua9b2'), ('\ua9cf', '\ua9cf'), - ('\uaa00', '\uaa28'), ('\uaa40', '\uaa42'), - ('\uaa44', '\uaa4b'), ('\uaa60', '\uaa6f'), - ('\uaa70', '\uaa70'), ('\uaa71', '\uaa76'), - ('\uaa7a', '\uaa7a'), ('\uaa80', '\uaaaf'), - ('\uaab1', '\uaab1'), ('\uaab5', '\uaab6'), - ('\uaab9', '\uaabd'), ('\uaac0', '\uaac0'), - ('\uaac2', '\uaac2'), ('\uaadb', '\uaadc'), - ('\uaadd', '\uaadd'), ('\uaae0', '\uaaea'), - ('\uaaf2', '\uaaf2'), ('\uaaf3', '\uaaf4'), - ('\uab01', '\uab06'), ('\uab09', '\uab0e'), - ('\uab11', '\uab16'), ('\uab20', '\uab26'), - ('\uab28', '\uab2e'), ('\uabc0', '\uabe2'), - ('\uac00', '\ud7a3'), ('\ud7b0', '\ud7c6'), - ('\ud7cb', '\ud7fb'), ('\uf900', '\ufa6d'), - ('\ufa70', '\ufad9'), ('\ufb00', '\ufb06'), - ('\ufb13', '\ufb17'), ('\ufb1d', '\ufb1d'), - ('\ufb1f', '\ufb28'), ('\ufb2a', '\ufb36'), - ('\ufb38', '\ufb3c'), ('\ufb3e', '\ufb3e'), - ('\ufb40', '\ufb41'), ('\ufb43', '\ufb44'), - ('\ufb46', '\ufbb1'), ('\ufbd3', '\ufc5d'), - ('\ufc64', '\ufd3d'), ('\ufd50', '\ufd8f'), - ('\ufd92', '\ufdc7'), ('\ufdf0', '\ufdf9'), - ('\ufe71', '\ufe71'), ('\ufe73', '\ufe73'), - ('\ufe77', '\ufe77'), ('\ufe79', '\ufe79'), - ('\ufe7b', '\ufe7b'), ('\ufe7d', '\ufe7d'), - ('\ufe7f', '\ufefc'), ('\uff21', '\uff3a'), - ('\uff41', '\uff5a'), ('\uff66', '\uff6f'), - ('\uff70', '\uff70'), ('\uff71', '\uff9d'), - ('\uffa0', '\uffbe'), ('\uffc2', '\uffc7'), - ('\uffca', '\uffcf'), ('\uffd2', '\uffd7'), - ('\uffda', '\uffdc'), ('\U00010000', '\U0001000b'), - ('\U0001000d', '\U00010026'), ('\U00010028', '\U0001003a'), - ('\U0001003c', '\U0001003d'), ('\U0001003f', '\U0001004d'), - ('\U00010050', '\U0001005d'), ('\U00010080', '\U000100fa'), - ('\U00010140', '\U00010174'), ('\U00010280', '\U0001029c'), - ('\U000102a0', '\U000102d0'), ('\U00010300', '\U0001031e'), - ('\U00010330', '\U00010340'), ('\U00010341', '\U00010341'), - ('\U00010342', '\U00010349'), ('\U0001034a', '\U0001034a'), - ('\U00010380', '\U0001039d'), ('\U000103a0', '\U000103c3'), - ('\U000103c8', '\U000103cf'), ('\U000103d1', '\U000103d5'), - ('\U00010400', '\U0001044f'), ('\U00010450', '\U0001049d'), - ('\U00010800', '\U00010805'), ('\U00010808', '\U00010808'), - ('\U0001080a', '\U00010835'), ('\U00010837', '\U00010838'), - ('\U0001083c', '\U0001083c'), ('\U0001083f', '\U00010855'), - ('\U00010900', '\U00010915'), ('\U00010920', '\U00010939'), - ('\U00010980', '\U000109b7'), ('\U000109be', '\U000109bf'), - ('\U00010a00', '\U00010a00'), ('\U00010a10', '\U00010a13'), - ('\U00010a15', '\U00010a17'), ('\U00010a19', '\U00010a33'), - ('\U00010a60', '\U00010a7c'), ('\U00010b00', '\U00010b35'), - ('\U00010b40', '\U00010b55'), ('\U00010b60', '\U00010b72'), - ('\U00010c00', '\U00010c48'), ('\U00011003', '\U00011037'), - ('\U00011083', '\U000110af'), ('\U000110d0', '\U000110e8'), - ('\U00011103', '\U00011126'), ('\U00011183', '\U000111b2'), - ('\U000111c1', '\U000111c4'), ('\U00011680', '\U000116aa'), - ('\U00012000', '\U0001236e'), ('\U00012400', '\U00012462'), - ('\U00013000', '\U0001342e'), ('\U00016800', '\U00016a38'), - ('\U00016f00', '\U00016f44'), ('\U00016f50', '\U00016f50'), - ('\U00016f93', '\U00016f9f'), ('\U0001b000', '\U0001b001'), - ('\U0001d400', '\U0001d454'), ('\U0001d456', '\U0001d49c'), - ('\U0001d49e', '\U0001d49f'), ('\U0001d4a2', '\U0001d4a2'), - ('\U0001d4a5', '\U0001d4a6'), ('\U0001d4a9', '\U0001d4ac'), - ('\U0001d4ae', '\U0001d4b9'), ('\U0001d4bb', '\U0001d4bb'), - ('\U0001d4bd', '\U0001d4c3'), ('\U0001d4c5', '\U0001d505'), - ('\U0001d507', '\U0001d50a'), ('\U0001d50d', '\U0001d514'), - ('\U0001d516', '\U0001d51c'), ('\U0001d51e', '\U0001d539'), - ('\U0001d53b', '\U0001d53e'), ('\U0001d540', '\U0001d544'), - ('\U0001d546', '\U0001d546'), ('\U0001d54a', '\U0001d550'), - ('\U0001d552', '\U0001d6a5'), ('\U0001d6a8', '\U0001d6c0'), - ('\U0001d6c2', '\U0001d6da'), ('\U0001d6dc', '\U0001d6fa'), - ('\U0001d6fc', '\U0001d714'), ('\U0001d716', '\U0001d734'), - ('\U0001d736', '\U0001d74e'), ('\U0001d750', '\U0001d76e'), - ('\U0001d770', '\U0001d788'), ('\U0001d78a', '\U0001d7a8'), - ('\U0001d7aa', '\U0001d7c2'), ('\U0001d7c4', '\U0001d7cb'), - ('\U0001ee00', '\U0001ee03'), ('\U0001ee05', '\U0001ee1f'), - ('\U0001ee21', '\U0001ee22'), ('\U0001ee24', '\U0001ee24'), - ('\U0001ee27', '\U0001ee27'), ('\U0001ee29', '\U0001ee32'), - ('\U0001ee34', '\U0001ee37'), ('\U0001ee39', '\U0001ee39'), - ('\U0001ee3b', '\U0001ee3b'), ('\U0001ee42', '\U0001ee42'), - ('\U0001ee47', '\U0001ee47'), ('\U0001ee49', '\U0001ee49'), - ('\U0001ee4b', '\U0001ee4b'), ('\U0001ee4d', '\U0001ee4f'), - ('\U0001ee51', '\U0001ee52'), ('\U0001ee54', '\U0001ee54'), - ('\U0001ee57', '\U0001ee57'), ('\U0001ee59', '\U0001ee59'), - ('\U0001ee5b', '\U0001ee5b'), ('\U0001ee5d', '\U0001ee5d'), - ('\U0001ee5f', '\U0001ee5f'), ('\U0001ee61', '\U0001ee62'), - ('\U0001ee64', '\U0001ee64'), ('\U0001ee67', '\U0001ee6a'), - ('\U0001ee6c', '\U0001ee72'), ('\U0001ee74', '\U0001ee77'), - ('\U0001ee79', '\U0001ee7c'), ('\U0001ee7e', '\U0001ee7e'), - ('\U0001ee80', '\U0001ee89'), ('\U0001ee8b', '\U0001ee9b'), - ('\U0001eea1', '\U0001eea3'), ('\U0001eea5', '\U0001eea9'), - ('\U0001eeab', '\U0001eebb'), ('\U00020000', '\U0002a6d6'), - ('\U0002a700', '\U0002b734'), ('\U0002b740', '\U0002b81d'), - ('\U0002f800', '\U0002fa1d') - ]; - - pub fn XID_Start(c: char) -> bool { - bsearch_range_table(c, XID_Start_table) - } -} diff --git a/src/libstd/arc.rs b/src/libextra/arc.rs similarity index 100% rename from src/libstd/arc.rs rename to src/libextra/arc.rs diff --git a/src/libstd/arena.rs b/src/libextra/arena.rs similarity index 100% rename from src/libstd/arena.rs rename to src/libextra/arena.rs diff --git a/src/libstd/base64.rs b/src/libextra/base64.rs similarity index 100% rename from src/libstd/base64.rs rename to src/libextra/base64.rs diff --git a/src/libstd/bitv.rs b/src/libextra/bitv.rs similarity index 100% rename from src/libstd/bitv.rs rename to src/libextra/bitv.rs diff --git a/src/libstd/c_vec.rs b/src/libextra/c_vec.rs similarity index 100% rename from src/libstd/c_vec.rs rename to src/libextra/c_vec.rs diff --git a/src/libextra/comm.rs b/src/libextra/comm.rs new file mode 100644 index 0000000000000..20ab2d61ecc07 --- /dev/null +++ b/src/libextra/comm.rs @@ -0,0 +1,110 @@ +// Copyright 2012 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. + +/*! + +Higher level communication abstractions. + +*/ + +use core::comm::{GenericChan, GenericSmartChan, GenericPort}; +use core::comm::{Chan, Port, Selectable, Peekable}; +use core::pipes; + +/// An extension of `pipes::stream` that allows both sending and receiving. +pub struct DuplexStream { + priv chan: Chan, + priv port: Port, +} + +// Allow these methods to be used without import: +pub impl DuplexStream { + fn send(&self, x: T) { + self.chan.send(x) + } + fn try_send(&self, x: T) -> bool { + self.chan.try_send(x) + } + fn recv(&self, ) -> U { + self.port.recv() + } + fn try_recv(&self) -> Option { + self.port.try_recv() + } + fn peek(&self) -> bool { + self.port.peek() + } +} + +impl GenericChan for DuplexStream { + fn send(&self, x: T) { + self.chan.send(x) + } +} + +impl GenericSmartChan for DuplexStream { + fn try_send(&self, x: T) -> bool { + self.chan.try_send(x) + } +} + +impl GenericPort for DuplexStream { + fn recv(&self) -> U { + self.port.recv() + } + + fn try_recv(&self) -> Option { + self.port.try_recv() + } +} + +impl Peekable for DuplexStream { + fn peek(&self) -> bool { + self.port.peek() + } +} + +impl Selectable for DuplexStream { + fn header(&mut self) -> *mut pipes::PacketHeader { + self.port.header() + } +} + +/// Creates a bidirectional stream. +pub fn DuplexStream() + -> (DuplexStream, DuplexStream) +{ + let (p1, c2) = comm::stream(); + let (p2, c1) = comm::stream(); + (DuplexStream { + chan: c1, + port: p1 + }, + DuplexStream { + chan: c2, + port: p2 + }) +} + +#[cfg(test)] +mod test { + use comm::DuplexStream; + + #[test] + pub fn DuplexStream1() { + let (left, right) = DuplexStream(); + + left.send(~"abc"); + right.send(123); + + assert!(left.recv() == 123); + assert!(right.recv() == ~"abc"); + } +} diff --git a/src/libstd/dbg.rs b/src/libextra/dbg.rs similarity index 100% rename from src/libstd/dbg.rs rename to src/libextra/dbg.rs diff --git a/src/libstd/deque.rs b/src/libextra/deque.rs similarity index 100% rename from src/libstd/deque.rs rename to src/libextra/deque.rs diff --git a/src/libstd/dlist.rs b/src/libextra/dlist.rs similarity index 100% rename from src/libstd/dlist.rs rename to src/libextra/dlist.rs diff --git a/src/libstd/ebml.rs b/src/libextra/ebml.rs similarity index 100% rename from src/libstd/ebml.rs rename to src/libextra/ebml.rs diff --git a/src/libstd/fileinput.rs b/src/libextra/fileinput.rs similarity index 100% rename from src/libstd/fileinput.rs rename to src/libextra/fileinput.rs diff --git a/src/libstd/flate.rs b/src/libextra/flate.rs similarity index 100% rename from src/libstd/flate.rs rename to src/libextra/flate.rs diff --git a/src/libstd/flatpipes.rs b/src/libextra/flatpipes.rs similarity index 100% rename from src/libstd/flatpipes.rs rename to src/libextra/flatpipes.rs diff --git a/src/libstd/fun_treemap.rs b/src/libextra/fun_treemap.rs similarity index 100% rename from src/libstd/fun_treemap.rs rename to src/libextra/fun_treemap.rs diff --git a/src/libstd/future.rs b/src/libextra/future.rs similarity index 100% rename from src/libstd/future.rs rename to src/libextra/future.rs diff --git a/src/libstd/getopts.rs b/src/libextra/getopts.rs similarity index 100% rename from src/libstd/getopts.rs rename to src/libextra/getopts.rs diff --git a/src/libstd/io_util.rs b/src/libextra/io_util.rs similarity index 100% rename from src/libstd/io_util.rs rename to src/libextra/io_util.rs diff --git a/src/libstd/json.rs b/src/libextra/json.rs similarity index 100% rename from src/libstd/json.rs rename to src/libextra/json.rs diff --git a/src/libstd/list.rs b/src/libextra/list.rs similarity index 100% rename from src/libstd/list.rs rename to src/libextra/list.rs diff --git a/src/libstd/md4.rs b/src/libextra/md4.rs similarity index 100% rename from src/libstd/md4.rs rename to src/libextra/md4.rs diff --git a/src/libstd/net.rs b/src/libextra/net.rs similarity index 100% rename from src/libstd/net.rs rename to src/libextra/net.rs diff --git a/src/libstd/net_ip.rs b/src/libextra/net_ip.rs similarity index 100% rename from src/libstd/net_ip.rs rename to src/libextra/net_ip.rs diff --git a/src/libstd/net_tcp.rs b/src/libextra/net_tcp.rs similarity index 100% rename from src/libstd/net_tcp.rs rename to src/libextra/net_tcp.rs diff --git a/src/libstd/net_url.rs b/src/libextra/net_url.rs similarity index 100% rename from src/libstd/net_url.rs rename to src/libextra/net_url.rs diff --git a/src/libstd/num/bigint.rs b/src/libextra/num/bigint.rs similarity index 100% rename from src/libstd/num/bigint.rs rename to src/libextra/num/bigint.rs diff --git a/src/libstd/num/complex.rs b/src/libextra/num/complex.rs similarity index 100% rename from src/libstd/num/complex.rs rename to src/libextra/num/complex.rs diff --git a/src/libstd/num/rational.rs b/src/libextra/num/rational.rs similarity index 100% rename from src/libstd/num/rational.rs rename to src/libextra/num/rational.rs diff --git a/src/libstd/par.rs b/src/libextra/par.rs similarity index 100% rename from src/libstd/par.rs rename to src/libextra/par.rs diff --git a/src/libstd/priority_queue.rs b/src/libextra/priority_queue.rs similarity index 100% rename from src/libstd/priority_queue.rs rename to src/libextra/priority_queue.rs diff --git a/src/libstd/rc.rs b/src/libextra/rc.rs similarity index 100% rename from src/libstd/rc.rs rename to src/libextra/rc.rs diff --git a/src/libstd/rl.rs b/src/libextra/rl.rs similarity index 100% rename from src/libstd/rl.rs rename to src/libextra/rl.rs diff --git a/src/libstd/rope.rs b/src/libextra/rope.rs similarity index 100% rename from src/libstd/rope.rs rename to src/libextra/rope.rs diff --git a/src/libstd/semver.rs b/src/libextra/semver.rs similarity index 100% rename from src/libstd/semver.rs rename to src/libextra/semver.rs diff --git a/src/libstd/serialize.rs b/src/libextra/serialize.rs similarity index 100% rename from src/libstd/serialize.rs rename to src/libextra/serialize.rs diff --git a/src/libstd/sha1.rs b/src/libextra/sha1.rs similarity index 100% rename from src/libstd/sha1.rs rename to src/libextra/sha1.rs diff --git a/src/libstd/smallintmap.rs b/src/libextra/smallintmap.rs similarity index 100% rename from src/libstd/smallintmap.rs rename to src/libextra/smallintmap.rs diff --git a/src/libstd/sort.rs b/src/libextra/sort.rs similarity index 100% rename from src/libstd/sort.rs rename to src/libextra/sort.rs diff --git a/src/libstd/stats.rs b/src/libextra/stats.rs similarity index 100% rename from src/libstd/stats.rs rename to src/libextra/stats.rs diff --git a/src/libstd/std.rc b/src/libextra/std.rc similarity index 100% rename from src/libstd/std.rc rename to src/libextra/std.rc diff --git a/src/libstd/sync.rs b/src/libextra/sync.rs similarity index 100% rename from src/libstd/sync.rs rename to src/libextra/sync.rs diff --git a/src/libstd/task_pool.rs b/src/libextra/task_pool.rs similarity index 100% rename from src/libstd/task_pool.rs rename to src/libextra/task_pool.rs diff --git a/src/libstd/tempfile.rs b/src/libextra/tempfile.rs similarity index 100% rename from src/libstd/tempfile.rs rename to src/libextra/tempfile.rs diff --git a/src/libstd/term.rs b/src/libextra/term.rs similarity index 100% rename from src/libstd/term.rs rename to src/libextra/term.rs diff --git a/src/libstd/test.rs b/src/libextra/test.rs similarity index 100% rename from src/libstd/test.rs rename to src/libextra/test.rs diff --git a/src/libstd/time.rs b/src/libextra/time.rs similarity index 100% rename from src/libstd/time.rs rename to src/libextra/time.rs diff --git a/src/libstd/timer.rs b/src/libextra/timer.rs similarity index 100% rename from src/libstd/timer.rs rename to src/libextra/timer.rs diff --git a/src/libstd/treemap.rs b/src/libextra/treemap.rs similarity index 100% rename from src/libstd/treemap.rs rename to src/libextra/treemap.rs diff --git a/src/libextra/unicode.rs b/src/libextra/unicode.rs new file mode 100644 index 0000000000000..77996de6d8394 --- /dev/null +++ b/src/libextra/unicode.rs @@ -0,0 +1,248 @@ +// Copyright 2012 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. + +#[forbid(deprecated_mode)]; + +pub mod icu { + pub type UBool = u8; + pub type UProperty = int; + pub type UChar32 = char; + + pub static TRUE : u8 = 1u8; + pub static FALSE : u8 = 1u8; + + pub static UCHAR_ALPHABETIC : UProperty = 0; + pub static UCHAR_BINARY_START : UProperty = 0; // = UCHAR_ALPHABETIC + pub static UCHAR_ASCII_HEX_DIGIT : UProperty = 1; + pub static UCHAR_BIDI_CONTROL : UProperty = 2; + + pub static UCHAR_BIDI_MIRRORED : UProperty = 3; + pub static UCHAR_DASH : UProperty = 4; + pub static UCHAR_DEFAULT_IGNORABLE_CODE_POINT : UProperty = 5; + pub static UCHAR_DEPRECATED : UProperty = 6; + + pub static UCHAR_DIACRITIC : UProperty = 7; + pub static UCHAR_EXTENDER : UProperty = 8; + pub static UCHAR_FULL_COMPOSITION_EXCLUSION : UProperty = 9; + pub static UCHAR_GRAPHEME_BASE : UProperty = 10; + + pub static UCHAR_GRAPHEME_EXTEND : UProperty = 11; + pub static UCHAR_GRAPHEME_LINK : UProperty = 12; + pub static UCHAR_HEX_DIGIT : UProperty = 13; + pub static UCHAR_HYPHEN : UProperty = 14; + + pub static UCHAR_ID_CONTINUE : UProperty = 15; + pub static UCHAR_ID_START : UProperty = 16; + pub static UCHAR_IDEOGRAPHIC : UProperty = 17; + pub static UCHAR_IDS_BINARY_OPERATOR : UProperty = 18; + + pub static UCHAR_IDS_TRINARY_OPERATOR : UProperty = 19; + pub static UCHAR_JOIN_CONTROL : UProperty = 20; + pub static UCHAR_LOGICAL_ORDER_EXCEPTION : UProperty = 21; + pub static UCHAR_LOWERCASE : UProperty = 22; + + pub static UCHAR_MATH : UProperty = 23; + pub static UCHAR_NONCHARACTER_CODE_POINT : UProperty = 24; + pub static UCHAR_QUOTATION_MARK : UProperty = 25; + pub static UCHAR_RADICAL : UProperty = 26; + + pub static UCHAR_SOFT_DOTTED : UProperty = 27; + pub static UCHAR_TERMINAL_PUNCTUATION : UProperty = 28; + pub static UCHAR_UNIFIED_IDEOGRAPH : UProperty = 29; + pub static UCHAR_UPPERCASE : UProperty = 30; + + pub static UCHAR_WHITE_SPACE : UProperty = 31; + pub static UCHAR_XID_CONTINUE : UProperty = 32; + pub static UCHAR_XID_START : UProperty = 33; + pub static UCHAR_CASE_SENSITIVE : UProperty = 34; + + pub static UCHAR_S_TERM : UProperty = 35; + pub static UCHAR_VARIATION_SELECTOR : UProperty = 36; + pub static UCHAR_NFD_INERT : UProperty = 37; + pub static UCHAR_NFKD_INERT : UProperty = 38; + + pub static UCHAR_NFC_INERT : UProperty = 39; + pub static UCHAR_NFKC_INERT : UProperty = 40; + pub static UCHAR_SEGMENT_STARTER : UProperty = 41; + pub static UCHAR_PATTERN_SYNTAX : UProperty = 42; + + pub static UCHAR_PATTERN_WHITE_SPACE : UProperty = 43; + pub static UCHAR_POSIX_ALNUM : UProperty = 44; + pub static UCHAR_POSIX_BLANK : UProperty = 45; + pub static UCHAR_POSIX_GRAPH : UProperty = 46; + + pub static UCHAR_POSIX_PRINT : UProperty = 47; + pub static UCHAR_POSIX_XDIGIT : UProperty = 48; + pub static UCHAR_CASED : UProperty = 49; + pub static UCHAR_CASE_IGNORABLE : UProperty = 50; + + pub static UCHAR_CHANGES_WHEN_LOWERCASED : UProperty = 51; + pub static UCHAR_CHANGES_WHEN_UPPERCASED : UProperty = 52; + pub static UCHAR_CHANGES_WHEN_TITLECASED : UProperty = 53; + pub static UCHAR_CHANGES_WHEN_CASEFOLDED : UProperty = 54; + + pub static UCHAR_CHANGES_WHEN_CASEMAPPED : UProperty = 55; + pub static UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED : UProperty = 56; + pub static UCHAR_BINARY_LIMIT : UProperty = 57; + pub static UCHAR_BIDI_CLASS : UProperty = 0x1000; + + pub static UCHAR_INT_START : UProperty = 0x1000; // UCHAR_BIDI_CLASS + pub static UCHAR_BLOCK : UProperty = 0x1001; + pub static UCHAR_CANONICAL_COMBINING_CLASS : UProperty = 0x1002; + pub static UCHAR_DECOMPOSITION_TYPE : UProperty = 0x1003; + + pub static UCHAR_EAST_ASIAN_WIDTH : UProperty = 0x1004; + pub static UCHAR_GENERAL_CATEGORY : UProperty = 0x1005; + pub static UCHAR_JOINING_GROUP : UProperty = 0x1006; + pub static UCHAR_JOINING_TYPE : UProperty = 0x1007; + + pub static UCHAR_LINE_BREAK : UProperty = 0x1008; + pub static UCHAR_NUMERIC_TYPE : UProperty = 0x1009; + pub static UCHAR_SCRIPT : UProperty = 0x100A; + pub static UCHAR_HANGUL_SYLLABLE_TYPE : UProperty = 0x100B; + + pub static UCHAR_NFD_QUICK_CHECK : UProperty = 0x100C; + pub static UCHAR_NFKD_QUICK_CHECK : UProperty = 0x100D; + pub static UCHAR_NFC_QUICK_CHECK : UProperty = 0x100E; + pub static UCHAR_NFKC_QUICK_CHECK : UProperty = 0x100F; + + pub static UCHAR_LEAD_CANONICAL_COMBINING_CLASS : UProperty = 0x1010; + pub static UCHAR_TRAIL_CANONICAL_COMBINING_CLASS : UProperty = 0x1011; + pub static UCHAR_GRAPHEME_CLUSTER_BREAK : UProperty = 0x1012; + pub static UCHAR_SENTENCE_BREAK : UProperty = 0x1013; + + pub static UCHAR_WORD_BREAK : UProperty = 0x1014; + pub static UCHAR_INT_LIMIT : UProperty = 0x1015; + + pub static UCHAR_GENERAL_CATEGORY_MASK : UProperty = 0x2000; + pub static UCHAR_MASK_START : UProperty = 0x2000; + // = UCHAR_GENERAL_CATEGORY_MASK + pub static UCHAR_MASK_LIMIT : UProperty = 0x2001; + + pub static UCHAR_NUMERIC_VALUE : UProperty = 0x3000; + pub static UCHAR_DOUBLE_START : UProperty = 0x3000; + // = UCHAR_NUMERIC_VALUE + pub static UCHAR_DOUBLE_LIMIT : UProperty = 0x3001; + + pub static UCHAR_AGE : UProperty = 0x4000; + pub static UCHAR_STRING_START : UProperty = 0x4000; // = UCHAR_AGE + pub static UCHAR_BIDI_MIRRORING_GLYPH : UProperty = 0x4001; + pub static UCHAR_CASE_FOLDING : UProperty = 0x4002; + + pub static UCHAR_ISO_COMMENT : UProperty = 0x4003; + pub static UCHAR_LOWERCASE_MAPPING : UProperty = 0x4004; + pub static UCHAR_NAME : UProperty = 0x4005; + pub static UCHAR_SIMPLE_CASE_FOLDING : UProperty = 0x4006; + + pub static UCHAR_SIMPLE_LOWERCASE_MAPPING : UProperty = 0x4007; + pub static UCHAR_SIMPLE_TITLECASE_MAPPING : UProperty = 0x4008; + pub static UCHAR_SIMPLE_UPPERCASE_MAPPING : UProperty = 0x4009; + pub static UCHAR_TITLECASE_MAPPING : UProperty = 0x400A; + + pub static UCHAR_UNICODE_1_NAME : UProperty = 0x400B; + pub static UCHAR_UPPERCASE_MAPPING : UProperty = 0x400C; + pub static UCHAR_STRING_LIMIT : UProperty = 0x400D; + + pub static UCHAR_SCRIPT_EXTENSIONS : UProperty = 0x7000; + pub static UCHAR_OTHER_PROPERTY_START : UProperty = 0x7000; + // = UCHAR_SCRIPT_EXTENSIONS; + pub static UCHAR_OTHER_PROPERTY_LIMIT : UProperty = 0x7001; + + pub static UCHAR_INVALID_CODE : UProperty = -1; + + pub mod libicu { + #[link_name = "icuuc"] + #[abi = "cdecl"] + pub extern { + unsafe fn u_hasBinaryProperty(c: UChar32, which: UProperty) + -> UBool; + unsafe fn u_isdigit(c: UChar32) -> UBool; + unsafe fn u_islower(c: UChar32) -> UBool; + unsafe fn u_isspace(c: UChar32) -> UBool; + unsafe fn u_isupper(c: UChar32) -> UBool; + unsafe fn u_tolower(c: UChar32) -> UChar32; + unsafe fn u_toupper(c: UChar32) -> UChar32; + } + } +} + +pub fn is_XID_start(c: char) -> bool { + return icu::libicu::u_hasBinaryProperty(c, icu::UCHAR_XID_START) + == icu::TRUE; +} + +pub fn is_XID_continue(c: char) -> bool { + return icu::libicu::u_hasBinaryProperty(c, icu::UCHAR_XID_START) + == icu::TRUE; +} + +/* +Function: is_digit + +Returns true if a character is a digit. +*/ +pub fn is_digit(c: char) -> bool { + return icu::libicu::u_isdigit(c) == icu::TRUE; +} + +/* +Function: is_lower + +Returns true if a character is a lowercase letter. +*/ +pub fn is_lower(c: char) -> bool { + return icu::libicu::u_islower(c) == icu::TRUE; +} + +/* +Function: is_space + +Returns true if a character is space. +*/ +pub fn is_space(c: char) -> bool { + return icu::libicu::u_isspace(c) == icu::TRUE; +} + +/* +Function: is_upper + +Returns true if a character is an uppercase letter. +*/ +pub fn is_upper(c: char) -> bool { + return icu::libicu::u_isupper(c) == icu::TRUE; +} + +#[cfg(test)] +mod tests { + + #[test] + fn test_is_digit() { + assert!((unicode::icu::is_digit('0'))); + assert!((!unicode::icu::is_digit('m'))); + } + + #[test] + fn test_is_lower() { + assert!((unicode::icu::is_lower('m'))); + assert!((!unicode::icu::is_lower('M'))); + } + + #[test] + fn test_is_space() { + assert!((unicode::icu::is_space(' '))); + assert!((!unicode::icu::is_space('m'))); + } + + #[test] + fn test_is_upper() { + assert!((unicode::icu::is_upper('M'))); + assert!((!unicode::icu::is_upper('m'))); + } +} diff --git a/src/libstd/uv.rs b/src/libextra/uv.rs similarity index 100% rename from src/libstd/uv.rs rename to src/libextra/uv.rs diff --git a/src/libstd/uv_global_loop.rs b/src/libextra/uv_global_loop.rs similarity index 100% rename from src/libstd/uv_global_loop.rs rename to src/libextra/uv_global_loop.rs diff --git a/src/libstd/uv_iotask.rs b/src/libextra/uv_iotask.rs similarity index 100% rename from src/libstd/uv_iotask.rs rename to src/libextra/uv_iotask.rs diff --git a/src/libstd/uv_ll.rs b/src/libextra/uv_ll.rs similarity index 100% rename from src/libstd/uv_ll.rs rename to src/libextra/uv_ll.rs diff --git a/src/libstd/workcache.rs b/src/libextra/workcache.rs similarity index 100% rename from src/libstd/workcache.rs rename to src/libextra/workcache.rs diff --git a/src/libcore/at_vec.rs b/src/libstd/at_vec.rs similarity index 100% rename from src/libcore/at_vec.rs rename to src/libstd/at_vec.rs diff --git a/src/libcore/bool.rs b/src/libstd/bool.rs similarity index 100% rename from src/libcore/bool.rs rename to src/libstd/bool.rs diff --git a/src/libcore/cast.rs b/src/libstd/cast.rs similarity index 100% rename from src/libcore/cast.rs rename to src/libstd/cast.rs diff --git a/src/libcore/cell.rs b/src/libstd/cell.rs similarity index 100% rename from src/libcore/cell.rs rename to src/libstd/cell.rs diff --git a/src/libcore/char.rs b/src/libstd/char.rs similarity index 100% rename from src/libcore/char.rs rename to src/libstd/char.rs diff --git a/src/libcore/cleanup.rs b/src/libstd/cleanup.rs similarity index 100% rename from src/libcore/cleanup.rs rename to src/libstd/cleanup.rs diff --git a/src/libcore/clone.rs b/src/libstd/clone.rs similarity index 100% rename from src/libcore/clone.rs rename to src/libstd/clone.rs diff --git a/src/libcore/cmp.rs b/src/libstd/cmp.rs similarity index 100% rename from src/libcore/cmp.rs rename to src/libstd/cmp.rs diff --git a/src/libstd/comm.rs b/src/libstd/comm.rs index 28d3d329b2615..59eb915c239fe 100644 --- a/src/libstd/comm.rs +++ b/src/libstd/comm.rs @@ -9,102 +9,802 @@ // except according to those terms. /*! +Message passing +*/ -Higher level communication abstractions. +use cast::{transmute, transmute_mut}; +use container::Container; +use either::{Either, Left, Right}; +use kinds::Owned; +use option::{Option, Some, None}; +use uint; +use vec; +use vec::OwnedVector; +use util::replace; +use unstable::sync::{Exclusive, exclusive}; +use rtcomm = rt::comm; +use rt; -*/ +use pipes::{wait_many, PacketHeader}; + +// FIXME #5160: Making this public exposes some plumbing from +// pipes. Needs some refactoring +pub use pipes::Selectable; -use core::comm::{GenericChan, GenericSmartChan, GenericPort}; -use core::comm::{Chan, Port, Selectable, Peekable}; -use core::pipes; +/// A trait for things that can send multiple messages. +pub trait GenericChan { + /// Sends a message. + fn send(&self, x: T); +} + +/// Things that can send multiple messages and can detect when the receiver +/// is closed +pub trait GenericSmartChan { + /// Sends a message, or report if the receiver has closed the connection. + fn try_send(&self, x: T) -> bool; +} + +/// A trait for things that can receive multiple messages. +pub trait GenericPort { + /// Receives a message, or fails if the connection closes. + fn recv(&self) -> T; + + /** Receives a message, or returns `none` if + the connection is closed or closes. + */ + fn try_recv(&self) -> Option; +} + +/// Ports that can `peek` +pub trait Peekable { + /// Returns true if a message is available + fn peek(&self) -> bool; +} -/// An extension of `pipes::stream` that allows both sending and receiving. -pub struct DuplexStream { - priv chan: Chan, - priv port: Port, +/// An endpoint that can send many messages. +pub struct Chan { + inner: Either, rtcomm::Chan> } -// Allow these methods to be used without import: -pub impl DuplexStream { +/// An endpoint that can receive many messages. +pub struct Port { + inner: Either, rtcomm::Port> +} + +/** Creates a `(Port, Chan)` pair. + +These allow sending or receiving an unlimited number of messages. + +*/ +pub fn stream() -> (Port, Chan) { + let (port, chan) = match rt::context() { + rt::OldTaskContext => match pipesy::stream() { + (p, c) => (Left(p), Left(c)) + }, + _ => match rtcomm::stream() { + (p, c) => (Right(p), Right(c)) + } + }; + let port = Port { inner: port }; + let chan = Chan { inner: chan }; + return (port, chan); +} + +impl GenericChan for Chan { fn send(&self, x: T) { - self.chan.send(x) + match self.inner { + Left(ref chan) => chan.send(x), + Right(ref chan) => chan.send(x) + } } +} + +impl GenericSmartChan for Chan { fn try_send(&self, x: T) -> bool { - self.chan.try_send(x) + match self.inner { + Left(ref chan) => chan.try_send(x), + Right(ref chan) => chan.try_send(x) + } } - fn recv(&self, ) -> U { - self.port.recv() +} + +impl GenericPort for Port { + fn recv(&self) -> T { + match self.inner { + Left(ref port) => port.recv(), + Right(ref port) => port.recv() + } } - fn try_recv(&self) -> Option { - self.port.try_recv() + + fn try_recv(&self) -> Option { + match self.inner { + Left(ref port) => port.try_recv(), + Right(ref port) => port.try_recv() + } } +} + +impl Peekable for Port { fn peek(&self) -> bool { - self.port.peek() + match self.inner { + Left(ref port) => port.peek(), + Right(ref port) => port.peek() + } + } +} + +impl Selectable for Port { + fn header(&mut self) -> *mut PacketHeader { + match self.inner { + Left(ref mut port) => port.header(), + Right(_) => fail!("can't select on newsched ports") + } + } +} + +/// Treat many ports as one. +#[unsafe_mut_field(ports)] +pub struct PortSet { + ports: ~[pipesy::Port], +} + +pub impl PortSet { + fn new() -> PortSet { + PortSet { + ports: ~[] + } + } + + fn add(&self, port: Port) { + let Port { inner } = port; + let port = match inner { + Left(p) => p, + Right(_) => fail!("PortSet not implemented") + }; + unsafe { + let self_ports = transmute_mut(&self.ports); + self_ports.push(port) + } + } + + fn chan(&self) -> Chan { + let (po, ch) = stream(); + self.add(po); + ch + } +} + +impl GenericPort for PortSet { + fn try_recv(&self) -> Option { + unsafe { + let self_ports = transmute_mut(&self.ports); + let mut result = None; + // we have to swap the ports array so we aren't borrowing + // aliasable mutable memory. + let mut ports = replace(self_ports, ~[]); + while result.is_none() && ports.len() > 0 { + let i = wait_many(ports); + match ports[i].try_recv() { + Some(m) => { + result = Some(m); + } + None => { + // Remove this port. + let _ = ports.swap_remove(i); + } + } + } + *self_ports = ports; + result + } + } + fn recv(&self) -> T { + self.try_recv().expect("port_set: endpoints closed") } } -impl GenericChan for DuplexStream { +impl Peekable for PortSet { + fn peek(&self) -> bool { + // It'd be nice to use self.port.each, but that version isn't + // pure. + for uint::range(0, vec::uniq_len(&const self.ports)) |i| { + let port: &pipesy::Port = &self.ports[i]; + if port.peek() { + return true; + } + } + false + } +} + +/// A channel that can be shared between many senders. +pub struct SharedChan { + ch: Exclusive> +} + +impl SharedChan { + /// Converts a `chan` into a `shared_chan`. + pub fn new(c: Chan) -> SharedChan { + let Chan { inner } = c; + let c = match inner { + Left(c) => c, + Right(_) => fail!("SharedChan not implemented") + }; + SharedChan { ch: exclusive(c) } + } +} + +impl GenericChan for SharedChan { fn send(&self, x: T) { - self.chan.send(x) + let mut xx = Some(x); + do self.ch.with_imm |chan| { + let x = replace(&mut xx, None); + chan.send(x.unwrap()) + } } } -impl GenericSmartChan for DuplexStream { +impl GenericSmartChan for SharedChan { fn try_send(&self, x: T) -> bool { - self.chan.try_send(x) + let mut xx = Some(x); + do self.ch.with_imm |chan| { + let x = replace(&mut xx, None); + chan.try_send(x.unwrap()) + } + } +} + +impl ::clone::Clone for SharedChan { + fn clone(&self) -> SharedChan { + SharedChan { ch: self.ch.clone() } } } -impl GenericPort for DuplexStream { - fn recv(&self) -> U { - self.port.recv() +pub struct PortOne { + inner: Either, rtcomm::PortOne> +} + +pub struct ChanOne { + inner: Either, rtcomm::ChanOne> +} + +pub fn oneshot() -> (PortOne, ChanOne) { + let (port, chan) = match rt::context() { + rt::OldTaskContext => match pipesy::oneshot() { + (p, c) => (Left(p), Left(c)), + }, + _ => match rtcomm::oneshot() { + (p, c) => (Right(p), Right(c)) + } + }; + let port = PortOne { inner: port }; + let chan = ChanOne { inner: chan }; + return (port, chan); +} + +impl PortOne { + pub fn recv(self) -> T { + let PortOne { inner } = self; + match inner { + Left(p) => p.recv(), + Right(p) => p.recv() + } } - fn try_recv(&self) -> Option { - self.port.try_recv() + pub fn try_recv(self) -> Option { + let PortOne { inner } = self; + match inner { + Left(p) => p.try_recv(), + Right(p) => p.try_recv() + } } } -impl Peekable for DuplexStream { - fn peek(&self) -> bool { - self.port.peek() +impl ChanOne { + pub fn send(self, data: T) { + let ChanOne { inner } = self; + match inner { + Left(p) => p.send(data), + Right(p) => p.send(data) + } + } + + pub fn try_send(self, data: T) -> bool { + let ChanOne { inner } = self; + match inner { + Left(p) => p.try_send(data), + Right(p) => p.try_send(data) + } + } +} + +pub fn recv_one(port: PortOne) -> T { + let PortOne { inner } = port; + match inner { + Left(p) => pipesy::recv_one(p), + Right(p) => p.recv() + } +} + +pub fn try_recv_one(port: PortOne) -> Option { + let PortOne { inner } = port; + match inner { + Left(p) => pipesy::try_recv_one(p), + Right(p) => p.try_recv() + } +} + +pub fn send_one(chan: ChanOne, data: T) { + let ChanOne { inner } = chan; + match inner { + Left(c) => pipesy::send_one(c, data), + Right(c) => c.send(data) + } +} + +pub fn try_send_one(chan: ChanOne, data: T) -> bool { + let ChanOne { inner } = chan; + match inner { + Left(c) => pipesy::try_send_one(c, data), + Right(c) => c.try_send(data) + } +} + +mod pipesy { + + use kinds::Owned; + use option::{Option, Some, None}; + use pipes::{recv, try_recv, peek, PacketHeader}; + use super::{GenericChan, GenericSmartChan, GenericPort, Peekable, Selectable}; + use cast::transmute_mut; + use util::replace; + + /*proto! oneshot ( + Oneshot:send { + send(T) -> ! + } + )*/ + + #[allow(non_camel_case_types)] + pub mod oneshot { + priv use core::kinds::Owned; + use ptr::to_mut_unsafe_ptr; + + pub fn init() -> (client::Oneshot, server::Oneshot) { + pub use core::pipes::HasBuffer; + + let buffer = ~::core::pipes::Buffer { + header: ::core::pipes::BufferHeader(), + data: __Buffer { + Oneshot: ::core::pipes::mk_packet::>() + }, + }; + do ::core::pipes::entangle_buffer(buffer) |buffer, data| { + data.Oneshot.set_buffer(buffer); + to_mut_unsafe_ptr(&mut data.Oneshot) + } + } + #[allow(non_camel_case_types)] + pub enum Oneshot { pub send(T), } + #[allow(non_camel_case_types)] + pub struct __Buffer { + Oneshot: ::core::pipes::Packet>, + } + + #[allow(non_camel_case_types)] + pub mod client { + + priv use core::kinds::Owned; + + #[allow(non_camel_case_types)] + pub fn try_send(pipe: Oneshot, x_0: T) -> + ::core::option::Option<()> { + { + use super::send; + let message = send(x_0); + if ::core::pipes::send(pipe, message) { + ::core::pipes::rt::make_some(()) + } else { ::core::pipes::rt::make_none() } + } + } + + #[allow(non_camel_case_types)] + pub fn send(pipe: Oneshot, x_0: T) { + { + use super::send; + let message = send(x_0); + ::core::pipes::send(pipe, message); + } + } + + #[allow(non_camel_case_types)] + pub type Oneshot = + ::core::pipes::SendPacketBuffered, + super::__Buffer>; + } + + #[allow(non_camel_case_types)] + pub mod server { + #[allow(non_camel_case_types)] + pub type Oneshot = + ::core::pipes::RecvPacketBuffered, + super::__Buffer>; + } + } + + /// The send end of a oneshot pipe. + pub struct ChanOne { + contents: oneshot::client::Oneshot + } + + impl ChanOne { + pub fn new(contents: oneshot::client::Oneshot) -> ChanOne { + ChanOne { + contents: contents + } + } + } + + /// The receive end of a oneshot pipe. + pub struct PortOne { + contents: oneshot::server::Oneshot + } + + impl PortOne { + pub fn new(contents: oneshot::server::Oneshot) -> PortOne { + PortOne { + contents: contents + } + } + } + + /// Initialiase a (send-endpoint, recv-endpoint) oneshot pipe pair. + pub fn oneshot() -> (PortOne, ChanOne) { + let (chan, port) = oneshot::init(); + (PortOne::new(port), ChanOne::new(chan)) + } + + pub impl PortOne { + fn recv(self) -> T { recv_one(self) } + fn try_recv(self) -> Option { try_recv_one(self) } + fn unwrap(self) -> oneshot::server::Oneshot { + match self { + PortOne { contents: s } => s + } + } + } + + pub impl ChanOne { + fn send(self, data: T) { send_one(self, data) } + fn try_send(self, data: T) -> bool { try_send_one(self, data) } + fn unwrap(self) -> oneshot::client::Oneshot { + match self { + ChanOne { contents: s } => s + } + } + } + + /** + * Receive a message from a oneshot pipe, failing if the connection was + * closed. + */ + pub fn recv_one(port: PortOne) -> T { + match port { + PortOne { contents: port } => { + let oneshot::send(message) = recv(port); + message + } + } + } + + /// Receive a message from a oneshot pipe unless the connection was closed. + pub fn try_recv_one (port: PortOne) -> Option { + match port { + PortOne { contents: port } => { + let message = try_recv(port); + + if message.is_none() { + None + } else { + let oneshot::send(message) = message.unwrap(); + Some(message) + } + } + } + } + + /// Send a message on a oneshot pipe, failing if the connection was closed. + pub fn send_one(chan: ChanOne, data: T) { + match chan { + ChanOne { contents: chan } => oneshot::client::send(chan, data), + } + } + + /** + * Send a message on a oneshot pipe, or return false if the connection was + * closed. + */ + pub fn try_send_one(chan: ChanOne, data: T) -> bool { + match chan { + ChanOne { contents: chan } => { + oneshot::client::try_send(chan, data).is_some() + } + } + } + + // Streams - Make pipes a little easier in general. + + /*proto! streamp ( + Open:send { + data(T) -> Open + } + )*/ + + #[allow(non_camel_case_types)] + pub mod streamp { + priv use core::kinds::Owned; + + pub fn init() -> (client::Open, server::Open) { + pub use core::pipes::HasBuffer; + ::core::pipes::entangle() + } + + #[allow(non_camel_case_types)] + pub enum Open { pub data(T, server::Open), } + + #[allow(non_camel_case_types)] + pub mod client { + priv use core::kinds::Owned; + + #[allow(non_camel_case_types)] + pub fn try_data(pipe: Open, x_0: T) -> + ::core::option::Option> { + { + use super::data; + let (c, s) = ::core::pipes::entangle(); + let message = data(x_0, s); + if ::core::pipes::send(pipe, message) { + ::core::pipes::rt::make_some(c) + } else { ::core::pipes::rt::make_none() } + } + } + + #[allow(non_camel_case_types)] + pub fn data(pipe: Open, x_0: T) -> Open { + { + use super::data; + let (c, s) = ::core::pipes::entangle(); + let message = data(x_0, s); + ::core::pipes::send(pipe, message); + c + } + } + + #[allow(non_camel_case_types)] + pub type Open = ::core::pipes::SendPacket>; + } + + #[allow(non_camel_case_types)] + pub mod server { + #[allow(non_camel_case_types)] + pub type Open = ::core::pipes::RecvPacket>; + } + } + + /// An endpoint that can send many messages. + #[unsafe_mut_field(endp)] + pub struct Chan { + endp: Option> + } + + /// An endpoint that can receive many messages. + #[unsafe_mut_field(endp)] + pub struct Port { + endp: Option>, + } + + /** Creates a `(Port, Chan)` pair. + + These allow sending or receiving an unlimited number of messages. + + */ + pub fn stream() -> (Port, Chan) { + let (c, s) = streamp::init(); + + (Port { + endp: Some(s) + }, Chan { + endp: Some(c) + }) + } + + impl GenericChan for Chan { + #[inline(always)] + fn send(&self, x: T) { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + *self_endp = Some(streamp::client::data(endp.unwrap(), x)) + } + } + } + + impl GenericSmartChan for Chan { + #[inline(always)] + fn try_send(&self, x: T) -> bool { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + match streamp::client::try_data(endp.unwrap(), x) { + Some(next) => { + *self_endp = Some(next); + true + } + None => false + } + } + } + } + + impl GenericPort for Port { + #[inline(always)] + fn recv(&self) -> T { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + let streamp::data(x, endp) = recv(endp.unwrap()); + *self_endp = Some(endp); + x + } + } + + #[inline(always)] + fn try_recv(&self) -> Option { + unsafe { + let self_endp = transmute_mut(&self.endp); + let endp = replace(self_endp, None); + match try_recv(endp.unwrap()) { + Some(streamp::data(x, endp)) => { + *self_endp = Some(endp); + Some(x) + } + None => None + } + } + } + } + + impl Peekable for Port { + #[inline(always)] + fn peek(&self) -> bool { + unsafe { + let self_endp = transmute_mut(&self.endp); + let mut endp = replace(self_endp, None); + let peek = match endp { + Some(ref mut endp) => peek(endp), + None => fail!("peeking empty stream") + }; + *self_endp = endp; + peek + } + } + } + + impl Selectable for Port { + fn header(&mut self) -> *mut PacketHeader { + match self.endp { + Some(ref mut endp) => endp.header(), + None => fail!("peeking empty stream") + } } } -impl Selectable for DuplexStream { - fn header(&mut self) -> *mut pipes::PacketHeader { - self.port.header() +} + +/// Returns the index of an endpoint that is ready to receive. +pub fn selecti(endpoints: &mut [T]) -> uint { + wait_many(endpoints) +} + +/// Returns 0 or 1 depending on which endpoint is ready to receive +pub fn select2i(a: &mut A, b: &mut B) + -> Either<(), ()> { + let mut endpoints = [ a.header(), b.header() ]; + match wait_many(endpoints) { + 0 => Left(()), + 1 => Right(()), + _ => fail!("wait returned unexpected index"), } } -/// Creates a bidirectional stream. -pub fn DuplexStream() - -> (DuplexStream, DuplexStream) -{ - let (p1, c2) = comm::stream(); - let (p2, c1) = comm::stream(); - (DuplexStream { - chan: c1, - port: p1 - }, - DuplexStream { - chan: c2, - port: p2 - }) +/// Receive a message from one of two endpoints. +pub trait Select2 { + /// Receive a message or return `None` if a connection closes. + fn try_select(&mut self) -> Either, Option>; + /// Receive a message or fail if a connection closes. + fn select(&mut self) -> Either; +} + +impl, + Right:Selectable + GenericPort> + Select2 + for (Left, Right) { + fn select(&mut self) -> Either { + // XXX: Bad borrow check workaround. + unsafe { + let this: &(Left, Right) = transmute(self); + match *this { + (ref lp, ref rp) => { + let lp: &mut Left = transmute(lp); + let rp: &mut Right = transmute(rp); + match select2i(lp, rp) { + Left(()) => Left(lp.recv()), + Right(()) => Right(rp.recv()), + } + } + } + } + } + + fn try_select(&mut self) -> Either, Option> { + // XXX: Bad borrow check workaround. + unsafe { + let this: &(Left, Right) = transmute(self); + match *this { + (ref lp, ref rp) => { + let lp: &mut Left = transmute(lp); + let rp: &mut Right = transmute(rp); + match select2i(lp, rp) { + Left(()) => Left (lp.try_recv()), + Right(()) => Right(rp.try_recv()), + } + } + } + } + } } #[cfg(test)] mod test { - use comm::DuplexStream; + use either::Right; + use super::{Chan, Port, oneshot, stream}; + + #[test] + fn test_select2() { + let (p1, c1) = stream(); + let (p2, c2) = stream(); + + c1.send(~"abc"); + + let mut tuple = (p1, p2); + match tuple.select() { + Right(_) => fail!(), + _ => (), + } + + c2.send(123); + } + + #[test] + fn test_oneshot() { + let (p, c) = oneshot(); + + c.send(()); + + p.recv() + } #[test] - pub fn DuplexStream1() { - let (left, right) = DuplexStream(); + fn test_peek_terminated() { + let (port, chan): (Port, Chan) = stream(); - left.send(~"abc"); - right.send(123); + { + // Destroy the channel + let _chan = chan; + } - assert_eq!(left.recv(), 123); - assert_eq!(right.recv(), ~"abc"); + assert!(!port.peek()); } } diff --git a/src/libcore/condition.rs b/src/libstd/condition.rs similarity index 100% rename from src/libcore/condition.rs rename to src/libstd/condition.rs diff --git a/src/libcore/container.rs b/src/libstd/container.rs similarity index 100% rename from src/libcore/container.rs rename to src/libstd/container.rs diff --git a/src/libcore/core.rc b/src/libstd/core.rc similarity index 100% rename from src/libcore/core.rc rename to src/libstd/core.rc diff --git a/src/libcore/either.rs b/src/libstd/either.rs similarity index 100% rename from src/libcore/either.rs rename to src/libstd/either.rs diff --git a/src/libcore/from_str.rs b/src/libstd/from_str.rs similarity index 100% rename from src/libcore/from_str.rs rename to src/libstd/from_str.rs diff --git a/src/libcore/gc.rs b/src/libstd/gc.rs similarity index 100% rename from src/libcore/gc.rs rename to src/libstd/gc.rs diff --git a/src/libcore/hash.rs b/src/libstd/hash.rs similarity index 100% rename from src/libcore/hash.rs rename to src/libstd/hash.rs diff --git a/src/libcore/hashmap.rs b/src/libstd/hashmap.rs similarity index 100% rename from src/libcore/hashmap.rs rename to src/libstd/hashmap.rs diff --git a/src/libcore/io.rs b/src/libstd/io.rs similarity index 100% rename from src/libcore/io.rs rename to src/libstd/io.rs diff --git a/src/libcore/iter.rs b/src/libstd/iter.rs similarity index 100% rename from src/libcore/iter.rs rename to src/libstd/iter.rs diff --git a/src/libcore/iterator.rs b/src/libstd/iterator.rs similarity index 100% rename from src/libcore/iterator.rs rename to src/libstd/iterator.rs diff --git a/src/libcore/kinds.rs b/src/libstd/kinds.rs similarity index 100% rename from src/libcore/kinds.rs rename to src/libstd/kinds.rs diff --git a/src/libcore/libc.rs b/src/libstd/libc.rs similarity index 100% rename from src/libcore/libc.rs rename to src/libstd/libc.rs diff --git a/src/libcore/local_data.rs b/src/libstd/local_data.rs similarity index 100% rename from src/libcore/local_data.rs rename to src/libstd/local_data.rs diff --git a/src/libcore/logging.rs b/src/libstd/logging.rs similarity index 100% rename from src/libcore/logging.rs rename to src/libstd/logging.rs diff --git a/src/libcore/macros.rs b/src/libstd/macros.rs similarity index 100% rename from src/libcore/macros.rs rename to src/libstd/macros.rs diff --git a/src/libcore/managed.rs b/src/libstd/managed.rs similarity index 100% rename from src/libcore/managed.rs rename to src/libstd/managed.rs diff --git a/src/libcore/nil.rs b/src/libstd/nil.rs similarity index 100% rename from src/libcore/nil.rs rename to src/libstd/nil.rs diff --git a/src/libcore/num/cmath.rs b/src/libstd/num/cmath.rs similarity index 100% rename from src/libcore/num/cmath.rs rename to src/libstd/num/cmath.rs diff --git a/src/libcore/num/f32.rs b/src/libstd/num/f32.rs similarity index 100% rename from src/libcore/num/f32.rs rename to src/libstd/num/f32.rs diff --git a/src/libcore/num/f64.rs b/src/libstd/num/f64.rs similarity index 100% rename from src/libcore/num/f64.rs rename to src/libstd/num/f64.rs diff --git a/src/libcore/num/float.rs b/src/libstd/num/float.rs similarity index 100% rename from src/libcore/num/float.rs rename to src/libstd/num/float.rs diff --git a/src/libcore/num/int-template.rs b/src/libstd/num/int-template.rs similarity index 100% rename from src/libcore/num/int-template.rs rename to src/libstd/num/int-template.rs diff --git a/src/libcore/num/int-template/i16.rs b/src/libstd/num/int-template/i16.rs similarity index 100% rename from src/libcore/num/int-template/i16.rs rename to src/libstd/num/int-template/i16.rs diff --git a/src/libcore/num/int-template/i32.rs b/src/libstd/num/int-template/i32.rs similarity index 100% rename from src/libcore/num/int-template/i32.rs rename to src/libstd/num/int-template/i32.rs diff --git a/src/libcore/num/int-template/i64.rs b/src/libstd/num/int-template/i64.rs similarity index 100% rename from src/libcore/num/int-template/i64.rs rename to src/libstd/num/int-template/i64.rs diff --git a/src/libcore/num/int-template/i8.rs b/src/libstd/num/int-template/i8.rs similarity index 100% rename from src/libcore/num/int-template/i8.rs rename to src/libstd/num/int-template/i8.rs diff --git a/src/libcore/num/int-template/int.rs b/src/libstd/num/int-template/int.rs similarity index 100% rename from src/libcore/num/int-template/int.rs rename to src/libstd/num/int-template/int.rs diff --git a/src/libcore/num/num.rs b/src/libstd/num/num.rs similarity index 100% rename from src/libcore/num/num.rs rename to src/libstd/num/num.rs diff --git a/src/libcore/num/strconv.rs b/src/libstd/num/strconv.rs similarity index 100% rename from src/libcore/num/strconv.rs rename to src/libstd/num/strconv.rs diff --git a/src/libcore/num/uint-template.rs b/src/libstd/num/uint-template.rs similarity index 100% rename from src/libcore/num/uint-template.rs rename to src/libstd/num/uint-template.rs diff --git a/src/libcore/num/uint-template/u16.rs b/src/libstd/num/uint-template/u16.rs similarity index 100% rename from src/libcore/num/uint-template/u16.rs rename to src/libstd/num/uint-template/u16.rs diff --git a/src/libcore/num/uint-template/u32.rs b/src/libstd/num/uint-template/u32.rs similarity index 100% rename from src/libcore/num/uint-template/u32.rs rename to src/libstd/num/uint-template/u32.rs diff --git a/src/libcore/num/uint-template/u64.rs b/src/libstd/num/uint-template/u64.rs similarity index 100% rename from src/libcore/num/uint-template/u64.rs rename to src/libstd/num/uint-template/u64.rs diff --git a/src/libcore/num/uint-template/u8.rs b/src/libstd/num/uint-template/u8.rs similarity index 100% rename from src/libcore/num/uint-template/u8.rs rename to src/libstd/num/uint-template/u8.rs diff --git a/src/libcore/num/uint-template/uint.rs b/src/libstd/num/uint-template/uint.rs similarity index 100% rename from src/libcore/num/uint-template/uint.rs rename to src/libstd/num/uint-template/uint.rs diff --git a/src/libcore/old_iter.rs b/src/libstd/old_iter.rs similarity index 100% rename from src/libcore/old_iter.rs rename to src/libstd/old_iter.rs diff --git a/src/libcore/ops.rs b/src/libstd/ops.rs similarity index 100% rename from src/libcore/ops.rs rename to src/libstd/ops.rs diff --git a/src/libcore/option.rs b/src/libstd/option.rs similarity index 100% rename from src/libcore/option.rs rename to src/libstd/option.rs diff --git a/src/libcore/os.rs b/src/libstd/os.rs similarity index 100% rename from src/libcore/os.rs rename to src/libstd/os.rs diff --git a/src/libcore/owned.rs b/src/libstd/owned.rs similarity index 100% rename from src/libcore/owned.rs rename to src/libstd/owned.rs diff --git a/src/libcore/path.rs b/src/libstd/path.rs similarity index 100% rename from src/libcore/path.rs rename to src/libstd/path.rs diff --git a/src/libcore/pipes.rs b/src/libstd/pipes.rs similarity index 100% rename from src/libcore/pipes.rs rename to src/libstd/pipes.rs diff --git a/src/libcore/prelude.rs b/src/libstd/prelude.rs similarity index 100% rename from src/libcore/prelude.rs rename to src/libstd/prelude.rs diff --git a/src/libcore/ptr.rs b/src/libstd/ptr.rs similarity index 100% rename from src/libcore/ptr.rs rename to src/libstd/ptr.rs diff --git a/src/libcore/rand.rs b/src/libstd/rand.rs similarity index 100% rename from src/libcore/rand.rs rename to src/libstd/rand.rs diff --git a/src/libcore/rand/distributions.rs b/src/libstd/rand/distributions.rs similarity index 100% rename from src/libcore/rand/distributions.rs rename to src/libstd/rand/distributions.rs diff --git a/src/libcore/rand/ziggurat_tables.rs b/src/libstd/rand/ziggurat_tables.rs similarity index 100% rename from src/libcore/rand/ziggurat_tables.rs rename to src/libstd/rand/ziggurat_tables.rs diff --git a/src/libcore/reflect.rs b/src/libstd/reflect.rs similarity index 100% rename from src/libcore/reflect.rs rename to src/libstd/reflect.rs diff --git a/src/libcore/repr.rs b/src/libstd/repr.rs similarity index 100% rename from src/libcore/repr.rs rename to src/libstd/repr.rs diff --git a/src/libcore/result.rs b/src/libstd/result.rs similarity index 100% rename from src/libcore/result.rs rename to src/libstd/result.rs diff --git a/src/libcore/rt/context.rs b/src/libstd/rt/context.rs similarity index 100% rename from src/libcore/rt/context.rs rename to src/libstd/rt/context.rs diff --git a/src/libcore/rt/env.rs b/src/libstd/rt/env.rs similarity index 100% rename from src/libcore/rt/env.rs rename to src/libstd/rt/env.rs diff --git a/src/libcore/rt/io/comm_adapters.rs b/src/libstd/rt/io/comm_adapters.rs similarity index 100% rename from src/libcore/rt/io/comm_adapters.rs rename to src/libstd/rt/io/comm_adapters.rs diff --git a/src/libcore/rt/io/extensions.rs b/src/libstd/rt/io/extensions.rs similarity index 100% rename from src/libcore/rt/io/extensions.rs rename to src/libstd/rt/io/extensions.rs diff --git a/src/libcore/rt/io/file.rs b/src/libstd/rt/io/file.rs similarity index 100% rename from src/libcore/rt/io/file.rs rename to src/libstd/rt/io/file.rs diff --git a/src/libcore/rt/io/flate.rs b/src/libstd/rt/io/flate.rs similarity index 100% rename from src/libcore/rt/io/flate.rs rename to src/libstd/rt/io/flate.rs diff --git a/src/libcore/rt/io/mem.rs b/src/libstd/rt/io/mem.rs similarity index 100% rename from src/libcore/rt/io/mem.rs rename to src/libstd/rt/io/mem.rs diff --git a/src/libcore/rt/io/mod.rs b/src/libstd/rt/io/mod.rs similarity index 100% rename from src/libcore/rt/io/mod.rs rename to src/libstd/rt/io/mod.rs diff --git a/src/libcore/rt/io/native/file.rs b/src/libstd/rt/io/native/file.rs similarity index 100% rename from src/libcore/rt/io/native/file.rs rename to src/libstd/rt/io/native/file.rs diff --git a/src/libcore/rt/io/net/http.rs b/src/libstd/rt/io/net/http.rs similarity index 100% rename from src/libcore/rt/io/net/http.rs rename to src/libstd/rt/io/net/http.rs diff --git a/src/libcore/rt/io/net/ip.rs b/src/libstd/rt/io/net/ip.rs similarity index 100% rename from src/libcore/rt/io/net/ip.rs rename to src/libstd/rt/io/net/ip.rs diff --git a/src/libcore/rt/io/net/tcp.rs b/src/libstd/rt/io/net/tcp.rs similarity index 100% rename from src/libcore/rt/io/net/tcp.rs rename to src/libstd/rt/io/net/tcp.rs diff --git a/src/libcore/rt/io/net/udp.rs b/src/libstd/rt/io/net/udp.rs similarity index 100% rename from src/libcore/rt/io/net/udp.rs rename to src/libstd/rt/io/net/udp.rs diff --git a/src/libcore/rt/io/net/unix.rs b/src/libstd/rt/io/net/unix.rs similarity index 100% rename from src/libcore/rt/io/net/unix.rs rename to src/libstd/rt/io/net/unix.rs diff --git a/src/libcore/rt/io/option.rs b/src/libstd/rt/io/option.rs similarity index 100% rename from src/libcore/rt/io/option.rs rename to src/libstd/rt/io/option.rs diff --git a/src/libcore/rt/io/stdio.rs b/src/libstd/rt/io/stdio.rs similarity index 100% rename from src/libcore/rt/io/stdio.rs rename to src/libstd/rt/io/stdio.rs diff --git a/src/libcore/rt/io/support.rs b/src/libstd/rt/io/support.rs similarity index 100% rename from src/libcore/rt/io/support.rs rename to src/libstd/rt/io/support.rs diff --git a/src/libcore/rt/local_heap.rs b/src/libstd/rt/local_heap.rs similarity index 100% rename from src/libcore/rt/local_heap.rs rename to src/libstd/rt/local_heap.rs diff --git a/src/libcore/rt/mod.rs b/src/libstd/rt/mod.rs similarity index 100% rename from src/libcore/rt/mod.rs rename to src/libstd/rt/mod.rs diff --git a/src/libcore/rt/rtio.rs b/src/libstd/rt/rtio.rs similarity index 100% rename from src/libcore/rt/rtio.rs rename to src/libstd/rt/rtio.rs diff --git a/src/libcore/rt/stack.rs b/src/libstd/rt/stack.rs similarity index 100% rename from src/libcore/rt/stack.rs rename to src/libstd/rt/stack.rs diff --git a/src/libcore/rt/task.rs b/src/libstd/rt/task.rs similarity index 100% rename from src/libcore/rt/task.rs rename to src/libstd/rt/task.rs diff --git a/src/libcore/rt/test.rs b/src/libstd/rt/test.rs similarity index 100% rename from src/libcore/rt/test.rs rename to src/libstd/rt/test.rs diff --git a/src/libcore/rt/thread.rs b/src/libstd/rt/thread.rs similarity index 100% rename from src/libcore/rt/thread.rs rename to src/libstd/rt/thread.rs diff --git a/src/libcore/rt/thread_local_storage.rs b/src/libstd/rt/thread_local_storage.rs similarity index 100% rename from src/libcore/rt/thread_local_storage.rs rename to src/libstd/rt/thread_local_storage.rs diff --git a/src/libcore/rt/uv/file.rs b/src/libstd/rt/uv/file.rs similarity index 100% rename from src/libcore/rt/uv/file.rs rename to src/libstd/rt/uv/file.rs diff --git a/src/libcore/rt/uv/mod.rs b/src/libstd/rt/uv/mod.rs similarity index 100% rename from src/libcore/rt/uv/mod.rs rename to src/libstd/rt/uv/mod.rs diff --git a/src/libcore/rt/uv/net.rs b/src/libstd/rt/uv/net.rs similarity index 100% rename from src/libcore/rt/uv/net.rs rename to src/libstd/rt/uv/net.rs diff --git a/src/libcore/rt/uv/uvio.rs b/src/libstd/rt/uvio.rs similarity index 51% rename from src/libcore/rt/uv/uvio.rs rename to src/libstd/rt/uvio.rs index cacd67314ebac..24bffd8d1cd24 100644 --- a/src/libcore/rt/uv/uvio.rs +++ b/src/libstd/rt/uvio.rs @@ -10,24 +10,20 @@ use option::*; use result::*; + +use super::io::net::ip::IpAddr; +use super::uv::*; +use super::rtio::*; use ops::Drop; +use old_iter::CopyableIter; use cell::{Cell, empty_cell}; use cast::transmute; -use clone::Clone; -use rt::io::IoError; -use rt::io::net::ip::IpAddr; -use rt::uv::*; -use rt::uv::idle::IdleWatcher; -use rt::rtio::*; -use rt::sched::Scheduler; -use rt::io::{standard_error, OtherIoError}; -use rt::tube::Tube; -use rt::local::Local; +use super::sched::{Scheduler, local_sched}; #[cfg(test)] use container::Container; #[cfg(test)] use uint; #[cfg(test)] use unstable::run_in_bare_thread; -#[cfg(test)] use rt::test::*; +#[cfg(test)] use super::test::*; pub struct UvEventLoop { uvio: UvIoFactory @@ -68,16 +64,7 @@ impl EventLoop for UvEventLoop { assert!(status.is_none()); let mut idle_watcher = idle_watcher; idle_watcher.stop(); - idle_watcher.close(||()); - f(); - } - } - - fn callback_ms(&mut self, ms: u64, f: ~fn()) { - let mut timer = TimerWatcher::new(self.uvio.uv_loop()); - do timer.start(ms, 0) |timer, status| { - assert!(status.is_none()); - timer.close(||()); + idle_watcher.close(); f(); } } @@ -97,7 +84,7 @@ fn test_callback_run_once() { unsafe { *count_ptr += 1 } } event_loop.run(); - assert_eq!(count, 1); + assert!(count == 1); } } @@ -113,20 +100,20 @@ impl IoFactory for UvIoFactory { // Connect to an address and return a new stream // NB: This blocks the task waiting on the connection. // It would probably be better to return a future - fn tcp_connect(&mut self, addr: IpAddr) -> Result<~RtioTcpStreamObject, IoError> { + fn connect(&mut self, addr: IpAddr) -> Option<~StreamObject> { // Create a cell in the task to hold the result. We will fill // the cell before resuming the task. let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; + let result_cell_ptr: *Cell> = &result_cell; - let scheduler = Local::take::(); + let scheduler = local_sched::take(); assert!(scheduler.in_task_context()); // Block this task and take ownership, switch to scheduler context do scheduler.deschedule_running_task_and_then |task| { rtdebug!("connect: entered scheduler context"); - do Local::borrow:: |scheduler| { + do local_sched::borrow |scheduler| { assert!(!scheduler.in_task_context()); } let mut tcp_watcher = TcpWatcher::new(self.uv_loop()); @@ -135,26 +122,21 @@ impl IoFactory for UvIoFactory { // Wait for a connection do tcp_watcher.connect(addr) |stream_watcher, status| { rtdebug!("connect: in connect callback"); - if status.is_none() { + let maybe_stream = if status.is_none() { rtdebug!("status is none"); - let res = Ok(~UvTcpStream { watcher: stream_watcher }); - - // Store the stream in the task's stack - unsafe { (*result_cell_ptr).put_back(res); } - - // Context switch - let scheduler = Local::take::(); - scheduler.resume_task_immediately(task_cell.take()); + Some(~UvStream(stream_watcher)) } else { rtdebug!("status is some"); - let task_cell = Cell(task_cell.take()); - do stream_watcher.close { - let res = Err(uv_error_to_io_error(status.get())); - unsafe { (*result_cell_ptr).put_back(res); } - let scheduler = Local::take::(); - scheduler.resume_task_immediately(task_cell.take()); - } + stream_watcher.close(||()); + None }; + + // Store the stream in the task's stack + unsafe { (*result_cell_ptr).put_back(maybe_stream); } + + // Context switch + let scheduler = local_sched::take(); + scheduler.resume_task_immediately(task_cell.take()); } } @@ -162,132 +144,111 @@ impl IoFactory for UvIoFactory { return result_cell.take(); } - fn tcp_bind(&mut self, addr: IpAddr) -> Result<~RtioTcpListenerObject, IoError> { + fn bind(&mut self, addr: IpAddr) -> Option<~TcpListenerObject> { let mut watcher = TcpWatcher::new(self.uv_loop()); - match watcher.bind(addr) { - Ok(_) => Ok(~UvTcpListener::new(watcher)), - Err(uverr) => { - let scheduler = Local::take::(); - do scheduler.deschedule_running_task_and_then |task| { - let task_cell = Cell(task); - do watcher.as_stream().close { - let scheduler = Local::take::(); - scheduler.resume_task_immediately(task_cell.take()); - } - } - Err(uv_error_to_io_error(uverr)) - } - } + watcher.bind(addr); + return Some(~UvTcpListener(watcher)); } } -// FIXME #6090: Prefer newtype structs but Drop doesn't work -pub struct UvTcpListener { - watcher: TcpWatcher, - listening: bool, - incoming_streams: Tube> -} +pub struct UvTcpListener(TcpWatcher); impl UvTcpListener { - fn new(watcher: TcpWatcher) -> UvTcpListener { - UvTcpListener { - watcher: watcher, - listening: false, - incoming_streams: Tube::new() - } + fn watcher(&self) -> TcpWatcher { + match self { &UvTcpListener(w) => w } } - fn watcher(&self) -> TcpWatcher { self.watcher } + fn close(&self) { + // XXX: Need to wait until close finishes before returning + self.watcher().as_stream().close(||()); + } } impl Drop for UvTcpListener { fn finalize(&self) { - let watcher = self.watcher(); - let scheduler = Local::take::(); - do scheduler.deschedule_running_task_and_then |task| { - let task_cell = Cell(task); - do watcher.as_stream().close { - let scheduler = Local::take::(); - scheduler.resume_task_immediately(task_cell.take()); - } - } + // XXX: Again, this never gets called. Use .close() instead + //self.watcher().as_stream().close(||()); } } -impl RtioTcpListener for UvTcpListener { +impl TcpListener for UvTcpListener { - fn accept(&mut self) -> Result<~RtioTcpStreamObject, IoError> { + fn listen(&mut self) -> Option<~StreamObject> { rtdebug!("entering listen"); + let result_cell = empty_cell(); + let result_cell_ptr: *Cell> = &result_cell; - if self.listening { - return self.incoming_streams.recv(); - } + let server_tcp_watcher = self.watcher(); - self.listening = true; + let scheduler = local_sched::take(); + assert!(scheduler.in_task_context()); - let server_tcp_watcher = self.watcher(); - let incoming_streams_cell = Cell(self.incoming_streams.clone()); - - let incoming_streams_cell = Cell(incoming_streams_cell.take()); - let mut server_tcp_watcher = server_tcp_watcher; - do server_tcp_watcher.listen |server_stream_watcher, status| { - let maybe_stream = if status.is_none() { - let mut server_stream_watcher = server_stream_watcher; - let mut loop_ = server_stream_watcher.event_loop(); - let client_tcp_watcher = TcpWatcher::new(&mut loop_); - let client_tcp_watcher = client_tcp_watcher.as_stream(); - // XXX: Need's to be surfaced in interface - server_stream_watcher.accept(client_tcp_watcher); - Ok(~UvTcpStream { watcher: client_tcp_watcher }) - } else { - Err(standard_error(OtherIoError)) - }; + do scheduler.deschedule_running_task_and_then |task| { + let task_cell = Cell(task); + let mut server_tcp_watcher = server_tcp_watcher; + do server_tcp_watcher.listen |server_stream_watcher, status| { + let maybe_stream = if status.is_none() { + let mut server_stream_watcher = server_stream_watcher; + let mut loop_ = loop_from_watcher(&server_stream_watcher); + let client_tcp_watcher = TcpWatcher::new(&mut loop_).as_stream(); + // XXX: Needs to be surfaced in interface + server_stream_watcher.accept(client_tcp_watcher); + Some(~UvStream::new(client_tcp_watcher)) + } else { + None + }; + + unsafe { (*result_cell_ptr).put_back(maybe_stream); } - let mut incoming_streams = incoming_streams_cell.take(); - incoming_streams.send(maybe_stream); - incoming_streams_cell.put_back(incoming_streams); + rtdebug!("resuming task from listen"); + // Context switch + let scheduler = local_sched::take(); + scheduler.resume_task_immediately(task_cell.take()); + } } - return self.incoming_streams.recv(); + assert!(!result_cell.is_empty()); + return result_cell.take(); } } -// FIXME #6090: Prefer newtype structs but Drop doesn't work -pub struct UvTcpStream { - watcher: StreamWatcher -} +pub struct UvStream(StreamWatcher); -impl UvTcpStream { - fn watcher(&self) -> StreamWatcher { self.watcher } +impl UvStream { + fn new(watcher: StreamWatcher) -> UvStream { + UvStream(watcher) + } + + fn watcher(&self) -> StreamWatcher { + match self { &UvStream(w) => w } + } + + // XXX: finalize isn't working for ~UvStream??? + fn close(&self) { + // XXX: Need to wait until this finishes before returning + self.watcher().close(||()); + } } -impl Drop for UvTcpStream { +impl Drop for UvStream { fn finalize(&self) { - rtdebug!("closing tcp stream"); - let watcher = self.watcher(); - let scheduler = Local::take::(); - do scheduler.deschedule_running_task_and_then |task| { - let task_cell = Cell(task); - do watcher.close { - let scheduler = Local::take::(); - scheduler.resume_task_immediately(task_cell.take()); - } - } + rtdebug!("closing stream"); + //self.watcher().close(||()); } } -impl RtioTcpStream for UvTcpStream { - fn read(&mut self, buf: &mut [u8]) -> Result { +impl Stream for UvStream { + fn read(&mut self, buf: &mut [u8]) -> Result { let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; + let result_cell_ptr: *Cell> = &result_cell; - let scheduler = Local::take::(); + let scheduler = local_sched::take(); assert!(scheduler.in_task_context()); let watcher = self.watcher(); let buf_ptr: *&mut [u8] = &buf; do scheduler.deschedule_running_task_and_then |task| { rtdebug!("read: entered scheduler context"); - do Local::borrow:: |scheduler| { + do local_sched::borrow |scheduler| { assert!(!scheduler.in_task_context()); } let mut watcher = watcher; @@ -310,12 +271,12 @@ impl RtioTcpStream for UvTcpStream { assert!(nread >= 0); Ok(nread as uint) } else { - Err(uv_error_to_io_error(status.unwrap())) + Err(()) }; unsafe { (*result_cell_ptr).put_back(result); } - let scheduler = Local::take::(); + let scheduler = local_sched::take(); scheduler.resume_task_immediately(task_cell.take()); } } @@ -324,27 +285,29 @@ impl RtioTcpStream for UvTcpStream { return result_cell.take(); } - fn write(&mut self, buf: &[u8]) -> Result<(), IoError> { + fn write(&mut self, buf: &[u8]) -> Result<(), ()> { let result_cell = empty_cell(); - let result_cell_ptr: *Cell> = &result_cell; - let scheduler = Local::take::(); + let result_cell_ptr: *Cell> = &result_cell; + let scheduler = local_sched::take(); assert!(scheduler.in_task_context()); let watcher = self.watcher(); let buf_ptr: *&[u8] = &buf; do scheduler.deschedule_running_task_and_then |task| { let mut watcher = watcher; let task_cell = Cell(task); - let buf = unsafe { slice_to_uv_buf(*buf_ptr) }; + let buf = unsafe { &*buf_ptr }; + // XXX: OMGCOPIES + let buf = buf.to_vec(); do watcher.write(buf) |_watcher, status| { let result = if status.is_none() { Ok(()) } else { - Err(uv_error_to_io_error(status.unwrap())) + Err(()) }; unsafe { (*result_cell_ptr).put_back(result); } - let scheduler = Local::take::(); + let scheduler = local_sched::take(); scheduler.resume_task_immediately(task_cell.take()); } } @@ -357,12 +320,10 @@ impl RtioTcpStream for UvTcpStream { #[test] fn test_simple_io_no_connect() { do run_in_newsched_task { - unsafe { - let io = Local::unsafe_borrow::(); - let addr = next_test_ip4(); - let maybe_chan = (*io).tcp_connect(addr); - assert!(maybe_chan.is_err()); - } + let io = unsafe { local_sched::unsafe_borrow_io() }; + let addr = next_test_ip4(); + let maybe_chan = io.connect(addr); + assert!(maybe_chan.is_none()); } } @@ -374,24 +335,27 @@ fn test_simple_tcp_server_and_client() { // Start the server first so it's listening when we connect do spawntask_immediately { unsafe { - let io = Local::unsafe_borrow::(); - let mut listener = (*io).tcp_bind(addr).unwrap(); - let mut stream = listener.accept().unwrap(); + let io = local_sched::unsafe_borrow_io(); + let mut listener = io.bind(addr).unwrap(); + let mut stream = listener.listen().unwrap(); let mut buf = [0, .. 2048]; let nread = stream.read(buf).unwrap(); - assert_eq!(nread, 8); + assert!(nread == 8); for uint::range(0, nread) |i| { rtdebug!("%u", buf[i] as uint); - assert_eq!(buf[i], i as u8); + assert!(buf[i] == i as u8); } + stream.close(); + listener.close(); } } do spawntask_immediately { unsafe { - let io = Local::unsafe_borrow::(); - let mut stream = (*io).tcp_connect(addr).unwrap(); + let io = local_sched::unsafe_borrow_io(); + let mut stream = io.connect(addr).unwrap(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.close(); } } } @@ -403,9 +367,9 @@ fn test_read_and_block() { let addr = next_test_ip4(); do spawntask_immediately { - let io = unsafe { Local::unsafe_borrow::() }; - let mut listener = unsafe { (*io).tcp_bind(addr).unwrap() }; - let mut stream = listener.accept().unwrap(); + let io = unsafe { local_sched::unsafe_borrow_io() }; + let mut listener = io.bind(addr).unwrap(); + let mut stream = listener.listen().unwrap(); let mut buf = [0, .. 2048]; let expected = 32; @@ -416,36 +380,38 @@ fn test_read_and_block() { let nread = stream.read(buf).unwrap(); for uint::range(0, nread) |i| { let val = buf[i] as uint; - assert_eq!(val, current % 8); + assert!(val == current % 8); current += 1; } reads += 1; - let scheduler = Local::take::(); + let scheduler = local_sched::take(); // Yield to the other task in hopes that it // will trigger a read callback while we are // not ready for it do scheduler.deschedule_running_task_and_then |task| { let task = Cell(task); - do Local::borrow:: |scheduler| { - scheduler.enqueue_task(task.take()); + do local_sched::borrow |scheduler| { + scheduler.task_queue.push_back(task.take()); } } } // Make sure we had multiple reads assert!(reads > 1); + + stream.close(); + listener.close(); } do spawntask_immediately { - unsafe { - let io = Local::unsafe_borrow::(); - let mut stream = (*io).tcp_connect(addr).unwrap(); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - stream.write([0, 1, 2, 3, 4, 5, 6, 7]); - } + let io = unsafe { local_sched::unsafe_borrow_io() }; + let mut stream = io.connect(addr).unwrap(); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.close(); } } @@ -459,34 +425,35 @@ fn test_read_read_read() { do spawntask_immediately { unsafe { - let io = Local::unsafe_borrow::(); - let mut listener = (*io).tcp_bind(addr).unwrap(); - let mut stream = listener.accept().unwrap(); + let io = local_sched::unsafe_borrow_io(); + let mut listener = io.bind(addr).unwrap(); + let mut stream = listener.listen().unwrap(); let buf = [1, .. 2048]; let mut total_bytes_written = 0; while total_bytes_written < MAX { stream.write(buf); total_bytes_written += buf.len(); } + stream.close(); + listener.close(); } } do spawntask_immediately { - unsafe { - let io = Local::unsafe_borrow::(); - let mut stream = (*io).tcp_connect(addr).unwrap(); - let mut buf = [0, .. 2048]; - let mut total_bytes_read = 0; - while total_bytes_read < MAX { - let nread = stream.read(buf).unwrap(); - rtdebug!("read %u bytes", nread as uint); - total_bytes_read += nread; - for uint::range(0, nread) |i| { - assert_eq!(buf[i], 1); - } + let io = unsafe { local_sched::unsafe_borrow_io() }; + let mut stream = io.connect(addr).unwrap(); + let mut buf = [0, .. 2048]; + let mut total_bytes_read = 0; + while total_bytes_read < MAX { + let nread = stream.read(buf).unwrap(); + rtdebug!("read %u bytes", nread as uint); + total_bytes_read += nread; + for uint::range(0, nread) |i| { + assert!(buf[i] == 1); } - rtdebug!("read %u bytes total", total_bytes_read as uint); } + rtdebug!("read %u bytes total", total_bytes_read as uint); + stream.close(); } } } diff --git a/src/libcore/rt/uv/uvll.rs b/src/libstd/rt/uvll.rs similarity index 95% rename from src/libcore/rt/uv/uvll.rs rename to src/libstd/rt/uvll.rs index ddc9040d73091..0d298bde6b508 100644 --- a/src/libcore/rt/uv/uvll.rs +++ b/src/libstd/rt/uvll.rs @@ -33,15 +33,6 @@ use libc::{size_t, c_int, c_uint, c_void, c_char, uintptr_t}; use libc::{malloc, free}; use prelude::*; -pub static UNKNOWN: c_int = -1; -pub static OK: c_int = 0; -pub static EOF: c_int = 1; -pub static EADDRINFO: c_int = 2; -pub static EACCES: c_int = 3; -pub static ECONNREFUSED: c_int = 12; -pub static ECONNRESET: c_int = 13; -pub static EPIPE: c_int = 36; - pub struct uv_err_t { code: c_int, sys_errno_: c_int @@ -132,14 +123,14 @@ pub unsafe fn free_req(v: *c_void) { #[test] fn handle_sanity_check() { unsafe { - assert_eq!(UV_HANDLE_TYPE_MAX as uint, rust_uv_handle_type_max()); + assert!(UV_HANDLE_TYPE_MAX as uint == rust_uv_handle_type_max()); } } #[test] fn request_sanity_check() { unsafe { - assert_eq!(UV_REQ_TYPE_MAX as uint, rust_uv_req_type_max()); + assert!(UV_REQ_TYPE_MAX as uint == rust_uv_req_type_max()); } } @@ -269,9 +260,9 @@ pub unsafe fn buf_init(input: *u8, len: uint) -> uv_buf_t { pub unsafe fn timer_init(loop_ptr: *c_void, timer_ptr: *uv_timer_t) -> c_int { return rust_uv_timer_init(loop_ptr, timer_ptr); } -pub unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: u64, - repeat: u64) -> c_int { - return rust_uv_timer_start(timer_ptr, cb, timeout, repeat); +pub unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: uint, + repeat: uint) -> c_int { + return rust_uv_timer_start(timer_ptr, cb, timeout as c_uint, repeat as c_uint); } pub unsafe fn timer_stop(timer_ptr: *uv_timer_t) -> c_int { return rust_uv_timer_stop(timer_ptr); @@ -432,8 +423,8 @@ extern { timer_handle: *uv_timer_t) -> c_int; fn rust_uv_timer_start(timer_handle: *uv_timer_t, cb: *u8, - timeout: libc::uint64_t, - repeat: libc::uint64_t) -> c_int; + timeout: c_uint, + repeat: c_uint) -> c_int; fn rust_uv_timer_stop(handle: *uv_timer_t) -> c_int; fn rust_uv_malloc_buf_base_of(sug_size: size_t) -> *u8; diff --git a/src/libcore/rt/work_queue.rs b/src/libstd/rt/work_queue.rs similarity index 100% rename from src/libcore/rt/work_queue.rs rename to src/libstd/rt/work_queue.rs diff --git a/src/libcore/run.rs b/src/libstd/run.rs similarity index 100% rename from src/libcore/run.rs rename to src/libstd/run.rs diff --git a/src/libcore/stackwalk.rs b/src/libstd/stackwalk.rs similarity index 100% rename from src/libcore/stackwalk.rs rename to src/libstd/stackwalk.rs diff --git a/src/libcore/str.rs b/src/libstd/str.rs similarity index 100% rename from src/libcore/str.rs rename to src/libstd/str.rs diff --git a/src/libcore/str/ascii.rs b/src/libstd/str/ascii.rs similarity index 100% rename from src/libcore/str/ascii.rs rename to src/libstd/str/ascii.rs diff --git a/src/libcore/sys.rs b/src/libstd/sys.rs similarity index 100% rename from src/libcore/sys.rs rename to src/libstd/sys.rs diff --git a/src/libcore/task/local_data_priv.rs b/src/libstd/task/local_data_priv.rs similarity index 100% rename from src/libcore/task/local_data_priv.rs rename to src/libstd/task/local_data_priv.rs diff --git a/src/libcore/task/mod.rs b/src/libstd/task/mod.rs similarity index 100% rename from src/libcore/task/mod.rs rename to src/libstd/task/mod.rs diff --git a/src/libcore/task/rt.rs b/src/libstd/task/rt.rs similarity index 100% rename from src/libcore/task/rt.rs rename to src/libstd/task/rt.rs diff --git a/src/libcore/task/spawn.rs b/src/libstd/task/spawn.rs similarity index 100% rename from src/libcore/task/spawn.rs rename to src/libstd/task/spawn.rs diff --git a/src/libcore/to_bytes.rs b/src/libstd/to_bytes.rs similarity index 100% rename from src/libcore/to_bytes.rs rename to src/libstd/to_bytes.rs diff --git a/src/libcore/to_str.rs b/src/libstd/to_str.rs similarity index 100% rename from src/libcore/to_str.rs rename to src/libstd/to_str.rs diff --git a/src/libcore/trie.rs b/src/libstd/trie.rs similarity index 100% rename from src/libcore/trie.rs rename to src/libstd/trie.rs diff --git a/src/libcore/tuple.rs b/src/libstd/tuple.rs similarity index 100% rename from src/libcore/tuple.rs rename to src/libstd/tuple.rs diff --git a/src/libstd/unicode.rs b/src/libstd/unicode.rs index 77996de6d8394..d6e2c5eee6aca 100644 --- a/src/libstd/unicode.rs +++ b/src/libstd/unicode.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -8,241 +8,2637 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[forbid(deprecated_mode)]; - -pub mod icu { - pub type UBool = u8; - pub type UProperty = int; - pub type UChar32 = char; - - pub static TRUE : u8 = 1u8; - pub static FALSE : u8 = 1u8; - - pub static UCHAR_ALPHABETIC : UProperty = 0; - pub static UCHAR_BINARY_START : UProperty = 0; // = UCHAR_ALPHABETIC - pub static UCHAR_ASCII_HEX_DIGIT : UProperty = 1; - pub static UCHAR_BIDI_CONTROL : UProperty = 2; - - pub static UCHAR_BIDI_MIRRORED : UProperty = 3; - pub static UCHAR_DASH : UProperty = 4; - pub static UCHAR_DEFAULT_IGNORABLE_CODE_POINT : UProperty = 5; - pub static UCHAR_DEPRECATED : UProperty = 6; - - pub static UCHAR_DIACRITIC : UProperty = 7; - pub static UCHAR_EXTENDER : UProperty = 8; - pub static UCHAR_FULL_COMPOSITION_EXCLUSION : UProperty = 9; - pub static UCHAR_GRAPHEME_BASE : UProperty = 10; - - pub static UCHAR_GRAPHEME_EXTEND : UProperty = 11; - pub static UCHAR_GRAPHEME_LINK : UProperty = 12; - pub static UCHAR_HEX_DIGIT : UProperty = 13; - pub static UCHAR_HYPHEN : UProperty = 14; - - pub static UCHAR_ID_CONTINUE : UProperty = 15; - pub static UCHAR_ID_START : UProperty = 16; - pub static UCHAR_IDEOGRAPHIC : UProperty = 17; - pub static UCHAR_IDS_BINARY_OPERATOR : UProperty = 18; - - pub static UCHAR_IDS_TRINARY_OPERATOR : UProperty = 19; - pub static UCHAR_JOIN_CONTROL : UProperty = 20; - pub static UCHAR_LOGICAL_ORDER_EXCEPTION : UProperty = 21; - pub static UCHAR_LOWERCASE : UProperty = 22; - - pub static UCHAR_MATH : UProperty = 23; - pub static UCHAR_NONCHARACTER_CODE_POINT : UProperty = 24; - pub static UCHAR_QUOTATION_MARK : UProperty = 25; - pub static UCHAR_RADICAL : UProperty = 26; - - pub static UCHAR_SOFT_DOTTED : UProperty = 27; - pub static UCHAR_TERMINAL_PUNCTUATION : UProperty = 28; - pub static UCHAR_UNIFIED_IDEOGRAPH : UProperty = 29; - pub static UCHAR_UPPERCASE : UProperty = 30; - - pub static UCHAR_WHITE_SPACE : UProperty = 31; - pub static UCHAR_XID_CONTINUE : UProperty = 32; - pub static UCHAR_XID_START : UProperty = 33; - pub static UCHAR_CASE_SENSITIVE : UProperty = 34; - - pub static UCHAR_S_TERM : UProperty = 35; - pub static UCHAR_VARIATION_SELECTOR : UProperty = 36; - pub static UCHAR_NFD_INERT : UProperty = 37; - pub static UCHAR_NFKD_INERT : UProperty = 38; - - pub static UCHAR_NFC_INERT : UProperty = 39; - pub static UCHAR_NFKC_INERT : UProperty = 40; - pub static UCHAR_SEGMENT_STARTER : UProperty = 41; - pub static UCHAR_PATTERN_SYNTAX : UProperty = 42; - - pub static UCHAR_PATTERN_WHITE_SPACE : UProperty = 43; - pub static UCHAR_POSIX_ALNUM : UProperty = 44; - pub static UCHAR_POSIX_BLANK : UProperty = 45; - pub static UCHAR_POSIX_GRAPH : UProperty = 46; - - pub static UCHAR_POSIX_PRINT : UProperty = 47; - pub static UCHAR_POSIX_XDIGIT : UProperty = 48; - pub static UCHAR_CASED : UProperty = 49; - pub static UCHAR_CASE_IGNORABLE : UProperty = 50; - - pub static UCHAR_CHANGES_WHEN_LOWERCASED : UProperty = 51; - pub static UCHAR_CHANGES_WHEN_UPPERCASED : UProperty = 52; - pub static UCHAR_CHANGES_WHEN_TITLECASED : UProperty = 53; - pub static UCHAR_CHANGES_WHEN_CASEFOLDED : UProperty = 54; - - pub static UCHAR_CHANGES_WHEN_CASEMAPPED : UProperty = 55; - pub static UCHAR_CHANGES_WHEN_NFKC_CASEFOLDED : UProperty = 56; - pub static UCHAR_BINARY_LIMIT : UProperty = 57; - pub static UCHAR_BIDI_CLASS : UProperty = 0x1000; - - pub static UCHAR_INT_START : UProperty = 0x1000; // UCHAR_BIDI_CLASS - pub static UCHAR_BLOCK : UProperty = 0x1001; - pub static UCHAR_CANONICAL_COMBINING_CLASS : UProperty = 0x1002; - pub static UCHAR_DECOMPOSITION_TYPE : UProperty = 0x1003; - - pub static UCHAR_EAST_ASIAN_WIDTH : UProperty = 0x1004; - pub static UCHAR_GENERAL_CATEGORY : UProperty = 0x1005; - pub static UCHAR_JOINING_GROUP : UProperty = 0x1006; - pub static UCHAR_JOINING_TYPE : UProperty = 0x1007; - - pub static UCHAR_LINE_BREAK : UProperty = 0x1008; - pub static UCHAR_NUMERIC_TYPE : UProperty = 0x1009; - pub static UCHAR_SCRIPT : UProperty = 0x100A; - pub static UCHAR_HANGUL_SYLLABLE_TYPE : UProperty = 0x100B; - - pub static UCHAR_NFD_QUICK_CHECK : UProperty = 0x100C; - pub static UCHAR_NFKD_QUICK_CHECK : UProperty = 0x100D; - pub static UCHAR_NFC_QUICK_CHECK : UProperty = 0x100E; - pub static UCHAR_NFKC_QUICK_CHECK : UProperty = 0x100F; - - pub static UCHAR_LEAD_CANONICAL_COMBINING_CLASS : UProperty = 0x1010; - pub static UCHAR_TRAIL_CANONICAL_COMBINING_CLASS : UProperty = 0x1011; - pub static UCHAR_GRAPHEME_CLUSTER_BREAK : UProperty = 0x1012; - pub static UCHAR_SENTENCE_BREAK : UProperty = 0x1013; - - pub static UCHAR_WORD_BREAK : UProperty = 0x1014; - pub static UCHAR_INT_LIMIT : UProperty = 0x1015; - - pub static UCHAR_GENERAL_CATEGORY_MASK : UProperty = 0x2000; - pub static UCHAR_MASK_START : UProperty = 0x2000; - // = UCHAR_GENERAL_CATEGORY_MASK - pub static UCHAR_MASK_LIMIT : UProperty = 0x2001; - - pub static UCHAR_NUMERIC_VALUE : UProperty = 0x3000; - pub static UCHAR_DOUBLE_START : UProperty = 0x3000; - // = UCHAR_NUMERIC_VALUE - pub static UCHAR_DOUBLE_LIMIT : UProperty = 0x3001; - - pub static UCHAR_AGE : UProperty = 0x4000; - pub static UCHAR_STRING_START : UProperty = 0x4000; // = UCHAR_AGE - pub static UCHAR_BIDI_MIRRORING_GLYPH : UProperty = 0x4001; - pub static UCHAR_CASE_FOLDING : UProperty = 0x4002; - - pub static UCHAR_ISO_COMMENT : UProperty = 0x4003; - pub static UCHAR_LOWERCASE_MAPPING : UProperty = 0x4004; - pub static UCHAR_NAME : UProperty = 0x4005; - pub static UCHAR_SIMPLE_CASE_FOLDING : UProperty = 0x4006; - - pub static UCHAR_SIMPLE_LOWERCASE_MAPPING : UProperty = 0x4007; - pub static UCHAR_SIMPLE_TITLECASE_MAPPING : UProperty = 0x4008; - pub static UCHAR_SIMPLE_UPPERCASE_MAPPING : UProperty = 0x4009; - pub static UCHAR_TITLECASE_MAPPING : UProperty = 0x400A; - - pub static UCHAR_UNICODE_1_NAME : UProperty = 0x400B; - pub static UCHAR_UPPERCASE_MAPPING : UProperty = 0x400C; - pub static UCHAR_STRING_LIMIT : UProperty = 0x400D; - - pub static UCHAR_SCRIPT_EXTENSIONS : UProperty = 0x7000; - pub static UCHAR_OTHER_PROPERTY_START : UProperty = 0x7000; - // = UCHAR_SCRIPT_EXTENSIONS; - pub static UCHAR_OTHER_PROPERTY_LIMIT : UProperty = 0x7001; - - pub static UCHAR_INVALID_CODE : UProperty = -1; - - pub mod libicu { - #[link_name = "icuuc"] - #[abi = "cdecl"] - pub extern { - unsafe fn u_hasBinaryProperty(c: UChar32, which: UProperty) - -> UBool; - unsafe fn u_isdigit(c: UChar32) -> UBool; - unsafe fn u_islower(c: UChar32) -> UBool; - unsafe fn u_isspace(c: UChar32) -> UBool; - unsafe fn u_isupper(c: UChar32) -> UBool; - unsafe fn u_tolower(c: UChar32) -> UChar32; - unsafe fn u_toupper(c: UChar32) -> UChar32; - } +#[doc(hidden)]; // FIXME #3538 + +// The following code was generated by "src/etc/unicode.py" + +pub mod general_category { + + fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use cmp::{Equal, Less, Greater}; + use vec::bsearch; + use option::None; + (do bsearch(r) |&(lo,hi)| { + if lo <= c && c <= hi { Equal } + else if hi < c { Less } + else { Greater } + }) != None } -} -pub fn is_XID_start(c: char) -> bool { - return icu::libicu::u_hasBinaryProperty(c, icu::UCHAR_XID_START) - == icu::TRUE; -} -pub fn is_XID_continue(c: char) -> bool { - return icu::libicu::u_hasBinaryProperty(c, icu::UCHAR_XID_START) - == icu::TRUE; -} + static Cc_table : &'static [(char,char)] = &[ + ('\x00', '\x1f'), ('\x7f', '\x9f') + ]; -/* -Function: is_digit + pub fn Cc(c: char) -> bool { + bsearch_range_table(c, Cc_table) + } -Returns true if a character is a digit. -*/ -pub fn is_digit(c: char) -> bool { - return icu::libicu::u_isdigit(c) == icu::TRUE; -} + static Cf_table : &'static [(char,char)] = &[ + ('\xad', '\xad'), ('\u0600', '\u0604'), + ('\u06dd', '\u06dd'), ('\u070f', '\u070f'), + ('\u200b', '\u200f'), ('\u202a', '\u202e'), + ('\u2060', '\u206f'), ('\ufeff', '\ufeff'), + ('\ufff9', '\ufffb'), ('\U000110bd', '\U000110bd'), + ('\U0001d173', '\U0001d17a'), ('\U000e0001', '\U000e007f') + ]; -/* -Function: is_lower + pub fn Cf(c: char) -> bool { + bsearch_range_table(c, Cf_table) + } -Returns true if a character is a lowercase letter. -*/ -pub fn is_lower(c: char) -> bool { - return icu::libicu::u_islower(c) == icu::TRUE; -} + static Co_table : &'static [(char,char)] = &[ + ('\ue000', '\uf8ff') + ]; -/* -Function: is_space + pub fn Co(c: char) -> bool { + bsearch_range_table(c, Co_table) + } -Returns true if a character is space. -*/ -pub fn is_space(c: char) -> bool { - return icu::libicu::u_isspace(c) == icu::TRUE; -} + static Cs_table : &'static [(char,char)] = &[ + ('\ud800', '\udfff') + ]; + + pub fn Cs(c: char) -> bool { + bsearch_range_table(c, Cs_table) + } + + static Ll_table : &'static [(char,char)] = &[ + ('\x61', '\x7a'), ('\xb5', '\xb5'), + ('\xdf', '\xf6'), ('\xf8', '\xff'), + ('\u0101', '\u0101'), ('\u0103', '\u0103'), + ('\u0105', '\u0105'), ('\u0107', '\u0107'), + ('\u0109', '\u0109'), ('\u010b', '\u010b'), + ('\u010d', '\u010d'), ('\u010f', '\u010f'), + ('\u0111', '\u0111'), ('\u0113', '\u0113'), + ('\u0115', '\u0115'), ('\u0117', '\u0117'), + ('\u0119', '\u0119'), ('\u011b', '\u011b'), + ('\u011d', '\u011d'), ('\u011f', '\u011f'), + ('\u0121', '\u0121'), ('\u0123', '\u0123'), + ('\u0125', '\u0125'), ('\u0127', '\u0127'), + ('\u0129', '\u0129'), ('\u012b', '\u012b'), + ('\u012d', '\u012d'), ('\u012f', '\u012f'), + ('\u0131', '\u0131'), ('\u0133', '\u0133'), + ('\u0135', '\u0135'), ('\u0137', '\u0138'), + ('\u013a', '\u013a'), ('\u013c', '\u013c'), + ('\u013e', '\u013e'), ('\u0140', '\u0140'), + ('\u0142', '\u0142'), ('\u0144', '\u0144'), + ('\u0146', '\u0146'), ('\u0148', '\u0149'), + ('\u014b', '\u014b'), ('\u014d', '\u014d'), + ('\u014f', '\u014f'), ('\u0151', '\u0151'), + ('\u0153', '\u0153'), ('\u0155', '\u0155'), + ('\u0157', '\u0157'), ('\u0159', '\u0159'), + ('\u015b', '\u015b'), ('\u015d', '\u015d'), + ('\u015f', '\u015f'), ('\u0161', '\u0161'), + ('\u0163', '\u0163'), ('\u0165', '\u0165'), + ('\u0167', '\u0167'), ('\u0169', '\u0169'), + ('\u016b', '\u016b'), ('\u016d', '\u016d'), + ('\u016f', '\u016f'), ('\u0171', '\u0171'), + ('\u0173', '\u0173'), ('\u0175', '\u0175'), + ('\u0177', '\u0177'), ('\u017a', '\u017a'), + ('\u017c', '\u017c'), ('\u017e', '\u0180'), + ('\u0183', '\u0183'), ('\u0185', '\u0185'), + ('\u0188', '\u0188'), ('\u018c', '\u018d'), + ('\u0192', '\u0192'), ('\u0195', '\u0195'), + ('\u0199', '\u019b'), ('\u019e', '\u019e'), + ('\u01a1', '\u01a1'), ('\u01a3', '\u01a3'), + ('\u01a5', '\u01a5'), ('\u01a8', '\u01a8'), + ('\u01aa', '\u01ab'), ('\u01ad', '\u01ad'), + ('\u01b0', '\u01b0'), ('\u01b4', '\u01b4'), + ('\u01b6', '\u01b6'), ('\u01b9', '\u01ba'), + ('\u01bd', '\u01bf'), ('\u01c6', '\u01c6'), + ('\u01c9', '\u01c9'), ('\u01cc', '\u01cc'), + ('\u01ce', '\u01ce'), ('\u01d0', '\u01d0'), + ('\u01d2', '\u01d2'), ('\u01d4', '\u01d4'), + ('\u01d6', '\u01d6'), ('\u01d8', '\u01d8'), + ('\u01da', '\u01da'), ('\u01dc', '\u01dd'), + ('\u01df', '\u01df'), ('\u01e1', '\u01e1'), + ('\u01e3', '\u01e3'), ('\u01e5', '\u01e5'), + ('\u01e7', '\u01e7'), ('\u01e9', '\u01e9'), + ('\u01eb', '\u01eb'), ('\u01ed', '\u01ed'), + ('\u01ef', '\u01f0'), ('\u01f3', '\u01f3'), + ('\u01f5', '\u01f5'), ('\u01f9', '\u01f9'), + ('\u01fb', '\u01fb'), ('\u01fd', '\u01fd'), + ('\u01ff', '\u01ff'), ('\u0201', '\u0201'), + ('\u0203', '\u0203'), ('\u0205', '\u0205'), + ('\u0207', '\u0207'), ('\u0209', '\u0209'), + ('\u020b', '\u020b'), ('\u020d', '\u020d'), + ('\u020f', '\u020f'), ('\u0211', '\u0211'), + ('\u0213', '\u0213'), ('\u0215', '\u0215'), + ('\u0217', '\u0217'), ('\u0219', '\u0219'), + ('\u021b', '\u021b'), ('\u021d', '\u021d'), + ('\u021f', '\u021f'), ('\u0221', '\u0221'), + ('\u0223', '\u0223'), ('\u0225', '\u0225'), + ('\u0227', '\u0227'), ('\u0229', '\u0229'), + ('\u022b', '\u022b'), ('\u022d', '\u022d'), + ('\u022f', '\u022f'), ('\u0231', '\u0231'), + ('\u0233', '\u0239'), ('\u023c', '\u023c'), + ('\u023f', '\u0240'), ('\u0242', '\u0242'), + ('\u0247', '\u0247'), ('\u0249', '\u0249'), + ('\u024b', '\u024b'), ('\u024d', '\u024d'), + ('\u024f', '\u0293'), ('\u0295', '\u02af'), + ('\u0371', '\u0371'), ('\u0373', '\u0373'), + ('\u0377', '\u0377'), ('\u037b', '\u037d'), + ('\u0390', '\u0390'), ('\u03ac', '\u03ce'), + ('\u03d0', '\u03d1'), ('\u03d5', '\u03d7'), + ('\u03d9', '\u03d9'), ('\u03db', '\u03db'), + ('\u03dd', '\u03dd'), ('\u03df', '\u03df'), + ('\u03e1', '\u03e1'), ('\u03e3', '\u03e3'), + ('\u03e5', '\u03e5'), ('\u03e7', '\u03e7'), + ('\u03e9', '\u03e9'), ('\u03eb', '\u03eb'), + ('\u03ed', '\u03ed'), ('\u03ef', '\u03f3'), + ('\u03f5', '\u03f5'), ('\u03f8', '\u03f8'), + ('\u03fb', '\u03fc'), ('\u0430', '\u045f'), + ('\u0461', '\u0461'), ('\u0463', '\u0463'), + ('\u0465', '\u0465'), ('\u0467', '\u0467'), + ('\u0469', '\u0469'), ('\u046b', '\u046b'), + ('\u046d', '\u046d'), ('\u046f', '\u046f'), + ('\u0471', '\u0471'), ('\u0473', '\u0473'), + ('\u0475', '\u0475'), ('\u0477', '\u0477'), + ('\u0479', '\u0479'), ('\u047b', '\u047b'), + ('\u047d', '\u047d'), ('\u047f', '\u047f'), + ('\u0481', '\u0481'), ('\u048b', '\u048b'), + ('\u048d', '\u048d'), ('\u048f', '\u048f'), + ('\u0491', '\u0491'), ('\u0493', '\u0493'), + ('\u0495', '\u0495'), ('\u0497', '\u0497'), + ('\u0499', '\u0499'), ('\u049b', '\u049b'), + ('\u049d', '\u049d'), ('\u049f', '\u049f'), + ('\u04a1', '\u04a1'), ('\u04a3', '\u04a3'), + ('\u04a5', '\u04a5'), ('\u04a7', '\u04a7'), + ('\u04a9', '\u04a9'), ('\u04ab', '\u04ab'), + ('\u04ad', '\u04ad'), ('\u04af', '\u04af'), + ('\u04b1', '\u04b1'), ('\u04b3', '\u04b3'), + ('\u04b5', '\u04b5'), ('\u04b7', '\u04b7'), + ('\u04b9', '\u04b9'), ('\u04bb', '\u04bb'), + ('\u04bd', '\u04bd'), ('\u04bf', '\u04bf'), + ('\u04c2', '\u04c2'), ('\u04c4', '\u04c4'), + ('\u04c6', '\u04c6'), ('\u04c8', '\u04c8'), + ('\u04ca', '\u04ca'), ('\u04cc', '\u04cc'), + ('\u04ce', '\u04cf'), ('\u04d1', '\u04d1'), + ('\u04d3', '\u04d3'), ('\u04d5', '\u04d5'), + ('\u04d7', '\u04d7'), ('\u04d9', '\u04d9'), + ('\u04db', '\u04db'), ('\u04dd', '\u04dd'), + ('\u04df', '\u04df'), ('\u04e1', '\u04e1'), + ('\u04e3', '\u04e3'), ('\u04e5', '\u04e5'), + ('\u04e7', '\u04e7'), ('\u04e9', '\u04e9'), + ('\u04eb', '\u04eb'), ('\u04ed', '\u04ed'), + ('\u04ef', '\u04ef'), ('\u04f1', '\u04f1'), + ('\u04f3', '\u04f3'), ('\u04f5', '\u04f5'), + ('\u04f7', '\u04f7'), ('\u04f9', '\u04f9'), + ('\u04fb', '\u04fb'), ('\u04fd', '\u04fd'), + ('\u04ff', '\u04ff'), ('\u0501', '\u0501'), + ('\u0503', '\u0503'), ('\u0505', '\u0505'), + ('\u0507', '\u0507'), ('\u0509', '\u0509'), + ('\u050b', '\u050b'), ('\u050d', '\u050d'), + ('\u050f', '\u050f'), ('\u0511', '\u0511'), + ('\u0513', '\u0513'), ('\u0515', '\u0515'), + ('\u0517', '\u0517'), ('\u0519', '\u0519'), + ('\u051b', '\u051b'), ('\u051d', '\u051d'), + ('\u051f', '\u051f'), ('\u0521', '\u0521'), + ('\u0523', '\u0523'), ('\u0525', '\u0525'), + ('\u0527', '\u0527'), ('\u0561', '\u0587'), + ('\u1d00', '\u1d2b'), ('\u1d6b', '\u1d77'), + ('\u1d79', '\u1d9a'), ('\u1e01', '\u1e01'), + ('\u1e03', '\u1e03'), ('\u1e05', '\u1e05'), + ('\u1e07', '\u1e07'), ('\u1e09', '\u1e09'), + ('\u1e0b', '\u1e0b'), ('\u1e0d', '\u1e0d'), + ('\u1e0f', '\u1e0f'), ('\u1e11', '\u1e11'), + ('\u1e13', '\u1e13'), ('\u1e15', '\u1e15'), + ('\u1e17', '\u1e17'), ('\u1e19', '\u1e19'), + ('\u1e1b', '\u1e1b'), ('\u1e1d', '\u1e1d'), + ('\u1e1f', '\u1e1f'), ('\u1e21', '\u1e21'), + ('\u1e23', '\u1e23'), ('\u1e25', '\u1e25'), + ('\u1e27', '\u1e27'), ('\u1e29', '\u1e29'), + ('\u1e2b', '\u1e2b'), ('\u1e2d', '\u1e2d'), + ('\u1e2f', '\u1e2f'), ('\u1e31', '\u1e31'), + ('\u1e33', '\u1e33'), ('\u1e35', '\u1e35'), + ('\u1e37', '\u1e37'), ('\u1e39', '\u1e39'), + ('\u1e3b', '\u1e3b'), ('\u1e3d', '\u1e3d'), + ('\u1e3f', '\u1e3f'), ('\u1e41', '\u1e41'), + ('\u1e43', '\u1e43'), ('\u1e45', '\u1e45'), + ('\u1e47', '\u1e47'), ('\u1e49', '\u1e49'), + ('\u1e4b', '\u1e4b'), ('\u1e4d', '\u1e4d'), + ('\u1e4f', '\u1e4f'), ('\u1e51', '\u1e51'), + ('\u1e53', '\u1e53'), ('\u1e55', '\u1e55'), + ('\u1e57', '\u1e57'), ('\u1e59', '\u1e59'), + ('\u1e5b', '\u1e5b'), ('\u1e5d', '\u1e5d'), + ('\u1e5f', '\u1e5f'), ('\u1e61', '\u1e61'), + ('\u1e63', '\u1e63'), ('\u1e65', '\u1e65'), + ('\u1e67', '\u1e67'), ('\u1e69', '\u1e69'), + ('\u1e6b', '\u1e6b'), ('\u1e6d', '\u1e6d'), + ('\u1e6f', '\u1e6f'), ('\u1e71', '\u1e71'), + ('\u1e73', '\u1e73'), ('\u1e75', '\u1e75'), + ('\u1e77', '\u1e77'), ('\u1e79', '\u1e79'), + ('\u1e7b', '\u1e7b'), ('\u1e7d', '\u1e7d'), + ('\u1e7f', '\u1e7f'), ('\u1e81', '\u1e81'), + ('\u1e83', '\u1e83'), ('\u1e85', '\u1e85'), + ('\u1e87', '\u1e87'), ('\u1e89', '\u1e89'), + ('\u1e8b', '\u1e8b'), ('\u1e8d', '\u1e8d'), + ('\u1e8f', '\u1e8f'), ('\u1e91', '\u1e91'), + ('\u1e93', '\u1e93'), ('\u1e95', '\u1e9d'), + ('\u1e9f', '\u1e9f'), ('\u1ea1', '\u1ea1'), + ('\u1ea3', '\u1ea3'), ('\u1ea5', '\u1ea5'), + ('\u1ea7', '\u1ea7'), ('\u1ea9', '\u1ea9'), + ('\u1eab', '\u1eab'), ('\u1ead', '\u1ead'), + ('\u1eaf', '\u1eaf'), ('\u1eb1', '\u1eb1'), + ('\u1eb3', '\u1eb3'), ('\u1eb5', '\u1eb5'), + ('\u1eb7', '\u1eb7'), ('\u1eb9', '\u1eb9'), + ('\u1ebb', '\u1ebb'), ('\u1ebd', '\u1ebd'), + ('\u1ebf', '\u1ebf'), ('\u1ec1', '\u1ec1'), + ('\u1ec3', '\u1ec3'), ('\u1ec5', '\u1ec5'), + ('\u1ec7', '\u1ec7'), ('\u1ec9', '\u1ec9'), + ('\u1ecb', '\u1ecb'), ('\u1ecd', '\u1ecd'), + ('\u1ecf', '\u1ecf'), ('\u1ed1', '\u1ed1'), + ('\u1ed3', '\u1ed3'), ('\u1ed5', '\u1ed5'), + ('\u1ed7', '\u1ed7'), ('\u1ed9', '\u1ed9'), + ('\u1edb', '\u1edb'), ('\u1edd', '\u1edd'), + ('\u1edf', '\u1edf'), ('\u1ee1', '\u1ee1'), + ('\u1ee3', '\u1ee3'), ('\u1ee5', '\u1ee5'), + ('\u1ee7', '\u1ee7'), ('\u1ee9', '\u1ee9'), + ('\u1eeb', '\u1eeb'), ('\u1eed', '\u1eed'), + ('\u1eef', '\u1eef'), ('\u1ef1', '\u1ef1'), + ('\u1ef3', '\u1ef3'), ('\u1ef5', '\u1ef5'), + ('\u1ef7', '\u1ef7'), ('\u1ef9', '\u1ef9'), + ('\u1efb', '\u1efb'), ('\u1efd', '\u1efd'), + ('\u1eff', '\u1f07'), ('\u1f10', '\u1f15'), + ('\u1f20', '\u1f27'), ('\u1f30', '\u1f37'), + ('\u1f40', '\u1f45'), ('\u1f50', '\u1f57'), + ('\u1f60', '\u1f67'), ('\u1f70', '\u1f87'), + ('\u1f90', '\u1f97'), ('\u1fa0', '\u1fa7'), + ('\u1fb0', '\u1fb7'), ('\u1fbe', '\u1fbe'), + ('\u1fc2', '\u1fc7'), ('\u1fd0', '\u1fd7'), + ('\u1fe0', '\u1fe7'), ('\u1ff2', '\u1ff7'), + ('\u210a', '\u210a'), ('\u210e', '\u210f'), + ('\u2113', '\u2113'), ('\u212f', '\u212f'), + ('\u2134', '\u2134'), ('\u2139', '\u2139'), + ('\u213c', '\u213d'), ('\u2146', '\u2149'), + ('\u214e', '\u214e'), ('\u2184', '\u2184'), + ('\u2c30', '\u2c5e'), ('\u2c61', '\u2c61'), + ('\u2c65', '\u2c66'), ('\u2c68', '\u2c68'), + ('\u2c6a', '\u2c6a'), ('\u2c6c', '\u2c6c'), + ('\u2c71', '\u2c71'), ('\u2c73', '\u2c74'), + ('\u2c76', '\u2c7b'), ('\u2c81', '\u2c81'), + ('\u2c83', '\u2c83'), ('\u2c85', '\u2c85'), + ('\u2c87', '\u2c87'), ('\u2c89', '\u2c89'), + ('\u2c8b', '\u2c8b'), ('\u2c8d', '\u2c8d'), + ('\u2c8f', '\u2c8f'), ('\u2c91', '\u2c91'), + ('\u2c93', '\u2c93'), ('\u2c95', '\u2c95'), + ('\u2c97', '\u2c97'), ('\u2c99', '\u2c99'), + ('\u2c9b', '\u2c9b'), ('\u2c9d', '\u2c9d'), + ('\u2c9f', '\u2c9f'), ('\u2ca1', '\u2ca1'), + ('\u2ca3', '\u2ca3'), ('\u2ca5', '\u2ca5'), + ('\u2ca7', '\u2ca7'), ('\u2ca9', '\u2ca9'), + ('\u2cab', '\u2cab'), ('\u2cad', '\u2cad'), + ('\u2caf', '\u2caf'), ('\u2cb1', '\u2cb1'), + ('\u2cb3', '\u2cb3'), ('\u2cb5', '\u2cb5'), + ('\u2cb7', '\u2cb7'), ('\u2cb9', '\u2cb9'), + ('\u2cbb', '\u2cbb'), ('\u2cbd', '\u2cbd'), + ('\u2cbf', '\u2cbf'), ('\u2cc1', '\u2cc1'), + ('\u2cc3', '\u2cc3'), ('\u2cc5', '\u2cc5'), + ('\u2cc7', '\u2cc7'), ('\u2cc9', '\u2cc9'), + ('\u2ccb', '\u2ccb'), ('\u2ccd', '\u2ccd'), + ('\u2ccf', '\u2ccf'), ('\u2cd1', '\u2cd1'), + ('\u2cd3', '\u2cd3'), ('\u2cd5', '\u2cd5'), + ('\u2cd7', '\u2cd7'), ('\u2cd9', '\u2cd9'), + ('\u2cdb', '\u2cdb'), ('\u2cdd', '\u2cdd'), + ('\u2cdf', '\u2cdf'), ('\u2ce1', '\u2ce1'), + ('\u2ce3', '\u2ce4'), ('\u2cec', '\u2cec'), + ('\u2cee', '\u2cee'), ('\u2cf3', '\u2cf3'), + ('\u2d00', '\u2d2d'), ('\ua641', '\ua641'), + ('\ua643', '\ua643'), ('\ua645', '\ua645'), + ('\ua647', '\ua647'), ('\ua649', '\ua649'), + ('\ua64b', '\ua64b'), ('\ua64d', '\ua64d'), + ('\ua64f', '\ua64f'), ('\ua651', '\ua651'), + ('\ua653', '\ua653'), ('\ua655', '\ua655'), + ('\ua657', '\ua657'), ('\ua659', '\ua659'), + ('\ua65b', '\ua65b'), ('\ua65d', '\ua65d'), + ('\ua65f', '\ua65f'), ('\ua661', '\ua661'), + ('\ua663', '\ua663'), ('\ua665', '\ua665'), + ('\ua667', '\ua667'), ('\ua669', '\ua669'), + ('\ua66b', '\ua66b'), ('\ua66d', '\ua66d'), + ('\ua681', '\ua681'), ('\ua683', '\ua683'), + ('\ua685', '\ua685'), ('\ua687', '\ua687'), + ('\ua689', '\ua689'), ('\ua68b', '\ua68b'), + ('\ua68d', '\ua68d'), ('\ua68f', '\ua68f'), + ('\ua691', '\ua691'), ('\ua693', '\ua693'), + ('\ua695', '\ua695'), ('\ua697', '\ua697'), + ('\ua723', '\ua723'), ('\ua725', '\ua725'), + ('\ua727', '\ua727'), ('\ua729', '\ua729'), + ('\ua72b', '\ua72b'), ('\ua72d', '\ua72d'), + ('\ua72f', '\ua731'), ('\ua733', '\ua733'), + ('\ua735', '\ua735'), ('\ua737', '\ua737'), + ('\ua739', '\ua739'), ('\ua73b', '\ua73b'), + ('\ua73d', '\ua73d'), ('\ua73f', '\ua73f'), + ('\ua741', '\ua741'), ('\ua743', '\ua743'), + ('\ua745', '\ua745'), ('\ua747', '\ua747'), + ('\ua749', '\ua749'), ('\ua74b', '\ua74b'), + ('\ua74d', '\ua74d'), ('\ua74f', '\ua74f'), + ('\ua751', '\ua751'), ('\ua753', '\ua753'), + ('\ua755', '\ua755'), ('\ua757', '\ua757'), + ('\ua759', '\ua759'), ('\ua75b', '\ua75b'), + ('\ua75d', '\ua75d'), ('\ua75f', '\ua75f'), + ('\ua761', '\ua761'), ('\ua763', '\ua763'), + ('\ua765', '\ua765'), ('\ua767', '\ua767'), + ('\ua769', '\ua769'), ('\ua76b', '\ua76b'), + ('\ua76d', '\ua76d'), ('\ua76f', '\ua76f'), + ('\ua771', '\ua778'), ('\ua77a', '\ua77a'), + ('\ua77c', '\ua77c'), ('\ua77f', '\ua77f'), + ('\ua781', '\ua781'), ('\ua783', '\ua783'), + ('\ua785', '\ua785'), ('\ua787', '\ua787'), + ('\ua78c', '\ua78c'), ('\ua78e', '\ua78e'), + ('\ua791', '\ua791'), ('\ua793', '\ua793'), + ('\ua7a1', '\ua7a1'), ('\ua7a3', '\ua7a3'), + ('\ua7a5', '\ua7a5'), ('\ua7a7', '\ua7a7'), + ('\ua7a9', '\ua7a9'), ('\ua7fa', '\ua7fa'), + ('\ufb00', '\ufb17'), ('\uff41', '\uff5a'), + ('\U00010428', '\U0001044f'), ('\U0001d41a', '\U0001d433'), + ('\U0001d44e', '\U0001d467'), ('\U0001d482', '\U0001d49b'), + ('\U0001d4b6', '\U0001d4cf'), ('\U0001d4ea', '\U0001d503'), + ('\U0001d51e', '\U0001d537'), ('\U0001d552', '\U0001d56b'), + ('\U0001d586', '\U0001d59f'), ('\U0001d5ba', '\U0001d5d3'), + ('\U0001d5ee', '\U0001d607'), ('\U0001d622', '\U0001d63b'), + ('\U0001d656', '\U0001d66f'), ('\U0001d68a', '\U0001d6a5'), + ('\U0001d6c2', '\U0001d6da'), ('\U0001d6dc', '\U0001d6e1'), + ('\U0001d6fc', '\U0001d714'), ('\U0001d716', '\U0001d71b'), + ('\U0001d736', '\U0001d74e'), ('\U0001d750', '\U0001d755'), + ('\U0001d770', '\U0001d788'), ('\U0001d78a', '\U0001d78f'), + ('\U0001d7aa', '\U0001d7c2'), ('\U0001d7c4', '\U0001d7c9'), + ('\U0001d7cb', '\U0001d7cb') + ]; + + pub fn Ll(c: char) -> bool { + bsearch_range_table(c, Ll_table) + } + + static Lm_table : &'static [(char,char)] = &[ + ('\u02b0', '\u02c1'), ('\u02c6', '\u02d1'), + ('\u02e0', '\u02e4'), ('\u02ec', '\u02ec'), + ('\u02ee', '\u02ee'), ('\u0374', '\u0374'), + ('\u037a', '\u037a'), ('\u0559', '\u0559'), + ('\u0640', '\u0640'), ('\u06e5', '\u06e6'), + ('\u07f4', '\u07f5'), ('\u07fa', '\u07fa'), + ('\u081a', '\u081a'), ('\u0824', '\u0824'), + ('\u0828', '\u0828'), ('\u0971', '\u0971'), + ('\u0e46', '\u0e46'), ('\u0ec6', '\u0ec6'), + ('\u10fc', '\u10fc'), ('\u17d7', '\u17d7'), + ('\u1843', '\u1843'), ('\u1aa7', '\u1aa7'), + ('\u1c78', '\u1c7d'), ('\u1d2c', '\u1d6a'), + ('\u1d78', '\u1d78'), ('\u1d9b', '\u1dbf'), + ('\u2071', '\u2071'), ('\u207f', '\u207f'), + ('\u2090', '\u209c'), ('\u2c7c', '\u2c7d'), + ('\u2d6f', '\u2d6f'), ('\u2e2f', '\u2e2f'), + ('\u3005', '\u3005'), ('\u3031', '\u3035'), + ('\u303b', '\u303b'), ('\u309d', '\u309e'), + ('\u30fc', '\u30fe'), ('\ua015', '\ua015'), + ('\ua4f8', '\ua4fd'), ('\ua60c', '\ua60c'), + ('\ua67f', '\ua67f'), ('\ua717', '\ua71f'), + ('\ua770', '\ua770'), ('\ua788', '\ua788'), + ('\ua7f8', '\ua7f9'), ('\ua9cf', '\ua9cf'), + ('\uaa70', '\uaa70'), ('\uaadd', '\uaadd'), + ('\uaaf3', '\uaaf4'), ('\uff70', '\uff70'), + ('\uff9e', '\uff9f'), ('\U00016f93', '\U00016f9f') + ]; + + pub fn Lm(c: char) -> bool { + bsearch_range_table(c, Lm_table) + } + + static Lo_table : &'static [(char,char)] = &[ + ('\xaa', '\xaa'), ('\xba', '\xba'), + ('\u01bb', '\u01bb'), ('\u01c0', '\u01c3'), + ('\u0294', '\u0294'), ('\u05d0', '\u05f2'), + ('\u0620', '\u063f'), ('\u0641', '\u064a'), + ('\u066e', '\u066f'), ('\u0671', '\u06d3'), + ('\u06d5', '\u06d5'), ('\u06ee', '\u06ef'), + ('\u06fa', '\u06fc'), ('\u06ff', '\u06ff'), + ('\u0710', '\u0710'), ('\u0712', '\u072f'), + ('\u074d', '\u07a5'), ('\u07b1', '\u07b1'), + ('\u07ca', '\u07ea'), ('\u0800', '\u0815'), + ('\u0840', '\u0858'), ('\u08a0', '\u08ac'), + ('\u0904', '\u0939'), ('\u093d', '\u093d'), + ('\u0950', '\u0950'), ('\u0958', '\u0961'), + ('\u0972', '\u097f'), ('\u0985', '\u09b9'), + ('\u09bd', '\u09bd'), ('\u09ce', '\u09ce'), + ('\u09dc', '\u09e1'), ('\u09f0', '\u09f1'), + ('\u0a05', '\u0a39'), ('\u0a59', '\u0a5e'), + ('\u0a72', '\u0a74'), ('\u0a85', '\u0ab9'), + ('\u0abd', '\u0abd'), ('\u0ad0', '\u0ae1'), + ('\u0b05', '\u0b39'), ('\u0b3d', '\u0b3d'), + ('\u0b5c', '\u0b61'), ('\u0b71', '\u0b71'), + ('\u0b83', '\u0bb9'), ('\u0bd0', '\u0bd0'), + ('\u0c05', '\u0c3d'), ('\u0c58', '\u0c61'), + ('\u0c85', '\u0cb9'), ('\u0cbd', '\u0cbd'), + ('\u0cde', '\u0ce1'), ('\u0cf1', '\u0cf2'), + ('\u0d05', '\u0d3d'), ('\u0d4e', '\u0d4e'), + ('\u0d60', '\u0d61'), ('\u0d7a', '\u0d7f'), + ('\u0d85', '\u0dc6'), ('\u0e01', '\u0e30'), + ('\u0e32', '\u0e33'), ('\u0e40', '\u0e45'), + ('\u0e81', '\u0eb0'), ('\u0eb2', '\u0eb3'), + ('\u0ebd', '\u0ec4'), ('\u0edc', '\u0f00'), + ('\u0f40', '\u0f6c'), ('\u0f88', '\u0f8c'), + ('\u1000', '\u102a'), ('\u103f', '\u103f'), + ('\u1050', '\u1055'), ('\u105a', '\u105d'), + ('\u1061', '\u1061'), ('\u1065', '\u1066'), + ('\u106e', '\u1070'), ('\u1075', '\u1081'), + ('\u108e', '\u108e'), ('\u10d0', '\u10fa'), + ('\u10fd', '\u135a'), ('\u1380', '\u138f'), + ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), + ('\u166f', '\u167f'), ('\u1681', '\u169a'), + ('\u16a0', '\u16ea'), ('\u1700', '\u1711'), + ('\u1720', '\u1731'), ('\u1740', '\u1751'), + ('\u1760', '\u1770'), ('\u1780', '\u17b3'), + ('\u17dc', '\u17dc'), ('\u1820', '\u1842'), + ('\u1844', '\u18a8'), ('\u18aa', '\u191c'), + ('\u1950', '\u19ab'), ('\u19c1', '\u19c7'), + ('\u1a00', '\u1a16'), ('\u1a20', '\u1a54'), + ('\u1b05', '\u1b33'), ('\u1b45', '\u1b4b'), + ('\u1b83', '\u1ba0'), ('\u1bae', '\u1baf'), + ('\u1bba', '\u1be5'), ('\u1c00', '\u1c23'), + ('\u1c4d', '\u1c4f'), ('\u1c5a', '\u1c77'), + ('\u1ce9', '\u1cec'), ('\u1cee', '\u1cf1'), + ('\u1cf5', '\u1cf6'), ('\u2135', '\u2138'), + ('\u2d30', '\u2d67'), ('\u2d80', '\u2dde'), + ('\u3006', '\u3006'), ('\u303c', '\u303c'), + ('\u3041', '\u3096'), ('\u309f', '\u309f'), + ('\u30a1', '\u30fa'), ('\u30ff', '\u318e'), + ('\u31a0', '\u31ba'), ('\u31f0', '\u31ff'), + ('\u3400', '\u4db5'), ('\u4e00', '\ua014'), + ('\ua016', '\ua48c'), ('\ua4d0', '\ua4f7'), + ('\ua500', '\ua60b'), ('\ua610', '\ua61f'), + ('\ua62a', '\ua62b'), ('\ua66e', '\ua66e'), + ('\ua6a0', '\ua6e5'), ('\ua7fb', '\ua801'), + ('\ua803', '\ua805'), ('\ua807', '\ua80a'), + ('\ua80c', '\ua822'), ('\ua840', '\ua873'), + ('\ua882', '\ua8b3'), ('\ua8f2', '\ua8f7'), + ('\ua8fb', '\ua8fb'), ('\ua90a', '\ua925'), + ('\ua930', '\ua946'), ('\ua960', '\ua97c'), + ('\ua984', '\ua9b2'), ('\uaa00', '\uaa28'), + ('\uaa40', '\uaa42'), ('\uaa44', '\uaa4b'), + ('\uaa60', '\uaa6f'), ('\uaa71', '\uaa76'), + ('\uaa7a', '\uaa7a'), ('\uaa80', '\uaaaf'), + ('\uaab1', '\uaab1'), ('\uaab5', '\uaab6'), + ('\uaab9', '\uaabd'), ('\uaac0', '\uaac0'), + ('\uaac2', '\uaadc'), ('\uaae0', '\uaaea'), + ('\uaaf2', '\uaaf2'), ('\uab01', '\uabe2'), + ('\uac00', '\ud7fb'), ('\uf900', '\ufad9'), + ('\ufb1d', '\ufb1d'), ('\ufb1f', '\ufb28'), + ('\ufb2a', '\ufbb1'), ('\ufbd3', '\ufd3d'), + ('\ufd50', '\ufdfb'), ('\ufe70', '\ufefc'), + ('\uff66', '\uff6f'), ('\uff71', '\uff9d'), + ('\uffa0', '\uffdc'), ('\U00010000', '\U000100fa'), + ('\U00010280', '\U0001031e'), ('\U00010330', '\U00010340'), + ('\U00010342', '\U00010349'), ('\U00010380', '\U0001039d'), + ('\U000103a0', '\U000103cf'), ('\U00010450', '\U0001049d'), + ('\U00010800', '\U00010855'), ('\U00010900', '\U00010915'), + ('\U00010920', '\U00010939'), ('\U00010980', '\U00010a00'), + ('\U00010a10', '\U00010a33'), ('\U00010a60', '\U00010a7c'), + ('\U00010b00', '\U00010b35'), ('\U00010b40', '\U00010b55'), + ('\U00010b60', '\U00010b72'), ('\U00010c00', '\U00010c48'), + ('\U00011003', '\U00011037'), ('\U00011083', '\U000110af'), + ('\U000110d0', '\U000110e8'), ('\U00011103', '\U00011126'), + ('\U00011183', '\U000111b2'), ('\U000111c1', '\U000111c4'), + ('\U00011680', '\U000116aa'), ('\U00012000', '\U0001236e'), + ('\U00013000', '\U00016f50'), ('\U0001b000', '\U0001b001'), + ('\U0001ee00', '\U0001eebb'), ('\U00020000', '\U0002fa1d') + ]; + + pub fn Lo(c: char) -> bool { + bsearch_range_table(c, Lo_table) + } + + static Lt_table : &'static [(char,char)] = &[ + ('\u01c5', '\u01c5'), ('\u01c8', '\u01c8'), + ('\u01cb', '\u01cb'), ('\u01f2', '\u01f2'), + ('\u1f88', '\u1f8f'), ('\u1f98', '\u1f9f'), + ('\u1fa8', '\u1faf'), ('\u1fbc', '\u1fbc'), + ('\u1fcc', '\u1fcc'), ('\u1ffc', '\u1ffc') + ]; + + pub fn Lt(c: char) -> bool { + bsearch_range_table(c, Lt_table) + } + + static Lu_table : &'static [(char,char)] = &[ + ('\x41', '\x5a'), ('\xc0', '\xd6'), + ('\xd8', '\xde'), ('\u0100', '\u0100'), + ('\u0102', '\u0102'), ('\u0104', '\u0104'), + ('\u0106', '\u0106'), ('\u0108', '\u0108'), + ('\u010a', '\u010a'), ('\u010c', '\u010c'), + ('\u010e', '\u010e'), ('\u0110', '\u0110'), + ('\u0112', '\u0112'), ('\u0114', '\u0114'), + ('\u0116', '\u0116'), ('\u0118', '\u0118'), + ('\u011a', '\u011a'), ('\u011c', '\u011c'), + ('\u011e', '\u011e'), ('\u0120', '\u0120'), + ('\u0122', '\u0122'), ('\u0124', '\u0124'), + ('\u0126', '\u0126'), ('\u0128', '\u0128'), + ('\u012a', '\u012a'), ('\u012c', '\u012c'), + ('\u012e', '\u012e'), ('\u0130', '\u0130'), + ('\u0132', '\u0132'), ('\u0134', '\u0134'), + ('\u0136', '\u0136'), ('\u0139', '\u0139'), + ('\u013b', '\u013b'), ('\u013d', '\u013d'), + ('\u013f', '\u013f'), ('\u0141', '\u0141'), + ('\u0143', '\u0143'), ('\u0145', '\u0145'), + ('\u0147', '\u0147'), ('\u014a', '\u014a'), + ('\u014c', '\u014c'), ('\u014e', '\u014e'), + ('\u0150', '\u0150'), ('\u0152', '\u0152'), + ('\u0154', '\u0154'), ('\u0156', '\u0156'), + ('\u0158', '\u0158'), ('\u015a', '\u015a'), + ('\u015c', '\u015c'), ('\u015e', '\u015e'), + ('\u0160', '\u0160'), ('\u0162', '\u0162'), + ('\u0164', '\u0164'), ('\u0166', '\u0166'), + ('\u0168', '\u0168'), ('\u016a', '\u016a'), + ('\u016c', '\u016c'), ('\u016e', '\u016e'), + ('\u0170', '\u0170'), ('\u0172', '\u0172'), + ('\u0174', '\u0174'), ('\u0176', '\u0176'), + ('\u0178', '\u0179'), ('\u017b', '\u017b'), + ('\u017d', '\u017d'), ('\u0181', '\u0182'), + ('\u0184', '\u0184'), ('\u0186', '\u0187'), + ('\u0189', '\u018b'), ('\u018e', '\u0191'), + ('\u0193', '\u0194'), ('\u0196', '\u0198'), + ('\u019c', '\u019d'), ('\u019f', '\u01a0'), + ('\u01a2', '\u01a2'), ('\u01a4', '\u01a4'), + ('\u01a6', '\u01a7'), ('\u01a9', '\u01a9'), + ('\u01ac', '\u01ac'), ('\u01ae', '\u01af'), + ('\u01b1', '\u01b3'), ('\u01b5', '\u01b5'), + ('\u01b7', '\u01b8'), ('\u01bc', '\u01bc'), + ('\u01c4', '\u01c4'), ('\u01c7', '\u01c7'), + ('\u01ca', '\u01ca'), ('\u01cd', '\u01cd'), + ('\u01cf', '\u01cf'), ('\u01d1', '\u01d1'), + ('\u01d3', '\u01d3'), ('\u01d5', '\u01d5'), + ('\u01d7', '\u01d7'), ('\u01d9', '\u01d9'), + ('\u01db', '\u01db'), ('\u01de', '\u01de'), + ('\u01e0', '\u01e0'), ('\u01e2', '\u01e2'), + ('\u01e4', '\u01e4'), ('\u01e6', '\u01e6'), + ('\u01e8', '\u01e8'), ('\u01ea', '\u01ea'), + ('\u01ec', '\u01ec'), ('\u01ee', '\u01ee'), + ('\u01f1', '\u01f1'), ('\u01f4', '\u01f4'), + ('\u01f6', '\u01f8'), ('\u01fa', '\u01fa'), + ('\u01fc', '\u01fc'), ('\u01fe', '\u01fe'), + ('\u0200', '\u0200'), ('\u0202', '\u0202'), + ('\u0204', '\u0204'), ('\u0206', '\u0206'), + ('\u0208', '\u0208'), ('\u020a', '\u020a'), + ('\u020c', '\u020c'), ('\u020e', '\u020e'), + ('\u0210', '\u0210'), ('\u0212', '\u0212'), + ('\u0214', '\u0214'), ('\u0216', '\u0216'), + ('\u0218', '\u0218'), ('\u021a', '\u021a'), + ('\u021c', '\u021c'), ('\u021e', '\u021e'), + ('\u0220', '\u0220'), ('\u0222', '\u0222'), + ('\u0224', '\u0224'), ('\u0226', '\u0226'), + ('\u0228', '\u0228'), ('\u022a', '\u022a'), + ('\u022c', '\u022c'), ('\u022e', '\u022e'), + ('\u0230', '\u0230'), ('\u0232', '\u0232'), + ('\u023a', '\u023b'), ('\u023d', '\u023e'), + ('\u0241', '\u0241'), ('\u0243', '\u0246'), + ('\u0248', '\u0248'), ('\u024a', '\u024a'), + ('\u024c', '\u024c'), ('\u024e', '\u024e'), + ('\u0370', '\u0370'), ('\u0372', '\u0372'), + ('\u0376', '\u0376'), ('\u0386', '\u0386'), + ('\u0388', '\u038f'), ('\u0391', '\u03ab'), + ('\u03cf', '\u03cf'), ('\u03d2', '\u03d4'), + ('\u03d8', '\u03d8'), ('\u03da', '\u03da'), + ('\u03dc', '\u03dc'), ('\u03de', '\u03de'), + ('\u03e0', '\u03e0'), ('\u03e2', '\u03e2'), + ('\u03e4', '\u03e4'), ('\u03e6', '\u03e6'), + ('\u03e8', '\u03e8'), ('\u03ea', '\u03ea'), + ('\u03ec', '\u03ec'), ('\u03ee', '\u03ee'), + ('\u03f4', '\u03f4'), ('\u03f7', '\u03f7'), + ('\u03f9', '\u03fa'), ('\u03fd', '\u042f'), + ('\u0460', '\u0460'), ('\u0462', '\u0462'), + ('\u0464', '\u0464'), ('\u0466', '\u0466'), + ('\u0468', '\u0468'), ('\u046a', '\u046a'), + ('\u046c', '\u046c'), ('\u046e', '\u046e'), + ('\u0470', '\u0470'), ('\u0472', '\u0472'), + ('\u0474', '\u0474'), ('\u0476', '\u0476'), + ('\u0478', '\u0478'), ('\u047a', '\u047a'), + ('\u047c', '\u047c'), ('\u047e', '\u047e'), + ('\u0480', '\u0480'), ('\u048a', '\u048a'), + ('\u048c', '\u048c'), ('\u048e', '\u048e'), + ('\u0490', '\u0490'), ('\u0492', '\u0492'), + ('\u0494', '\u0494'), ('\u0496', '\u0496'), + ('\u0498', '\u0498'), ('\u049a', '\u049a'), + ('\u049c', '\u049c'), ('\u049e', '\u049e'), + ('\u04a0', '\u04a0'), ('\u04a2', '\u04a2'), + ('\u04a4', '\u04a4'), ('\u04a6', '\u04a6'), + ('\u04a8', '\u04a8'), ('\u04aa', '\u04aa'), + ('\u04ac', '\u04ac'), ('\u04ae', '\u04ae'), + ('\u04b0', '\u04b0'), ('\u04b2', '\u04b2'), + ('\u04b4', '\u04b4'), ('\u04b6', '\u04b6'), + ('\u04b8', '\u04b8'), ('\u04ba', '\u04ba'), + ('\u04bc', '\u04bc'), ('\u04be', '\u04be'), + ('\u04c0', '\u04c1'), ('\u04c3', '\u04c3'), + ('\u04c5', '\u04c5'), ('\u04c7', '\u04c7'), + ('\u04c9', '\u04c9'), ('\u04cb', '\u04cb'), + ('\u04cd', '\u04cd'), ('\u04d0', '\u04d0'), + ('\u04d2', '\u04d2'), ('\u04d4', '\u04d4'), + ('\u04d6', '\u04d6'), ('\u04d8', '\u04d8'), + ('\u04da', '\u04da'), ('\u04dc', '\u04dc'), + ('\u04de', '\u04de'), ('\u04e0', '\u04e0'), + ('\u04e2', '\u04e2'), ('\u04e4', '\u04e4'), + ('\u04e6', '\u04e6'), ('\u04e8', '\u04e8'), + ('\u04ea', '\u04ea'), ('\u04ec', '\u04ec'), + ('\u04ee', '\u04ee'), ('\u04f0', '\u04f0'), + ('\u04f2', '\u04f2'), ('\u04f4', '\u04f4'), + ('\u04f6', '\u04f6'), ('\u04f8', '\u04f8'), + ('\u04fa', '\u04fa'), ('\u04fc', '\u04fc'), + ('\u04fe', '\u04fe'), ('\u0500', '\u0500'), + ('\u0502', '\u0502'), ('\u0504', '\u0504'), + ('\u0506', '\u0506'), ('\u0508', '\u0508'), + ('\u050a', '\u050a'), ('\u050c', '\u050c'), + ('\u050e', '\u050e'), ('\u0510', '\u0510'), + ('\u0512', '\u0512'), ('\u0514', '\u0514'), + ('\u0516', '\u0516'), ('\u0518', '\u0518'), + ('\u051a', '\u051a'), ('\u051c', '\u051c'), + ('\u051e', '\u051e'), ('\u0520', '\u0520'), + ('\u0522', '\u0522'), ('\u0524', '\u0524'), + ('\u0526', '\u0526'), ('\u0531', '\u0556'), + ('\u10a0', '\u10cd'), ('\u1e00', '\u1e00'), + ('\u1e02', '\u1e02'), ('\u1e04', '\u1e04'), + ('\u1e06', '\u1e06'), ('\u1e08', '\u1e08'), + ('\u1e0a', '\u1e0a'), ('\u1e0c', '\u1e0c'), + ('\u1e0e', '\u1e0e'), ('\u1e10', '\u1e10'), + ('\u1e12', '\u1e12'), ('\u1e14', '\u1e14'), + ('\u1e16', '\u1e16'), ('\u1e18', '\u1e18'), + ('\u1e1a', '\u1e1a'), ('\u1e1c', '\u1e1c'), + ('\u1e1e', '\u1e1e'), ('\u1e20', '\u1e20'), + ('\u1e22', '\u1e22'), ('\u1e24', '\u1e24'), + ('\u1e26', '\u1e26'), ('\u1e28', '\u1e28'), + ('\u1e2a', '\u1e2a'), ('\u1e2c', '\u1e2c'), + ('\u1e2e', '\u1e2e'), ('\u1e30', '\u1e30'), + ('\u1e32', '\u1e32'), ('\u1e34', '\u1e34'), + ('\u1e36', '\u1e36'), ('\u1e38', '\u1e38'), + ('\u1e3a', '\u1e3a'), ('\u1e3c', '\u1e3c'), + ('\u1e3e', '\u1e3e'), ('\u1e40', '\u1e40'), + ('\u1e42', '\u1e42'), ('\u1e44', '\u1e44'), + ('\u1e46', '\u1e46'), ('\u1e48', '\u1e48'), + ('\u1e4a', '\u1e4a'), ('\u1e4c', '\u1e4c'), + ('\u1e4e', '\u1e4e'), ('\u1e50', '\u1e50'), + ('\u1e52', '\u1e52'), ('\u1e54', '\u1e54'), + ('\u1e56', '\u1e56'), ('\u1e58', '\u1e58'), + ('\u1e5a', '\u1e5a'), ('\u1e5c', '\u1e5c'), + ('\u1e5e', '\u1e5e'), ('\u1e60', '\u1e60'), + ('\u1e62', '\u1e62'), ('\u1e64', '\u1e64'), + ('\u1e66', '\u1e66'), ('\u1e68', '\u1e68'), + ('\u1e6a', '\u1e6a'), ('\u1e6c', '\u1e6c'), + ('\u1e6e', '\u1e6e'), ('\u1e70', '\u1e70'), + ('\u1e72', '\u1e72'), ('\u1e74', '\u1e74'), + ('\u1e76', '\u1e76'), ('\u1e78', '\u1e78'), + ('\u1e7a', '\u1e7a'), ('\u1e7c', '\u1e7c'), + ('\u1e7e', '\u1e7e'), ('\u1e80', '\u1e80'), + ('\u1e82', '\u1e82'), ('\u1e84', '\u1e84'), + ('\u1e86', '\u1e86'), ('\u1e88', '\u1e88'), + ('\u1e8a', '\u1e8a'), ('\u1e8c', '\u1e8c'), + ('\u1e8e', '\u1e8e'), ('\u1e90', '\u1e90'), + ('\u1e92', '\u1e92'), ('\u1e94', '\u1e94'), + ('\u1e9e', '\u1e9e'), ('\u1ea0', '\u1ea0'), + ('\u1ea2', '\u1ea2'), ('\u1ea4', '\u1ea4'), + ('\u1ea6', '\u1ea6'), ('\u1ea8', '\u1ea8'), + ('\u1eaa', '\u1eaa'), ('\u1eac', '\u1eac'), + ('\u1eae', '\u1eae'), ('\u1eb0', '\u1eb0'), + ('\u1eb2', '\u1eb2'), ('\u1eb4', '\u1eb4'), + ('\u1eb6', '\u1eb6'), ('\u1eb8', '\u1eb8'), + ('\u1eba', '\u1eba'), ('\u1ebc', '\u1ebc'), + ('\u1ebe', '\u1ebe'), ('\u1ec0', '\u1ec0'), + ('\u1ec2', '\u1ec2'), ('\u1ec4', '\u1ec4'), + ('\u1ec6', '\u1ec6'), ('\u1ec8', '\u1ec8'), + ('\u1eca', '\u1eca'), ('\u1ecc', '\u1ecc'), + ('\u1ece', '\u1ece'), ('\u1ed0', '\u1ed0'), + ('\u1ed2', '\u1ed2'), ('\u1ed4', '\u1ed4'), + ('\u1ed6', '\u1ed6'), ('\u1ed8', '\u1ed8'), + ('\u1eda', '\u1eda'), ('\u1edc', '\u1edc'), + ('\u1ede', '\u1ede'), ('\u1ee0', '\u1ee0'), + ('\u1ee2', '\u1ee2'), ('\u1ee4', '\u1ee4'), + ('\u1ee6', '\u1ee6'), ('\u1ee8', '\u1ee8'), + ('\u1eea', '\u1eea'), ('\u1eec', '\u1eec'), + ('\u1eee', '\u1eee'), ('\u1ef0', '\u1ef0'), + ('\u1ef2', '\u1ef2'), ('\u1ef4', '\u1ef4'), + ('\u1ef6', '\u1ef6'), ('\u1ef8', '\u1ef8'), + ('\u1efa', '\u1efa'), ('\u1efc', '\u1efc'), + ('\u1efe', '\u1efe'), ('\u1f08', '\u1f0f'), + ('\u1f18', '\u1f1d'), ('\u1f28', '\u1f2f'), + ('\u1f38', '\u1f3f'), ('\u1f48', '\u1f4d'), + ('\u1f59', '\u1f5f'), ('\u1f68', '\u1f6f'), + ('\u1fb8', '\u1fbb'), ('\u1fc8', '\u1fcb'), + ('\u1fd8', '\u1fdb'), ('\u1fe8', '\u1fec'), + ('\u1ff8', '\u1ffb'), ('\u2102', '\u2102'), + ('\u2107', '\u2107'), ('\u210b', '\u210d'), + ('\u2110', '\u2112'), ('\u2115', '\u2115'), + ('\u2119', '\u211d'), ('\u2124', '\u2124'), + ('\u2126', '\u2126'), ('\u2128', '\u2128'), + ('\u212a', '\u212d'), ('\u2130', '\u2133'), + ('\u213e', '\u213f'), ('\u2145', '\u2145'), + ('\u2183', '\u2183'), ('\u2c00', '\u2c2e'), + ('\u2c60', '\u2c60'), ('\u2c62', '\u2c64'), + ('\u2c67', '\u2c67'), ('\u2c69', '\u2c69'), + ('\u2c6b', '\u2c6b'), ('\u2c6d', '\u2c70'), + ('\u2c72', '\u2c72'), ('\u2c75', '\u2c75'), + ('\u2c7e', '\u2c80'), ('\u2c82', '\u2c82'), + ('\u2c84', '\u2c84'), ('\u2c86', '\u2c86'), + ('\u2c88', '\u2c88'), ('\u2c8a', '\u2c8a'), + ('\u2c8c', '\u2c8c'), ('\u2c8e', '\u2c8e'), + ('\u2c90', '\u2c90'), ('\u2c92', '\u2c92'), + ('\u2c94', '\u2c94'), ('\u2c96', '\u2c96'), + ('\u2c98', '\u2c98'), ('\u2c9a', '\u2c9a'), + ('\u2c9c', '\u2c9c'), ('\u2c9e', '\u2c9e'), + ('\u2ca0', '\u2ca0'), ('\u2ca2', '\u2ca2'), + ('\u2ca4', '\u2ca4'), ('\u2ca6', '\u2ca6'), + ('\u2ca8', '\u2ca8'), ('\u2caa', '\u2caa'), + ('\u2cac', '\u2cac'), ('\u2cae', '\u2cae'), + ('\u2cb0', '\u2cb0'), ('\u2cb2', '\u2cb2'), + ('\u2cb4', '\u2cb4'), ('\u2cb6', '\u2cb6'), + ('\u2cb8', '\u2cb8'), ('\u2cba', '\u2cba'), + ('\u2cbc', '\u2cbc'), ('\u2cbe', '\u2cbe'), + ('\u2cc0', '\u2cc0'), ('\u2cc2', '\u2cc2'), + ('\u2cc4', '\u2cc4'), ('\u2cc6', '\u2cc6'), + ('\u2cc8', '\u2cc8'), ('\u2cca', '\u2cca'), + ('\u2ccc', '\u2ccc'), ('\u2cce', '\u2cce'), + ('\u2cd0', '\u2cd0'), ('\u2cd2', '\u2cd2'), + ('\u2cd4', '\u2cd4'), ('\u2cd6', '\u2cd6'), + ('\u2cd8', '\u2cd8'), ('\u2cda', '\u2cda'), + ('\u2cdc', '\u2cdc'), ('\u2cde', '\u2cde'), + ('\u2ce0', '\u2ce0'), ('\u2ce2', '\u2ce2'), + ('\u2ceb', '\u2ceb'), ('\u2ced', '\u2ced'), + ('\u2cf2', '\u2cf2'), ('\ua640', '\ua640'), + ('\ua642', '\ua642'), ('\ua644', '\ua644'), + ('\ua646', '\ua646'), ('\ua648', '\ua648'), + ('\ua64a', '\ua64a'), ('\ua64c', '\ua64c'), + ('\ua64e', '\ua64e'), ('\ua650', '\ua650'), + ('\ua652', '\ua652'), ('\ua654', '\ua654'), + ('\ua656', '\ua656'), ('\ua658', '\ua658'), + ('\ua65a', '\ua65a'), ('\ua65c', '\ua65c'), + ('\ua65e', '\ua65e'), ('\ua660', '\ua660'), + ('\ua662', '\ua662'), ('\ua664', '\ua664'), + ('\ua666', '\ua666'), ('\ua668', '\ua668'), + ('\ua66a', '\ua66a'), ('\ua66c', '\ua66c'), + ('\ua680', '\ua680'), ('\ua682', '\ua682'), + ('\ua684', '\ua684'), ('\ua686', '\ua686'), + ('\ua688', '\ua688'), ('\ua68a', '\ua68a'), + ('\ua68c', '\ua68c'), ('\ua68e', '\ua68e'), + ('\ua690', '\ua690'), ('\ua692', '\ua692'), + ('\ua694', '\ua694'), ('\ua696', '\ua696'), + ('\ua722', '\ua722'), ('\ua724', '\ua724'), + ('\ua726', '\ua726'), ('\ua728', '\ua728'), + ('\ua72a', '\ua72a'), ('\ua72c', '\ua72c'), + ('\ua72e', '\ua72e'), ('\ua732', '\ua732'), + ('\ua734', '\ua734'), ('\ua736', '\ua736'), + ('\ua738', '\ua738'), ('\ua73a', '\ua73a'), + ('\ua73c', '\ua73c'), ('\ua73e', '\ua73e'), + ('\ua740', '\ua740'), ('\ua742', '\ua742'), + ('\ua744', '\ua744'), ('\ua746', '\ua746'), + ('\ua748', '\ua748'), ('\ua74a', '\ua74a'), + ('\ua74c', '\ua74c'), ('\ua74e', '\ua74e'), + ('\ua750', '\ua750'), ('\ua752', '\ua752'), + ('\ua754', '\ua754'), ('\ua756', '\ua756'), + ('\ua758', '\ua758'), ('\ua75a', '\ua75a'), + ('\ua75c', '\ua75c'), ('\ua75e', '\ua75e'), + ('\ua760', '\ua760'), ('\ua762', '\ua762'), + ('\ua764', '\ua764'), ('\ua766', '\ua766'), + ('\ua768', '\ua768'), ('\ua76a', '\ua76a'), + ('\ua76c', '\ua76c'), ('\ua76e', '\ua76e'), + ('\ua779', '\ua779'), ('\ua77b', '\ua77b'), + ('\ua77d', '\ua77e'), ('\ua780', '\ua780'), + ('\ua782', '\ua782'), ('\ua784', '\ua784'), + ('\ua786', '\ua786'), ('\ua78b', '\ua78b'), + ('\ua78d', '\ua78d'), ('\ua790', '\ua790'), + ('\ua792', '\ua792'), ('\ua7a0', '\ua7a0'), + ('\ua7a2', '\ua7a2'), ('\ua7a4', '\ua7a4'), + ('\ua7a6', '\ua7a6'), ('\ua7a8', '\ua7a8'), + ('\ua7aa', '\ua7aa'), ('\uff21', '\uff3a'), + ('\U00010400', '\U00010427'), ('\U0001d400', '\U0001d419'), + ('\U0001d434', '\U0001d44d'), ('\U0001d468', '\U0001d481'), + ('\U0001d49c', '\U0001d4b5'), ('\U0001d4d0', '\U0001d4e9'), + ('\U0001d504', '\U0001d51c'), ('\U0001d538', '\U0001d550'), + ('\U0001d56c', '\U0001d585'), ('\U0001d5a0', '\U0001d5b9'), + ('\U0001d5d4', '\U0001d5ed'), ('\U0001d608', '\U0001d621'), + ('\U0001d63c', '\U0001d655'), ('\U0001d670', '\U0001d689'), + ('\U0001d6a8', '\U0001d6c0'), ('\U0001d6e2', '\U0001d6fa'), + ('\U0001d71c', '\U0001d734'), ('\U0001d756', '\U0001d76e'), + ('\U0001d790', '\U0001d7a8'), ('\U0001d7ca', '\U0001d7ca') + ]; + + pub fn Lu(c: char) -> bool { + bsearch_range_table(c, Lu_table) + } + + static Mc_table : &'static [(char,char)] = &[ + ('\u0903', '\u0903'), ('\u093b', '\u093b'), + ('\u093e', '\u0940'), ('\u0949', '\u094c'), + ('\u094e', '\u094f'), ('\u0982', '\u0983'), + ('\u09be', '\u09c0'), ('\u09c7', '\u09cc'), + ('\u09d7', '\u09d7'), ('\u0a03', '\u0a03'), + ('\u0a3e', '\u0a40'), ('\u0a83', '\u0a83'), + ('\u0abe', '\u0ac0'), ('\u0ac9', '\u0acc'), + ('\u0b02', '\u0b03'), ('\u0b3e', '\u0b3e'), + ('\u0b40', '\u0b40'), ('\u0b47', '\u0b4c'), + ('\u0b57', '\u0b57'), ('\u0bbe', '\u0bbf'), + ('\u0bc1', '\u0bcc'), ('\u0bd7', '\u0bd7'), + ('\u0c01', '\u0c03'), ('\u0c41', '\u0c44'), + ('\u0c82', '\u0c83'), ('\u0cbe', '\u0cbe'), + ('\u0cc0', '\u0cc4'), ('\u0cc7', '\u0ccb'), + ('\u0cd5', '\u0cd6'), ('\u0d02', '\u0d03'), + ('\u0d3e', '\u0d40'), ('\u0d46', '\u0d4c'), + ('\u0d57', '\u0d57'), ('\u0d82', '\u0d83'), + ('\u0dcf', '\u0dd1'), ('\u0dd8', '\u0df3'), + ('\u0f3e', '\u0f3f'), ('\u0f7f', '\u0f7f'), + ('\u102b', '\u102c'), ('\u1031', '\u1031'), + ('\u1038', '\u1038'), ('\u103b', '\u103c'), + ('\u1056', '\u1057'), ('\u1062', '\u1064'), + ('\u1067', '\u106d'), ('\u1083', '\u1084'), + ('\u1087', '\u108c'), ('\u108f', '\u108f'), + ('\u109a', '\u109c'), ('\u17b6', '\u17b6'), + ('\u17be', '\u17c5'), ('\u17c7', '\u17c8'), + ('\u1923', '\u1926'), ('\u1929', '\u1931'), + ('\u1933', '\u1938'), ('\u19b0', '\u19c0'), + ('\u19c8', '\u19c9'), ('\u1a19', '\u1a1b'), + ('\u1a55', '\u1a55'), ('\u1a57', '\u1a57'), + ('\u1a61', '\u1a61'), ('\u1a63', '\u1a64'), + ('\u1a6d', '\u1a72'), ('\u1b04', '\u1b04'), + ('\u1b35', '\u1b35'), ('\u1b3b', '\u1b3b'), + ('\u1b3d', '\u1b41'), ('\u1b43', '\u1b44'), + ('\u1b82', '\u1b82'), ('\u1ba1', '\u1ba1'), + ('\u1ba6', '\u1ba7'), ('\u1baa', '\u1baa'), + ('\u1bac', '\u1bad'), ('\u1be7', '\u1be7'), + ('\u1bea', '\u1bec'), ('\u1bee', '\u1bee'), + ('\u1bf2', '\u1bf3'), ('\u1c24', '\u1c2b'), + ('\u1c34', '\u1c35'), ('\u1ce1', '\u1ce1'), + ('\u1cf2', '\u1cf3'), ('\u302e', '\u302f'), + ('\ua823', '\ua824'), ('\ua827', '\ua827'), + ('\ua880', '\ua881'), ('\ua8b4', '\ua8c3'), + ('\ua952', '\ua953'), ('\ua983', '\ua983'), + ('\ua9b4', '\ua9b5'), ('\ua9ba', '\ua9bb'), + ('\ua9bd', '\ua9c0'), ('\uaa2f', '\uaa30'), + ('\uaa33', '\uaa34'), ('\uaa4d', '\uaa4d'), + ('\uaa7b', '\uaa7b'), ('\uaaeb', '\uaaeb'), + ('\uaaee', '\uaaef'), ('\uaaf5', '\uaaf5'), + ('\uabe3', '\uabe4'), ('\uabe6', '\uabe7'), + ('\uabe9', '\uabea'), ('\uabec', '\uabec'), + ('\U00011000', '\U00011000'), ('\U00011002', '\U00011002'), + ('\U00011082', '\U00011082'), ('\U000110b0', '\U000110b2'), + ('\U000110b7', '\U000110b8'), ('\U0001112c', '\U0001112c'), + ('\U00011182', '\U00011182'), ('\U000111b3', '\U000111b5'), + ('\U000111bf', '\U000111c0'), ('\U000116ac', '\U000116ac'), + ('\U000116ae', '\U000116af'), ('\U000116b6', '\U000116b6'), + ('\U00016f51', '\U00016f7e'), ('\U0001d165', '\U0001d166'), + ('\U0001d16d', '\U0001d172') + ]; + + pub fn Mc(c: char) -> bool { + bsearch_range_table(c, Mc_table) + } + + static Me_table : &'static [(char,char)] = &[ + ('\u0488', '\u0489'), ('\u20dd', '\u20e0'), + ('\u20e2', '\u20e4'), ('\ua670', '\ua672') + ]; + + pub fn Me(c: char) -> bool { + bsearch_range_table(c, Me_table) + } + + static Mn_table : &'static [(char,char)] = &[ + ('\u0300', '\u036f'), ('\u0483', '\u0487'), + ('\u0591', '\u05bd'), ('\u05bf', '\u05bf'), + ('\u05c1', '\u05c2'), ('\u05c4', '\u05c5'), + ('\u05c7', '\u05c7'), ('\u0610', '\u061a'), + ('\u064b', '\u065f'), ('\u0670', '\u0670'), + ('\u06d6', '\u06dc'), ('\u06df', '\u06e4'), + ('\u06e7', '\u06e8'), ('\u06ea', '\u06ed'), + ('\u0711', '\u0711'), ('\u0730', '\u074a'), + ('\u07a6', '\u07b0'), ('\u07eb', '\u07f3'), + ('\u0816', '\u0819'), ('\u081b', '\u0823'), + ('\u0825', '\u0827'), ('\u0829', '\u082d'), + ('\u0859', '\u085b'), ('\u08e4', '\u0902'), + ('\u093a', '\u093a'), ('\u093c', '\u093c'), + ('\u0941', '\u0948'), ('\u094d', '\u094d'), + ('\u0951', '\u0957'), ('\u0962', '\u0963'), + ('\u0981', '\u0981'), ('\u09bc', '\u09bc'), + ('\u09c1', '\u09c4'), ('\u09cd', '\u09cd'), + ('\u09e2', '\u09e3'), ('\u0a01', '\u0a02'), + ('\u0a3c', '\u0a3c'), ('\u0a41', '\u0a51'), + ('\u0a70', '\u0a71'), ('\u0a75', '\u0a82'), + ('\u0abc', '\u0abc'), ('\u0ac1', '\u0ac8'), + ('\u0acd', '\u0acd'), ('\u0ae2', '\u0ae3'), + ('\u0b01', '\u0b01'), ('\u0b3c', '\u0b3c'), + ('\u0b3f', '\u0b3f'), ('\u0b41', '\u0b44'), + ('\u0b4d', '\u0b56'), ('\u0b62', '\u0b63'), + ('\u0b82', '\u0b82'), ('\u0bc0', '\u0bc0'), + ('\u0bcd', '\u0bcd'), ('\u0c3e', '\u0c40'), + ('\u0c46', '\u0c56'), ('\u0c62', '\u0c63'), + ('\u0cbc', '\u0cbc'), ('\u0cbf', '\u0cbf'), + ('\u0cc6', '\u0cc6'), ('\u0ccc', '\u0ccd'), + ('\u0ce2', '\u0ce3'), ('\u0d41', '\u0d44'), + ('\u0d4d', '\u0d4d'), ('\u0d62', '\u0d63'), + ('\u0dca', '\u0dca'), ('\u0dd2', '\u0dd6'), + ('\u0e31', '\u0e31'), ('\u0e34', '\u0e3a'), + ('\u0e47', '\u0e4e'), ('\u0eb1', '\u0eb1'), + ('\u0eb4', '\u0ebc'), ('\u0ec8', '\u0ecd'), + ('\u0f18', '\u0f19'), ('\u0f35', '\u0f35'), + ('\u0f37', '\u0f37'), ('\u0f39', '\u0f39'), + ('\u0f71', '\u0f7e'), ('\u0f80', '\u0f84'), + ('\u0f86', '\u0f87'), ('\u0f8d', '\u0fbc'), + ('\u0fc6', '\u0fc6'), ('\u102d', '\u1030'), + ('\u1032', '\u1037'), ('\u1039', '\u103a'), + ('\u103d', '\u103e'), ('\u1058', '\u1059'), + ('\u105e', '\u1060'), ('\u1071', '\u1074'), + ('\u1082', '\u1082'), ('\u1085', '\u1086'), + ('\u108d', '\u108d'), ('\u109d', '\u109d'), + ('\u135d', '\u135f'), ('\u1712', '\u1714'), + ('\u1732', '\u1734'), ('\u1752', '\u1753'), + ('\u1772', '\u1773'), ('\u17b4', '\u17b5'), + ('\u17b7', '\u17bd'), ('\u17c6', '\u17c6'), + ('\u17c9', '\u17d3'), ('\u17dd', '\u17dd'), + ('\u180b', '\u180d'), ('\u18a9', '\u18a9'), + ('\u1920', '\u1922'), ('\u1927', '\u1928'), + ('\u1932', '\u1932'), ('\u1939', '\u193b'), + ('\u1a17', '\u1a18'), ('\u1a56', '\u1a56'), + ('\u1a58', '\u1a60'), ('\u1a62', '\u1a62'), + ('\u1a65', '\u1a6c'), ('\u1a73', '\u1a7f'), + ('\u1b00', '\u1b03'), ('\u1b34', '\u1b34'), + ('\u1b36', '\u1b3a'), ('\u1b3c', '\u1b3c'), + ('\u1b42', '\u1b42'), ('\u1b6b', '\u1b73'), + ('\u1b80', '\u1b81'), ('\u1ba2', '\u1ba5'), + ('\u1ba8', '\u1ba9'), ('\u1bab', '\u1bab'), + ('\u1be6', '\u1be6'), ('\u1be8', '\u1be9'), + ('\u1bed', '\u1bed'), ('\u1bef', '\u1bf1'), + ('\u1c2c', '\u1c33'), ('\u1c36', '\u1c37'), + ('\u1cd0', '\u1cd2'), ('\u1cd4', '\u1ce0'), + ('\u1ce2', '\u1ce8'), ('\u1ced', '\u1ced'), + ('\u1cf4', '\u1cf4'), ('\u1dc0', '\u1dff'), + ('\u20d0', '\u20dc'), ('\u20e1', '\u20e1'), + ('\u20e5', '\u20f0'), ('\u2cef', '\u2cf1'), + ('\u2d7f', '\u2d7f'), ('\u2de0', '\u2dff'), + ('\u302a', '\u302d'), ('\u3099', '\u309a'), + ('\ua66f', '\ua66f'), ('\ua674', '\ua67d'), + ('\ua69f', '\ua69f'), ('\ua6f0', '\ua6f1'), + ('\ua802', '\ua802'), ('\ua806', '\ua806'), + ('\ua80b', '\ua80b'), ('\ua825', '\ua826'), + ('\ua8c4', '\ua8c4'), ('\ua8e0', '\ua8f1'), + ('\ua926', '\ua92d'), ('\ua947', '\ua951'), + ('\ua980', '\ua982'), ('\ua9b3', '\ua9b3'), + ('\ua9b6', '\ua9b9'), ('\ua9bc', '\ua9bc'), + ('\uaa29', '\uaa2e'), ('\uaa31', '\uaa32'), + ('\uaa35', '\uaa36'), ('\uaa43', '\uaa43'), + ('\uaa4c', '\uaa4c'), ('\uaab0', '\uaab0'), + ('\uaab2', '\uaab4'), ('\uaab7', '\uaab8'), + ('\uaabe', '\uaabf'), ('\uaac1', '\uaac1'), + ('\uaaec', '\uaaed'), ('\uaaf6', '\uaaf6'), + ('\uabe5', '\uabe5'), ('\uabe8', '\uabe8'), + ('\uabed', '\uabed'), ('\ufb1e', '\ufb1e'), + ('\ufe00', '\ufe0f'), ('\ufe20', '\ufe26'), + ('\U000101fd', '\U000101fd'), ('\U00010a01', '\U00010a0f'), + ('\U00010a38', '\U00010a3f'), ('\U00011001', '\U00011001'), + ('\U00011038', '\U00011046'), ('\U00011080', '\U00011081'), + ('\U000110b3', '\U000110b6'), ('\U000110b9', '\U000110ba'), + ('\U00011100', '\U00011102'), ('\U00011127', '\U0001112b'), + ('\U0001112d', '\U00011134'), ('\U00011180', '\U00011181'), + ('\U000111b6', '\U000111be'), ('\U000116ab', '\U000116ab'), + ('\U000116ad', '\U000116ad'), ('\U000116b0', '\U000116b5'), + ('\U000116b7', '\U000116b7'), ('\U00016f8f', '\U00016f92'), + ('\U0001d167', '\U0001d169'), ('\U0001d17b', '\U0001d182'), + ('\U0001d185', '\U0001d18b'), ('\U0001d1aa', '\U0001d1ad'), + ('\U0001d242', '\U0001d244'), ('\U000e0100', '\U000e01ef') + ]; + + pub fn Mn(c: char) -> bool { + bsearch_range_table(c, Mn_table) + } + + static Nd_table : &'static [(char,char)] = &[ + ('\x30', '\x39'), ('\u0660', '\u0669'), + ('\u06f0', '\u06f9'), ('\u07c0', '\u07c9'), + ('\u0966', '\u096f'), ('\u09e6', '\u09ef'), + ('\u0a66', '\u0a6f'), ('\u0ae6', '\u0aef'), + ('\u0b66', '\u0b6f'), ('\u0be6', '\u0bef'), + ('\u0c66', '\u0c6f'), ('\u0ce6', '\u0cef'), + ('\u0d66', '\u0d6f'), ('\u0e50', '\u0e59'), + ('\u0ed0', '\u0ed9'), ('\u0f20', '\u0f29'), + ('\u1040', '\u1049'), ('\u1090', '\u1099'), + ('\u17e0', '\u17e9'), ('\u1810', '\u1819'), + ('\u1946', '\u194f'), ('\u19d0', '\u19d9'), + ('\u1a80', '\u1a99'), ('\u1b50', '\u1b59'), + ('\u1bb0', '\u1bb9'), ('\u1c40', '\u1c49'), + ('\u1c50', '\u1c59'), ('\ua620', '\ua629'), + ('\ua8d0', '\ua8d9'), ('\ua900', '\ua909'), + ('\ua9d0', '\ua9d9'), ('\uaa50', '\uaa59'), + ('\uabf0', '\uabf9'), ('\uff10', '\uff19'), + ('\U000104a0', '\U000104a9'), ('\U00011066', '\U0001106f'), + ('\U000110f0', '\U000110f9'), ('\U00011136', '\U0001113f'), + ('\U000111d0', '\U000111d9'), ('\U000116c0', '\U000116c9'), + ('\U0001d7ce', '\U0001d7ff') + ]; + + pub fn Nd(c: char) -> bool { + bsearch_range_table(c, Nd_table) + } + + static Nl_table : &'static [(char,char)] = &[ + ('\u16ee', '\u16f0'), ('\u2160', '\u2182'), + ('\u2185', '\u2188'), ('\u3007', '\u3007'), + ('\u3021', '\u3029'), ('\u3038', '\u303a'), + ('\ua6e6', '\ua6ef'), ('\U00010140', '\U00010174'), + ('\U00010341', '\U00010341'), ('\U0001034a', '\U0001034a'), + ('\U000103d1', '\U000103d5'), ('\U00012400', '\U00012462') + ]; + + pub fn Nl(c: char) -> bool { + bsearch_range_table(c, Nl_table) + } + + static No_table : &'static [(char,char)] = &[ + ('\xb2', '\xb3'), ('\xb9', '\xb9'), + ('\xbc', '\xbe'), ('\u09f4', '\u09f9'), + ('\u0b72', '\u0b77'), ('\u0bf0', '\u0bf2'), + ('\u0c78', '\u0c7e'), ('\u0d70', '\u0d75'), + ('\u0f2a', '\u0f33'), ('\u1369', '\u137c'), + ('\u17f0', '\u17f9'), ('\u19da', '\u19da'), + ('\u2070', '\u2070'), ('\u2074', '\u2079'), + ('\u2080', '\u2089'), ('\u2150', '\u215f'), + ('\u2189', '\u2189'), ('\u2460', '\u249b'), + ('\u24ea', '\u24ff'), ('\u2776', '\u2793'), + ('\u2cfd', '\u2cfd'), ('\u3192', '\u3195'), + ('\u3220', '\u3229'), ('\u3248', '\u324f'), + ('\u3251', '\u325f'), ('\u3280', '\u3289'), + ('\u32b1', '\u32bf'), ('\ua830', '\ua835'), + ('\U00010107', '\U00010133'), ('\U00010175', '\U00010178'), + ('\U0001018a', '\U0001018a'), ('\U00010320', '\U00010323'), + ('\U00010858', '\U0001085f'), ('\U00010916', '\U0001091b'), + ('\U00010a40', '\U00010a47'), ('\U00010a7d', '\U00010a7e'), + ('\U00010b58', '\U00010b5f'), ('\U00010b78', '\U00010b7f'), + ('\U00010e60', '\U00010e7e'), ('\U00011052', '\U00011065'), + ('\U0001d360', '\U0001d371'), ('\U0001f100', '\U0001f10a') + ]; + + pub fn No(c: char) -> bool { + bsearch_range_table(c, No_table) + } -/* -Function: is_upper + static Pc_table : &'static [(char,char)] = &[ + ('\x5f', '\x5f'), ('\u203f', '\u2040'), + ('\u2054', '\u2054'), ('\ufe33', '\ufe34'), + ('\ufe4d', '\ufe4f'), ('\uff3f', '\uff3f') + ]; + + pub fn Pc(c: char) -> bool { + bsearch_range_table(c, Pc_table) + } + + static Pd_table : &'static [(char,char)] = &[ + ('\x2d', '\x2d'), ('\u058a', '\u058a'), + ('\u05be', '\u05be'), ('\u1400', '\u1400'), + ('\u1806', '\u1806'), ('\u2010', '\u2015'), + ('\u2e17', '\u2e17'), ('\u2e1a', '\u2e1a'), + ('\u2e3a', '\u2e3b'), ('\u301c', '\u301c'), + ('\u3030', '\u3030'), ('\u30a0', '\u30a0'), + ('\ufe31', '\ufe32'), ('\ufe58', '\ufe58'), + ('\ufe63', '\ufe63'), ('\uff0d', '\uff0d') + ]; + + pub fn Pd(c: char) -> bool { + bsearch_range_table(c, Pd_table) + } + + static Pe_table : &'static [(char,char)] = &[ + ('\x29', '\x29'), ('\x5d', '\x5d'), + ('\x7d', '\x7d'), ('\u0f3b', '\u0f3b'), + ('\u0f3d', '\u0f3d'), ('\u169c', '\u169c'), + ('\u2046', '\u2046'), ('\u207e', '\u207e'), + ('\u208e', '\u208e'), ('\u232a', '\u232a'), + ('\u2769', '\u2769'), ('\u276b', '\u276b'), + ('\u276d', '\u276d'), ('\u276f', '\u276f'), + ('\u2771', '\u2771'), ('\u2773', '\u2773'), + ('\u2775', '\u2775'), ('\u27c6', '\u27c6'), + ('\u27e7', '\u27e7'), ('\u27e9', '\u27e9'), + ('\u27eb', '\u27eb'), ('\u27ed', '\u27ed'), + ('\u27ef', '\u27ef'), ('\u2984', '\u2984'), + ('\u2986', '\u2986'), ('\u2988', '\u2988'), + ('\u298a', '\u298a'), ('\u298c', '\u298c'), + ('\u298e', '\u298e'), ('\u2990', '\u2990'), + ('\u2992', '\u2992'), ('\u2994', '\u2994'), + ('\u2996', '\u2996'), ('\u2998', '\u2998'), + ('\u29d9', '\u29d9'), ('\u29db', '\u29db'), + ('\u29fd', '\u29fd'), ('\u2e23', '\u2e23'), + ('\u2e25', '\u2e25'), ('\u2e27', '\u2e27'), + ('\u2e29', '\u2e29'), ('\u3009', '\u3009'), + ('\u300b', '\u300b'), ('\u300d', '\u300d'), + ('\u300f', '\u300f'), ('\u3011', '\u3011'), + ('\u3015', '\u3015'), ('\u3017', '\u3017'), + ('\u3019', '\u3019'), ('\u301b', '\u301b'), + ('\u301e', '\u301f'), ('\ufd3f', '\ufd3f'), + ('\ufe18', '\ufe18'), ('\ufe36', '\ufe36'), + ('\ufe38', '\ufe38'), ('\ufe3a', '\ufe3a'), + ('\ufe3c', '\ufe3c'), ('\ufe3e', '\ufe3e'), + ('\ufe40', '\ufe40'), ('\ufe42', '\ufe42'), + ('\ufe44', '\ufe44'), ('\ufe48', '\ufe48'), + ('\ufe5a', '\ufe5a'), ('\ufe5c', '\ufe5c'), + ('\ufe5e', '\ufe5e'), ('\uff09', '\uff09'), + ('\uff3d', '\uff3d'), ('\uff5d', '\uff5d'), + ('\uff60', '\uff60'), ('\uff63', '\uff63') + ]; + + pub fn Pe(c: char) -> bool { + bsearch_range_table(c, Pe_table) + } + + static Pf_table : &'static [(char,char)] = &[ + ('\xbb', '\xbb'), ('\u2019', '\u2019'), + ('\u201d', '\u201d'), ('\u203a', '\u203a'), + ('\u2e03', '\u2e03'), ('\u2e05', '\u2e05'), + ('\u2e0a', '\u2e0a'), ('\u2e0d', '\u2e0d'), + ('\u2e1d', '\u2e1d'), ('\u2e21', '\u2e21') + ]; + + pub fn Pf(c: char) -> bool { + bsearch_range_table(c, Pf_table) + } + + static Pi_table : &'static [(char,char)] = &[ + ('\xab', '\xab'), ('\u2018', '\u2018'), + ('\u201b', '\u201c'), ('\u201f', '\u201f'), + ('\u2039', '\u2039'), ('\u2e02', '\u2e02'), + ('\u2e04', '\u2e04'), ('\u2e09', '\u2e09'), + ('\u2e0c', '\u2e0c'), ('\u2e1c', '\u2e1c'), + ('\u2e20', '\u2e20') + ]; + + pub fn Pi(c: char) -> bool { + bsearch_range_table(c, Pi_table) + } + + static Po_table : &'static [(char,char)] = &[ + ('\x21', '\x23'), ('\x25', '\x27'), + ('\x2a', '\x2a'), ('\x2c', '\x2c'), + ('\x2e', '\x2f'), ('\x3a', '\x3b'), + ('\x3f', '\x40'), ('\x5c', '\x5c'), + ('\xa1', '\xa1'), ('\xa7', '\xa7'), + ('\xb6', '\xb7'), ('\xbf', '\xbf'), + ('\u037e', '\u037e'), ('\u0387', '\u0387'), + ('\u055a', '\u055f'), ('\u0589', '\u0589'), + ('\u05c0', '\u05c0'), ('\u05c3', '\u05c3'), + ('\u05c6', '\u05c6'), ('\u05f3', '\u05f4'), + ('\u0609', '\u060a'), ('\u060c', '\u060d'), + ('\u061b', '\u061f'), ('\u066a', '\u066d'), + ('\u06d4', '\u06d4'), ('\u0700', '\u070d'), + ('\u07f7', '\u07f9'), ('\u0830', '\u083e'), + ('\u085e', '\u085e'), ('\u0964', '\u0965'), + ('\u0970', '\u0970'), ('\u0af0', '\u0af0'), + ('\u0df4', '\u0df4'), ('\u0e4f', '\u0e4f'), + ('\u0e5a', '\u0e5b'), ('\u0f04', '\u0f12'), + ('\u0f14', '\u0f14'), ('\u0f85', '\u0f85'), + ('\u0fd0', '\u0fd4'), ('\u0fd9', '\u0fda'), + ('\u104a', '\u104f'), ('\u10fb', '\u10fb'), + ('\u1360', '\u1368'), ('\u166d', '\u166e'), + ('\u16eb', '\u16ed'), ('\u1735', '\u1736'), + ('\u17d4', '\u17d6'), ('\u17d8', '\u17da'), + ('\u1800', '\u1805'), ('\u1807', '\u180a'), + ('\u1944', '\u1945'), ('\u1a1e', '\u1a1f'), + ('\u1aa0', '\u1aa6'), ('\u1aa8', '\u1aad'), + ('\u1b5a', '\u1b60'), ('\u1bfc', '\u1bff'), + ('\u1c3b', '\u1c3f'), ('\u1c7e', '\u1cc7'), + ('\u1cd3', '\u1cd3'), ('\u2016', '\u2017'), + ('\u2020', '\u2027'), ('\u2030', '\u2038'), + ('\u203b', '\u203e'), ('\u2041', '\u2043'), + ('\u2047', '\u2051'), ('\u2053', '\u2053'), + ('\u2055', '\u205e'), ('\u2cf9', '\u2cfc'), + ('\u2cfe', '\u2cff'), ('\u2d70', '\u2d70'), + ('\u2e00', '\u2e01'), ('\u2e06', '\u2e08'), + ('\u2e0b', '\u2e0b'), ('\u2e0e', '\u2e16'), + ('\u2e18', '\u2e19'), ('\u2e1b', '\u2e1b'), + ('\u2e1e', '\u2e1f'), ('\u2e2a', '\u2e2e'), + ('\u2e30', '\u2e39'), ('\u3001', '\u3003'), + ('\u303d', '\u303d'), ('\u30fb', '\u30fb'), + ('\ua4fe', '\ua4ff'), ('\ua60d', '\ua60f'), + ('\ua673', '\ua673'), ('\ua67e', '\ua67e'), + ('\ua6f2', '\ua6f7'), ('\ua874', '\ua877'), + ('\ua8ce', '\ua8cf'), ('\ua8f8', '\ua8fa'), + ('\ua92e', '\ua92f'), ('\ua95f', '\ua95f'), + ('\ua9c1', '\ua9cd'), ('\ua9de', '\ua9df'), + ('\uaa5c', '\uaa5f'), ('\uaade', '\uaadf'), + ('\uaaf0', '\uaaf1'), ('\uabeb', '\uabeb'), + ('\ufe10', '\ufe16'), ('\ufe19', '\ufe19'), + ('\ufe30', '\ufe30'), ('\ufe45', '\ufe46'), + ('\ufe49', '\ufe4c'), ('\ufe50', '\ufe57'), + ('\ufe5f', '\ufe61'), ('\ufe68', '\ufe68'), + ('\ufe6a', '\ufe6b'), ('\uff01', '\uff03'), + ('\uff05', '\uff07'), ('\uff0a', '\uff0a'), + ('\uff0c', '\uff0c'), ('\uff0e', '\uff0f'), + ('\uff1a', '\uff1b'), ('\uff1f', '\uff20'), + ('\uff3c', '\uff3c'), ('\uff61', '\uff61'), + ('\uff64', '\uff65'), ('\U00010100', '\U00010102'), + ('\U0001039f', '\U0001039f'), ('\U000103d0', '\U000103d0'), + ('\U00010857', '\U00010857'), ('\U0001091f', '\U0001091f'), + ('\U0001093f', '\U0001093f'), ('\U00010a50', '\U00010a58'), + ('\U00010a7f', '\U00010a7f'), ('\U00010b39', '\U00010b3f'), + ('\U00011047', '\U0001104d'), ('\U000110bb', '\U000110bc'), + ('\U000110be', '\U000110c1'), ('\U00011140', '\U00011143'), + ('\U000111c5', '\U000111c8'), ('\U00012470', '\U00012473') + ]; + + pub fn Po(c: char) -> bool { + bsearch_range_table(c, Po_table) + } + + static Ps_table : &'static [(char,char)] = &[ + ('\x28', '\x28'), ('\x5b', '\x5b'), + ('\x7b', '\x7b'), ('\u0f3a', '\u0f3a'), + ('\u0f3c', '\u0f3c'), ('\u169b', '\u169b'), + ('\u201a', '\u201a'), ('\u201e', '\u201e'), + ('\u2045', '\u2045'), ('\u207d', '\u207d'), + ('\u208d', '\u208d'), ('\u2329', '\u2329'), + ('\u2768', '\u2768'), ('\u276a', '\u276a'), + ('\u276c', '\u276c'), ('\u276e', '\u276e'), + ('\u2770', '\u2770'), ('\u2772', '\u2772'), + ('\u2774', '\u2774'), ('\u27c5', '\u27c5'), + ('\u27e6', '\u27e6'), ('\u27e8', '\u27e8'), + ('\u27ea', '\u27ea'), ('\u27ec', '\u27ec'), + ('\u27ee', '\u27ee'), ('\u2983', '\u2983'), + ('\u2985', '\u2985'), ('\u2987', '\u2987'), + ('\u2989', '\u2989'), ('\u298b', '\u298b'), + ('\u298d', '\u298d'), ('\u298f', '\u298f'), + ('\u2991', '\u2991'), ('\u2993', '\u2993'), + ('\u2995', '\u2995'), ('\u2997', '\u2997'), + ('\u29d8', '\u29d8'), ('\u29da', '\u29da'), + ('\u29fc', '\u29fc'), ('\u2e22', '\u2e22'), + ('\u2e24', '\u2e24'), ('\u2e26', '\u2e26'), + ('\u2e28', '\u2e28'), ('\u3008', '\u3008'), + ('\u300a', '\u300a'), ('\u300c', '\u300c'), + ('\u300e', '\u300e'), ('\u3010', '\u3010'), + ('\u3014', '\u3014'), ('\u3016', '\u3016'), + ('\u3018', '\u3018'), ('\u301a', '\u301a'), + ('\u301d', '\u301d'), ('\ufd3e', '\ufd3e'), + ('\ufe17', '\ufe17'), ('\ufe35', '\ufe35'), + ('\ufe37', '\ufe37'), ('\ufe39', '\ufe39'), + ('\ufe3b', '\ufe3b'), ('\ufe3d', '\ufe3d'), + ('\ufe3f', '\ufe3f'), ('\ufe41', '\ufe41'), + ('\ufe43', '\ufe43'), ('\ufe47', '\ufe47'), + ('\ufe59', '\ufe59'), ('\ufe5b', '\ufe5b'), + ('\ufe5d', '\ufe5d'), ('\uff08', '\uff08'), + ('\uff3b', '\uff3b'), ('\uff5b', '\uff5b'), + ('\uff5f', '\uff5f'), ('\uff62', '\uff62') + ]; + + pub fn Ps(c: char) -> bool { + bsearch_range_table(c, Ps_table) + } + + static Sc_table : &'static [(char,char)] = &[ + ('\x24', '\x24'), ('\xa2', '\xa5'), + ('\u058f', '\u058f'), ('\u060b', '\u060b'), + ('\u09f2', '\u09f3'), ('\u09fb', '\u09fb'), + ('\u0af1', '\u0af1'), ('\u0bf9', '\u0bf9'), + ('\u0e3f', '\u0e3f'), ('\u17db', '\u17db'), + ('\u20a0', '\u20ba'), ('\ua838', '\ua838'), + ('\ufdfc', '\ufdfc'), ('\ufe69', '\ufe69'), + ('\uff04', '\uff04'), ('\uffe0', '\uffe1'), + ('\uffe5', '\uffe6') + ]; + + pub fn Sc(c: char) -> bool { + bsearch_range_table(c, Sc_table) + } + + static Sk_table : &'static [(char,char)] = &[ + ('\x5e', '\x5e'), ('\x60', '\x60'), + ('\xa8', '\xa8'), ('\xaf', '\xaf'), + ('\xb4', '\xb4'), ('\xb8', '\xb8'), + ('\u02c2', '\u02c5'), ('\u02d2', '\u02df'), + ('\u02e5', '\u02eb'), ('\u02ed', '\u02ed'), + ('\u02ef', '\u02ff'), ('\u0375', '\u0375'), + ('\u0384', '\u0385'), ('\u1fbd', '\u1fbd'), + ('\u1fbf', '\u1fc1'), ('\u1fcd', '\u1fcf'), + ('\u1fdd', '\u1fdf'), ('\u1fed', '\u1fef'), + ('\u1ffd', '\u1ffe'), ('\u309b', '\u309c'), + ('\ua700', '\ua716'), ('\ua720', '\ua721'), + ('\ua789', '\ua78a'), ('\ufbb2', '\ufbc1'), + ('\uff3e', '\uff3e'), ('\uff40', '\uff40'), + ('\uffe3', '\uffe3') + ]; + + pub fn Sk(c: char) -> bool { + bsearch_range_table(c, Sk_table) + } + + static Sm_table : &'static [(char,char)] = &[ + ('\x2b', '\x2b'), ('\x3c', '\x3e'), + ('\x7c', '\x7c'), ('\x7e', '\x7e'), + ('\xac', '\xac'), ('\xb1', '\xb1'), + ('\xd7', '\xd7'), ('\xf7', '\xf7'), + ('\u03f6', '\u03f6'), ('\u0606', '\u0608'), + ('\u2044', '\u2044'), ('\u2052', '\u2052'), + ('\u207a', '\u207c'), ('\u208a', '\u208c'), + ('\u2118', '\u2118'), ('\u2140', '\u2144'), + ('\u214b', '\u214b'), ('\u2190', '\u2194'), + ('\u219a', '\u219b'), ('\u21a0', '\u21a0'), + ('\u21a3', '\u21a3'), ('\u21a6', '\u21a6'), + ('\u21ae', '\u21ae'), ('\u21ce', '\u21cf'), + ('\u21d2', '\u21d2'), ('\u21d4', '\u21d4'), + ('\u21f4', '\u22ff'), ('\u2308', '\u230b'), + ('\u2320', '\u2321'), ('\u237c', '\u237c'), + ('\u239b', '\u23b3'), ('\u23dc', '\u23e1'), + ('\u25b7', '\u25b7'), ('\u25c1', '\u25c1'), + ('\u25f8', '\u25ff'), ('\u266f', '\u266f'), + ('\u27c0', '\u27c4'), ('\u27c7', '\u27e5'), + ('\u27f0', '\u27ff'), ('\u2900', '\u2982'), + ('\u2999', '\u29d7'), ('\u29dc', '\u29fb'), + ('\u29fe', '\u2aff'), ('\u2b30', '\u2b44'), + ('\u2b47', '\u2b4c'), ('\ufb29', '\ufb29'), + ('\ufe62', '\ufe62'), ('\ufe64', '\ufe66'), + ('\uff0b', '\uff0b'), ('\uff1c', '\uff1e'), + ('\uff5c', '\uff5c'), ('\uff5e', '\uff5e'), + ('\uffe2', '\uffe2'), ('\uffe9', '\uffec'), + ('\U0001d6c1', '\U0001d6c1'), ('\U0001d6db', '\U0001d6db'), + ('\U0001d6fb', '\U0001d6fb'), ('\U0001d715', '\U0001d715'), + ('\U0001d735', '\U0001d735'), ('\U0001d74f', '\U0001d74f'), + ('\U0001d76f', '\U0001d76f'), ('\U0001d789', '\U0001d789'), + ('\U0001d7a9', '\U0001d7a9'), ('\U0001d7c3', '\U0001d7c3'), + ('\U0001eef0', '\U0001eef1') + ]; + + pub fn Sm(c: char) -> bool { + bsearch_range_table(c, Sm_table) + } + + static So_table : &'static [(char,char)] = &[ + ('\xa6', '\xa6'), ('\xa9', '\xa9'), + ('\xae', '\xae'), ('\xb0', '\xb0'), + ('\u0482', '\u0482'), ('\u060e', '\u060f'), + ('\u06de', '\u06de'), ('\u06e9', '\u06e9'), + ('\u06fd', '\u06fe'), ('\u07f6', '\u07f6'), + ('\u09fa', '\u09fa'), ('\u0b70', '\u0b70'), + ('\u0bf3', '\u0bf8'), ('\u0bfa', '\u0bfa'), + ('\u0c7f', '\u0c7f'), ('\u0d79', '\u0d79'), + ('\u0f01', '\u0f03'), ('\u0f13', '\u0f13'), + ('\u0f15', '\u0f17'), ('\u0f1a', '\u0f1f'), + ('\u0f34', '\u0f34'), ('\u0f36', '\u0f36'), + ('\u0f38', '\u0f38'), ('\u0fbe', '\u0fc5'), + ('\u0fc7', '\u0fcf'), ('\u0fd5', '\u0fd8'), + ('\u109e', '\u109f'), ('\u1390', '\u1399'), + ('\u1940', '\u1940'), ('\u19de', '\u19ff'), + ('\u1b61', '\u1b6a'), ('\u1b74', '\u1b7c'), + ('\u2100', '\u2101'), ('\u2103', '\u2106'), + ('\u2108', '\u2109'), ('\u2114', '\u2114'), + ('\u2116', '\u2117'), ('\u211e', '\u2123'), + ('\u2125', '\u2125'), ('\u2127', '\u2127'), + ('\u2129', '\u2129'), ('\u212e', '\u212e'), + ('\u213a', '\u213b'), ('\u214a', '\u214a'), + ('\u214c', '\u214d'), ('\u214f', '\u214f'), + ('\u2195', '\u2199'), ('\u219c', '\u219f'), + ('\u21a1', '\u21a2'), ('\u21a4', '\u21a5'), + ('\u21a7', '\u21ad'), ('\u21af', '\u21cd'), + ('\u21d0', '\u21d1'), ('\u21d3', '\u21d3'), + ('\u21d5', '\u21f3'), ('\u2300', '\u2307'), + ('\u230c', '\u231f'), ('\u2322', '\u2328'), + ('\u232b', '\u237b'), ('\u237d', '\u239a'), + ('\u23b4', '\u23db'), ('\u23e2', '\u244a'), + ('\u249c', '\u24e9'), ('\u2500', '\u25b6'), + ('\u25b8', '\u25c0'), ('\u25c2', '\u25f7'), + ('\u2600', '\u266e'), ('\u2670', '\u2767'), + ('\u2794', '\u27bf'), ('\u2800', '\u28ff'), + ('\u2b00', '\u2b2f'), ('\u2b45', '\u2b46'), + ('\u2b50', '\u2b59'), ('\u2ce5', '\u2cea'), + ('\u2e80', '\u2ffb'), ('\u3004', '\u3004'), + ('\u3012', '\u3013'), ('\u3020', '\u3020'), + ('\u3036', '\u3037'), ('\u303e', '\u303f'), + ('\u3190', '\u3191'), ('\u3196', '\u319f'), + ('\u31c0', '\u31e3'), ('\u3200', '\u321e'), + ('\u322a', '\u3247'), ('\u3250', '\u3250'), + ('\u3260', '\u327f'), ('\u328a', '\u32b0'), + ('\u32c0', '\u33ff'), ('\u4dc0', '\u4dff'), + ('\ua490', '\ua4c6'), ('\ua828', '\ua82b'), + ('\ua836', '\ua837'), ('\ua839', '\ua839'), + ('\uaa77', '\uaa79'), ('\ufdfd', '\ufdfd'), + ('\uffe4', '\uffe4'), ('\uffe8', '\uffe8'), + ('\uffed', '\uffee'), ('\ufffc', '\ufffd'), + ('\U00010137', '\U0001013f'), ('\U00010179', '\U00010189'), + ('\U00010190', '\U000101fc'), ('\U0001d000', '\U0001d164'), + ('\U0001d16a', '\U0001d16c'), ('\U0001d183', '\U0001d184'), + ('\U0001d18c', '\U0001d1a9'), ('\U0001d1ae', '\U0001d241'), + ('\U0001d245', '\U0001d356'), ('\U0001f000', '\U0001f0df'), + ('\U0001f110', '\U0001f773') + ]; + + pub fn So(c: char) -> bool { + bsearch_range_table(c, So_table) + } + + static Zl_table : &'static [(char,char)] = &[ + ('\u2028', '\u2028') + ]; + + pub fn Zl(c: char) -> bool { + bsearch_range_table(c, Zl_table) + } + + static Zp_table : &'static [(char,char)] = &[ + ('\u2029', '\u2029') + ]; + + pub fn Zp(c: char) -> bool { + bsearch_range_table(c, Zp_table) + } + + static Zs_table : &'static [(char,char)] = &[ + ('\x20', '\x20'), ('\xa0', '\xa0'), + ('\u1680', '\u1680'), ('\u180e', '\u180e'), + ('\u2000', '\u200a'), ('\u202f', '\u202f'), + ('\u205f', '\u205f'), ('\u3000', '\u3000') + ]; + + pub fn Zs(c: char) -> bool { + bsearch_range_table(c, Zs_table) + } -Returns true if a character is an uppercase letter. -*/ -pub fn is_upper(c: char) -> bool { - return icu::libicu::u_isupper(c) == icu::TRUE; } -#[cfg(test)] -mod tests { +pub mod derived_property { - #[test] - fn test_is_digit() { - assert!((unicode::icu::is_digit('0'))); - assert!((!unicode::icu::is_digit('m'))); + + fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { + use cmp::{Equal, Less, Greater}; + use vec::bsearch; + use option::None; + (do bsearch(r) |&(lo,hi)| { + if lo <= c && c <= hi { Equal } + else if hi < c { Less } + else { Greater } + }) != None } - #[test] - fn test_is_lower() { - assert!((unicode::icu::is_lower('m'))); - assert!((!unicode::icu::is_lower('M'))); + + static Alphabetic_table : &'static [(char,char)] = &[ + ('\x41', '\x5a'), ('\x61', '\x7a'), + ('\xaa', '\xaa'), ('\xb5', '\xb5'), + ('\xba', '\xba'), ('\xc0', '\xd6'), + ('\xd8', '\xf6'), ('\xf8', '\u01ba'), + ('\u01bb', '\u01bb'), ('\u01bc', '\u01bf'), + ('\u01c0', '\u01c3'), ('\u01c4', '\u0293'), + ('\u0294', '\u0294'), ('\u0295', '\u02af'), + ('\u02b0', '\u02c1'), ('\u02c6', '\u02d1'), + ('\u02e0', '\u02e4'), ('\u02ec', '\u02ec'), + ('\u02ee', '\u02ee'), ('\u0345', '\u0345'), + ('\u0370', '\u0373'), ('\u0374', '\u0374'), + ('\u0376', '\u0377'), ('\u037a', '\u037a'), + ('\u037b', '\u037d'), ('\u0386', '\u0386'), + ('\u0388', '\u038a'), ('\u038c', '\u038c'), + ('\u038e', '\u03a1'), ('\u03a3', '\u03f5'), + ('\u03f7', '\u0481'), ('\u048a', '\u0527'), + ('\u0531', '\u0556'), ('\u0559', '\u0559'), + ('\u0561', '\u0587'), ('\u05b0', '\u05bd'), + ('\u05bf', '\u05bf'), ('\u05c1', '\u05c2'), + ('\u05c4', '\u05c5'), ('\u05c7', '\u05c7'), + ('\u05d0', '\u05ea'), ('\u05f0', '\u05f2'), + ('\u0610', '\u061a'), ('\u0620', '\u063f'), + ('\u0640', '\u0640'), ('\u0641', '\u064a'), + ('\u064b', '\u0657'), ('\u0659', '\u065f'), + ('\u066e', '\u066f'), ('\u0670', '\u0670'), + ('\u0671', '\u06d3'), ('\u06d5', '\u06d5'), + ('\u06d6', '\u06dc'), ('\u06e1', '\u06e4'), + ('\u06e5', '\u06e6'), ('\u06e7', '\u06e8'), + ('\u06ed', '\u06ed'), ('\u06ee', '\u06ef'), + ('\u06fa', '\u06fc'), ('\u06ff', '\u06ff'), + ('\u0710', '\u0710'), ('\u0711', '\u0711'), + ('\u0712', '\u072f'), ('\u0730', '\u073f'), + ('\u074d', '\u07a5'), ('\u07a6', '\u07b0'), + ('\u07b1', '\u07b1'), ('\u07ca', '\u07ea'), + ('\u07f4', '\u07f5'), ('\u07fa', '\u07fa'), + ('\u0800', '\u0815'), ('\u0816', '\u0817'), + ('\u081a', '\u081a'), ('\u081b', '\u0823'), + ('\u0824', '\u0824'), ('\u0825', '\u0827'), + ('\u0828', '\u0828'), ('\u0829', '\u082c'), + ('\u0840', '\u0858'), ('\u08a0', '\u08a0'), + ('\u08a2', '\u08ac'), ('\u08e4', '\u08e9'), + ('\u08f0', '\u08fe'), ('\u0900', '\u0902'), + ('\u0903', '\u0903'), ('\u0904', '\u0939'), + ('\u093a', '\u093a'), ('\u093b', '\u093b'), + ('\u093d', '\u093d'), ('\u093e', '\u0940'), + ('\u0941', '\u0948'), ('\u0949', '\u094c'), + ('\u094e', '\u094f'), ('\u0950', '\u0950'), + ('\u0955', '\u0957'), ('\u0958', '\u0961'), + ('\u0962', '\u0963'), ('\u0971', '\u0971'), + ('\u0972', '\u0977'), ('\u0979', '\u097f'), + ('\u0981', '\u0981'), ('\u0982', '\u0983'), + ('\u0985', '\u098c'), ('\u098f', '\u0990'), + ('\u0993', '\u09a8'), ('\u09aa', '\u09b0'), + ('\u09b2', '\u09b2'), ('\u09b6', '\u09b9'), + ('\u09bd', '\u09bd'), ('\u09be', '\u09c0'), + ('\u09c1', '\u09c4'), ('\u09c7', '\u09c8'), + ('\u09cb', '\u09cc'), ('\u09ce', '\u09ce'), + ('\u09d7', '\u09d7'), ('\u09dc', '\u09dd'), + ('\u09df', '\u09e1'), ('\u09e2', '\u09e3'), + ('\u09f0', '\u09f1'), ('\u0a01', '\u0a02'), + ('\u0a03', '\u0a03'), ('\u0a05', '\u0a0a'), + ('\u0a0f', '\u0a10'), ('\u0a13', '\u0a28'), + ('\u0a2a', '\u0a30'), ('\u0a32', '\u0a33'), + ('\u0a35', '\u0a36'), ('\u0a38', '\u0a39'), + ('\u0a3e', '\u0a40'), ('\u0a41', '\u0a42'), + ('\u0a47', '\u0a48'), ('\u0a4b', '\u0a4c'), + ('\u0a51', '\u0a51'), ('\u0a59', '\u0a5c'), + ('\u0a5e', '\u0a5e'), ('\u0a70', '\u0a71'), + ('\u0a72', '\u0a74'), ('\u0a75', '\u0a75'), + ('\u0a81', '\u0a82'), ('\u0a83', '\u0a83'), + ('\u0a85', '\u0a8d'), ('\u0a8f', '\u0a91'), + ('\u0a93', '\u0aa8'), ('\u0aaa', '\u0ab0'), + ('\u0ab2', '\u0ab3'), ('\u0ab5', '\u0ab9'), + ('\u0abd', '\u0abd'), ('\u0abe', '\u0ac0'), + ('\u0ac1', '\u0ac5'), ('\u0ac7', '\u0ac8'), + ('\u0ac9', '\u0ac9'), ('\u0acb', '\u0acc'), + ('\u0ad0', '\u0ad0'), ('\u0ae0', '\u0ae1'), + ('\u0ae2', '\u0ae3'), ('\u0b01', '\u0b01'), + ('\u0b02', '\u0b03'), ('\u0b05', '\u0b0c'), + ('\u0b0f', '\u0b10'), ('\u0b13', '\u0b28'), + ('\u0b2a', '\u0b30'), ('\u0b32', '\u0b33'), + ('\u0b35', '\u0b39'), ('\u0b3d', '\u0b3d'), + ('\u0b3e', '\u0b3e'), ('\u0b3f', '\u0b3f'), + ('\u0b40', '\u0b40'), ('\u0b41', '\u0b44'), + ('\u0b47', '\u0b48'), ('\u0b4b', '\u0b4c'), + ('\u0b56', '\u0b56'), ('\u0b57', '\u0b57'), + ('\u0b5c', '\u0b5d'), ('\u0b5f', '\u0b61'), + ('\u0b62', '\u0b63'), ('\u0b71', '\u0b71'), + ('\u0b82', '\u0b82'), ('\u0b83', '\u0b83'), + ('\u0b85', '\u0b8a'), ('\u0b8e', '\u0b90'), + ('\u0b92', '\u0b95'), ('\u0b99', '\u0b9a'), + ('\u0b9c', '\u0b9c'), ('\u0b9e', '\u0b9f'), + ('\u0ba3', '\u0ba4'), ('\u0ba8', '\u0baa'), + ('\u0bae', '\u0bb9'), ('\u0bbe', '\u0bbf'), + ('\u0bc0', '\u0bc0'), ('\u0bc1', '\u0bc2'), + ('\u0bc6', '\u0bc8'), ('\u0bca', '\u0bcc'), + ('\u0bd0', '\u0bd0'), ('\u0bd7', '\u0bd7'), + ('\u0c01', '\u0c03'), ('\u0c05', '\u0c0c'), + ('\u0c0e', '\u0c10'), ('\u0c12', '\u0c28'), + ('\u0c2a', '\u0c33'), ('\u0c35', '\u0c39'), + ('\u0c3d', '\u0c3d'), ('\u0c3e', '\u0c40'), + ('\u0c41', '\u0c44'), ('\u0c46', '\u0c48'), + ('\u0c4a', '\u0c4c'), ('\u0c55', '\u0c56'), + ('\u0c58', '\u0c59'), ('\u0c60', '\u0c61'), + ('\u0c62', '\u0c63'), ('\u0c82', '\u0c83'), + ('\u0c85', '\u0c8c'), ('\u0c8e', '\u0c90'), + ('\u0c92', '\u0ca8'), ('\u0caa', '\u0cb3'), + ('\u0cb5', '\u0cb9'), ('\u0cbd', '\u0cbd'), + ('\u0cbe', '\u0cbe'), ('\u0cbf', '\u0cbf'), + ('\u0cc0', '\u0cc4'), ('\u0cc6', '\u0cc6'), + ('\u0cc7', '\u0cc8'), ('\u0cca', '\u0ccb'), + ('\u0ccc', '\u0ccc'), ('\u0cd5', '\u0cd6'), + ('\u0cde', '\u0cde'), ('\u0ce0', '\u0ce1'), + ('\u0ce2', '\u0ce3'), ('\u0cf1', '\u0cf2'), + ('\u0d02', '\u0d03'), ('\u0d05', '\u0d0c'), + ('\u0d0e', '\u0d10'), ('\u0d12', '\u0d3a'), + ('\u0d3d', '\u0d3d'), ('\u0d3e', '\u0d40'), + ('\u0d41', '\u0d44'), ('\u0d46', '\u0d48'), + ('\u0d4a', '\u0d4c'), ('\u0d4e', '\u0d4e'), + ('\u0d57', '\u0d57'), ('\u0d60', '\u0d61'), + ('\u0d62', '\u0d63'), ('\u0d7a', '\u0d7f'), + ('\u0d82', '\u0d83'), ('\u0d85', '\u0d96'), + ('\u0d9a', '\u0db1'), ('\u0db3', '\u0dbb'), + ('\u0dbd', '\u0dbd'), ('\u0dc0', '\u0dc6'), + ('\u0dcf', '\u0dd1'), ('\u0dd2', '\u0dd4'), + ('\u0dd6', '\u0dd6'), ('\u0dd8', '\u0ddf'), + ('\u0df2', '\u0df3'), ('\u0e01', '\u0e30'), + ('\u0e31', '\u0e31'), ('\u0e32', '\u0e33'), + ('\u0e34', '\u0e3a'), ('\u0e40', '\u0e45'), + ('\u0e46', '\u0e46'), ('\u0e4d', '\u0e4d'), + ('\u0e81', '\u0e82'), ('\u0e84', '\u0e84'), + ('\u0e87', '\u0e88'), ('\u0e8a', '\u0e8a'), + ('\u0e8d', '\u0e8d'), ('\u0e94', '\u0e97'), + ('\u0e99', '\u0e9f'), ('\u0ea1', '\u0ea3'), + ('\u0ea5', '\u0ea5'), ('\u0ea7', '\u0ea7'), + ('\u0eaa', '\u0eab'), ('\u0ead', '\u0eb0'), + ('\u0eb1', '\u0eb1'), ('\u0eb2', '\u0eb3'), + ('\u0eb4', '\u0eb9'), ('\u0ebb', '\u0ebc'), + ('\u0ebd', '\u0ebd'), ('\u0ec0', '\u0ec4'), + ('\u0ec6', '\u0ec6'), ('\u0ecd', '\u0ecd'), + ('\u0edc', '\u0edf'), ('\u0f00', '\u0f00'), + ('\u0f40', '\u0f47'), ('\u0f49', '\u0f6c'), + ('\u0f71', '\u0f7e'), ('\u0f7f', '\u0f7f'), + ('\u0f80', '\u0f81'), ('\u0f88', '\u0f8c'), + ('\u0f8d', '\u0f97'), ('\u0f99', '\u0fbc'), + ('\u1000', '\u102a'), ('\u102b', '\u102c'), + ('\u102d', '\u1030'), ('\u1031', '\u1031'), + ('\u1032', '\u1036'), ('\u1038', '\u1038'), + ('\u103b', '\u103c'), ('\u103d', '\u103e'), + ('\u103f', '\u103f'), ('\u1050', '\u1055'), + ('\u1056', '\u1057'), ('\u1058', '\u1059'), + ('\u105a', '\u105d'), ('\u105e', '\u1060'), + ('\u1061', '\u1061'), ('\u1062', '\u1062'), + ('\u1065', '\u1066'), ('\u1067', '\u1068'), + ('\u106e', '\u1070'), ('\u1071', '\u1074'), + ('\u1075', '\u1081'), ('\u1082', '\u1082'), + ('\u1083', '\u1084'), ('\u1085', '\u1086'), + ('\u108e', '\u108e'), ('\u109c', '\u109c'), + ('\u109d', '\u109d'), ('\u10a0', '\u10c5'), + ('\u10c7', '\u10c7'), ('\u10cd', '\u10cd'), + ('\u10d0', '\u10fa'), ('\u10fc', '\u10fc'), + ('\u10fd', '\u1248'), ('\u124a', '\u124d'), + ('\u1250', '\u1256'), ('\u1258', '\u1258'), + ('\u125a', '\u125d'), ('\u1260', '\u1288'), + ('\u128a', '\u128d'), ('\u1290', '\u12b0'), + ('\u12b2', '\u12b5'), ('\u12b8', '\u12be'), + ('\u12c0', '\u12c0'), ('\u12c2', '\u12c5'), + ('\u12c8', '\u12d6'), ('\u12d8', '\u1310'), + ('\u1312', '\u1315'), ('\u1318', '\u135a'), + ('\u135f', '\u135f'), ('\u1380', '\u138f'), + ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), + ('\u166f', '\u167f'), ('\u1681', '\u169a'), + ('\u16a0', '\u16ea'), ('\u16ee', '\u16f0'), + ('\u1700', '\u170c'), ('\u170e', '\u1711'), + ('\u1712', '\u1713'), ('\u1720', '\u1731'), + ('\u1732', '\u1733'), ('\u1740', '\u1751'), + ('\u1752', '\u1753'), ('\u1760', '\u176c'), + ('\u176e', '\u1770'), ('\u1772', '\u1773'), + ('\u1780', '\u17b3'), ('\u17b6', '\u17b6'), + ('\u17b7', '\u17bd'), ('\u17be', '\u17c5'), + ('\u17c6', '\u17c6'), ('\u17c7', '\u17c8'), + ('\u17d7', '\u17d7'), ('\u17dc', '\u17dc'), + ('\u1820', '\u1842'), ('\u1843', '\u1843'), + ('\u1844', '\u1877'), ('\u1880', '\u18a8'), + ('\u18a9', '\u18a9'), ('\u18aa', '\u18aa'), + ('\u18b0', '\u18f5'), ('\u1900', '\u191c'), + ('\u1920', '\u1922'), ('\u1923', '\u1926'), + ('\u1927', '\u1928'), ('\u1929', '\u192b'), + ('\u1930', '\u1931'), ('\u1932', '\u1932'), + ('\u1933', '\u1938'), ('\u1950', '\u196d'), + ('\u1970', '\u1974'), ('\u1980', '\u19ab'), + ('\u19b0', '\u19c0'), ('\u19c1', '\u19c7'), + ('\u19c8', '\u19c9'), ('\u1a00', '\u1a16'), + ('\u1a17', '\u1a18'), ('\u1a19', '\u1a1b'), + ('\u1a20', '\u1a54'), ('\u1a55', '\u1a55'), + ('\u1a56', '\u1a56'), ('\u1a57', '\u1a57'), + ('\u1a58', '\u1a5e'), ('\u1a61', '\u1a61'), + ('\u1a62', '\u1a62'), ('\u1a63', '\u1a64'), + ('\u1a65', '\u1a6c'), ('\u1a6d', '\u1a72'), + ('\u1a73', '\u1a74'), ('\u1aa7', '\u1aa7'), + ('\u1b00', '\u1b03'), ('\u1b04', '\u1b04'), + ('\u1b05', '\u1b33'), ('\u1b35', '\u1b35'), + ('\u1b36', '\u1b3a'), ('\u1b3b', '\u1b3b'), + ('\u1b3c', '\u1b3c'), ('\u1b3d', '\u1b41'), + ('\u1b42', '\u1b42'), ('\u1b43', '\u1b43'), + ('\u1b45', '\u1b4b'), ('\u1b80', '\u1b81'), + ('\u1b82', '\u1b82'), ('\u1b83', '\u1ba0'), + ('\u1ba1', '\u1ba1'), ('\u1ba2', '\u1ba5'), + ('\u1ba6', '\u1ba7'), ('\u1ba8', '\u1ba9'), + ('\u1bac', '\u1bad'), ('\u1bae', '\u1baf'), + ('\u1bba', '\u1be5'), ('\u1be7', '\u1be7'), + ('\u1be8', '\u1be9'), ('\u1bea', '\u1bec'), + ('\u1bed', '\u1bed'), ('\u1bee', '\u1bee'), + ('\u1bef', '\u1bf1'), ('\u1c00', '\u1c23'), + ('\u1c24', '\u1c2b'), ('\u1c2c', '\u1c33'), + ('\u1c34', '\u1c35'), ('\u1c4d', '\u1c4f'), + ('\u1c5a', '\u1c77'), ('\u1c78', '\u1c7d'), + ('\u1ce9', '\u1cec'), ('\u1cee', '\u1cf1'), + ('\u1cf2', '\u1cf3'), ('\u1cf5', '\u1cf6'), + ('\u1d00', '\u1d2b'), ('\u1d2c', '\u1d6a'), + ('\u1d6b', '\u1d77'), ('\u1d78', '\u1d78'), + ('\u1d79', '\u1d9a'), ('\u1d9b', '\u1dbf'), + ('\u1e00', '\u1f15'), ('\u1f18', '\u1f1d'), + ('\u1f20', '\u1f45'), ('\u1f48', '\u1f4d'), + ('\u1f50', '\u1f57'), ('\u1f59', '\u1f59'), + ('\u1f5b', '\u1f5b'), ('\u1f5d', '\u1f5d'), + ('\u1f5f', '\u1f7d'), ('\u1f80', '\u1fb4'), + ('\u1fb6', '\u1fbc'), ('\u1fbe', '\u1fbe'), + ('\u1fc2', '\u1fc4'), ('\u1fc6', '\u1fcc'), + ('\u1fd0', '\u1fd3'), ('\u1fd6', '\u1fdb'), + ('\u1fe0', '\u1fec'), ('\u1ff2', '\u1ff4'), + ('\u1ff6', '\u1ffc'), ('\u2071', '\u2071'), + ('\u207f', '\u207f'), ('\u2090', '\u209c'), + ('\u2102', '\u2102'), ('\u2107', '\u2107'), + ('\u210a', '\u2113'), ('\u2115', '\u2115'), + ('\u2119', '\u211d'), ('\u2124', '\u2124'), + ('\u2126', '\u2126'), ('\u2128', '\u2128'), + ('\u212a', '\u212d'), ('\u212f', '\u2134'), + ('\u2135', '\u2138'), ('\u2139', '\u2139'), + ('\u213c', '\u213f'), ('\u2145', '\u2149'), + ('\u214e', '\u214e'), ('\u2160', '\u2182'), + ('\u2183', '\u2184'), ('\u2185', '\u2188'), + ('\u24b6', '\u24e9'), ('\u2c00', '\u2c2e'), + ('\u2c30', '\u2c5e'), ('\u2c60', '\u2c7b'), + ('\u2c7c', '\u2c7d'), ('\u2c7e', '\u2ce4'), + ('\u2ceb', '\u2cee'), ('\u2cf2', '\u2cf3'), + ('\u2d00', '\u2d25'), ('\u2d27', '\u2d27'), + ('\u2d2d', '\u2d2d'), ('\u2d30', '\u2d67'), + ('\u2d6f', '\u2d6f'), ('\u2d80', '\u2d96'), + ('\u2da0', '\u2da6'), ('\u2da8', '\u2dae'), + ('\u2db0', '\u2db6'), ('\u2db8', '\u2dbe'), + ('\u2dc0', '\u2dc6'), ('\u2dc8', '\u2dce'), + ('\u2dd0', '\u2dd6'), ('\u2dd8', '\u2dde'), + ('\u2de0', '\u2dff'), ('\u2e2f', '\u2e2f'), + ('\u3005', '\u3005'), ('\u3006', '\u3006'), + ('\u3007', '\u3007'), ('\u3021', '\u3029'), + ('\u3031', '\u3035'), ('\u3038', '\u303a'), + ('\u303b', '\u303b'), ('\u303c', '\u303c'), + ('\u3041', '\u3096'), ('\u309d', '\u309e'), + ('\u309f', '\u309f'), ('\u30a1', '\u30fa'), + ('\u30fc', '\u30fe'), ('\u30ff', '\u30ff'), + ('\u3105', '\u312d'), ('\u3131', '\u318e'), + ('\u31a0', '\u31ba'), ('\u31f0', '\u31ff'), + ('\u3400', '\u4db5'), ('\u4e00', '\u9fcc'), + ('\ua000', '\ua014'), ('\ua015', '\ua015'), + ('\ua016', '\ua48c'), ('\ua4d0', '\ua4f7'), + ('\ua4f8', '\ua4fd'), ('\ua500', '\ua60b'), + ('\ua60c', '\ua60c'), ('\ua610', '\ua61f'), + ('\ua62a', '\ua62b'), ('\ua640', '\ua66d'), + ('\ua66e', '\ua66e'), ('\ua674', '\ua67b'), + ('\ua67f', '\ua67f'), ('\ua680', '\ua697'), + ('\ua69f', '\ua69f'), ('\ua6a0', '\ua6e5'), + ('\ua6e6', '\ua6ef'), ('\ua717', '\ua71f'), + ('\ua722', '\ua76f'), ('\ua770', '\ua770'), + ('\ua771', '\ua787'), ('\ua788', '\ua788'), + ('\ua78b', '\ua78e'), ('\ua790', '\ua793'), + ('\ua7a0', '\ua7aa'), ('\ua7f8', '\ua7f9'), + ('\ua7fa', '\ua7fa'), ('\ua7fb', '\ua801'), + ('\ua803', '\ua805'), ('\ua807', '\ua80a'), + ('\ua80c', '\ua822'), ('\ua823', '\ua824'), + ('\ua825', '\ua826'), ('\ua827', '\ua827'), + ('\ua840', '\ua873'), ('\ua880', '\ua881'), + ('\ua882', '\ua8b3'), ('\ua8b4', '\ua8c3'), + ('\ua8f2', '\ua8f7'), ('\ua8fb', '\ua8fb'), + ('\ua90a', '\ua925'), ('\ua926', '\ua92a'), + ('\ua930', '\ua946'), ('\ua947', '\ua951'), + ('\ua952', '\ua952'), ('\ua960', '\ua97c'), + ('\ua980', '\ua982'), ('\ua983', '\ua983'), + ('\ua984', '\ua9b2'), ('\ua9b4', '\ua9b5'), + ('\ua9b6', '\ua9b9'), ('\ua9ba', '\ua9bb'), + ('\ua9bc', '\ua9bc'), ('\ua9bd', '\ua9bf'), + ('\ua9cf', '\ua9cf'), ('\uaa00', '\uaa28'), + ('\uaa29', '\uaa2e'), ('\uaa2f', '\uaa30'), + ('\uaa31', '\uaa32'), ('\uaa33', '\uaa34'), + ('\uaa35', '\uaa36'), ('\uaa40', '\uaa42'), + ('\uaa43', '\uaa43'), ('\uaa44', '\uaa4b'), + ('\uaa4c', '\uaa4c'), ('\uaa4d', '\uaa4d'), + ('\uaa60', '\uaa6f'), ('\uaa70', '\uaa70'), + ('\uaa71', '\uaa76'), ('\uaa7a', '\uaa7a'), + ('\uaa80', '\uaaaf'), ('\uaab0', '\uaab0'), + ('\uaab1', '\uaab1'), ('\uaab2', '\uaab4'), + ('\uaab5', '\uaab6'), ('\uaab7', '\uaab8'), + ('\uaab9', '\uaabd'), ('\uaabe', '\uaabe'), + ('\uaac0', '\uaac0'), ('\uaac2', '\uaac2'), + ('\uaadb', '\uaadc'), ('\uaadd', '\uaadd'), + ('\uaae0', '\uaaea'), ('\uaaeb', '\uaaeb'), + ('\uaaec', '\uaaed'), ('\uaaee', '\uaaef'), + ('\uaaf2', '\uaaf2'), ('\uaaf3', '\uaaf4'), + ('\uaaf5', '\uaaf5'), ('\uab01', '\uab06'), + ('\uab09', '\uab0e'), ('\uab11', '\uab16'), + ('\uab20', '\uab26'), ('\uab28', '\uab2e'), + ('\uabc0', '\uabe2'), ('\uabe3', '\uabe4'), + ('\uabe5', '\uabe5'), ('\uabe6', '\uabe7'), + ('\uabe8', '\uabe8'), ('\uabe9', '\uabea'), + ('\uac00', '\ud7a3'), ('\ud7b0', '\ud7c6'), + ('\ud7cb', '\ud7fb'), ('\uf900', '\ufa6d'), + ('\ufa70', '\ufad9'), ('\ufb00', '\ufb06'), + ('\ufb13', '\ufb17'), ('\ufb1d', '\ufb1d'), + ('\ufb1e', '\ufb1e'), ('\ufb1f', '\ufb28'), + ('\ufb2a', '\ufb36'), ('\ufb38', '\ufb3c'), + ('\ufb3e', '\ufb3e'), ('\ufb40', '\ufb41'), + ('\ufb43', '\ufb44'), ('\ufb46', '\ufbb1'), + ('\ufbd3', '\ufd3d'), ('\ufd50', '\ufd8f'), + ('\ufd92', '\ufdc7'), ('\ufdf0', '\ufdfb'), + ('\ufe70', '\ufe74'), ('\ufe76', '\ufefc'), + ('\uff21', '\uff3a'), ('\uff41', '\uff5a'), + ('\uff66', '\uff6f'), ('\uff70', '\uff70'), + ('\uff71', '\uff9d'), ('\uff9e', '\uff9f'), + ('\uffa0', '\uffbe'), ('\uffc2', '\uffc7'), + ('\uffca', '\uffcf'), ('\uffd2', '\uffd7'), + ('\uffda', '\uffdc'), ('\U00010000', '\U0001000b'), + ('\U0001000d', '\U00010026'), ('\U00010028', '\U0001003a'), + ('\U0001003c', '\U0001003d'), ('\U0001003f', '\U0001004d'), + ('\U00010050', '\U0001005d'), ('\U00010080', '\U000100fa'), + ('\U00010140', '\U00010174'), ('\U00010280', '\U0001029c'), + ('\U000102a0', '\U000102d0'), ('\U00010300', '\U0001031e'), + ('\U00010330', '\U00010340'), ('\U00010341', '\U00010341'), + ('\U00010342', '\U00010349'), ('\U0001034a', '\U0001034a'), + ('\U00010380', '\U0001039d'), ('\U000103a0', '\U000103c3'), + ('\U000103c8', '\U000103cf'), ('\U000103d1', '\U000103d5'), + ('\U00010400', '\U0001044f'), ('\U00010450', '\U0001049d'), + ('\U00010800', '\U00010805'), ('\U00010808', '\U00010808'), + ('\U0001080a', '\U00010835'), ('\U00010837', '\U00010838'), + ('\U0001083c', '\U0001083c'), ('\U0001083f', '\U00010855'), + ('\U00010900', '\U00010915'), ('\U00010920', '\U00010939'), + ('\U00010980', '\U000109b7'), ('\U000109be', '\U000109bf'), + ('\U00010a00', '\U00010a00'), ('\U00010a01', '\U00010a03'), + ('\U00010a05', '\U00010a06'), ('\U00010a0c', '\U00010a0f'), + ('\U00010a10', '\U00010a13'), ('\U00010a15', '\U00010a17'), + ('\U00010a19', '\U00010a33'), ('\U00010a60', '\U00010a7c'), + ('\U00010b00', '\U00010b35'), ('\U00010b40', '\U00010b55'), + ('\U00010b60', '\U00010b72'), ('\U00010c00', '\U00010c48'), + ('\U00011000', '\U00011000'), ('\U00011001', '\U00011001'), + ('\U00011002', '\U00011002'), ('\U00011003', '\U00011037'), + ('\U00011038', '\U00011045'), ('\U00011082', '\U00011082'), + ('\U00011083', '\U000110af'), ('\U000110b0', '\U000110b2'), + ('\U000110b3', '\U000110b6'), ('\U000110b7', '\U000110b8'), + ('\U000110d0', '\U000110e8'), ('\U00011100', '\U00011102'), + ('\U00011103', '\U00011126'), ('\U00011127', '\U0001112b'), + ('\U0001112c', '\U0001112c'), ('\U0001112d', '\U00011132'), + ('\U00011180', '\U00011181'), ('\U00011182', '\U00011182'), + ('\U00011183', '\U000111b2'), ('\U000111b3', '\U000111b5'), + ('\U000111b6', '\U000111be'), ('\U000111bf', '\U000111bf'), + ('\U000111c1', '\U000111c4'), ('\U00011680', '\U000116aa'), + ('\U000116ab', '\U000116ab'), ('\U000116ac', '\U000116ac'), + ('\U000116ad', '\U000116ad'), ('\U000116ae', '\U000116af'), + ('\U000116b0', '\U000116b5'), ('\U00012000', '\U0001236e'), + ('\U00012400', '\U00012462'), ('\U00013000', '\U0001342e'), + ('\U00016800', '\U00016a38'), ('\U00016f00', '\U00016f44'), + ('\U00016f50', '\U00016f50'), ('\U00016f51', '\U00016f7e'), + ('\U00016f93', '\U00016f9f'), ('\U0001b000', '\U0001b001'), + ('\U0001d400', '\U0001d454'), ('\U0001d456', '\U0001d49c'), + ('\U0001d49e', '\U0001d49f'), ('\U0001d4a2', '\U0001d4a2'), + ('\U0001d4a5', '\U0001d4a6'), ('\U0001d4a9', '\U0001d4ac'), + ('\U0001d4ae', '\U0001d4b9'), ('\U0001d4bb', '\U0001d4bb'), + ('\U0001d4bd', '\U0001d4c3'), ('\U0001d4c5', '\U0001d505'), + ('\U0001d507', '\U0001d50a'), ('\U0001d50d', '\U0001d514'), + ('\U0001d516', '\U0001d51c'), ('\U0001d51e', '\U0001d539'), + ('\U0001d53b', '\U0001d53e'), ('\U0001d540', '\U0001d544'), + ('\U0001d546', '\U0001d546'), ('\U0001d54a', '\U0001d550'), + ('\U0001d552', '\U0001d6a5'), ('\U0001d6a8', '\U0001d6c0'), + ('\U0001d6c2', '\U0001d6da'), ('\U0001d6dc', '\U0001d6fa'), + ('\U0001d6fc', '\U0001d714'), ('\U0001d716', '\U0001d734'), + ('\U0001d736', '\U0001d74e'), ('\U0001d750', '\U0001d76e'), + ('\U0001d770', '\U0001d788'), ('\U0001d78a', '\U0001d7a8'), + ('\U0001d7aa', '\U0001d7c2'), ('\U0001d7c4', '\U0001d7cb'), + ('\U0001ee00', '\U0001ee03'), ('\U0001ee05', '\U0001ee1f'), + ('\U0001ee21', '\U0001ee22'), ('\U0001ee24', '\U0001ee24'), + ('\U0001ee27', '\U0001ee27'), ('\U0001ee29', '\U0001ee32'), + ('\U0001ee34', '\U0001ee37'), ('\U0001ee39', '\U0001ee39'), + ('\U0001ee3b', '\U0001ee3b'), ('\U0001ee42', '\U0001ee42'), + ('\U0001ee47', '\U0001ee47'), ('\U0001ee49', '\U0001ee49'), + ('\U0001ee4b', '\U0001ee4b'), ('\U0001ee4d', '\U0001ee4f'), + ('\U0001ee51', '\U0001ee52'), ('\U0001ee54', '\U0001ee54'), + ('\U0001ee57', '\U0001ee57'), ('\U0001ee59', '\U0001ee59'), + ('\U0001ee5b', '\U0001ee5b'), ('\U0001ee5d', '\U0001ee5d'), + ('\U0001ee5f', '\U0001ee5f'), ('\U0001ee61', '\U0001ee62'), + ('\U0001ee64', '\U0001ee64'), ('\U0001ee67', '\U0001ee6a'), + ('\U0001ee6c', '\U0001ee72'), ('\U0001ee74', '\U0001ee77'), + ('\U0001ee79', '\U0001ee7c'), ('\U0001ee7e', '\U0001ee7e'), + ('\U0001ee80', '\U0001ee89'), ('\U0001ee8b', '\U0001ee9b'), + ('\U0001eea1', '\U0001eea3'), ('\U0001eea5', '\U0001eea9'), + ('\U0001eeab', '\U0001eebb'), ('\U00020000', '\U0002a6d6'), + ('\U0002a700', '\U0002b734'), ('\U0002b740', '\U0002b81d'), + ('\U0002f800', '\U0002fa1d') + ]; + + pub fn Alphabetic(c: char) -> bool { + bsearch_range_table(c, Alphabetic_table) } - #[test] - fn test_is_space() { - assert!((unicode::icu::is_space(' '))); - assert!((!unicode::icu::is_space('m'))); + static XID_Continue_table : &'static [(char,char)] = &[ + ('\x30', '\x39'), ('\x41', '\x5a'), + ('\x5f', '\x5f'), ('\x61', '\x7a'), + ('\xaa', '\xaa'), ('\xb5', '\xb5'), + ('\xb7', '\xb7'), ('\xba', '\xba'), + ('\xc0', '\xd6'), ('\xd8', '\xf6'), + ('\xf8', '\u01ba'), ('\u01bb', '\u01bb'), + ('\u01bc', '\u01bf'), ('\u01c0', '\u01c3'), + ('\u01c4', '\u0293'), ('\u0294', '\u0294'), + ('\u0295', '\u02af'), ('\u02b0', '\u02c1'), + ('\u02c6', '\u02d1'), ('\u02e0', '\u02e4'), + ('\u02ec', '\u02ec'), ('\u02ee', '\u02ee'), + ('\u0300', '\u036f'), ('\u0370', '\u0373'), + ('\u0374', '\u0374'), ('\u0376', '\u0377'), + ('\u037b', '\u037d'), ('\u0386', '\u0386'), + ('\u0387', '\u0387'), ('\u0388', '\u038a'), + ('\u038c', '\u038c'), ('\u038e', '\u03a1'), + ('\u03a3', '\u03f5'), ('\u03f7', '\u0481'), + ('\u0483', '\u0487'), ('\u048a', '\u0527'), + ('\u0531', '\u0556'), ('\u0559', '\u0559'), + ('\u0561', '\u0587'), ('\u0591', '\u05bd'), + ('\u05bf', '\u05bf'), ('\u05c1', '\u05c2'), + ('\u05c4', '\u05c5'), ('\u05c7', '\u05c7'), + ('\u05d0', '\u05ea'), ('\u05f0', '\u05f2'), + ('\u0610', '\u061a'), ('\u0620', '\u063f'), + ('\u0640', '\u0640'), ('\u0641', '\u064a'), + ('\u064b', '\u065f'), ('\u0660', '\u0669'), + ('\u066e', '\u066f'), ('\u0670', '\u0670'), + ('\u0671', '\u06d3'), ('\u06d5', '\u06d5'), + ('\u06d6', '\u06dc'), ('\u06df', '\u06e4'), + ('\u06e5', '\u06e6'), ('\u06e7', '\u06e8'), + ('\u06ea', '\u06ed'), ('\u06ee', '\u06ef'), + ('\u06f0', '\u06f9'), ('\u06fa', '\u06fc'), + ('\u06ff', '\u06ff'), ('\u0710', '\u0710'), + ('\u0711', '\u0711'), ('\u0712', '\u072f'), + ('\u0730', '\u074a'), ('\u074d', '\u07a5'), + ('\u07a6', '\u07b0'), ('\u07b1', '\u07b1'), + ('\u07c0', '\u07c9'), ('\u07ca', '\u07ea'), + ('\u07eb', '\u07f3'), ('\u07f4', '\u07f5'), + ('\u07fa', '\u07fa'), ('\u0800', '\u0815'), + ('\u0816', '\u0819'), ('\u081a', '\u081a'), + ('\u081b', '\u0823'), ('\u0824', '\u0824'), + ('\u0825', '\u0827'), ('\u0828', '\u0828'), + ('\u0829', '\u082d'), ('\u0840', '\u0858'), + ('\u0859', '\u085b'), ('\u08a0', '\u08a0'), + ('\u08a2', '\u08ac'), ('\u08e4', '\u08fe'), + ('\u0900', '\u0902'), ('\u0903', '\u0903'), + ('\u0904', '\u0939'), ('\u093a', '\u093a'), + ('\u093b', '\u093b'), ('\u093c', '\u093c'), + ('\u093d', '\u093d'), ('\u093e', '\u0940'), + ('\u0941', '\u0948'), ('\u0949', '\u094c'), + ('\u094d', '\u094d'), ('\u094e', '\u094f'), + ('\u0950', '\u0950'), ('\u0951', '\u0957'), + ('\u0958', '\u0961'), ('\u0962', '\u0963'), + ('\u0966', '\u096f'), ('\u0971', '\u0971'), + ('\u0972', '\u0977'), ('\u0979', '\u097f'), + ('\u0981', '\u0981'), ('\u0982', '\u0983'), + ('\u0985', '\u098c'), ('\u098f', '\u0990'), + ('\u0993', '\u09a8'), ('\u09aa', '\u09b0'), + ('\u09b2', '\u09b2'), ('\u09b6', '\u09b9'), + ('\u09bc', '\u09bc'), ('\u09bd', '\u09bd'), + ('\u09be', '\u09c0'), ('\u09c1', '\u09c4'), + ('\u09c7', '\u09c8'), ('\u09cb', '\u09cc'), + ('\u09cd', '\u09cd'), ('\u09ce', '\u09ce'), + ('\u09d7', '\u09d7'), ('\u09dc', '\u09dd'), + ('\u09df', '\u09e1'), ('\u09e2', '\u09e3'), + ('\u09e6', '\u09ef'), ('\u09f0', '\u09f1'), + ('\u0a01', '\u0a02'), ('\u0a03', '\u0a03'), + ('\u0a05', '\u0a0a'), ('\u0a0f', '\u0a10'), + ('\u0a13', '\u0a28'), ('\u0a2a', '\u0a30'), + ('\u0a32', '\u0a33'), ('\u0a35', '\u0a36'), + ('\u0a38', '\u0a39'), ('\u0a3c', '\u0a3c'), + ('\u0a3e', '\u0a40'), ('\u0a41', '\u0a42'), + ('\u0a47', '\u0a48'), ('\u0a4b', '\u0a4d'), + ('\u0a51', '\u0a51'), ('\u0a59', '\u0a5c'), + ('\u0a5e', '\u0a5e'), ('\u0a66', '\u0a6f'), + ('\u0a70', '\u0a71'), ('\u0a72', '\u0a74'), + ('\u0a75', '\u0a75'), ('\u0a81', '\u0a82'), + ('\u0a83', '\u0a83'), ('\u0a85', '\u0a8d'), + ('\u0a8f', '\u0a91'), ('\u0a93', '\u0aa8'), + ('\u0aaa', '\u0ab0'), ('\u0ab2', '\u0ab3'), + ('\u0ab5', '\u0ab9'), ('\u0abc', '\u0abc'), + ('\u0abd', '\u0abd'), ('\u0abe', '\u0ac0'), + ('\u0ac1', '\u0ac5'), ('\u0ac7', '\u0ac8'), + ('\u0ac9', '\u0ac9'), ('\u0acb', '\u0acc'), + ('\u0acd', '\u0acd'), ('\u0ad0', '\u0ad0'), + ('\u0ae0', '\u0ae1'), ('\u0ae2', '\u0ae3'), + ('\u0ae6', '\u0aef'), ('\u0b01', '\u0b01'), + ('\u0b02', '\u0b03'), ('\u0b05', '\u0b0c'), + ('\u0b0f', '\u0b10'), ('\u0b13', '\u0b28'), + ('\u0b2a', '\u0b30'), ('\u0b32', '\u0b33'), + ('\u0b35', '\u0b39'), ('\u0b3c', '\u0b3c'), + ('\u0b3d', '\u0b3d'), ('\u0b3e', '\u0b3e'), + ('\u0b3f', '\u0b3f'), ('\u0b40', '\u0b40'), + ('\u0b41', '\u0b44'), ('\u0b47', '\u0b48'), + ('\u0b4b', '\u0b4c'), ('\u0b4d', '\u0b4d'), + ('\u0b56', '\u0b56'), ('\u0b57', '\u0b57'), + ('\u0b5c', '\u0b5d'), ('\u0b5f', '\u0b61'), + ('\u0b62', '\u0b63'), ('\u0b66', '\u0b6f'), + ('\u0b71', '\u0b71'), ('\u0b82', '\u0b82'), + ('\u0b83', '\u0b83'), ('\u0b85', '\u0b8a'), + ('\u0b8e', '\u0b90'), ('\u0b92', '\u0b95'), + ('\u0b99', '\u0b9a'), ('\u0b9c', '\u0b9c'), + ('\u0b9e', '\u0b9f'), ('\u0ba3', '\u0ba4'), + ('\u0ba8', '\u0baa'), ('\u0bae', '\u0bb9'), + ('\u0bbe', '\u0bbf'), ('\u0bc0', '\u0bc0'), + ('\u0bc1', '\u0bc2'), ('\u0bc6', '\u0bc8'), + ('\u0bca', '\u0bcc'), ('\u0bcd', '\u0bcd'), + ('\u0bd0', '\u0bd0'), ('\u0bd7', '\u0bd7'), + ('\u0be6', '\u0bef'), ('\u0c01', '\u0c03'), + ('\u0c05', '\u0c0c'), ('\u0c0e', '\u0c10'), + ('\u0c12', '\u0c28'), ('\u0c2a', '\u0c33'), + ('\u0c35', '\u0c39'), ('\u0c3d', '\u0c3d'), + ('\u0c3e', '\u0c40'), ('\u0c41', '\u0c44'), + ('\u0c46', '\u0c48'), ('\u0c4a', '\u0c4d'), + ('\u0c55', '\u0c56'), ('\u0c58', '\u0c59'), + ('\u0c60', '\u0c61'), ('\u0c62', '\u0c63'), + ('\u0c66', '\u0c6f'), ('\u0c82', '\u0c83'), + ('\u0c85', '\u0c8c'), ('\u0c8e', '\u0c90'), + ('\u0c92', '\u0ca8'), ('\u0caa', '\u0cb3'), + ('\u0cb5', '\u0cb9'), ('\u0cbc', '\u0cbc'), + ('\u0cbd', '\u0cbd'), ('\u0cbe', '\u0cbe'), + ('\u0cbf', '\u0cbf'), ('\u0cc0', '\u0cc4'), + ('\u0cc6', '\u0cc6'), ('\u0cc7', '\u0cc8'), + ('\u0cca', '\u0ccb'), ('\u0ccc', '\u0ccd'), + ('\u0cd5', '\u0cd6'), ('\u0cde', '\u0cde'), + ('\u0ce0', '\u0ce1'), ('\u0ce2', '\u0ce3'), + ('\u0ce6', '\u0cef'), ('\u0cf1', '\u0cf2'), + ('\u0d02', '\u0d03'), ('\u0d05', '\u0d0c'), + ('\u0d0e', '\u0d10'), ('\u0d12', '\u0d3a'), + ('\u0d3d', '\u0d3d'), ('\u0d3e', '\u0d40'), + ('\u0d41', '\u0d44'), ('\u0d46', '\u0d48'), + ('\u0d4a', '\u0d4c'), ('\u0d4d', '\u0d4d'), + ('\u0d4e', '\u0d4e'), ('\u0d57', '\u0d57'), + ('\u0d60', '\u0d61'), ('\u0d62', '\u0d63'), + ('\u0d66', '\u0d6f'), ('\u0d7a', '\u0d7f'), + ('\u0d82', '\u0d83'), ('\u0d85', '\u0d96'), + ('\u0d9a', '\u0db1'), ('\u0db3', '\u0dbb'), + ('\u0dbd', '\u0dbd'), ('\u0dc0', '\u0dc6'), + ('\u0dca', '\u0dca'), ('\u0dcf', '\u0dd1'), + ('\u0dd2', '\u0dd4'), ('\u0dd6', '\u0dd6'), + ('\u0dd8', '\u0ddf'), ('\u0df2', '\u0df3'), + ('\u0e01', '\u0e30'), ('\u0e31', '\u0e31'), + ('\u0e32', '\u0e33'), ('\u0e34', '\u0e3a'), + ('\u0e40', '\u0e45'), ('\u0e46', '\u0e46'), + ('\u0e47', '\u0e4e'), ('\u0e50', '\u0e59'), + ('\u0e81', '\u0e82'), ('\u0e84', '\u0e84'), + ('\u0e87', '\u0e88'), ('\u0e8a', '\u0e8a'), + ('\u0e8d', '\u0e8d'), ('\u0e94', '\u0e97'), + ('\u0e99', '\u0e9f'), ('\u0ea1', '\u0ea3'), + ('\u0ea5', '\u0ea5'), ('\u0ea7', '\u0ea7'), + ('\u0eaa', '\u0eab'), ('\u0ead', '\u0eb0'), + ('\u0eb1', '\u0eb1'), ('\u0eb2', '\u0eb3'), + ('\u0eb4', '\u0eb9'), ('\u0ebb', '\u0ebc'), + ('\u0ebd', '\u0ebd'), ('\u0ec0', '\u0ec4'), + ('\u0ec6', '\u0ec6'), ('\u0ec8', '\u0ecd'), + ('\u0ed0', '\u0ed9'), ('\u0edc', '\u0edf'), + ('\u0f00', '\u0f00'), ('\u0f18', '\u0f19'), + ('\u0f20', '\u0f29'), ('\u0f35', '\u0f35'), + ('\u0f37', '\u0f37'), ('\u0f39', '\u0f39'), + ('\u0f3e', '\u0f3f'), ('\u0f40', '\u0f47'), + ('\u0f49', '\u0f6c'), ('\u0f71', '\u0f7e'), + ('\u0f7f', '\u0f7f'), ('\u0f80', '\u0f84'), + ('\u0f86', '\u0f87'), ('\u0f88', '\u0f8c'), + ('\u0f8d', '\u0f97'), ('\u0f99', '\u0fbc'), + ('\u0fc6', '\u0fc6'), ('\u1000', '\u102a'), + ('\u102b', '\u102c'), ('\u102d', '\u1030'), + ('\u1031', '\u1031'), ('\u1032', '\u1037'), + ('\u1038', '\u1038'), ('\u1039', '\u103a'), + ('\u103b', '\u103c'), ('\u103d', '\u103e'), + ('\u103f', '\u103f'), ('\u1040', '\u1049'), + ('\u1050', '\u1055'), ('\u1056', '\u1057'), + ('\u1058', '\u1059'), ('\u105a', '\u105d'), + ('\u105e', '\u1060'), ('\u1061', '\u1061'), + ('\u1062', '\u1064'), ('\u1065', '\u1066'), + ('\u1067', '\u106d'), ('\u106e', '\u1070'), + ('\u1071', '\u1074'), ('\u1075', '\u1081'), + ('\u1082', '\u1082'), ('\u1083', '\u1084'), + ('\u1085', '\u1086'), ('\u1087', '\u108c'), + ('\u108d', '\u108d'), ('\u108e', '\u108e'), + ('\u108f', '\u108f'), ('\u1090', '\u1099'), + ('\u109a', '\u109c'), ('\u109d', '\u109d'), + ('\u10a0', '\u10c5'), ('\u10c7', '\u10c7'), + ('\u10cd', '\u10cd'), ('\u10d0', '\u10fa'), + ('\u10fc', '\u10fc'), ('\u10fd', '\u1248'), + ('\u124a', '\u124d'), ('\u1250', '\u1256'), + ('\u1258', '\u1258'), ('\u125a', '\u125d'), + ('\u1260', '\u1288'), ('\u128a', '\u128d'), + ('\u1290', '\u12b0'), ('\u12b2', '\u12b5'), + ('\u12b8', '\u12be'), ('\u12c0', '\u12c0'), + ('\u12c2', '\u12c5'), ('\u12c8', '\u12d6'), + ('\u12d8', '\u1310'), ('\u1312', '\u1315'), + ('\u1318', '\u135a'), ('\u135d', '\u135f'), + ('\u1369', '\u1371'), ('\u1380', '\u138f'), + ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), + ('\u166f', '\u167f'), ('\u1681', '\u169a'), + ('\u16a0', '\u16ea'), ('\u16ee', '\u16f0'), + ('\u1700', '\u170c'), ('\u170e', '\u1711'), + ('\u1712', '\u1714'), ('\u1720', '\u1731'), + ('\u1732', '\u1734'), ('\u1740', '\u1751'), + ('\u1752', '\u1753'), ('\u1760', '\u176c'), + ('\u176e', '\u1770'), ('\u1772', '\u1773'), + ('\u1780', '\u17b3'), ('\u17b4', '\u17b5'), + ('\u17b6', '\u17b6'), ('\u17b7', '\u17bd'), + ('\u17be', '\u17c5'), ('\u17c6', '\u17c6'), + ('\u17c7', '\u17c8'), ('\u17c9', '\u17d3'), + ('\u17d7', '\u17d7'), ('\u17dc', '\u17dc'), + ('\u17dd', '\u17dd'), ('\u17e0', '\u17e9'), + ('\u180b', '\u180d'), ('\u1810', '\u1819'), + ('\u1820', '\u1842'), ('\u1843', '\u1843'), + ('\u1844', '\u1877'), ('\u1880', '\u18a8'), + ('\u18a9', '\u18a9'), ('\u18aa', '\u18aa'), + ('\u18b0', '\u18f5'), ('\u1900', '\u191c'), + ('\u1920', '\u1922'), ('\u1923', '\u1926'), + ('\u1927', '\u1928'), ('\u1929', '\u192b'), + ('\u1930', '\u1931'), ('\u1932', '\u1932'), + ('\u1933', '\u1938'), ('\u1939', '\u193b'), + ('\u1946', '\u194f'), ('\u1950', '\u196d'), + ('\u1970', '\u1974'), ('\u1980', '\u19ab'), + ('\u19b0', '\u19c0'), ('\u19c1', '\u19c7'), + ('\u19c8', '\u19c9'), ('\u19d0', '\u19d9'), + ('\u19da', '\u19da'), ('\u1a00', '\u1a16'), + ('\u1a17', '\u1a18'), ('\u1a19', '\u1a1b'), + ('\u1a20', '\u1a54'), ('\u1a55', '\u1a55'), + ('\u1a56', '\u1a56'), ('\u1a57', '\u1a57'), + ('\u1a58', '\u1a5e'), ('\u1a60', '\u1a60'), + ('\u1a61', '\u1a61'), ('\u1a62', '\u1a62'), + ('\u1a63', '\u1a64'), ('\u1a65', '\u1a6c'), + ('\u1a6d', '\u1a72'), ('\u1a73', '\u1a7c'), + ('\u1a7f', '\u1a7f'), ('\u1a80', '\u1a89'), + ('\u1a90', '\u1a99'), ('\u1aa7', '\u1aa7'), + ('\u1b00', '\u1b03'), ('\u1b04', '\u1b04'), + ('\u1b05', '\u1b33'), ('\u1b34', '\u1b34'), + ('\u1b35', '\u1b35'), ('\u1b36', '\u1b3a'), + ('\u1b3b', '\u1b3b'), ('\u1b3c', '\u1b3c'), + ('\u1b3d', '\u1b41'), ('\u1b42', '\u1b42'), + ('\u1b43', '\u1b44'), ('\u1b45', '\u1b4b'), + ('\u1b50', '\u1b59'), ('\u1b6b', '\u1b73'), + ('\u1b80', '\u1b81'), ('\u1b82', '\u1b82'), + ('\u1b83', '\u1ba0'), ('\u1ba1', '\u1ba1'), + ('\u1ba2', '\u1ba5'), ('\u1ba6', '\u1ba7'), + ('\u1ba8', '\u1ba9'), ('\u1baa', '\u1baa'), + ('\u1bab', '\u1bab'), ('\u1bac', '\u1bad'), + ('\u1bae', '\u1baf'), ('\u1bb0', '\u1bb9'), + ('\u1bba', '\u1be5'), ('\u1be6', '\u1be6'), + ('\u1be7', '\u1be7'), ('\u1be8', '\u1be9'), + ('\u1bea', '\u1bec'), ('\u1bed', '\u1bed'), + ('\u1bee', '\u1bee'), ('\u1bef', '\u1bf1'), + ('\u1bf2', '\u1bf3'), ('\u1c00', '\u1c23'), + ('\u1c24', '\u1c2b'), ('\u1c2c', '\u1c33'), + ('\u1c34', '\u1c35'), ('\u1c36', '\u1c37'), + ('\u1c40', '\u1c49'), ('\u1c4d', '\u1c4f'), + ('\u1c50', '\u1c59'), ('\u1c5a', '\u1c77'), + ('\u1c78', '\u1c7d'), ('\u1cd0', '\u1cd2'), + ('\u1cd4', '\u1ce0'), ('\u1ce1', '\u1ce1'), + ('\u1ce2', '\u1ce8'), ('\u1ce9', '\u1cec'), + ('\u1ced', '\u1ced'), ('\u1cee', '\u1cf1'), + ('\u1cf2', '\u1cf3'), ('\u1cf4', '\u1cf4'), + ('\u1cf5', '\u1cf6'), ('\u1d00', '\u1d2b'), + ('\u1d2c', '\u1d6a'), ('\u1d6b', '\u1d77'), + ('\u1d78', '\u1d78'), ('\u1d79', '\u1d9a'), + ('\u1d9b', '\u1dbf'), ('\u1dc0', '\u1de6'), + ('\u1dfc', '\u1dff'), ('\u1e00', '\u1f15'), + ('\u1f18', '\u1f1d'), ('\u1f20', '\u1f45'), + ('\u1f48', '\u1f4d'), ('\u1f50', '\u1f57'), + ('\u1f59', '\u1f59'), ('\u1f5b', '\u1f5b'), + ('\u1f5d', '\u1f5d'), ('\u1f5f', '\u1f7d'), + ('\u1f80', '\u1fb4'), ('\u1fb6', '\u1fbc'), + ('\u1fbe', '\u1fbe'), ('\u1fc2', '\u1fc4'), + ('\u1fc6', '\u1fcc'), ('\u1fd0', '\u1fd3'), + ('\u1fd6', '\u1fdb'), ('\u1fe0', '\u1fec'), + ('\u1ff2', '\u1ff4'), ('\u1ff6', '\u1ffc'), + ('\u203f', '\u2040'), ('\u2054', '\u2054'), + ('\u2071', '\u2071'), ('\u207f', '\u207f'), + ('\u2090', '\u209c'), ('\u20d0', '\u20dc'), + ('\u20e1', '\u20e1'), ('\u20e5', '\u20f0'), + ('\u2102', '\u2102'), ('\u2107', '\u2107'), + ('\u210a', '\u2113'), ('\u2115', '\u2115'), + ('\u2118', '\u2118'), ('\u2119', '\u211d'), + ('\u2124', '\u2124'), ('\u2126', '\u2126'), + ('\u2128', '\u2128'), ('\u212a', '\u212d'), + ('\u212e', '\u212e'), ('\u212f', '\u2134'), + ('\u2135', '\u2138'), ('\u2139', '\u2139'), + ('\u213c', '\u213f'), ('\u2145', '\u2149'), + ('\u214e', '\u214e'), ('\u2160', '\u2182'), + ('\u2183', '\u2184'), ('\u2185', '\u2188'), + ('\u2c00', '\u2c2e'), ('\u2c30', '\u2c5e'), + ('\u2c60', '\u2c7b'), ('\u2c7c', '\u2c7d'), + ('\u2c7e', '\u2ce4'), ('\u2ceb', '\u2cee'), + ('\u2cef', '\u2cf1'), ('\u2cf2', '\u2cf3'), + ('\u2d00', '\u2d25'), ('\u2d27', '\u2d27'), + ('\u2d2d', '\u2d2d'), ('\u2d30', '\u2d67'), + ('\u2d6f', '\u2d6f'), ('\u2d7f', '\u2d7f'), + ('\u2d80', '\u2d96'), ('\u2da0', '\u2da6'), + ('\u2da8', '\u2dae'), ('\u2db0', '\u2db6'), + ('\u2db8', '\u2dbe'), ('\u2dc0', '\u2dc6'), + ('\u2dc8', '\u2dce'), ('\u2dd0', '\u2dd6'), + ('\u2dd8', '\u2dde'), ('\u2de0', '\u2dff'), + ('\u3005', '\u3005'), ('\u3006', '\u3006'), + ('\u3007', '\u3007'), ('\u3021', '\u3029'), + ('\u302a', '\u302d'), ('\u302e', '\u302f'), + ('\u3031', '\u3035'), ('\u3038', '\u303a'), + ('\u303b', '\u303b'), ('\u303c', '\u303c'), + ('\u3041', '\u3096'), ('\u3099', '\u309a'), + ('\u309d', '\u309e'), ('\u309f', '\u309f'), + ('\u30a1', '\u30fa'), ('\u30fc', '\u30fe'), + ('\u30ff', '\u30ff'), ('\u3105', '\u312d'), + ('\u3131', '\u318e'), ('\u31a0', '\u31ba'), + ('\u31f0', '\u31ff'), ('\u3400', '\u4db5'), + ('\u4e00', '\u9fcc'), ('\ua000', '\ua014'), + ('\ua015', '\ua015'), ('\ua016', '\ua48c'), + ('\ua4d0', '\ua4f7'), ('\ua4f8', '\ua4fd'), + ('\ua500', '\ua60b'), ('\ua60c', '\ua60c'), + ('\ua610', '\ua61f'), ('\ua620', '\ua629'), + ('\ua62a', '\ua62b'), ('\ua640', '\ua66d'), + ('\ua66e', '\ua66e'), ('\ua66f', '\ua66f'), + ('\ua674', '\ua67d'), ('\ua67f', '\ua67f'), + ('\ua680', '\ua697'), ('\ua69f', '\ua69f'), + ('\ua6a0', '\ua6e5'), ('\ua6e6', '\ua6ef'), + ('\ua6f0', '\ua6f1'), ('\ua717', '\ua71f'), + ('\ua722', '\ua76f'), ('\ua770', '\ua770'), + ('\ua771', '\ua787'), ('\ua788', '\ua788'), + ('\ua78b', '\ua78e'), ('\ua790', '\ua793'), + ('\ua7a0', '\ua7aa'), ('\ua7f8', '\ua7f9'), + ('\ua7fa', '\ua7fa'), ('\ua7fb', '\ua801'), + ('\ua802', '\ua802'), ('\ua803', '\ua805'), + ('\ua806', '\ua806'), ('\ua807', '\ua80a'), + ('\ua80b', '\ua80b'), ('\ua80c', '\ua822'), + ('\ua823', '\ua824'), ('\ua825', '\ua826'), + ('\ua827', '\ua827'), ('\ua840', '\ua873'), + ('\ua880', '\ua881'), ('\ua882', '\ua8b3'), + ('\ua8b4', '\ua8c3'), ('\ua8c4', '\ua8c4'), + ('\ua8d0', '\ua8d9'), ('\ua8e0', '\ua8f1'), + ('\ua8f2', '\ua8f7'), ('\ua8fb', '\ua8fb'), + ('\ua900', '\ua909'), ('\ua90a', '\ua925'), + ('\ua926', '\ua92d'), ('\ua930', '\ua946'), + ('\ua947', '\ua951'), ('\ua952', '\ua953'), + ('\ua960', '\ua97c'), ('\ua980', '\ua982'), + ('\ua983', '\ua983'), ('\ua984', '\ua9b2'), + ('\ua9b3', '\ua9b3'), ('\ua9b4', '\ua9b5'), + ('\ua9b6', '\ua9b9'), ('\ua9ba', '\ua9bb'), + ('\ua9bc', '\ua9bc'), ('\ua9bd', '\ua9c0'), + ('\ua9cf', '\ua9cf'), ('\ua9d0', '\ua9d9'), + ('\uaa00', '\uaa28'), ('\uaa29', '\uaa2e'), + ('\uaa2f', '\uaa30'), ('\uaa31', '\uaa32'), + ('\uaa33', '\uaa34'), ('\uaa35', '\uaa36'), + ('\uaa40', '\uaa42'), ('\uaa43', '\uaa43'), + ('\uaa44', '\uaa4b'), ('\uaa4c', '\uaa4c'), + ('\uaa4d', '\uaa4d'), ('\uaa50', '\uaa59'), + ('\uaa60', '\uaa6f'), ('\uaa70', '\uaa70'), + ('\uaa71', '\uaa76'), ('\uaa7a', '\uaa7a'), + ('\uaa7b', '\uaa7b'), ('\uaa80', '\uaaaf'), + ('\uaab0', '\uaab0'), ('\uaab1', '\uaab1'), + ('\uaab2', '\uaab4'), ('\uaab5', '\uaab6'), + ('\uaab7', '\uaab8'), ('\uaab9', '\uaabd'), + ('\uaabe', '\uaabf'), ('\uaac0', '\uaac0'), + ('\uaac1', '\uaac1'), ('\uaac2', '\uaac2'), + ('\uaadb', '\uaadc'), ('\uaadd', '\uaadd'), + ('\uaae0', '\uaaea'), ('\uaaeb', '\uaaeb'), + ('\uaaec', '\uaaed'), ('\uaaee', '\uaaef'), + ('\uaaf2', '\uaaf2'), ('\uaaf3', '\uaaf4'), + ('\uaaf5', '\uaaf5'), ('\uaaf6', '\uaaf6'), + ('\uab01', '\uab06'), ('\uab09', '\uab0e'), + ('\uab11', '\uab16'), ('\uab20', '\uab26'), + ('\uab28', '\uab2e'), ('\uabc0', '\uabe2'), + ('\uabe3', '\uabe4'), ('\uabe5', '\uabe5'), + ('\uabe6', '\uabe7'), ('\uabe8', '\uabe8'), + ('\uabe9', '\uabea'), ('\uabec', '\uabec'), + ('\uabed', '\uabed'), ('\uabf0', '\uabf9'), + ('\uac00', '\ud7a3'), ('\ud7b0', '\ud7c6'), + ('\ud7cb', '\ud7fb'), ('\uf900', '\ufa6d'), + ('\ufa70', '\ufad9'), ('\ufb00', '\ufb06'), + ('\ufb13', '\ufb17'), ('\ufb1d', '\ufb1d'), + ('\ufb1e', '\ufb1e'), ('\ufb1f', '\ufb28'), + ('\ufb2a', '\ufb36'), ('\ufb38', '\ufb3c'), + ('\ufb3e', '\ufb3e'), ('\ufb40', '\ufb41'), + ('\ufb43', '\ufb44'), ('\ufb46', '\ufbb1'), + ('\ufbd3', '\ufc5d'), ('\ufc64', '\ufd3d'), + ('\ufd50', '\ufd8f'), ('\ufd92', '\ufdc7'), + ('\ufdf0', '\ufdf9'), ('\ufe00', '\ufe0f'), + ('\ufe20', '\ufe26'), ('\ufe33', '\ufe34'), + ('\ufe4d', '\ufe4f'), ('\ufe71', '\ufe71'), + ('\ufe73', '\ufe73'), ('\ufe77', '\ufe77'), + ('\ufe79', '\ufe79'), ('\ufe7b', '\ufe7b'), + ('\ufe7d', '\ufe7d'), ('\ufe7f', '\ufefc'), + ('\uff10', '\uff19'), ('\uff21', '\uff3a'), + ('\uff3f', '\uff3f'), ('\uff41', '\uff5a'), + ('\uff66', '\uff6f'), ('\uff70', '\uff70'), + ('\uff71', '\uff9d'), ('\uff9e', '\uff9f'), + ('\uffa0', '\uffbe'), ('\uffc2', '\uffc7'), + ('\uffca', '\uffcf'), ('\uffd2', '\uffd7'), + ('\uffda', '\uffdc'), ('\U00010000', '\U0001000b'), + ('\U0001000d', '\U00010026'), ('\U00010028', '\U0001003a'), + ('\U0001003c', '\U0001003d'), ('\U0001003f', '\U0001004d'), + ('\U00010050', '\U0001005d'), ('\U00010080', '\U000100fa'), + ('\U00010140', '\U00010174'), ('\U000101fd', '\U000101fd'), + ('\U00010280', '\U0001029c'), ('\U000102a0', '\U000102d0'), + ('\U00010300', '\U0001031e'), ('\U00010330', '\U00010340'), + ('\U00010341', '\U00010341'), ('\U00010342', '\U00010349'), + ('\U0001034a', '\U0001034a'), ('\U00010380', '\U0001039d'), + ('\U000103a0', '\U000103c3'), ('\U000103c8', '\U000103cf'), + ('\U000103d1', '\U000103d5'), ('\U00010400', '\U0001044f'), + ('\U00010450', '\U0001049d'), ('\U000104a0', '\U000104a9'), + ('\U00010800', '\U00010805'), ('\U00010808', '\U00010808'), + ('\U0001080a', '\U00010835'), ('\U00010837', '\U00010838'), + ('\U0001083c', '\U0001083c'), ('\U0001083f', '\U00010855'), + ('\U00010900', '\U00010915'), ('\U00010920', '\U00010939'), + ('\U00010980', '\U000109b7'), ('\U000109be', '\U000109bf'), + ('\U00010a00', '\U00010a00'), ('\U00010a01', '\U00010a03'), + ('\U00010a05', '\U00010a06'), ('\U00010a0c', '\U00010a0f'), + ('\U00010a10', '\U00010a13'), ('\U00010a15', '\U00010a17'), + ('\U00010a19', '\U00010a33'), ('\U00010a38', '\U00010a3a'), + ('\U00010a3f', '\U00010a3f'), ('\U00010a60', '\U00010a7c'), + ('\U00010b00', '\U00010b35'), ('\U00010b40', '\U00010b55'), + ('\U00010b60', '\U00010b72'), ('\U00010c00', '\U00010c48'), + ('\U00011000', '\U00011000'), ('\U00011001', '\U00011001'), + ('\U00011002', '\U00011002'), ('\U00011003', '\U00011037'), + ('\U00011038', '\U00011046'), ('\U00011066', '\U0001106f'), + ('\U00011080', '\U00011081'), ('\U00011082', '\U00011082'), + ('\U00011083', '\U000110af'), ('\U000110b0', '\U000110b2'), + ('\U000110b3', '\U000110b6'), ('\U000110b7', '\U000110b8'), + ('\U000110b9', '\U000110ba'), ('\U000110d0', '\U000110e8'), + ('\U000110f0', '\U000110f9'), ('\U00011100', '\U00011102'), + ('\U00011103', '\U00011126'), ('\U00011127', '\U0001112b'), + ('\U0001112c', '\U0001112c'), ('\U0001112d', '\U00011134'), + ('\U00011136', '\U0001113f'), ('\U00011180', '\U00011181'), + ('\U00011182', '\U00011182'), ('\U00011183', '\U000111b2'), + ('\U000111b3', '\U000111b5'), ('\U000111b6', '\U000111be'), + ('\U000111bf', '\U000111c0'), ('\U000111c1', '\U000111c4'), + ('\U000111d0', '\U000111d9'), ('\U00011680', '\U000116aa'), + ('\U000116ab', '\U000116ab'), ('\U000116ac', '\U000116ac'), + ('\U000116ad', '\U000116ad'), ('\U000116ae', '\U000116af'), + ('\U000116b0', '\U000116b5'), ('\U000116b6', '\U000116b6'), + ('\U000116b7', '\U000116b7'), ('\U000116c0', '\U000116c9'), + ('\U00012000', '\U0001236e'), ('\U00012400', '\U00012462'), + ('\U00013000', '\U0001342e'), ('\U00016800', '\U00016a38'), + ('\U00016f00', '\U00016f44'), ('\U00016f50', '\U00016f50'), + ('\U00016f51', '\U00016f7e'), ('\U00016f8f', '\U00016f92'), + ('\U00016f93', '\U00016f9f'), ('\U0001b000', '\U0001b001'), + ('\U0001d165', '\U0001d166'), ('\U0001d167', '\U0001d169'), + ('\U0001d16d', '\U0001d172'), ('\U0001d17b', '\U0001d182'), + ('\U0001d185', '\U0001d18b'), ('\U0001d1aa', '\U0001d1ad'), + ('\U0001d242', '\U0001d244'), ('\U0001d400', '\U0001d454'), + ('\U0001d456', '\U0001d49c'), ('\U0001d49e', '\U0001d49f'), + ('\U0001d4a2', '\U0001d4a2'), ('\U0001d4a5', '\U0001d4a6'), + ('\U0001d4a9', '\U0001d4ac'), ('\U0001d4ae', '\U0001d4b9'), + ('\U0001d4bb', '\U0001d4bb'), ('\U0001d4bd', '\U0001d4c3'), + ('\U0001d4c5', '\U0001d505'), ('\U0001d507', '\U0001d50a'), + ('\U0001d50d', '\U0001d514'), ('\U0001d516', '\U0001d51c'), + ('\U0001d51e', '\U0001d539'), ('\U0001d53b', '\U0001d53e'), + ('\U0001d540', '\U0001d544'), ('\U0001d546', '\U0001d546'), + ('\U0001d54a', '\U0001d550'), ('\U0001d552', '\U0001d6a5'), + ('\U0001d6a8', '\U0001d6c0'), ('\U0001d6c2', '\U0001d6da'), + ('\U0001d6dc', '\U0001d6fa'), ('\U0001d6fc', '\U0001d714'), + ('\U0001d716', '\U0001d734'), ('\U0001d736', '\U0001d74e'), + ('\U0001d750', '\U0001d76e'), ('\U0001d770', '\U0001d788'), + ('\U0001d78a', '\U0001d7a8'), ('\U0001d7aa', '\U0001d7c2'), + ('\U0001d7c4', '\U0001d7cb'), ('\U0001d7ce', '\U0001d7ff'), + ('\U0001ee00', '\U0001ee03'), ('\U0001ee05', '\U0001ee1f'), + ('\U0001ee21', '\U0001ee22'), ('\U0001ee24', '\U0001ee24'), + ('\U0001ee27', '\U0001ee27'), ('\U0001ee29', '\U0001ee32'), + ('\U0001ee34', '\U0001ee37'), ('\U0001ee39', '\U0001ee39'), + ('\U0001ee3b', '\U0001ee3b'), ('\U0001ee42', '\U0001ee42'), + ('\U0001ee47', '\U0001ee47'), ('\U0001ee49', '\U0001ee49'), + ('\U0001ee4b', '\U0001ee4b'), ('\U0001ee4d', '\U0001ee4f'), + ('\U0001ee51', '\U0001ee52'), ('\U0001ee54', '\U0001ee54'), + ('\U0001ee57', '\U0001ee57'), ('\U0001ee59', '\U0001ee59'), + ('\U0001ee5b', '\U0001ee5b'), ('\U0001ee5d', '\U0001ee5d'), + ('\U0001ee5f', '\U0001ee5f'), ('\U0001ee61', '\U0001ee62'), + ('\U0001ee64', '\U0001ee64'), ('\U0001ee67', '\U0001ee6a'), + ('\U0001ee6c', '\U0001ee72'), ('\U0001ee74', '\U0001ee77'), + ('\U0001ee79', '\U0001ee7c'), ('\U0001ee7e', '\U0001ee7e'), + ('\U0001ee80', '\U0001ee89'), ('\U0001ee8b', '\U0001ee9b'), + ('\U0001eea1', '\U0001eea3'), ('\U0001eea5', '\U0001eea9'), + ('\U0001eeab', '\U0001eebb'), ('\U00020000', '\U0002a6d6'), + ('\U0002a700', '\U0002b734'), ('\U0002b740', '\U0002b81d'), + ('\U0002f800', '\U0002fa1d'), ('\U000e0100', '\U000e01ef') + ]; + + pub fn XID_Continue(c: char) -> bool { + bsearch_range_table(c, XID_Continue_table) } - #[test] - fn test_is_upper() { - assert!((unicode::icu::is_upper('M'))); - assert!((!unicode::icu::is_upper('m'))); + static XID_Start_table : &'static [(char,char)] = &[ + ('\x41', '\x5a'), ('\x61', '\x7a'), + ('\xaa', '\xaa'), ('\xb5', '\xb5'), + ('\xba', '\xba'), ('\xc0', '\xd6'), + ('\xd8', '\xf6'), ('\xf8', '\u01ba'), + ('\u01bb', '\u01bb'), ('\u01bc', '\u01bf'), + ('\u01c0', '\u01c3'), ('\u01c4', '\u0293'), + ('\u0294', '\u0294'), ('\u0295', '\u02af'), + ('\u02b0', '\u02c1'), ('\u02c6', '\u02d1'), + ('\u02e0', '\u02e4'), ('\u02ec', '\u02ec'), + ('\u02ee', '\u02ee'), ('\u0370', '\u0373'), + ('\u0374', '\u0374'), ('\u0376', '\u0377'), + ('\u037b', '\u037d'), ('\u0386', '\u0386'), + ('\u0388', '\u038a'), ('\u038c', '\u038c'), + ('\u038e', '\u03a1'), ('\u03a3', '\u03f5'), + ('\u03f7', '\u0481'), ('\u048a', '\u0527'), + ('\u0531', '\u0556'), ('\u0559', '\u0559'), + ('\u0561', '\u0587'), ('\u05d0', '\u05ea'), + ('\u05f0', '\u05f2'), ('\u0620', '\u063f'), + ('\u0640', '\u0640'), ('\u0641', '\u064a'), + ('\u066e', '\u066f'), ('\u0671', '\u06d3'), + ('\u06d5', '\u06d5'), ('\u06e5', '\u06e6'), + ('\u06ee', '\u06ef'), ('\u06fa', '\u06fc'), + ('\u06ff', '\u06ff'), ('\u0710', '\u0710'), + ('\u0712', '\u072f'), ('\u074d', '\u07a5'), + ('\u07b1', '\u07b1'), ('\u07ca', '\u07ea'), + ('\u07f4', '\u07f5'), ('\u07fa', '\u07fa'), + ('\u0800', '\u0815'), ('\u081a', '\u081a'), + ('\u0824', '\u0824'), ('\u0828', '\u0828'), + ('\u0840', '\u0858'), ('\u08a0', '\u08a0'), + ('\u08a2', '\u08ac'), ('\u0904', '\u0939'), + ('\u093d', '\u093d'), ('\u0950', '\u0950'), + ('\u0958', '\u0961'), ('\u0971', '\u0971'), + ('\u0972', '\u0977'), ('\u0979', '\u097f'), + ('\u0985', '\u098c'), ('\u098f', '\u0990'), + ('\u0993', '\u09a8'), ('\u09aa', '\u09b0'), + ('\u09b2', '\u09b2'), ('\u09b6', '\u09b9'), + ('\u09bd', '\u09bd'), ('\u09ce', '\u09ce'), + ('\u09dc', '\u09dd'), ('\u09df', '\u09e1'), + ('\u09f0', '\u09f1'), ('\u0a05', '\u0a0a'), + ('\u0a0f', '\u0a10'), ('\u0a13', '\u0a28'), + ('\u0a2a', '\u0a30'), ('\u0a32', '\u0a33'), + ('\u0a35', '\u0a36'), ('\u0a38', '\u0a39'), + ('\u0a59', '\u0a5c'), ('\u0a5e', '\u0a5e'), + ('\u0a72', '\u0a74'), ('\u0a85', '\u0a8d'), + ('\u0a8f', '\u0a91'), ('\u0a93', '\u0aa8'), + ('\u0aaa', '\u0ab0'), ('\u0ab2', '\u0ab3'), + ('\u0ab5', '\u0ab9'), ('\u0abd', '\u0abd'), + ('\u0ad0', '\u0ad0'), ('\u0ae0', '\u0ae1'), + ('\u0b05', '\u0b0c'), ('\u0b0f', '\u0b10'), + ('\u0b13', '\u0b28'), ('\u0b2a', '\u0b30'), + ('\u0b32', '\u0b33'), ('\u0b35', '\u0b39'), + ('\u0b3d', '\u0b3d'), ('\u0b5c', '\u0b5d'), + ('\u0b5f', '\u0b61'), ('\u0b71', '\u0b71'), + ('\u0b83', '\u0b83'), ('\u0b85', '\u0b8a'), + ('\u0b8e', '\u0b90'), ('\u0b92', '\u0b95'), + ('\u0b99', '\u0b9a'), ('\u0b9c', '\u0b9c'), + ('\u0b9e', '\u0b9f'), ('\u0ba3', '\u0ba4'), + ('\u0ba8', '\u0baa'), ('\u0bae', '\u0bb9'), + ('\u0bd0', '\u0bd0'), ('\u0c05', '\u0c0c'), + ('\u0c0e', '\u0c10'), ('\u0c12', '\u0c28'), + ('\u0c2a', '\u0c33'), ('\u0c35', '\u0c39'), + ('\u0c3d', '\u0c3d'), ('\u0c58', '\u0c59'), + ('\u0c60', '\u0c61'), ('\u0c85', '\u0c8c'), + ('\u0c8e', '\u0c90'), ('\u0c92', '\u0ca8'), + ('\u0caa', '\u0cb3'), ('\u0cb5', '\u0cb9'), + ('\u0cbd', '\u0cbd'), ('\u0cde', '\u0cde'), + ('\u0ce0', '\u0ce1'), ('\u0cf1', '\u0cf2'), + ('\u0d05', '\u0d0c'), ('\u0d0e', '\u0d10'), + ('\u0d12', '\u0d3a'), ('\u0d3d', '\u0d3d'), + ('\u0d4e', '\u0d4e'), ('\u0d60', '\u0d61'), + ('\u0d7a', '\u0d7f'), ('\u0d85', '\u0d96'), + ('\u0d9a', '\u0db1'), ('\u0db3', '\u0dbb'), + ('\u0dbd', '\u0dbd'), ('\u0dc0', '\u0dc6'), + ('\u0e01', '\u0e30'), ('\u0e32', '\u0e32'), + ('\u0e40', '\u0e45'), ('\u0e46', '\u0e46'), + ('\u0e81', '\u0e82'), ('\u0e84', '\u0e84'), + ('\u0e87', '\u0e88'), ('\u0e8a', '\u0e8a'), + ('\u0e8d', '\u0e8d'), ('\u0e94', '\u0e97'), + ('\u0e99', '\u0e9f'), ('\u0ea1', '\u0ea3'), + ('\u0ea5', '\u0ea5'), ('\u0ea7', '\u0ea7'), + ('\u0eaa', '\u0eab'), ('\u0ead', '\u0eb0'), + ('\u0eb2', '\u0eb2'), ('\u0ebd', '\u0ebd'), + ('\u0ec0', '\u0ec4'), ('\u0ec6', '\u0ec6'), + ('\u0edc', '\u0edf'), ('\u0f00', '\u0f00'), + ('\u0f40', '\u0f47'), ('\u0f49', '\u0f6c'), + ('\u0f88', '\u0f8c'), ('\u1000', '\u102a'), + ('\u103f', '\u103f'), ('\u1050', '\u1055'), + ('\u105a', '\u105d'), ('\u1061', '\u1061'), + ('\u1065', '\u1066'), ('\u106e', '\u1070'), + ('\u1075', '\u1081'), ('\u108e', '\u108e'), + ('\u10a0', '\u10c5'), ('\u10c7', '\u10c7'), + ('\u10cd', '\u10cd'), ('\u10d0', '\u10fa'), + ('\u10fc', '\u10fc'), ('\u10fd', '\u1248'), + ('\u124a', '\u124d'), ('\u1250', '\u1256'), + ('\u1258', '\u1258'), ('\u125a', '\u125d'), + ('\u1260', '\u1288'), ('\u128a', '\u128d'), + ('\u1290', '\u12b0'), ('\u12b2', '\u12b5'), + ('\u12b8', '\u12be'), ('\u12c0', '\u12c0'), + ('\u12c2', '\u12c5'), ('\u12c8', '\u12d6'), + ('\u12d8', '\u1310'), ('\u1312', '\u1315'), + ('\u1318', '\u135a'), ('\u1380', '\u138f'), + ('\u13a0', '\u13f4'), ('\u1401', '\u166c'), + ('\u166f', '\u167f'), ('\u1681', '\u169a'), + ('\u16a0', '\u16ea'), ('\u16ee', '\u16f0'), + ('\u1700', '\u170c'), ('\u170e', '\u1711'), + ('\u1720', '\u1731'), ('\u1740', '\u1751'), + ('\u1760', '\u176c'), ('\u176e', '\u1770'), + ('\u1780', '\u17b3'), ('\u17d7', '\u17d7'), + ('\u17dc', '\u17dc'), ('\u1820', '\u1842'), + ('\u1843', '\u1843'), ('\u1844', '\u1877'), + ('\u1880', '\u18a8'), ('\u18aa', '\u18aa'), + ('\u18b0', '\u18f5'), ('\u1900', '\u191c'), + ('\u1950', '\u196d'), ('\u1970', '\u1974'), + ('\u1980', '\u19ab'), ('\u19c1', '\u19c7'), + ('\u1a00', '\u1a16'), ('\u1a20', '\u1a54'), + ('\u1aa7', '\u1aa7'), ('\u1b05', '\u1b33'), + ('\u1b45', '\u1b4b'), ('\u1b83', '\u1ba0'), + ('\u1bae', '\u1baf'), ('\u1bba', '\u1be5'), + ('\u1c00', '\u1c23'), ('\u1c4d', '\u1c4f'), + ('\u1c5a', '\u1c77'), ('\u1c78', '\u1c7d'), + ('\u1ce9', '\u1cec'), ('\u1cee', '\u1cf1'), + ('\u1cf5', '\u1cf6'), ('\u1d00', '\u1d2b'), + ('\u1d2c', '\u1d6a'), ('\u1d6b', '\u1d77'), + ('\u1d78', '\u1d78'), ('\u1d79', '\u1d9a'), + ('\u1d9b', '\u1dbf'), ('\u1e00', '\u1f15'), + ('\u1f18', '\u1f1d'), ('\u1f20', '\u1f45'), + ('\u1f48', '\u1f4d'), ('\u1f50', '\u1f57'), + ('\u1f59', '\u1f59'), ('\u1f5b', '\u1f5b'), + ('\u1f5d', '\u1f5d'), ('\u1f5f', '\u1f7d'), + ('\u1f80', '\u1fb4'), ('\u1fb6', '\u1fbc'), + ('\u1fbe', '\u1fbe'), ('\u1fc2', '\u1fc4'), + ('\u1fc6', '\u1fcc'), ('\u1fd0', '\u1fd3'), + ('\u1fd6', '\u1fdb'), ('\u1fe0', '\u1fec'), + ('\u1ff2', '\u1ff4'), ('\u1ff6', '\u1ffc'), + ('\u2071', '\u2071'), ('\u207f', '\u207f'), + ('\u2090', '\u209c'), ('\u2102', '\u2102'), + ('\u2107', '\u2107'), ('\u210a', '\u2113'), + ('\u2115', '\u2115'), ('\u2118', '\u2118'), + ('\u2119', '\u211d'), ('\u2124', '\u2124'), + ('\u2126', '\u2126'), ('\u2128', '\u2128'), + ('\u212a', '\u212d'), ('\u212e', '\u212e'), + ('\u212f', '\u2134'), ('\u2135', '\u2138'), + ('\u2139', '\u2139'), ('\u213c', '\u213f'), + ('\u2145', '\u2149'), ('\u214e', '\u214e'), + ('\u2160', '\u2182'), ('\u2183', '\u2184'), + ('\u2185', '\u2188'), ('\u2c00', '\u2c2e'), + ('\u2c30', '\u2c5e'), ('\u2c60', '\u2c7b'), + ('\u2c7c', '\u2c7d'), ('\u2c7e', '\u2ce4'), + ('\u2ceb', '\u2cee'), ('\u2cf2', '\u2cf3'), + ('\u2d00', '\u2d25'), ('\u2d27', '\u2d27'), + ('\u2d2d', '\u2d2d'), ('\u2d30', '\u2d67'), + ('\u2d6f', '\u2d6f'), ('\u2d80', '\u2d96'), + ('\u2da0', '\u2da6'), ('\u2da8', '\u2dae'), + ('\u2db0', '\u2db6'), ('\u2db8', '\u2dbe'), + ('\u2dc0', '\u2dc6'), ('\u2dc8', '\u2dce'), + ('\u2dd0', '\u2dd6'), ('\u2dd8', '\u2dde'), + ('\u3005', '\u3005'), ('\u3006', '\u3006'), + ('\u3007', '\u3007'), ('\u3021', '\u3029'), + ('\u3031', '\u3035'), ('\u3038', '\u303a'), + ('\u303b', '\u303b'), ('\u303c', '\u303c'), + ('\u3041', '\u3096'), ('\u309d', '\u309e'), + ('\u309f', '\u309f'), ('\u30a1', '\u30fa'), + ('\u30fc', '\u30fe'), ('\u30ff', '\u30ff'), + ('\u3105', '\u312d'), ('\u3131', '\u318e'), + ('\u31a0', '\u31ba'), ('\u31f0', '\u31ff'), + ('\u3400', '\u4db5'), ('\u4e00', '\u9fcc'), + ('\ua000', '\ua014'), ('\ua015', '\ua015'), + ('\ua016', '\ua48c'), ('\ua4d0', '\ua4f7'), + ('\ua4f8', '\ua4fd'), ('\ua500', '\ua60b'), + ('\ua60c', '\ua60c'), ('\ua610', '\ua61f'), + ('\ua62a', '\ua62b'), ('\ua640', '\ua66d'), + ('\ua66e', '\ua66e'), ('\ua67f', '\ua67f'), + ('\ua680', '\ua697'), ('\ua6a0', '\ua6e5'), + ('\ua6e6', '\ua6ef'), ('\ua717', '\ua71f'), + ('\ua722', '\ua76f'), ('\ua770', '\ua770'), + ('\ua771', '\ua787'), ('\ua788', '\ua788'), + ('\ua78b', '\ua78e'), ('\ua790', '\ua793'), + ('\ua7a0', '\ua7aa'), ('\ua7f8', '\ua7f9'), + ('\ua7fa', '\ua7fa'), ('\ua7fb', '\ua801'), + ('\ua803', '\ua805'), ('\ua807', '\ua80a'), + ('\ua80c', '\ua822'), ('\ua840', '\ua873'), + ('\ua882', '\ua8b3'), ('\ua8f2', '\ua8f7'), + ('\ua8fb', '\ua8fb'), ('\ua90a', '\ua925'), + ('\ua930', '\ua946'), ('\ua960', '\ua97c'), + ('\ua984', '\ua9b2'), ('\ua9cf', '\ua9cf'), + ('\uaa00', '\uaa28'), ('\uaa40', '\uaa42'), + ('\uaa44', '\uaa4b'), ('\uaa60', '\uaa6f'), + ('\uaa70', '\uaa70'), ('\uaa71', '\uaa76'), + ('\uaa7a', '\uaa7a'), ('\uaa80', '\uaaaf'), + ('\uaab1', '\uaab1'), ('\uaab5', '\uaab6'), + ('\uaab9', '\uaabd'), ('\uaac0', '\uaac0'), + ('\uaac2', '\uaac2'), ('\uaadb', '\uaadc'), + ('\uaadd', '\uaadd'), ('\uaae0', '\uaaea'), + ('\uaaf2', '\uaaf2'), ('\uaaf3', '\uaaf4'), + ('\uab01', '\uab06'), ('\uab09', '\uab0e'), + ('\uab11', '\uab16'), ('\uab20', '\uab26'), + ('\uab28', '\uab2e'), ('\uabc0', '\uabe2'), + ('\uac00', '\ud7a3'), ('\ud7b0', '\ud7c6'), + ('\ud7cb', '\ud7fb'), ('\uf900', '\ufa6d'), + ('\ufa70', '\ufad9'), ('\ufb00', '\ufb06'), + ('\ufb13', '\ufb17'), ('\ufb1d', '\ufb1d'), + ('\ufb1f', '\ufb28'), ('\ufb2a', '\ufb36'), + ('\ufb38', '\ufb3c'), ('\ufb3e', '\ufb3e'), + ('\ufb40', '\ufb41'), ('\ufb43', '\ufb44'), + ('\ufb46', '\ufbb1'), ('\ufbd3', '\ufc5d'), + ('\ufc64', '\ufd3d'), ('\ufd50', '\ufd8f'), + ('\ufd92', '\ufdc7'), ('\ufdf0', '\ufdf9'), + ('\ufe71', '\ufe71'), ('\ufe73', '\ufe73'), + ('\ufe77', '\ufe77'), ('\ufe79', '\ufe79'), + ('\ufe7b', '\ufe7b'), ('\ufe7d', '\ufe7d'), + ('\ufe7f', '\ufefc'), ('\uff21', '\uff3a'), + ('\uff41', '\uff5a'), ('\uff66', '\uff6f'), + ('\uff70', '\uff70'), ('\uff71', '\uff9d'), + ('\uffa0', '\uffbe'), ('\uffc2', '\uffc7'), + ('\uffca', '\uffcf'), ('\uffd2', '\uffd7'), + ('\uffda', '\uffdc'), ('\U00010000', '\U0001000b'), + ('\U0001000d', '\U00010026'), ('\U00010028', '\U0001003a'), + ('\U0001003c', '\U0001003d'), ('\U0001003f', '\U0001004d'), + ('\U00010050', '\U0001005d'), ('\U00010080', '\U000100fa'), + ('\U00010140', '\U00010174'), ('\U00010280', '\U0001029c'), + ('\U000102a0', '\U000102d0'), ('\U00010300', '\U0001031e'), + ('\U00010330', '\U00010340'), ('\U00010341', '\U00010341'), + ('\U00010342', '\U00010349'), ('\U0001034a', '\U0001034a'), + ('\U00010380', '\U0001039d'), ('\U000103a0', '\U000103c3'), + ('\U000103c8', '\U000103cf'), ('\U000103d1', '\U000103d5'), + ('\U00010400', '\U0001044f'), ('\U00010450', '\U0001049d'), + ('\U00010800', '\U00010805'), ('\U00010808', '\U00010808'), + ('\U0001080a', '\U00010835'), ('\U00010837', '\U00010838'), + ('\U0001083c', '\U0001083c'), ('\U0001083f', '\U00010855'), + ('\U00010900', '\U00010915'), ('\U00010920', '\U00010939'), + ('\U00010980', '\U000109b7'), ('\U000109be', '\U000109bf'), + ('\U00010a00', '\U00010a00'), ('\U00010a10', '\U00010a13'), + ('\U00010a15', '\U00010a17'), ('\U00010a19', '\U00010a33'), + ('\U00010a60', '\U00010a7c'), ('\U00010b00', '\U00010b35'), + ('\U00010b40', '\U00010b55'), ('\U00010b60', '\U00010b72'), + ('\U00010c00', '\U00010c48'), ('\U00011003', '\U00011037'), + ('\U00011083', '\U000110af'), ('\U000110d0', '\U000110e8'), + ('\U00011103', '\U00011126'), ('\U00011183', '\U000111b2'), + ('\U000111c1', '\U000111c4'), ('\U00011680', '\U000116aa'), + ('\U00012000', '\U0001236e'), ('\U00012400', '\U00012462'), + ('\U00013000', '\U0001342e'), ('\U00016800', '\U00016a38'), + ('\U00016f00', '\U00016f44'), ('\U00016f50', '\U00016f50'), + ('\U00016f93', '\U00016f9f'), ('\U0001b000', '\U0001b001'), + ('\U0001d400', '\U0001d454'), ('\U0001d456', '\U0001d49c'), + ('\U0001d49e', '\U0001d49f'), ('\U0001d4a2', '\U0001d4a2'), + ('\U0001d4a5', '\U0001d4a6'), ('\U0001d4a9', '\U0001d4ac'), + ('\U0001d4ae', '\U0001d4b9'), ('\U0001d4bb', '\U0001d4bb'), + ('\U0001d4bd', '\U0001d4c3'), ('\U0001d4c5', '\U0001d505'), + ('\U0001d507', '\U0001d50a'), ('\U0001d50d', '\U0001d514'), + ('\U0001d516', '\U0001d51c'), ('\U0001d51e', '\U0001d539'), + ('\U0001d53b', '\U0001d53e'), ('\U0001d540', '\U0001d544'), + ('\U0001d546', '\U0001d546'), ('\U0001d54a', '\U0001d550'), + ('\U0001d552', '\U0001d6a5'), ('\U0001d6a8', '\U0001d6c0'), + ('\U0001d6c2', '\U0001d6da'), ('\U0001d6dc', '\U0001d6fa'), + ('\U0001d6fc', '\U0001d714'), ('\U0001d716', '\U0001d734'), + ('\U0001d736', '\U0001d74e'), ('\U0001d750', '\U0001d76e'), + ('\U0001d770', '\U0001d788'), ('\U0001d78a', '\U0001d7a8'), + ('\U0001d7aa', '\U0001d7c2'), ('\U0001d7c4', '\U0001d7cb'), + ('\U0001ee00', '\U0001ee03'), ('\U0001ee05', '\U0001ee1f'), + ('\U0001ee21', '\U0001ee22'), ('\U0001ee24', '\U0001ee24'), + ('\U0001ee27', '\U0001ee27'), ('\U0001ee29', '\U0001ee32'), + ('\U0001ee34', '\U0001ee37'), ('\U0001ee39', '\U0001ee39'), + ('\U0001ee3b', '\U0001ee3b'), ('\U0001ee42', '\U0001ee42'), + ('\U0001ee47', '\U0001ee47'), ('\U0001ee49', '\U0001ee49'), + ('\U0001ee4b', '\U0001ee4b'), ('\U0001ee4d', '\U0001ee4f'), + ('\U0001ee51', '\U0001ee52'), ('\U0001ee54', '\U0001ee54'), + ('\U0001ee57', '\U0001ee57'), ('\U0001ee59', '\U0001ee59'), + ('\U0001ee5b', '\U0001ee5b'), ('\U0001ee5d', '\U0001ee5d'), + ('\U0001ee5f', '\U0001ee5f'), ('\U0001ee61', '\U0001ee62'), + ('\U0001ee64', '\U0001ee64'), ('\U0001ee67', '\U0001ee6a'), + ('\U0001ee6c', '\U0001ee72'), ('\U0001ee74', '\U0001ee77'), + ('\U0001ee79', '\U0001ee7c'), ('\U0001ee7e', '\U0001ee7e'), + ('\U0001ee80', '\U0001ee89'), ('\U0001ee8b', '\U0001ee9b'), + ('\U0001eea1', '\U0001eea3'), ('\U0001eea5', '\U0001eea9'), + ('\U0001eeab', '\U0001eebb'), ('\U00020000', '\U0002a6d6'), + ('\U0002a700', '\U0002b734'), ('\U0002b740', '\U0002b81d'), + ('\U0002f800', '\U0002fa1d') + ]; + + pub fn XID_Start(c: char) -> bool { + bsearch_range_table(c, XID_Start_table) } } diff --git a/src/libcore/unstable/at_exit.rs b/src/libstd/unstable/at_exit.rs similarity index 100% rename from src/libcore/unstable/at_exit.rs rename to src/libstd/unstable/at_exit.rs diff --git a/src/libcore/rt/global_heap.rs b/src/libstd/unstable/exchange_alloc.rs similarity index 88% rename from src/libcore/rt/global_heap.rs rename to src/libstd/unstable/exchange_alloc.rs index ce7ff87b44580..3b35c2fb8047f 100644 --- a/src/libcore/rt/global_heap.rs +++ b/src/libstd/unstable/exchange_alloc.rs @@ -9,7 +9,7 @@ // except according to those terms. use sys::{TypeDesc, size_of}; -use libc::{c_void, size_t, uintptr_t}; +use libc::{c_void, size_t}; use c_malloc = libc::malloc; use c_free = libc::free; use managed::raw::{BoxHeaderRepr, BoxRepr}; @@ -34,7 +34,7 @@ pub unsafe fn malloc(td: *TypeDesc, size: uint) -> *c_void { box.header.prev = null(); box.header.next = null(); - let exchange_count = &mut *exchange_count_ptr(); + let exchange_count = &mut *rust_get_exchange_count_ptr(); atomic_xadd(exchange_count, 1); return transmute(box); @@ -52,7 +52,7 @@ pub unsafe fn malloc_raw(size: uint) -> *c_void { } pub unsafe fn free(ptr: *c_void) { - let exchange_count = &mut *exchange_count_ptr(); + let exchange_count = &mut *rust_get_exchange_count_ptr(); atomic_xsub(exchange_count, 1); assert!(ptr.is_not_null()); @@ -77,11 +77,7 @@ fn align_to(size: uint, align: uint) -> uint { (size + align - 1) & !(align - 1) } -fn exchange_count_ptr() -> *mut int { - // XXX: Need mutable globals - unsafe { transmute(&rust_exchange_count) } -} - extern { - static rust_exchange_count: uintptr_t; + #[rust_stack] + fn rust_get_exchange_count_ptr() -> *mut int; } diff --git a/src/libcore/unstable/extfmt.rs b/src/libstd/unstable/extfmt.rs similarity index 100% rename from src/libcore/unstable/extfmt.rs rename to src/libstd/unstable/extfmt.rs diff --git a/src/libcore/unstable/finally.rs b/src/libstd/unstable/finally.rs similarity index 100% rename from src/libcore/unstable/finally.rs rename to src/libstd/unstable/finally.rs diff --git a/src/libcore/unstable/global.rs b/src/libstd/unstable/global.rs similarity index 100% rename from src/libcore/unstable/global.rs rename to src/libstd/unstable/global.rs diff --git a/src/libcore/unstable/intrinsics.rs b/src/libstd/unstable/intrinsics.rs similarity index 100% rename from src/libcore/unstable/intrinsics.rs rename to src/libstd/unstable/intrinsics.rs diff --git a/src/libcore/unstable/lang.rs b/src/libstd/unstable/lang.rs similarity index 100% rename from src/libcore/unstable/lang.rs rename to src/libstd/unstable/lang.rs diff --git a/src/libcore/unstable/mod.rs b/src/libstd/unstable/mod.rs similarity index 100% rename from src/libcore/unstable/mod.rs rename to src/libstd/unstable/mod.rs diff --git a/src/libcore/unstable/simd.rs b/src/libstd/unstable/simd.rs similarity index 100% rename from src/libcore/unstable/simd.rs rename to src/libstd/unstable/simd.rs diff --git a/src/libcore/unstable/sync.rs b/src/libstd/unstable/sync.rs similarity index 100% rename from src/libcore/unstable/sync.rs rename to src/libstd/unstable/sync.rs diff --git a/src/libcore/unstable/weak_task.rs b/src/libstd/unstable/weak_task.rs similarity index 100% rename from src/libcore/unstable/weak_task.rs rename to src/libstd/unstable/weak_task.rs diff --git a/src/libcore/util.rs b/src/libstd/util.rs similarity index 100% rename from src/libcore/util.rs rename to src/libstd/util.rs diff --git a/src/libcore/vec.rs b/src/libstd/vec.rs similarity index 100% rename from src/libcore/vec.rs rename to src/libstd/vec.rs diff --git a/src/libuv b/src/libuv index dfae9c3e958dc..218ab86721eef 160000 --- a/src/libuv +++ b/src/libuv @@ -1 +1 @@ -Subproject commit dfae9c3e958dc086d9c0ab068cd76d196c95a433 +Subproject commit 218ab86721eefd7b7e97fa6d9f95a80a1fa8686c From ebfc2b8e5671a8c56988e05f83c3b1eeaf2abb9a Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Fri, 17 May 2013 13:12:42 -0700 Subject: [PATCH 187/248] librustc: Rename core injection to std injection --- src/librustc/driver/driver.rs | 4 ++-- .../front/{core_inject.rs => std_inject.rs} | 19 +++++++++---------- src/librustc/rustc.rc | 2 +- src/libstd/core.rc | 5 +++-- .../tag-that-dare-not-speak-its-name.rs | 2 +- src/test/run-pass/trait-to-str.rs | 2 +- src/test/run-pass/use.rs | 2 +- 7 files changed, 18 insertions(+), 18 deletions(-) rename src/librustc/front/{core_inject.rs => std_inject.rs} (85%) diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 33c70a3d4259f..837d3c285aaaa 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -198,8 +198,8 @@ pub fn compile_rest(sess: Session, crate = time(time_passes, ~"intrinsic injection", || front::intrinsic_inject::inject_intrinsic(sess, crate)); - crate = time(time_passes, ~"core injection", || - front::core_inject::maybe_inject_libcore_ref(sess, crate)); + crate = time(time_passes, ~"std injection", || + front::std_inject::maybe_inject_libstd_ref(sess, crate)); let ast_map = time(time_passes, ~"ast indexing", || syntax::ast_map::map_crate(sess.diagnostic(), crate)); diff --git a/src/librustc/front/core_inject.rs b/src/librustc/front/std_inject.rs similarity index 85% rename from src/librustc/front/core_inject.rs rename to src/librustc/front/std_inject.rs index b3e045d8af9a8..e84f552fd1ce9 100644 --- a/src/librustc/front/core_inject.rs +++ b/src/librustc/front/std_inject.rs @@ -16,23 +16,22 @@ use syntax::codemap; use syntax::codemap::dummy_sp; use syntax::fold; -static CORE_VERSION: &'static str = "0.7-pre"; +static STD_VERSION: &'static str = "0.7-pre"; -pub fn maybe_inject_libcore_ref(sess: Session, - crate: @ast::crate) -> @ast::crate { - if use_core(crate) { - inject_libcore_ref(sess, crate) +pub fn maybe_inject_libstd_ref(sess: Session, crate: @ast::crate) + -> @ast::crate { + if use_std(crate) { + inject_libstd_ref(sess, crate) } else { crate } } -fn use_core(crate: @ast::crate) -> bool { - !attr::attrs_contains_name(crate.node.attrs, "no_core") +fn use_std(crate: @ast::crate) -> bool { + !attr::attrs_contains_name(crate.node.attrs, "no_std") } -fn inject_libcore_ref(sess: Session, - crate: @ast::crate) -> @ast::crate { +fn inject_libstd_ref(sess: Session, crate: @ast::crate) -> @ast::crate { fn spanned(x: T) -> codemap::spanned { codemap::spanned { node: x, span: dummy_sp() } } @@ -48,7 +47,7 @@ fn inject_libcore_ref(sess: Session, style: ast::attr_inner, value: @spanned(ast::meta_name_value( @~"vers", - spanned(ast::lit_str(@CORE_VERSION.to_str())) + spanned(ast::lit_str(@STD_VERSION.to_str())) )), is_sugared_doc: false }) diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index 310b0c964eee4..a21c5dc7b36e0 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -102,7 +102,7 @@ pub mod middle { pub mod front { pub mod config; pub mod test; - pub mod core_inject; + pub mod std_inject; pub mod intrinsic_inject; } diff --git a/src/libstd/core.rc b/src/libstd/core.rc index 60093ff96bb26..6f4890c7834a7 100644 --- a/src/libstd/core.rc +++ b/src/libstd/core.rc @@ -57,8 +57,9 @@ they contained the following prologue: #[crate_type = "lib"]; -// Don't link to core. We are core. -#[no_core]; +// Don't link to std. We are std. +#[no_core]; // for stage0 +#[no_std]; #[deny(non_camel_case_types)]; diff --git a/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs b/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs index 22f6a34a181fb..f167ee3d5c48e 100644 --- a/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs +++ b/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs @@ -11,7 +11,7 @@ // error-pattern:mismatched types: expected `char` but found // Issue #876 -#[no_core]; +#[no_std]; extern mod core; diff --git a/src/test/run-pass/trait-to-str.rs b/src/test/run-pass/trait-to-str.rs index ca22b5942dbc7..9726eed58043e 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -10,7 +10,7 @@ // xfail-fast -#[no_core]; +#[no_std]; extern mod core; diff --git a/src/test/run-pass/use.rs b/src/test/run-pass/use.rs index 0bd4175d39043..11f9e7641e17b 100644 --- a/src/test/run-pass/use.rs +++ b/src/test/run-pass/use.rs @@ -10,7 +10,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[no_core]; +#[no_std]; extern mod core; extern mod zed(name = "core"); extern mod bar(name = "core", vers = "0.7-pre"); From f3723cf7c486fd22544b71d27eca5ed7082c6dff Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Fri, 17 May 2013 15:28:44 -0700 Subject: [PATCH 188/248] libextra: Rename the actual metadata names of libcore to libstd and libstd to libextra --- Makefile.in | 4 ++-- src/compiletest/common.rs | 2 ++ src/compiletest/compiletest.rc | 7 +++++-- src/compiletest/errors.rs | 2 ++ src/compiletest/header.rs | 2 ++ src/compiletest/procsrv.rs | 1 + src/compiletest/runtest.rs | 2 ++ src/compiletest/util.rs | 2 ++ src/driver/driver.rs | 5 +++++ src/libextra/arc.rs | 2 ++ src/libextra/arena.rs | 2 ++ src/libextra/base64.rs | 6 ++++++ src/libextra/bitv.rs | 2 ++ src/libextra/c_vec.rs | 2 ++ src/libextra/comm.rs | 2 ++ src/libextra/deque.rs | 2 ++ src/libextra/dlist.rs | 2 ++ src/libextra/ebml.rs | 4 ++++ src/libextra/fileinput.rs | 2 ++ src/libextra/flate.rs | 4 ++-- src/libextra/flatpipes.rs | 10 ++++++++++ src/libextra/fun_treemap.rs | 2 ++ src/libextra/future.rs | 2 ++ src/libextra/getopts.rs | 2 ++ src/libextra/json.rs | 2 ++ src/libextra/list.rs | 2 ++ src/libextra/md4.rs | 2 ++ src/libextra/net_ip.rs | 6 ++++++ src/libextra/net_tcp.rs | 2 ++ src/libextra/net_url.rs | 2 ++ src/libextra/num/bigint.rs | 2 ++ src/libextra/num/complex.rs | 2 ++ src/libextra/num/rational.rs | 2 ++ src/libextra/par.rs | 2 ++ src/libextra/priority_queue.rs | 2 ++ src/libextra/rc.rs | 2 ++ src/libextra/rl.rs | 2 ++ src/libextra/rope.rs | 14 ++++++++++++-- src/libextra/semver.rs | 2 ++ src/libextra/serialize.rs | 2 ++ src/libextra/sha1.rs | 2 ++ src/libextra/smallintmap.rs | 2 ++ src/libextra/sort.rs | 2 ++ src/libextra/stats.rs | 2 ++ src/libextra/std.rc | 10 +++++++++- src/libextra/sync.rs | 2 ++ src/libextra/task_pool.rs | 2 ++ src/libextra/tempfile.rs | 2 ++ src/libextra/term.rs | 2 ++ src/libextra/test.rs | 4 ++++ src/libextra/time.rs | 2 ++ src/libextra/timer.rs | 2 ++ src/libextra/treemap.rs | 2 ++ src/libextra/uv_global_loop.rs | 2 ++ src/libextra/uv_iotask.rs | 2 ++ src/libextra/uv_ll.rs | 2 ++ src/libextra/workcache.rs | 2 ++ src/libfuzzer/ast_match.rs | 2 ++ src/libfuzzer/cycles.rs | 2 ++ src/libfuzzer/fuzzer.rc | 9 +++++++-- src/libfuzzer/ivec_fuzz.rs | 3 ++- src/libfuzzer/rand_util.rs | 2 +- src/librust/rust.rc | 6 ++++++ src/librustc/back/link.rs | 6 ++++++ src/librustc/back/rpath.rs | 2 ++ src/librustc/driver/driver.rs | 2 ++ src/librustc/driver/session.rs | 2 ++ src/librustc/front/config.rs | 2 ++ src/librustc/front/intrinsic_inject.rs | 2 ++ src/librustc/front/std_inject.rs | 2 ++ src/librustc/front/test.rs | 2 ++ src/librustc/lib/llvm.rs | 2 ++ src/librustc/metadata/creader.rs | 3 ++- src/librustc/metadata/csearch.rs | 2 ++ src/librustc/metadata/cstore.rs | 2 ++ src/librustc/metadata/decoder.rs | 2 ++ src/librustc/metadata/encoder.rs | 2 ++ src/librustc/metadata/filesearch.rs | 2 ++ src/librustc/metadata/loader.rs | 3 ++- src/librustc/metadata/tydecode.rs | 2 ++ src/librustc/metadata/tyencode.rs | 2 ++ src/librustc/middle/astencode.rs | 2 ++ src/librustc/middle/borrowck/check_loans.rs | 2 ++ src/librustc/middle/check_const.rs | 2 ++ src/librustc/middle/check_match.rs | 2 ++ src/librustc/middle/const_eval.rs | 2 ++ src/librustc/middle/dataflow.rs | 2 ++ src/librustc/middle/entry.rs | 2 ++ src/librustc/middle/freevars.rs | 2 ++ src/librustc/middle/kind.rs | 2 ++ src/librustc/middle/lang_items.rs | 2 ++ src/librustc/middle/lint.rs | 3 +++ src/librustc/middle/liveness.rs | 1 + src/librustc/middle/mem_categorization.rs | 2 ++ src/librustc/middle/moves.rs | 2 ++ src/librustc/middle/pat_util.rs | 2 ++ src/librustc/middle/privacy.rs | 2 ++ src/librustc/middle/region.rs | 2 ++ src/librustc/middle/resolve.rs | 2 ++ src/librustc/middle/subst.rs | 2 ++ src/librustc/middle/trans/_match.rs | 2 ++ src/librustc/middle/trans/asm.rs | 2 ++ src/librustc/middle/trans/base.rs | 2 ++ src/librustc/middle/trans/build.rs | 2 ++ src/librustc/middle/trans/cabi_mips.rs | 2 ++ src/librustc/middle/trans/cabi_x86.rs | 2 ++ src/librustc/middle/trans/callee.rs | 2 ++ src/librustc/middle/trans/closure.rs | 2 ++ src/librustc/middle/trans/common.rs | 6 ++---- src/librustc/middle/trans/consts.rs | 2 ++ src/librustc/middle/trans/controlflow.rs | 2 ++ src/librustc/middle/trans/datum.rs | 2 ++ src/librustc/middle/trans/debuginfo.rs | 1 + src/librustc/middle/trans/expr.rs | 2 ++ src/librustc/middle/trans/foreign.rs | 2 ++ src/librustc/middle/trans/glue.rs | 2 ++ src/librustc/middle/trans/inline.rs | 2 ++ src/librustc/middle/trans/meth.rs | 2 ++ src/librustc/middle/trans/monomorphize.rs | 2 ++ src/librustc/middle/trans/reachable.rs | 1 + src/librustc/middle/trans/type_of.rs | 2 ++ src/librustc/middle/trans/write_guard.rs | 2 ++ src/librustc/middle/ty.rs | 1 + src/librustc/middle/typeck/astconv.rs | 2 ++ src/librustc/middle/typeck/check/_match.rs | 2 ++ src/librustc/middle/typeck/check/method.rs | 2 ++ src/librustc/middle/typeck/check/mod.rs | 2 ++ src/librustc/middle/typeck/check/regionck.rs | 4 ++++ src/librustc/middle/typeck/check/regionmanip.rs | 2 ++ src/librustc/middle/typeck/check/vtable.rs | 2 ++ src/librustc/middle/typeck/check/writeback.rs | 2 ++ src/librustc/middle/typeck/coherence.rs | 1 + src/librustc/middle/typeck/collect.rs | 2 ++ src/librustc/middle/typeck/infer/coercion.rs | 2 ++ src/librustc/middle/typeck/infer/combine.rs | 2 ++ src/librustc/middle/typeck/infer/glb.rs | 2 ++ src/librustc/middle/typeck/infer/lattice.rs | 2 ++ src/librustc/middle/typeck/infer/lub.rs | 2 ++ src/librustc/middle/typeck/infer/mod.rs | 2 ++ .../middle/typeck/infer/region_inference.rs | 2 ++ src/librustc/middle/typeck/infer/resolve.rs | 2 ++ src/librustc/middle/typeck/infer/sub.rs | 2 ++ src/librustc/middle/typeck/infer/to_str.rs | 2 ++ src/librustc/middle/typeck/infer/unify.rs | 2 ++ src/librustc/middle/typeck/mod.rs | 2 ++ src/librustc/middle/typeck/rscope.rs | 2 ++ src/librustc/rustc.rc | 8 +++++++- src/librustc/util/common.rs | 2 ++ src/librustc/util/enum_set.rs | 4 ++++ src/librustc/util/ppaux.rs | 2 ++ src/librustdoc/astsrv.rs | 2 ++ src/librustdoc/attr_parser.rs | 2 ++ src/librustdoc/attr_pass.rs | 2 ++ src/librustdoc/config.rs | 1 + src/librustdoc/demo.rs | 2 ++ src/librustdoc/desc_to_brief_pass.rs | 2 ++ src/librustdoc/doc.rs | 2 ++ src/librustdoc/extract.rs | 2 ++ src/librustdoc/fold.rs | 2 ++ src/librustdoc/markdown_index_pass.rs | 2 ++ src/librustdoc/markdown_pass.rs | 2 ++ src/librustdoc/markdown_writer.rs | 2 ++ src/librustdoc/page_pass.rs | 2 ++ src/librustdoc/parse.rs | 2 ++ src/librustdoc/pass.rs | 2 ++ src/librustdoc/path_pass.rs | 2 ++ src/librustdoc/prune_private_pass.rs | 2 ++ src/librustdoc/rustdoc.rc | 8 +++++++- src/librustdoc/sectionalize_pass.rs | 2 ++ src/librustdoc/text_pass.rs | 2 ++ src/librustdoc/tystr_pass.rs | 2 ++ src/librustdoc/unindent_pass.rs | 2 ++ src/librustdoc/util.rs | 2 ++ src/librusti/rusti.rc | 8 +++++++- src/librustpkg/context.rs | 2 ++ src/librustpkg/path_util.rs | 1 + src/librustpkg/rustpkg.rc | 7 ++++++- src/librustpkg/util.rs | 1 + src/libstd/core.rc | 15 ++++++++------- src/libsyntax/abi.rs | 2 ++ src/libsyntax/ast.rs | 2 ++ src/libsyntax/ast_map.rs | 2 ++ src/libsyntax/ast_util.rs | 2 ++ src/libsyntax/attr.rs | 2 ++ src/libsyntax/codemap.rs | 2 ++ src/libsyntax/diagnostic.rs | 2 ++ src/libsyntax/ext/asm.rs | 2 ++ src/libsyntax/ext/base.rs | 2 ++ src/libsyntax/ext/build.rs | 2 ++ src/libsyntax/ext/concat_idents.rs | 2 ++ src/libsyntax/ext/deriving/clone.rs | 3 ++- src/libsyntax/ext/deriving/cmp/eq.rs | 2 ++ src/libsyntax/ext/deriving/cmp/ord.rs | 1 + src/libsyntax/ext/deriving/cmp/totaleq.rs | 1 + src/libsyntax/ext/deriving/cmp/totalord.rs | 2 ++ src/libsyntax/ext/deriving/decodable.rs | 2 ++ src/libsyntax/ext/deriving/encodable.rs | 1 + src/libsyntax/ext/deriving/generic.rs | 2 ++ src/libsyntax/ext/deriving/iter_bytes.rs | 2 ++ src/libsyntax/ext/deriving/mod.rs | 2 ++ src/libsyntax/ext/deriving/rand.rs | 2 ++ src/libsyntax/ext/deriving/to_str.rs | 2 ++ src/libsyntax/ext/deriving/ty.rs | 2 ++ src/libsyntax/ext/env.rs | 2 ++ src/libsyntax/ext/expand.rs | 2 ++ src/libsyntax/ext/fmt.rs | 2 ++ src/libsyntax/ext/log_syntax.rs | 2 ++ src/libsyntax/ext/pipes/ast_builder.rs | 3 +++ src/libsyntax/ext/pipes/check.rs | 2 ++ src/libsyntax/ext/pipes/liveness.rs | 2 ++ src/libsyntax/ext/pipes/parse_proto.rs | 2 ++ src/libsyntax/ext/pipes/pipec.rs | 2 ++ src/libsyntax/ext/pipes/proto.rs | 2 ++ src/libsyntax/ext/quote.rs | 4 ++++ src/libsyntax/ext/source_util.rs | 2 ++ src/libsyntax/ext/trace_macros.rs | 2 ++ src/libsyntax/ext/tt/macro_parser.rs | 3 +++ src/libsyntax/ext/tt/macro_rules.rs | 1 + src/libsyntax/ext/tt/transcribe.rs | 2 ++ src/libsyntax/fold.rs | 2 ++ src/libsyntax/parse/comments.rs | 2 ++ src/libsyntax/parse/common.rs | 2 ++ src/libsyntax/parse/lexer.rs | 2 ++ src/libsyntax/parse/obsolete.rs | 1 + src/libsyntax/parse/parser.rs | 2 ++ src/libsyntax/parse/token.rs | 2 ++ src/libsyntax/print/pp.rs | 3 +++ src/libsyntax/print/pprust.rs | 1 + src/libsyntax/syntax.rc | 8 +++++++- src/libsyntax/util/interner.rs | 5 +++++ src/libsyntax/visit.rs | 2 ++ 231 files changed, 545 insertions(+), 32 deletions(-) diff --git a/Makefile.in b/Makefile.in index 0a652c0f35017..3d8133df7a42a 100644 --- a/Makefile.in +++ b/Makefile.in @@ -215,8 +215,8 @@ CFG_LIBRUSTDOC_$(1) :=$(call CFG_LIB_NAME_$(1),rustdoc) CFG_LIBRUSTI_$(1) :=$(call CFG_LIB_NAME_$(1),rusti) CFG_LIBRUST_$(1) :=$(call CFG_LIB_NAME_$(1),rust) -EXTRALIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),std) -STDLIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),core) +EXTRALIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),extra) +STDLIB_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),std) LIBRUSTC_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),rustc) LIBSYNTAX_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),syntax) LIBFUZZER_GLOB_$(1) :=$(call CFG_LIB_GLOB_$(1),fuzzer) diff --git a/src/compiletest/common.rs b/src/compiletest/common.rs index 38289f6274180..869657326b7d2 100644 --- a/src/compiletest/common.rs +++ b/src/compiletest/common.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + #[deriving(Eq)] pub enum mode { mode_compile_fail, diff --git a/src/compiletest/compiletest.rc b/src/compiletest/compiletest.rc index 5d703f6721314..f9ad0d5f925fb 100644 --- a/src/compiletest/compiletest.rc +++ b/src/compiletest/compiletest.rc @@ -12,10 +12,13 @@ #[allow(non_camel_case_types)]; -extern mod std; +#[no_std]; -use core::*; +extern mod core(name = "std", vers = "0.7-pre"); +extern mod std(name = "extra", vers = "0.7-pre"); +use core::prelude::*; +use core::*; use std::getopts; use std::test; diff --git a/src/compiletest/errors.rs b/src/compiletest/errors.rs index aa8d61027b3c3..297ec9ee21e28 100644 --- a/src/compiletest/errors.rs +++ b/src/compiletest/errors.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + pub struct ExpectedError { line: uint, kind: ~str, msg: ~str } // Load any test directives embedded in the file diff --git a/src/compiletest/header.rs b/src/compiletest/header.rs index b1f4c9f515bb0..b3205a4861072 100644 --- a/src/compiletest/header.rs +++ b/src/compiletest/header.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use common; use common::config; diff --git a/src/compiletest/procsrv.rs b/src/compiletest/procsrv.rs index 71efa5596a8ad..2a4cd08c1242d 100644 --- a/src/compiletest/procsrv.rs +++ b/src/compiletest/procsrv.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use core::libc::c_int; use core::run::spawn_process; diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index d58c2e596bd75..da81df0e404d5 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use common::mode_run_pass; use common::mode_run_fail; use common::mode_compile_fail; diff --git a/src/compiletest/util.rs b/src/compiletest/util.rs index 05e5d902a47c9..e9b09e8aee895 100644 --- a/src/compiletest/util.rs +++ b/src/compiletest/util.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use common::config; use core::os::getenv; diff --git a/src/driver/driver.rs b/src/driver/driver.rs index b8bd79eedbb86..97e01d1bcdc01 100644 --- a/src/driver/driver.rs +++ b/src/driver/driver.rs @@ -8,6 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#[no_core]; +#[no_std]; + +extern mod core(name = "std", vers = "0.7-pre"); + #[cfg(rustpkg)] extern mod this(name = "rustpkg"); diff --git a/src/libextra/arc.rs b/src/libextra/arc.rs index 9c7db35f6f206..087b28ec01e6d 100644 --- a/src/libextra/arc.rs +++ b/src/libextra/arc.rs @@ -37,6 +37,8 @@ * ~~~ */ +use core::prelude::*; + use sync; use sync::{Mutex, mutex_with_condvars, RWlock, rwlock_with_condvars}; diff --git a/src/libextra/arena.rs b/src/libextra/arena.rs index a087a16caa245..690993e7bf9a2 100644 --- a/src/libextra/arena.rs +++ b/src/libextra/arena.rs @@ -32,6 +32,8 @@ // overhead when initializing plain-old-data and means we don't need // to waste time running the destructors of POD. +use core::prelude::*; + use list::{MutList, MutCons, MutNil}; use core::at_vec; diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs index a820862ef4c7a..e623740ca81e3 100644 --- a/src/libextra/base64.rs +++ b/src/libextra/base64.rs @@ -10,6 +10,12 @@ //! Base64 binary-to-text encoding +use core::prelude::*; + +use core::old_iter; +use core::str; +use core::vec; + pub trait ToBase64 { fn to_base64(&self) -> ~str; } diff --git a/src/libextra/bitv.rs b/src/libextra/bitv.rs index 9d22107931e9e..c12ebf8fb46ea 100644 --- a/src/libextra/bitv.rs +++ b/src/libextra/bitv.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use core::vec::from_elem; struct SmallBitv { diff --git a/src/libextra/c_vec.rs b/src/libextra/c_vec.rs index e463e5971881c..a8e71433ff8b5 100644 --- a/src/libextra/c_vec.rs +++ b/src/libextra/c_vec.rs @@ -36,6 +36,8 @@ * still held if needed. */ +use core::prelude::*; + /** * The type representing a foreign chunk of memory * diff --git a/src/libextra/comm.rs b/src/libextra/comm.rs index 20ab2d61ecc07..095da6570fd00 100644 --- a/src/libextra/comm.rs +++ b/src/libextra/comm.rs @@ -14,6 +14,8 @@ Higher level communication abstractions. */ +use core::prelude::*; + use core::comm::{GenericChan, GenericSmartChan, GenericPort}; use core::comm::{Chan, Port, Selectable, Peekable}; use core::pipes; diff --git a/src/libextra/deque.rs b/src/libextra/deque.rs index 60f1607417789..371b8ce94e7d0 100644 --- a/src/libextra/deque.rs +++ b/src/libextra/deque.rs @@ -10,6 +10,8 @@ //! A double-ended queue implemented as a circular buffer +use core::prelude::*; + use core::util::replace; static initial_capacity: uint = 32u; // 2^5 diff --git a/src/libextra/dlist.rs b/src/libextra/dlist.rs index 57cd03e16a097..c3ef1f25ad933 100644 --- a/src/libextra/dlist.rs +++ b/src/libextra/dlist.rs @@ -18,6 +18,8 @@ Do not use ==, !=, <, etc on doubly-linked lists -- it may not terminate. */ +use core::prelude::*; + use core::managed; pub type DListLink = Option<@mut DListNode>; diff --git a/src/libextra/ebml.rs b/src/libextra/ebml.rs index a7c18ebf5cdc8..762328a2e0f64 100644 --- a/src/libextra/ebml.rs +++ b/src/libextra/ebml.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + // Simple Extensible Binary Markup Language (ebml) reader and writer on a // cursor model. See the specification here: // http://www.matroska.org/technical/specs/rfc/index.html @@ -65,6 +67,8 @@ pub enum EbmlEncoderTag { // -------------------------------------- pub mod reader { + use core::prelude::*; + use ebml::{Doc, EbmlEncoderTag, EsBool, EsEnum, EsEnumBody, EsEnumVid}; use ebml::{EsI16, EsI32, EsI64, EsI8, EsInt}; use ebml::{EsLabel, EsOpaque, EsStr, EsU16, EsU32, EsU64, EsU8, EsUint}; diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index d9a932fbe7c54..a9024592426fd 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -94,6 +94,8 @@ total line count). } */ +use core::prelude::*; + use core::io::ReaderUtil; /** diff --git a/src/libextra/flate.rs b/src/libextra/flate.rs index b0d219bc945e9..c968bb5768d8b 100644 --- a/src/libextra/flate.rs +++ b/src/libextra/flate.rs @@ -14,9 +14,9 @@ Simple compression */ -use libc; use core::libc::{c_void, size_t, c_int}; -use vec; +use core::libc; +use core::vec; #[cfg(test)] use core::rand; #[cfg(test)] use core::rand::RngUtil; diff --git a/src/libextra/flatpipes.rs b/src/libextra/flatpipes.rs index a634f88dcf577..7c97cabd58910 100644 --- a/src/libextra/flatpipes.rs +++ b/src/libextra/flatpipes.rs @@ -47,6 +47,8 @@ block the scheduler thread, so will their pipes. */ +use core::prelude::*; + // The basic send/recv interface FlatChan and PortChan will implement use core::io; use core::comm::GenericChan; @@ -168,6 +170,8 @@ POD are not equivelant. */ pub mod pod { + use core::prelude::*; + use flatpipes::flatteners::{PodUnflattener, PodFlattener}; use flatpipes::bytepipes::{ReaderBytePort, WriterByteChan}; use flatpipes::bytepipes::{PipeBytePort, PipeByteChan}; @@ -331,6 +335,8 @@ pub impl,C:ByteChan> FlatChan { pub mod flatteners { + use core::prelude::*; + use ebml; use flatpipes::{Flattener, Unflattener}; use io_util::BufReader; @@ -501,6 +507,8 @@ pub mod flatteners { } pub mod bytepipes { + use core::prelude::*; + use flatpipes::{ByteChan, BytePort}; use core::io::{Writer, Reader, ReaderUtil}; @@ -628,6 +636,8 @@ pub mod bytepipes { #[cfg(test)] mod test { + use core::prelude::*; + use flatpipes::{Flattener, Unflattener}; use flatpipes::bytepipes::*; use flatpipes::pod; diff --git a/src/libextra/fun_treemap.rs b/src/libextra/fun_treemap.rs index 6b051fa21b1e5..fb9bb0740c520 100644 --- a/src/libextra/fun_treemap.rs +++ b/src/libextra/fun_treemap.rs @@ -19,6 +19,8 @@ * of features. */ +use core::prelude::*; + use core::cmp::{Eq, Ord}; use core::option::{Some, None}; diff --git a/src/libextra/future.rs b/src/libextra/future.rs index 02828b8eaee9e..f54286b3fdfd7 100644 --- a/src/libextra/future.rs +++ b/src/libextra/future.rs @@ -23,6 +23,8 @@ * ~~~ */ +use core::prelude::*; + use core::cast; use core::cell::Cell; use core::comm::{PortOne, oneshot, send_one, recv_one}; diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index 6a9a60baae6a2..f4779c24a4ab1 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -78,6 +78,8 @@ * ``` */ +use core::prelude::*; + use core::cmp::Eq; use core::result::{Err, Ok}; use core::result; diff --git a/src/libextra/json.rs b/src/libextra/json.rs index 44e965b5c4320..f56da368008d6 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -14,6 +14,8 @@ //! json serialization +use core::prelude::*; + use core::io::{WriterUtil, ReaderUtil}; use core::hashmap::HashMap; diff --git a/src/libextra/list.rs b/src/libextra/list.rs index 3a916233db817..919a4426cead9 100644 --- a/src/libextra/list.rs +++ b/src/libextra/list.rs @@ -10,6 +10,8 @@ //! A standard linked list +use core::prelude::*; + #[deriving(Eq)] pub enum List { Cons(T, @List), diff --git a/src/libextra/md4.rs b/src/libextra/md4.rs index da81f730eda82..f99de89588bf2 100644 --- a/src/libextra/md4.rs +++ b/src/libextra/md4.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use core::str; use core::uint; use core::vec; diff --git a/src/libextra/net_ip.rs b/src/libextra/net_ip.rs index 4f67f1c5f1351..e98c1f26d4c1f 100644 --- a/src/libextra/net_ip.rs +++ b/src/libextra/net_ip.rs @@ -10,6 +10,8 @@ //! Types/fns concerning Internet Protocol (IP), versions 4 & 6 +use core::prelude::*; + use core::libc; use core::comm::{stream, SharedChan}; use core::ptr; @@ -145,6 +147,8 @@ pub fn get_addr(node: &str, iotask: &iotask) } pub mod v4 { + use core::prelude::*; + use net::ip::{IpAddr, Ipv4, ParseAddrErr}; use uv::ll; use uv_ip4_addr = uv::ll::ip4_addr; @@ -246,6 +250,8 @@ pub mod v4 { } } pub mod v6 { + use core::prelude::*; + use net::ip::{IpAddr, Ipv6, ParseAddrErr}; use uv_ip6_addr = uv::ll::ip6_addr; use uv_ip6_name = uv::ll::ip6_name; diff --git a/src/libextra/net_tcp.rs b/src/libextra/net_tcp.rs index db61679890b27..d0a1385b706a5 100644 --- a/src/libextra/net_tcp.rs +++ b/src/libextra/net_tcp.rs @@ -11,6 +11,8 @@ //! High-level interface to libuv's TCP functionality // FIXME #4425: Need FFI fixes +use core::prelude::*; + use future; use future_spawn = future::spawn; use ip = net_ip; diff --git a/src/libextra/net_url.rs b/src/libextra/net_url.rs index fb57c717be960..f6d4d75c49858 100644 --- a/src/libextra/net_url.rs +++ b/src/libextra/net_url.rs @@ -10,6 +10,8 @@ //! Types/fns concerning URLs (see RFC 3986) +use core::prelude::*; + use core::cmp::Eq; use core::io::{Reader, ReaderUtil}; use core::io; diff --git a/src/libextra/num/bigint.rs b/src/libextra/num/bigint.rs index 21685b03c077d..fa7621462ef70 100644 --- a/src/libextra/num/bigint.rs +++ b/src/libextra/num/bigint.rs @@ -16,6 +16,8 @@ A BigUint is represented as an array of BigDigits. A BigInt is a combination of BigUint and Sign. */ +use core::prelude::*; + use core::cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater}; use core::num::{IntConvertible, Zero, One, ToStrRadix, FromStrRadix, Orderable}; diff --git a/src/libextra/num/complex.rs b/src/libextra/num/complex.rs index 41d2b4a101cd5..09bd66232eb04 100644 --- a/src/libextra/num/complex.rs +++ b/src/libextra/num/complex.rs @@ -11,6 +11,8 @@ //! Complex numbers. +use core::prelude::*; + use core::num::{Zero,One,ToStrRadix}; // FIXME #1284: handle complex NaN & infinity etc. This diff --git a/src/libextra/num/rational.rs b/src/libextra/num/rational.rs index d57c642c5a29c..d26ef06ebce17 100644 --- a/src/libextra/num/rational.rs +++ b/src/libextra/num/rational.rs @@ -11,6 +11,8 @@ //! Rational numbers +use core::prelude::*; + use core::num::{Zero,One,ToStrRadix,FromStrRadix,Round}; use core::from_str::FromStr; use super::bigint::BigInt; diff --git a/src/libextra/par.rs b/src/libextra/par.rs index e766d2d3bf090..52e7d517d6e2c 100644 --- a/src/libextra/par.rs +++ b/src/libextra/par.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use future_spawn = future::spawn; /** diff --git a/src/libextra/priority_queue.rs b/src/libextra/priority_queue.rs index f1e0027146c9e..6d41cd653ebff 100644 --- a/src/libextra/priority_queue.rs +++ b/src/libextra/priority_queue.rs @@ -10,6 +10,8 @@ //! A priority queue implemented with a binary heap +use core::prelude::*; + use core::old_iter::BaseIter; use core::unstable::intrinsics::{move_val_init, init}; use core::unstable::intrinsics::uninit; diff --git a/src/libextra/rc.rs b/src/libextra/rc.rs index 02f824b911302..a1a14c31b28e2 100644 --- a/src/libextra/rc.rs +++ b/src/libextra/rc.rs @@ -19,6 +19,8 @@ cycle cannot be created with `Rc` because there is no way to modify it after */ +use core::prelude::*; + use core::libc::{c_void, size_t, malloc, free}; use core::unstable::intrinsics; use core::util; diff --git a/src/libextra/rl.rs b/src/libextra/rl.rs index d15a8fc0136d4..4157442413991 100644 --- a/src/libextra/rl.rs +++ b/src/libextra/rl.rs @@ -11,6 +11,8 @@ // FIXME #3921. This is unsafe because linenoise uses global mutable // state without mutexes. +use core::prelude::*; + use core::libc::{c_char, c_int}; pub mod rustrt { diff --git a/src/libextra/rope.rs b/src/libextra/rope.rs index 04444789f827a..4efe131c7cb06 100644 --- a/src/libextra/rope.rs +++ b/src/libextra/rope.rs @@ -33,6 +33,8 @@ * * access to a character by index is logarithmic (linear in strings); */ +use core::prelude::*; + /// The type of ropes. pub type Rope = node::Root; @@ -439,8 +441,9 @@ pub fn loop_leaves(rope: Rope, it: &fn(node::Leaf) -> bool) -> bool{ pub mod iterator { pub mod leaf { - use rope::{Rope, node}; + use core::prelude::*; + use rope::{Rope, node}; pub fn start(rope: Rope) -> node::leaf_iterator::T { match (rope) { @@ -453,8 +456,9 @@ pub mod iterator { } } pub mod char { - use rope::{Rope, node}; + use core::prelude::*; + use rope::{Rope, node}; pub fn start(rope: Rope) -> node::char_iterator::T { match (rope) { @@ -548,6 +552,8 @@ pub fn char_at(rope: Rope, pos: uint) -> char { Section: Implementation */ pub mod node { + use core::prelude::*; + use rope::node; /// Implementation of type `rope` @@ -1127,6 +1133,8 @@ pub mod node { } pub mod leaf_iterator { + use core::prelude::*; + use rope::node::{Concat, Leaf, Node, height}; pub struct T { @@ -1166,6 +1174,8 @@ pub mod node { } pub mod char_iterator { + use core::prelude::*; + use rope::node::{Leaf, Node}; use rope::node::leaf_iterator; diff --git a/src/libextra/semver.rs b/src/libextra/semver.rs index 09855c9334e58..0b07886772687 100644 --- a/src/libextra/semver.rs +++ b/src/libextra/semver.rs @@ -10,6 +10,8 @@ //! Semver parsing and logic +use core::prelude::*; + use core::char; use core::cmp; use core::io::{ReaderUtil}; diff --git a/src/libextra/serialize.rs b/src/libextra/serialize.rs index c270f46751fcd..749e9d5dc611b 100644 --- a/src/libextra/serialize.rs +++ b/src/libextra/serialize.rs @@ -16,6 +16,8 @@ Core encoding and decoding interfaces. #[forbid(non_camel_case_types)]; +use core::prelude::*; + use core::hashmap::{HashMap, HashSet}; use core::trie::{TrieMap, TrieSet}; use deque::Deque; diff --git a/src/libextra/sha1.rs b/src/libextra/sha1.rs index d7051d734698f..8910442849e37 100644 --- a/src/libextra/sha1.rs +++ b/src/libextra/sha1.rs @@ -22,6 +22,8 @@ * the `reset` method. */ +use core::prelude::*; + use core::str; use core::uint; use core::vec; diff --git a/src/libextra/smallintmap.rs b/src/libextra/smallintmap.rs index aa8372bab78d9..3e5e62894dfc9 100644 --- a/src/libextra/smallintmap.rs +++ b/src/libextra/smallintmap.rs @@ -13,6 +13,8 @@ * are O(highest integer key). */ +use core::prelude::*; + use core::container::{Container, Mutable, Map, Set}; use core::old_iter::BaseIter; use core::old_iter; diff --git a/src/libextra/sort.rs b/src/libextra/sort.rs index d896fa8c096f7..2c4020e776c21 100644 --- a/src/libextra/sort.rs +++ b/src/libextra/sort.rs @@ -10,6 +10,8 @@ //! Sorting methods +use core::prelude::*; + use core::cmp::{Eq, Ord}; use core::vec::len; use core::vec; diff --git a/src/libextra/stats.rs b/src/libextra/stats.rs index 25323b4e1db8e..504930a884ee1 100644 --- a/src/libextra/stats.rs +++ b/src/libextra/stats.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use core::vec; use core::f64; use core::cmp; diff --git a/src/libextra/std.rc b/src/libextra/std.rc index 72f06f0befa25..90672d221c5cb 100644 --- a/src/libextra/std.rc +++ b/src/libextra/std.rc @@ -17,7 +17,7 @@ not required in or otherwise suitable for the core library. */ -#[link(name = "std", +#[link(name = "extra", vers = "0.7-pre", uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297", url = "https://github.com/mozilla/rust/tree/master/src/libstd")]; @@ -28,6 +28,14 @@ not required in or otherwise suitable for the core library. #[deny(non_camel_case_types)]; +#[no_core]; +#[no_std]; + +extern mod core(name = "std", vers = "0.7-pre"); + +use core::{str, unstable}; +use core::str::{StrSlice, OwnedStr}; + pub mod uv_ll; // General io and system-services modules diff --git a/src/libextra/sync.rs b/src/libextra/sync.rs index 002c6b2eca3ee..dc7f891b2593d 100644 --- a/src/libextra/sync.rs +++ b/src/libextra/sync.rs @@ -15,6 +15,8 @@ * in std. */ +use core::prelude::*; + use core::unstable::sync::{Exclusive, exclusive}; use core::ptr; use core::task; diff --git a/src/libextra/task_pool.rs b/src/libextra/task_pool.rs index 0c52e1ff80e21..926045a6b5250 100644 --- a/src/libextra/task_pool.rs +++ b/src/libextra/task_pool.rs @@ -11,6 +11,8 @@ /// A task pool abstraction. Useful for achieving predictable CPU /// parallelism. +use core::prelude::*; + use core::comm::Chan; use core::task::SchedMode; use core::task; diff --git a/src/libextra/tempfile.rs b/src/libextra/tempfile.rs index e02a7a337334e..d7ee326f2ffb5 100644 --- a/src/libextra/tempfile.rs +++ b/src/libextra/tempfile.rs @@ -10,6 +10,8 @@ //! Temporary files and directories +use core::prelude::*; + use core::rand::RngUtil; pub fn mkdtemp(tmpdir: &Path, suffix: &str) -> Option { diff --git a/src/libextra/term.rs b/src/libextra/term.rs index fcac70622104d..7dace57a1b52b 100644 --- a/src/libextra/term.rs +++ b/src/libextra/term.rs @@ -10,6 +10,8 @@ //! Simple ANSI color library +use core::prelude::*; + use core::io; use core::option; use core::os; diff --git a/src/libextra/test.rs b/src/libextra/test.rs index 4046ce83c9dcf..3245ad5d3346f 100644 --- a/src/libextra/test.rs +++ b/src/libextra/test.rs @@ -15,6 +15,8 @@ // simplest interface possible for representing and running tests // while providing a base that other test frameworks may build off of. +use core::prelude::*; + use getopts; use sort; use term; @@ -597,6 +599,8 @@ fn calc_result(desc: &TestDesc, task_succeeded: bool) -> TestResult { } pub mod bench { + use core::prelude::*; + use time::precise_time_ns; use test::{BenchHarness, BenchSamples}; use stats::Stats; diff --git a/src/libextra/time.rs b/src/libextra/time.rs index 565ce2d0dd3b3..624d7d4256a8a 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + static NSEC_PER_SEC: i32 = 1_000_000_000_i32; pub mod rustrt { diff --git a/src/libextra/timer.rs b/src/libextra/timer.rs index 092c718f1ced3..6a36d674279a2 100644 --- a/src/libextra/timer.rs +++ b/src/libextra/timer.rs @@ -10,6 +10,8 @@ //! Utilities that leverage libuv's `uv_timer_*` API +use core::prelude::*; + use uv; use uv::iotask; use uv::iotask::IoTask; diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index 93f8d06ee0836..f4257070e1984 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -12,6 +12,8 @@ //! trees. The only requirement for the types is that the key implements //! `TotalOrd`. +use core::prelude::*; + use core::iterator::*; use core::util::{swap, replace}; diff --git a/src/libextra/uv_global_loop.rs b/src/libextra/uv_global_loop.rs index d1471ba1e7705..e067f22d63832 100644 --- a/src/libextra/uv_global_loop.rs +++ b/src/libextra/uv_global_loop.rs @@ -10,6 +10,8 @@ //! A process-wide libuv event loop for library use. +use core::prelude::*; + use iotask = uv_iotask; use uv_iotask::{IoTask, spawn_iotask}; diff --git a/src/libextra/uv_iotask.rs b/src/libextra/uv_iotask.rs index 371eb338de303..ff726c1464c38 100644 --- a/src/libextra/uv_iotask.rs +++ b/src/libextra/uv_iotask.rs @@ -15,6 +15,8 @@ * `interact` function you can execute code in a uv callback. */ +use core::prelude::*; + use ll = uv_ll; use core::comm::{stream, Port, Chan, SharedChan}; diff --git a/src/libextra/uv_ll.rs b/src/libextra/uv_ll.rs index bc7703ec30a1c..014dea220292f 100644 --- a/src/libextra/uv_ll.rs +++ b/src/libextra/uv_ll.rs @@ -32,6 +32,8 @@ #[allow(non_camel_case_types)]; // C types +use core::prelude::*; + use core::libc::size_t; use core::libc::c_void; use core::ptr::to_unsafe_ptr; diff --git a/src/libextra/workcache.rs b/src/libextra/workcache.rs index ee57bf2f3a1b5..3c10b3d2ca770 100644 --- a/src/libextra/workcache.rs +++ b/src/libextra/workcache.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use json; use sha1; use serialize::{Encoder, Encodable, Decoder, Decodable}; diff --git a/src/libfuzzer/ast_match.rs b/src/libfuzzer/ast_match.rs index 2502830250dbe..d0bbcc024815c 100644 --- a/src/libfuzzer/ast_match.rs +++ b/src/libfuzzer/ast_match.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use std; use vec; diff --git a/src/libfuzzer/cycles.rs b/src/libfuzzer/cycles.rs index a6434d64cdc38..5f7152f109f24 100644 --- a/src/libfuzzer/cycles.rs +++ b/src/libfuzzer/cycles.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use std; use std::rand; use uint::range; diff --git a/src/libfuzzer/fuzzer.rc b/src/libfuzzer/fuzzer.rc index 468f50a0cc1ff..aac6796f30c23 100644 --- a/src/libfuzzer/fuzzer.rc +++ b/src/libfuzzer/fuzzer.rc @@ -20,9 +20,14 @@ #[allow(non_camel_case_types)]; -extern mod std; -extern mod syntax; +#[no_std]; +extern mod core(name = "std", vers = "0.7-pre"); +extern mod std(name = "extra", vers = "0.7-pre"); + +extern mod syntax(vers = "0.7-pre"); + +use core::prelude::*; use core::run; use syntax::diagnostic; diff --git a/src/libfuzzer/ivec_fuzz.rs b/src/libfuzzer/ivec_fuzz.rs index 25dc14c3d7888..d0f83d4ba5428 100644 --- a/src/libfuzzer/ivec_fuzz.rs +++ b/src/libfuzzer/ivec_fuzz.rs @@ -28,7 +28,8 @@ vec_edits is not an iter because iters might go away. */ -extern mod std; +use core::prelude::*; + use vec::slice; use vec::len; diff --git a/src/libfuzzer/rand_util.rs b/src/libfuzzer/rand_util.rs index c239e8ab9332e..32197ba2195ec 100644 --- a/src/libfuzzer/rand_util.rs +++ b/src/libfuzzer/rand_util.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +use core::prelude::*; use std::rand; // random uint less than n diff --git a/src/librust/rust.rc b/src/librust/rust.rc index 7b3585af9b4ab..f1d92f1d9576e 100644 --- a/src/librust/rust.rc +++ b/src/librust/rust.rc @@ -20,11 +20,17 @@ #[license = "MIT/ASL2"]; #[crate_type = "lib"]; +#[no_std]; + +extern mod core(name = "std"); + extern mod rustpkg; extern mod rustdoc; extern mod rusti; extern mod rustc; +use core::prelude::*; + use core::run; enum ValidUsage { diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index f999c20a7d0ec..42ce18cf88b68 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::rpath; use driver::session::Session; use driver::session; @@ -90,6 +92,8 @@ pub fn WriteOutputFile(sess: Session, } pub mod jit { + use core::prelude::*; + use back::link::llvm_err; use driver::session::Session; use lib::llvm::llvm; @@ -166,6 +170,8 @@ pub mod jit { } pub mod write { + use core::prelude::*; + use back::link::jit; use back::link::{WriteOutputFile, output_type}; use back::link::{output_type_assembly, output_type_bitcode}; diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 0dd37f0b9070a..f3e01a00e38aa 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use driver::session; use metadata::cstore; use metadata::filesearch; diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 837d3c285aaaa..a3f47d398fb7c 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::link; use back::{arm, x86, x86_64, mips}; use driver::session::{Aggressive}; diff --git a/src/librustc/driver/session.rs b/src/librustc/driver/session.rs index a340422d02311..788be3a3f2799 100644 --- a/src/librustc/driver/session.rs +++ b/src/librustc/driver/session.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::link; use back::target_strs; use back; diff --git a/src/librustc/front/config.rs b/src/librustc/front/config.rs index 6341b1c155cca..be2f5cf0f6138 100644 --- a/src/librustc/front/config.rs +++ b/src/librustc/front/config.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use syntax::{ast, fold, attr}; type in_cfg_pred = @fn(attrs: ~[ast::attribute]) -> bool; diff --git a/src/librustc/front/intrinsic_inject.rs b/src/librustc/front/intrinsic_inject.rs index fd26971629580..7a8a2a7eb9799 100644 --- a/src/librustc/front/intrinsic_inject.rs +++ b/src/librustc/front/intrinsic_inject.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use driver::session::Session; use syntax::parse; use syntax::ast; diff --git a/src/librustc/front/std_inject.rs b/src/librustc/front/std_inject.rs index e84f552fd1ce9..616b1cb98157a 100644 --- a/src/librustc/front/std_inject.rs +++ b/src/librustc/front/std_inject.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use driver::session::Session; use syntax::ast; diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index a0ff8cb5e4d24..2bc648814a31b 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -10,6 +10,8 @@ // Code that generates a test runner to run all the tests in a crate +use core::prelude::*; + use driver::session; use front::config; diff --git a/src/librustc/lib/llvm.rs b/src/librustc/lib/llvm.rs index 160f375897b82..ac675df3399e5 100644 --- a/src/librustc/lib/llvm.rs +++ b/src/librustc/lib/llvm.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use core::hashmap::HashMap; use core::libc::{c_uint, c_ushort}; diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index d40257879d0ec..55689d8df4e4b 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -8,9 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - //! Validates all used crates and extern libraries and loads their metadata +use core::prelude::*; + use metadata::cstore; use metadata::decoder; use metadata::filesearch::FileSearch; diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index b21417f5100c6..c887b2553f741 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -10,6 +10,8 @@ // Searching for information from the cstore +use core::prelude::*; + use metadata::common::*; use metadata::cstore; use metadata::decoder; diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 21815a9ed4718..0c0f094731459 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -12,6 +12,8 @@ // The crate store - a central repo for information collected about external // crates and libraries +use core::prelude::*; + use metadata::cstore; use metadata::decoder; diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index d6e7e64e4f801..ef9c945306264 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -10,6 +10,8 @@ // Decoding metadata from a single crate's metadata +use core::prelude::*; + use metadata::cstore::crate_metadata; use metadata::common::*; use metadata::csearch::{ProvidedTraitMethodInfo, StaticMethodInfo}; diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 297b0408dc524..e959983a98a10 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -10,6 +10,8 @@ // Metadata encoding +use core::prelude::*; + use metadata::common::*; use metadata::cstore; use metadata::decoder; diff --git a/src/librustc/metadata/filesearch.rs b/src/librustc/metadata/filesearch.rs index 7a7ee03b705fd..0d9b16d31171c 100644 --- a/src/librustc/metadata/filesearch.rs +++ b/src/librustc/metadata/filesearch.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + // A module for searching for libraries // FIXME (#2658): I'm not happy how this module turned out. Should // probably just be folded into cstore. diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 75639e8c689e1..c29a644c123f0 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -8,9 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. - //! Finds crate binaries and loads their metadata +use core::prelude::*; + use lib::llvm::{False, llvm, mk_object_file, mk_section_iter}; use metadata::decoder; use metadata::encoder; diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index ad5bd2447a6f0..a726ca4bd52a6 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -14,6 +14,8 @@ // tjc note: Would be great to have a `match check` macro equivalent // for some of these +use core::prelude::*; + use middle::ty; use syntax::abi::AbiSet; diff --git a/src/librustc/metadata/tyencode.rs b/src/librustc/metadata/tyencode.rs index b1be0fb599eea..bc9edcfeed383 100644 --- a/src/librustc/metadata/tyencode.rs +++ b/src/librustc/metadata/tyencode.rs @@ -10,6 +10,8 @@ // Type encoding +use core::prelude::*; + use middle::ty::param_ty; use middle::ty; diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 5188f464504a6..3bade41d0321d 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use c = metadata::common; use cstore = metadata::cstore; use driver::session::Session; diff --git a/src/librustc/middle/borrowck/check_loans.rs b/src/librustc/middle/borrowck/check_loans.rs index ce9027e257958..237a464dc9e96 100644 --- a/src/librustc/middle/borrowck/check_loans.rs +++ b/src/librustc/middle/borrowck/check_loans.rs @@ -17,6 +17,8 @@ // 3. assignments do not affect things loaned out as immutable // 4. moves do not affect things loaned out in any way +use core::prelude::*; + use middle::moves; use middle::borrowck::*; use mc = middle::mem_categorization; diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index faa489e5763f6..345b128239fc2 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use driver::session::Session; use middle::resolve; use middle::ty; diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 3717c6134726d..db5bdf85cb5d8 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::const_eval::{compare_const_vals, lookup_const_by_id}; use middle::const_eval::{eval_const_expr, const_val, const_bool}; use middle::pat_util::*; diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 751767fb58c14..49d31d240ecc3 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use metadata::csearch; use middle::astencode; use middle::ty; diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 9c9f72adc4df2..5898b6a5e4d15 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -16,6 +16,8 @@ * GEN and KILL bits for each expression. */ +use core::prelude::*; + use core::cast; use core::uint; use syntax::ast; diff --git a/src/librustc/middle/entry.rs b/src/librustc/middle/entry.rs index e478f29adf90a..b35ec2579d1d9 100644 --- a/src/librustc/middle/entry.rs +++ b/src/librustc/middle/entry.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use driver::session; use driver::session::Session; use syntax::parse::token::special_idents; diff --git a/src/librustc/middle/freevars.rs b/src/librustc/middle/freevars.rs index 872ad83b7391c..9dffd09e5481f 100644 --- a/src/librustc/middle/freevars.rs +++ b/src/librustc/middle/freevars.rs @@ -11,6 +11,8 @@ // A pass that annotates for each loops and functions with the free // variables that they contain. +use core::prelude::*; + use middle::resolve; use middle::ty; diff --git a/src/librustc/middle/kind.rs b/src/librustc/middle/kind.rs index bade18e1787a1..a03191e2c4dae 100644 --- a/src/librustc/middle/kind.rs +++ b/src/librustc/middle/kind.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::freevars::freevar_entry; use middle::freevars; use middle::pat_util; diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 24ee587b2f986..3a0f6f5c10aa4 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -19,6 +19,8 @@ // // * Functions called by the compiler itself. +use core::prelude::*; + use driver::session::Session; use metadata::csearch::each_lang_item; use metadata::cstore::iter_crate_data; diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index b14197649379b..11d1f5bd7d2df 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -8,6 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + +use driver::session::Session; use driver::session; use middle::ty; use middle::pat_util; diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 4608f773a1c26..e4b93468c2938 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -102,6 +102,7 @@ * to return explicitly. */ +use core::prelude::*; use middle::lint::{unused_variable, dead_assignment}; use middle::pat_util; diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index c9ec10ed30aa4..52c7bf0a21e7d 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -46,6 +46,8 @@ * then an index to jump forward to the relevant item. */ +use core::prelude::*; + use middle::ty; use middle::typeck; use util::ppaux::{ty_to_str, region_to_str, Repr}; diff --git a/src/librustc/middle/moves.rs b/src/librustc/middle/moves.rs index e81a9d6b78fcd..3b20344b3ead3 100644 --- a/src/librustc/middle/moves.rs +++ b/src/librustc/middle/moves.rs @@ -206,6 +206,8 @@ and so on. */ +use core::prelude::*; + use middle::pat_util::{pat_bindings}; use middle::freevars; use middle::ty; diff --git a/src/librustc/middle/pat_util.rs b/src/librustc/middle/pat_util.rs index b87adb75bc37a..1fd6012143b57 100644 --- a/src/librustc/middle/pat_util.rs +++ b/src/librustc/middle/pat_util.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::resolve; use core::hashmap::HashMap; diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 6ce074b526492..5f88c25653d60 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -11,6 +11,8 @@ // A pass that checks to make sure private fields and methods aren't used // outside their scopes. +use core::prelude::*; + use metadata::csearch; use middle::ty::{ty_struct, ty_enum}; use middle::ty; diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index cbe9e908da4f9..1731ced634f29 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -17,6 +17,8 @@ region parameterized. */ +use core::prelude::*; + use driver::session::Session; use metadata::csearch; use middle::resolve; diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 306671641a384..b2ef0c46afb08 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use driver::session::Session; use metadata::csearch::{each_path, get_trait_method_def_ids}; use metadata::csearch::get_method_name_and_explicit_self; diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index 5c7c33d35b238..fba174c68405d 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -10,6 +10,8 @@ // Type substitutions. +use core::prelude::*; + use middle::ty; use util::ppaux::Repr; diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index c7f2da9232961..9365a698a7e14 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -142,6 +142,8 @@ * */ +use core::prelude::*; + use back::abi; use lib::llvm::{llvm, ValueRef, BasicBlockRef}; use middle::const_eval; diff --git a/src/librustc/middle/trans/asm.rs b/src/librustc/middle/trans/asm.rs index 9211939cd2af7..e2baabc5baa49 100644 --- a/src/librustc/middle/trans/asm.rs +++ b/src/librustc/middle/trans/asm.rs @@ -12,6 +12,8 @@ # Translation of inline assembly. */ +use core::prelude::*; + use lib; use middle::trans::build::*; use middle::trans::callee; diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 17d3e2c4dfefe..605bd72d8d7f1 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -23,6 +23,8 @@ // but many TypeRefs correspond to one ty::t; for instance, tup(int, int, // int) and rec(x=int, y=int, z=int) will have the same TypeRef. +use core::prelude::*; + use back::link::{mangle_exported_name}; use back::{link, abi, upcall}; use driver::session; diff --git a/src/librustc/middle/trans/build.rs b/src/librustc/middle/trans/build.rs index 965516d8983cb..0411aad32c33b 100644 --- a/src/librustc/middle/trans/build.rs +++ b/src/librustc/middle/trans/build.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use lib::llvm::llvm; use lib::llvm::{CallConv, AtomicBinOp, AtomicOrdering, AsmDialect}; use lib::llvm::{Opcode, IntPredicate, RealPredicate, False}; diff --git a/src/librustc/middle/trans/cabi_mips.rs b/src/librustc/middle/trans/cabi_mips.rs index a1f54c2d1827f..2282952ab88b2 100644 --- a/src/librustc/middle/trans/cabi_mips.rs +++ b/src/librustc/middle/trans/cabi_mips.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use core::libc::c_uint; use lib::llvm::{llvm, TypeRef, Integer, Pointer, Float, Double}; use lib::llvm::{Struct, Array, Attribute}; diff --git a/src/librustc/middle/trans/cabi_x86.rs b/src/librustc/middle/trans/cabi_x86.rs index 3a45b281543cf..fbb605330245c 100644 --- a/src/librustc/middle/trans/cabi_x86.rs +++ b/src/librustc/middle/trans/cabi_x86.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use driver::session::{os_win32, os_macos}; use lib::llvm::*; use lib::llvm::llvm::*; diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index 6fbefb1d8aeda..3d4649bba4660 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -16,6 +16,8 @@ // and methods are represented as just a fn ptr and not a full // closure. +use core::prelude::*; + use back::abi; use driver::session; use lib; diff --git a/src/librustc/middle/trans/closure.rs b/src/librustc/middle/trans/closure.rs index 3a14d72e9bfdb..57df27ef19913 100644 --- a/src/librustc/middle/trans/closure.rs +++ b/src/librustc/middle/trans/closure.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::abi; use back::link::{mangle_internal_name_by_path_and_seq}; use lib::llvm::{llvm, ValueRef}; diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 5da664b696927..fac155a70024d 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -8,11 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +//! Code that is useful in various trans modules. -/** - Code that is useful in various trans modules. - -*/ +use core::prelude::*; use back::{abi, upcall}; use driver::session; diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index ac85a9f5eaca9..97ccb6d7908a4 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::abi; use lib::llvm::{llvm, ConstFCmp, ConstICmp, SetLinkage, PrivateLinkage, ValueRef, TypeRef, Bool, True, False}; diff --git a/src/librustc/middle/trans/controlflow.rs b/src/librustc/middle/trans/controlflow.rs index a1b673be66785..efe23aee9e6bf 100644 --- a/src/librustc/middle/trans/controlflow.rs +++ b/src/librustc/middle/trans/controlflow.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::link; use lib; use lib::llvm::*; diff --git a/src/librustc/middle/trans/datum.rs b/src/librustc/middle/trans/datum.rs index 4a9a907d5b7c0..6be5dbe1beb6c 100644 --- a/src/librustc/middle/trans/datum.rs +++ b/src/librustc/middle/trans/datum.rs @@ -85,6 +85,8 @@ * methods themselves. Most are only suitable for some types of * values. */ +use core::prelude::*; + use lib; use lib::llvm::ValueRef; use middle::trans::adt; diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 0582853d9e1a7..979559ad48109 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use driver::session; use lib::llvm::ValueRef; diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 9349c2bcd26f3..d581d8043f8e4 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -119,6 +119,8 @@ lvalues are *never* stored by value. */ +use core::prelude::*; + use back::abi; use lib::llvm::{ValueRef, TypeRef, llvm}; use lib; diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index 0ed0eb31c0b27..460d7407e5069 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::{link, abi}; use lib::llvm::{SequentiallyConsistent, Acquire, Release, Xchg}; use lib::llvm::{TypeRef, ValueRef}; diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index b731d0f93b75d..8dc97b5c35d83 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -12,6 +12,8 @@ // // Code relating to taking, dropping, etc as well as type descriptors. +use core::prelude::*; + use back::abi; use back::link::*; use driver::session; diff --git a/src/librustc/middle/trans/inline.rs b/src/librustc/middle/trans/inline.rs index 8c88119107f78..aa4bb775323c7 100644 --- a/src/librustc/middle/trans/inline.rs +++ b/src/librustc/middle/trans/inline.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use metadata::csearch; use middle::astencode; use middle::trans::base::{get_insn_ctxt}; diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index 7633c9069565c..baa0dfc79e9fc 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::abi; use lib::llvm::llvm; use lib::llvm::ValueRef; diff --git a/src/librustc/middle/trans/monomorphize.rs b/src/librustc/middle/trans/monomorphize.rs index f07cf58c6e9b6..1b3150f14b208 100644 --- a/src/librustc/middle/trans/monomorphize.rs +++ b/src/librustc/middle/trans/monomorphize.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use back::link::mangle_exported_name; use driver::session; use lib::llvm::ValueRef; diff --git a/src/librustc/middle/trans/reachable.rs b/src/librustc/middle/trans/reachable.rs index 471d8218ec4e7..62360771f55ac 100644 --- a/src/librustc/middle/trans/reachable.rs +++ b/src/librustc/middle/trans/reachable.rs @@ -15,6 +15,7 @@ // makes all other generics or inline functions that it references // reachable as well. +use core::prelude::*; use middle::resolve; use middle::ty; diff --git a/src/librustc/middle/trans/type_of.rs b/src/librustc/middle/trans/type_of.rs index 10c2a21e288bf..bddcb9a1d7377 100644 --- a/src/librustc/middle/trans/type_of.rs +++ b/src/librustc/middle/trans/type_of.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use lib::llvm::llvm; use lib::llvm::{TypeRef}; use middle::trans::adt; diff --git a/src/librustc/middle/trans/write_guard.rs b/src/librustc/middle/trans/write_guard.rs index 281e592f31e59..ffcef3ae78c1b 100644 --- a/src/librustc/middle/trans/write_guard.rs +++ b/src/librustc/middle/trans/write_guard.rs @@ -14,6 +14,8 @@ //! and for each in debugging (e.g., so you can use //! `RUST_LOG=rustc::middle::trans::write_guard`). +use core::prelude::*; + use lib::llvm::ValueRef; use middle::borrowck::{RootInfo, root_map_key, DynaImm, DynaMut}; use middle::trans::base::*; diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 2067431a9ef47..734c9ac04775d 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use driver::session; use metadata::csearch; diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index 222493b056456..5cc2b0dceddc1 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -52,6 +52,8 @@ * an rptr (`&r.T`) use the region `r` that appears in the rptr. */ +use core::prelude::*; + use middle::const_eval; use middle::ty::{substs}; use middle::ty::{ty_param_substs_and_ty}; diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index d6ef27ab7ff0c..77b10663ac790 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::pat_util::{PatIdMap, pat_id_map, pat_is_binding, pat_is_const}; use middle::ty; use middle::typeck::check::demand; diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index 7655212d9d64e..a34465db7cd43 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -79,6 +79,8 @@ obtained the type `Foo`, we would never match this method. */ +use core::prelude::*; + use middle::resolve; use middle::ty::*; use middle::ty; diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index cd58dc5fe48df..226d7fa7651d7 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -76,6 +76,8 @@ type parameter). */ +use core::prelude::*; + use middle::const_eval; use middle::pat_util::pat_id_map; use middle::pat_util; diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index 3f3df7bf83824..642022c5b8ff9 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -27,6 +27,8 @@ this point a bit better. */ +use core::prelude::*; + use middle::freevars::get_freevars; use middle::ty::{re_scope}; use middle::ty; @@ -778,6 +780,8 @@ pub mod guarantor { * but more special purpose. */ + use core::prelude::*; + use middle::typeck::check::regionck::{Rcx, infallibly_mk_subr}; use middle::typeck::check::regionck::mk_subregion_due_to_derefence; use middle::ty; diff --git a/src/librustc/middle/typeck/check/regionmanip.rs b/src/librustc/middle/typeck/check/regionmanip.rs index 87b105e3c7d4d..89cf3df6fedf9 100644 --- a/src/librustc/middle/typeck/check/regionmanip.rs +++ b/src/librustc/middle/typeck/check/regionmanip.rs @@ -10,6 +10,8 @@ // #[warn(deprecated_mode)]; +use core::prelude::*; + use middle::ty; use middle::typeck::isr_alist; diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc/middle/typeck/check/vtable.rs index 2e2b4550f6331..67d7b064115ee 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc/middle/typeck/check/vtable.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::resolve::Impl; use middle::ty::param_ty; use middle::ty; diff --git a/src/librustc/middle/typeck/check/writeback.rs b/src/librustc/middle/typeck/check/writeback.rs index 394d00bef2d44..29c1eaa28389b 100644 --- a/src/librustc/middle/typeck/check/writeback.rs +++ b/src/librustc/middle/typeck/check/writeback.rs @@ -12,6 +12,8 @@ // unresolved type variables and replaces "ty_var" types with their // substitutions. +use core::prelude::*; + use middle::pat_util; use middle::ty; use middle::typeck::check::{FnCtxt, SelfInfo}; diff --git a/src/librustc/middle/typeck/coherence.rs b/src/librustc/middle/typeck/coherence.rs index 8870f0fdc57f0..14a4034c6bb34 100644 --- a/src/librustc/middle/typeck/coherence.rs +++ b/src/librustc/middle/typeck/coherence.rs @@ -14,6 +14,7 @@ // has at most one implementation for each type. Then we build a mapping from // each trait in the system to its implementations. +use core::prelude::*; use driver; use metadata::csearch::{each_path, get_impl_trait}; diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc/middle/typeck/collect.rs index 6c7f73177fadf..b3b59c2fc9ee1 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc/middle/typeck/collect.rs @@ -30,6 +30,8 @@ are represented as `ty_param()` instances. */ +use core::prelude::*; + use metadata::csearch; use middle::ty::{substs, ty_param_bounds_and_ty}; use middle::ty; diff --git a/src/librustc/middle/typeck/infer/coercion.rs b/src/librustc/middle/typeck/infer/coercion.rs index 3620b609edf3b..64f0d439223b7 100644 --- a/src/librustc/middle/typeck/infer/coercion.rs +++ b/src/librustc/middle/typeck/infer/coercion.rs @@ -64,6 +64,8 @@ we may want to adjust precisely when coercions occur. */ +use core::prelude::*; + use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowFn}; use middle::ty::{AutoDerefRef}; use middle::ty::{vstore_slice, vstore_box, vstore_uniq}; diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/typeck/infer/combine.rs index b318e6ff3f6b6..d07752ee20a19 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/typeck/infer/combine.rs @@ -54,6 +54,8 @@ // terms of error reporting, although we do not do that properly right // now. +use core::prelude::*; + use middle::ty::{FloatVar, FnSig, IntVar, TyVar}; use middle::ty::{IntType, UintType, substs}; use middle::ty::{BuiltinBounds}; diff --git a/src/librustc/middle/typeck/infer/glb.rs b/src/librustc/middle/typeck/infer/glb.rs index 9ade6de6cf4fd..78989a1337634 100644 --- a/src/librustc/middle/typeck/infer/glb.rs +++ b/src/librustc/middle/typeck/infer/glb.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::ty::{BuiltinBounds}; use middle::ty::RegionVid; use middle::ty; diff --git a/src/librustc/middle/typeck/infer/lattice.rs b/src/librustc/middle/typeck/infer/lattice.rs index 57bab29664da8..81befc5f65066 100644 --- a/src/librustc/middle/typeck/infer/lattice.rs +++ b/src/librustc/middle/typeck/infer/lattice.rs @@ -32,6 +32,8 @@ * a lattice. */ +use core::prelude::*; + use middle::ty::{RegionVid, TyVar, Vid}; use middle::ty; use middle::typeck::isr_alist; diff --git a/src/librustc/middle/typeck/infer/lub.rs b/src/librustc/middle/typeck/infer/lub.rs index 82fd4e3ae6dd6..c906d3ef4951b 100644 --- a/src/librustc/middle/typeck/infer/lub.rs +++ b/src/librustc/middle/typeck/infer/lub.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::ty::{BuiltinBounds}; use middle::ty::RegionVid; use middle::ty; diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/typeck/infer/mod.rs index 2c42914f4b551..864f0e24eeb53 100644 --- a/src/librustc/middle/typeck/infer/mod.rs +++ b/src/librustc/middle/typeck/infer/mod.rs @@ -242,6 +242,8 @@ section on "Type Combining" below for details. */ +use core::prelude::*; + pub use middle::ty::IntVarValue; pub use middle::typeck::infer::resolve::resolve_and_force_all_but_regions; pub use middle::typeck::infer::resolve::{force_all, not_regions}; diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index 0a38e021879cb..14a79108f0646 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -536,6 +536,8 @@ more convincing in the future. */ +use core::prelude::*; + use middle::ty; use middle::ty::{FreeRegion, Region, RegionVid}; use middle::ty::{re_empty, re_static, re_infer, re_free, re_bound}; diff --git a/src/librustc/middle/typeck/infer/resolve.rs b/src/librustc/middle/typeck/infer/resolve.rs index 2b88825c49a69..217d9716f7dd5 100644 --- a/src/librustc/middle/typeck/infer/resolve.rs +++ b/src/librustc/middle/typeck/infer/resolve.rs @@ -46,6 +46,8 @@ // future). If you want to resolve everything but one type, you are // probably better off writing `resolve_all - resolve_ivar`. +use core::prelude::*; + use middle::ty::{FloatVar, FloatVid, IntVar, IntVid, RegionVid, TyVar, TyVid}; use middle::ty::{type_is_bot, IntType, UintType}; use middle::ty; diff --git a/src/librustc/middle/typeck/infer/sub.rs b/src/librustc/middle/typeck/infer/sub.rs index 8da3d7bfa000d..11fac4d5414c0 100644 --- a/src/librustc/middle/typeck/infer/sub.rs +++ b/src/librustc/middle/typeck/infer/sub.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::ty::{BuiltinBounds}; use middle::ty; use middle::ty::TyVar; diff --git a/src/librustc/middle/typeck/infer/to_str.rs b/src/librustc/middle/typeck/infer/to_str.rs index d9088c064939b..888339b707d27 100644 --- a/src/librustc/middle/typeck/infer/to_str.rs +++ b/src/librustc/middle/typeck/infer/to_str.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::ty::{FnSig, Vid}; use middle::ty::IntVarValue; use middle::ty; diff --git a/src/librustc/middle/typeck/infer/unify.rs b/src/librustc/middle/typeck/infer/unify.rs index d6e652592d835..39feedfce8bca 100644 --- a/src/librustc/middle/typeck/infer/unify.rs +++ b/src/librustc/middle/typeck/infer/unify.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use std::smallintmap::SmallIntMap; use middle::ty::{Vid, expected_found, IntVarValue}; diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index 048a6588ba2c5..8684b1b03e865 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -48,6 +48,8 @@ independently: */ +use core::prelude::*; + use driver::session; use middle::resolve; diff --git a/src/librustc/middle/typeck/rscope.rs b/src/librustc/middle/typeck/rscope.rs index 7c37784b09db9..1f787e14f189e 100644 --- a/src/librustc/middle/typeck/rscope.rs +++ b/src/librustc/middle/typeck/rscope.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use middle::ty; use syntax::ast; diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index a21c5dc7b36e0..f1263be6b4b54 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -21,9 +21,15 @@ #[allow(non_camel_case_types)]; #[deny(deprecated_pattern)]; -extern mod std; +#[no_core]; +#[no_std]; + +extern mod core(name = "std"); +extern mod std(name = "extra"); extern mod syntax; +use core::prelude::*; + use driver::driver::{host_triple, optgroups, early_error}; use driver::driver::{str_input, file_input, build_session_options}; use driver::driver::{build_session, build_configuration, parse_pretty}; diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index b4a479fc5970f..7bd8c6aadf23c 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use syntax::ast; use syntax::codemap::{span}; use syntax::visit; diff --git a/src/librustc/util/enum_set.rs b/src/librustc/util/enum_set.rs index 49750c5690955..048b602e81888 100644 --- a/src/librustc/util/enum_set.rs +++ b/src/librustc/util/enum_set.rs @@ -8,6 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + +use core; + #[deriving(Eq, IterBytes)] pub struct EnumSet { // We must maintain the invariant that no bits are set diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 06adb6cc364af..384298da92e27 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use metadata::encoder; use middle::ty::{ReSkolemized, ReVar}; use middle::ty::{bound_region, br_anon, br_named, br_self, br_cap_avoid}; diff --git a/src/librustdoc/astsrv.rs b/src/librustdoc/astsrv.rs index 47c99a8d9b773..21ce70e7f5f6e 100644 --- a/src/librustdoc/astsrv.rs +++ b/src/librustdoc/astsrv.rs @@ -17,6 +17,8 @@ query AST-related information, shielding the rest of Rustdoc from its non-sendableness. */ +use core::prelude::*; + use parse; use core::cell::Cell; diff --git a/src/librustdoc/attr_parser.rs b/src/librustdoc/attr_parser.rs index ec31795337bb5..92e2973acb6f6 100644 --- a/src/librustdoc/attr_parser.rs +++ b/src/librustdoc/attr_parser.rs @@ -15,6 +15,8 @@ The attribute parser provides methods for pulling documentation out of an AST's attributes. */ +use core::prelude::*; + use syntax::ast; use syntax::attr; diff --git a/src/librustdoc/attr_pass.rs b/src/librustdoc/attr_pass.rs index 35cbe394b86a3..e49e9b27d41ed 100644 --- a/src/librustdoc/attr_pass.rs +++ b/src/librustdoc/attr_pass.rs @@ -16,6 +16,8 @@ corresponding AST nodes. The information gathered here is the basis of the natural-language documentation for a crate. */ +use core::prelude::*; + use astsrv; use attr_parser; use doc::ItemUtils; diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 7464b708045af..85ceb6cccb749 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use core::cell::Cell; use core::run; diff --git a/src/librustdoc/demo.rs b/src/librustdoc/demo.rs index 7cbd92292c198..c5fb8f289f65e 100644 --- a/src/librustdoc/demo.rs +++ b/src/librustdoc/demo.rs @@ -21,6 +21,8 @@ * tests on this file */ +use core::prelude::*; + /// The base price of a muffin on a non-holiday static price_of_a_muffin: float = 70f; diff --git a/src/librustdoc/desc_to_brief_pass.rs b/src/librustdoc/desc_to_brief_pass.rs index c61b38743fd1f..1066f9e924a04 100644 --- a/src/librustdoc/desc_to_brief_pass.rs +++ b/src/librustdoc/desc_to_brief_pass.rs @@ -15,6 +15,8 @@ If the first paragraph of a long description is short enough then it is interpreted as the brief description. */ +use core::prelude::*; + use astsrv; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/doc.rs b/src/librustdoc/doc.rs index 1656eb0309812..b383a41a91c8d 100644 --- a/src/librustdoc/doc.rs +++ b/src/librustdoc/doc.rs @@ -10,6 +10,8 @@ //! The document model +use core::prelude::*; + use doc; pub type AstId = int; diff --git a/src/librustdoc/extract.rs b/src/librustdoc/extract.rs index e3da6e6844e52..2ebdd82165a40 100644 --- a/src/librustdoc/extract.rs +++ b/src/librustdoc/extract.rs @@ -10,6 +10,8 @@ //! Converts the Rust AST to the rustdoc document model +use core::prelude::*; + use astsrv; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/fold.rs b/src/librustdoc/fold.rs index 4c120aed91161..5bd394215a994 100644 --- a/src/librustdoc/fold.rs +++ b/src/librustdoc/fold.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use doc; #[cfg(test)] use extract; #[cfg(test)] use parse; diff --git a/src/librustdoc/markdown_index_pass.rs b/src/librustdoc/markdown_index_pass.rs index c7329c4a54b5e..9d55452acdfda 100644 --- a/src/librustdoc/markdown_index_pass.rs +++ b/src/librustdoc/markdown_index_pass.rs @@ -10,6 +10,8 @@ //! Build indexes as appropriate for the markdown pass +use core::prelude::*; + use astsrv; use config; use doc::ItemUtils; diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index 4f4bb4194a897..ff7955768d333 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -10,6 +10,8 @@ //! Generate markdown from a document tree +use core::prelude::*; + use astsrv; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/markdown_writer.rs b/src/librustdoc/markdown_writer.rs index 671364f4dbb34..b585b294b0d3e 100644 --- a/src/librustdoc/markdown_writer.rs +++ b/src/librustdoc/markdown_writer.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use config; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/page_pass.rs b/src/librustdoc/page_pass.rs index 02716ff73b6b3..f0d4c62960f86 100644 --- a/src/librustdoc/page_pass.rs +++ b/src/librustdoc/page_pass.rs @@ -15,6 +15,8 @@ Each page corresponds is a logical section. There may be pages for individual modules, pages for the crate, indexes, etc. */ +use core::prelude::*; + use astsrv; use config; use doc::ItemUtils; diff --git a/src/librustdoc/parse.rs b/src/librustdoc/parse.rs index 1f4133592f242..455720f47ef90 100644 --- a/src/librustdoc/parse.rs +++ b/src/librustdoc/parse.rs @@ -10,6 +10,8 @@ //! AST-parsing helpers +use core::prelude::*; + use rustc::driver::driver::{file_input, str_input}; use rustc::driver::driver; use rustc::driver::session; diff --git a/src/librustdoc/pass.rs b/src/librustdoc/pass.rs index 6527481d514c7..85eb5dc77aa27 100644 --- a/src/librustdoc/pass.rs +++ b/src/librustdoc/pass.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use astsrv; use doc; use time; diff --git a/src/librustdoc/path_pass.rs b/src/librustdoc/path_pass.rs index a31a8ac5933de..a7a36152ace39 100644 --- a/src/librustdoc/path_pass.rs +++ b/src/librustdoc/path_pass.rs @@ -10,6 +10,8 @@ //! Records the full path to items +use core::prelude::*; + use astsrv; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/prune_private_pass.rs b/src/librustdoc/prune_private_pass.rs index 9dfcc7c4ec692..26344ebbc6139 100644 --- a/src/librustdoc/prune_private_pass.rs +++ b/src/librustdoc/prune_private_pass.rs @@ -10,6 +10,8 @@ //! Prune things that are private +use core::prelude::*; + use extract; use syntax::ast; use syntax::ast_map; diff --git a/src/librustdoc/rustdoc.rc b/src/librustdoc/rustdoc.rc index fed8bc0e97209..9b73e393cb235 100644 --- a/src/librustdoc/rustdoc.rc +++ b/src/librustdoc/rustdoc.rc @@ -21,10 +21,16 @@ #[allow(non_implicitly_copyable_typarams)]; -extern mod std; +#[no_std]; + +extern mod core(name = "std"); +extern mod std(name = "extra"); + extern mod rustc; extern mod syntax; +use core::prelude::*; + use config::Config; use doc::Item; use doc::ItemUtils; diff --git a/src/librustdoc/sectionalize_pass.rs b/src/librustdoc/sectionalize_pass.rs index afd29ab724867..6333e2878793f 100644 --- a/src/librustdoc/sectionalize_pass.rs +++ b/src/librustdoc/sectionalize_pass.rs @@ -10,6 +10,8 @@ //! Breaks rustdocs into sections according to their headers +use core::prelude::*; + use astsrv; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/text_pass.rs b/src/librustdoc/text_pass.rs index 3b1a2059622b6..e6c6118a76589 100644 --- a/src/librustdoc/text_pass.rs +++ b/src/librustdoc/text_pass.rs @@ -10,6 +10,8 @@ //! Generic pass for performing an operation on all descriptions +use core::prelude::*; + use astsrv; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/tystr_pass.rs b/src/librustdoc/tystr_pass.rs index 12689466c8c32..941faf32d3675 100644 --- a/src/librustdoc/tystr_pass.rs +++ b/src/librustdoc/tystr_pass.rs @@ -10,6 +10,8 @@ //! Pulls type information out of the AST and attaches it to the document +use core::prelude::*; + use astsrv; use doc::ItemUtils; use doc; diff --git a/src/librustdoc/unindent_pass.rs b/src/librustdoc/unindent_pass.rs index 1e3e4acce050c..ef34de113cfc5 100644 --- a/src/librustdoc/unindent_pass.rs +++ b/src/librustdoc/unindent_pass.rs @@ -19,6 +19,8 @@ instances where the string containing the doc comment is opened in the middle of a line, and each of the following lines is indented. */ +use core::prelude::*; + use pass::Pass; use text_pass; diff --git a/src/librustdoc/util.rs b/src/librustdoc/util.rs index 0368b8a034610..fe39ac6bc505c 100644 --- a/src/librustdoc/util.rs +++ b/src/librustdoc/util.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + // Just a named container for our op, so it can have impls pub struct NominalOp { op: T diff --git a/src/librusti/rusti.rc b/src/librusti/rusti.rc index 1671dfe11a309..c79714bba3682 100644 --- a/src/librusti/rusti.rc +++ b/src/librusti/rusti.rc @@ -18,11 +18,17 @@ #[license = "MIT/ASL2"]; #[crate_type = "lib"]; -extern mod std; +#[no_std]; + +extern mod core(name = "std"); +extern mod std(name = "extra"); + extern mod rustc; extern mod syntax; +use core::prelude::*; use core::*; + use core::cell::Cell; use rustc::driver::{driver, session}; use syntax::{ast, diagnostic}; diff --git a/src/librustpkg/context.rs b/src/librustpkg/context.rs index 348d828bded2f..4f67118e52059 100644 --- a/src/librustpkg/context.rs +++ b/src/librustpkg/context.rs @@ -10,6 +10,8 @@ // Context data structure used by rustpkg +use core::prelude::*; + use core::hashmap::HashMap; pub struct Ctx { diff --git a/src/librustpkg/path_util.rs b/src/librustpkg/path_util.rs index bbd8d09235484..700b3338a3a22 100644 --- a/src/librustpkg/path_util.rs +++ b/src/librustpkg/path_util.rs @@ -10,6 +10,7 @@ // rustpkg utilities having to do with paths and directories +use core::prelude::*; pub use util::{PkgId, RemotePath, LocalPath}; use core::libc::consts::os::posix88::{S_IRUSR, S_IWUSR, S_IXUSR}; use core::os::mkdir_recursive; diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index 19dc973a4a150..79e978c01d1bb 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -18,10 +18,15 @@ #[license = "MIT/ASL2"]; #[crate_type = "lib"]; -extern mod std; +#[no_std]; + +extern mod core(name = "std"); +extern mod std(name = "extra"); + extern mod rustc; extern mod syntax; +use core::prelude::*; use core::*; pub use core::path::Path; use core::hashmap::HashMap; diff --git a/src/librustpkg/util.rs b/src/librustpkg/util.rs index 94101c4676f64..1425e68a85773 100644 --- a/src/librustpkg/util.rs +++ b/src/librustpkg/util.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use core::*; use core::cmp::Ord; use core::hash::Streaming; diff --git a/src/libstd/core.rc b/src/libstd/core.rc index 6f4890c7834a7..f9c4612d043f6 100644 --- a/src/libstd/core.rc +++ b/src/libstd/core.rc @@ -47,7 +47,7 @@ they contained the following prologue: */ -#[link(name = "core", +#[link(name = "std", vers = "0.7-pre", uuid = "c70c24a7-5551-4f73-8e37-380b11d80be8", url = "https://github.com/mozilla/rust/tree/master/src/libcore")]; @@ -64,10 +64,10 @@ they contained the following prologue: #[deny(non_camel_case_types)]; // Make core testable by not duplicating lang items. See #2912 -#[cfg(test)] extern mod realcore(name = "core"); -#[cfg(test)] pub use kinds = realcore::kinds; -#[cfg(test)] pub use ops = realcore::ops; -#[cfg(test)] pub use cmp = realcore::cmp; +#[cfg(test)] extern mod realstd(name = "std"); +#[cfg(test)] pub use kinds = realstd::kinds; +#[cfg(test)] pub use ops = realstd::ops; +#[cfg(test)] pub use cmp = realstd::cmp; // On Linux, link to the runtime with -lrt. #[cfg(target_os = "linux")] @@ -213,8 +213,8 @@ mod stackwalk; pub mod rt; // A curious inner-module that's not exported that contains the binding -// 'core' so that macro-expanded references to core::error and such -// can be resolved within libcore. +// 'std' so that macro-expanded references to std::error and such +// can be resolved within libstd. #[doc(hidden)] mod core { pub use clone; @@ -225,3 +225,4 @@ mod core { pub use sys; pub use pipes; } + diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index e67b5d118d365..2d4bc9a8c49fa 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use core::to_bytes; #[deriving(Eq)] diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index a8ff8dab54c19..f82d8d3798a61 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -10,6 +10,8 @@ // The Rust abstract syntax tree. +use core::prelude::*; + use codemap::{span, spanned}; use abi::AbiSet; use opt_vec::OptVec; diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index 5b08f59b35c2e..e3ef56541b8fb 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use abi::AbiSet; use ast::*; use ast; diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index e209fd14b5e02..283203059c888 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::*; use ast; use ast_util; diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 981df1156df59..4ac4aeed63a10 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -10,6 +10,8 @@ // Functions dealing with attributes and meta_items +use core::prelude::*; + use ast; use codemap::{spanned, dummy_spanned}; use attr; diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 2e235982a0f92..5f701c4be8b67 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -21,6 +21,8 @@ source code snippets, etc. */ +use core::prelude::*; + use core::to_bytes; use std::serialize::{Encodable, Decodable, Encoder, Decoder}; diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 21e2ad82b1493..528bc546fa30b 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use codemap::{Pos, span}; use codemap; diff --git a/src/libsyntax/ext/asm.rs b/src/libsyntax/ext/asm.rs index 162eced11242b..204eb9a9f8b77 100644 --- a/src/libsyntax/ext/asm.rs +++ b/src/libsyntax/ext/asm.rs @@ -12,6 +12,8 @@ * Inline assembly support. */ +use core::prelude::*; + use ast; use codemap::span; use ext::base; diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 9b71fb9647ce1..311636ee7c148 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap; use codemap::{CodeMap, span, ExpnInfo, ExpandedFrom}; diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 01a504101b914..58ea03ffceefe 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use abi::AbiSet; use ast::ident; use ast; diff --git a/src/libsyntax/ext/concat_idents.rs b/src/libsyntax/ext/concat_idents.rs index e6600e198fa6d..788f047773abc 100644 --- a/src/libsyntax/ext/concat_idents.rs +++ b/src/libsyntax/ext/concat_idents.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap::span; use ext::base::*; diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 007826a84165d..69e15a8dd67c0 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -8,13 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; use ext::build::AstBuilder; use ext::deriving::generic::*; - pub fn expand_deriving_clone(cx: @ExtCtxt, span: span, mitem: @meta_item, diff --git a/src/libsyntax/ext/deriving/cmp/eq.rs b/src/libsyntax/ext/deriving/cmp/eq.rs index 11c0a597cebab..81434e8ec623b 100644 --- a/src/libsyntax/ext/deriving/cmp/eq.rs +++ b/src/libsyntax/ext/deriving/cmp/eq.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 9438e1b0f858d..7e549c25665e3 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use ast::{meta_item, item, expr}; use codemap::span; diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index f1e952eb5f63c..39764a72ece74 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use ast::{meta_item, item, expr}; use codemap::span; diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index e26f4a34304cb..561a1577e7e6d 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index a8c84e8e361e5..f3ea6f28a0044 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -13,6 +13,8 @@ The compiler code necessary for #[deriving(Decodable)]. See encodable.rs for more. */ +use core::prelude::*; + use ast; use ast::*; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 72a1745f902be..00f7b7a1ebd1c 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -75,6 +75,7 @@ would yield functions like: } */ +use core::prelude::*; use ast; use ast::*; diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index b61c78721fee9..49f7ea598644b 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -162,6 +162,8 @@ StaticEnum(, ~[(, Left(1)), */ +use core::prelude::*; + use ast; use ast::{enum_def, expr, ident, Generics, struct_def}; diff --git a/src/libsyntax/ext/deriving/iter_bytes.rs b/src/libsyntax/ext/deriving/iter_bytes.rs index ae321c3e40956..7a818a4e04f52 100644 --- a/src/libsyntax/ext/deriving/iter_bytes.rs +++ b/src/libsyntax/ext/deriving/iter_bytes.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::{meta_item, item, expr, and}; use codemap::span; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 7da66f88ca908..e96682676bdd8 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -18,6 +18,8 @@ library. */ +use core::prelude::*; + use ast; use ast::{Ty, enum_def, expr, ident, item, Generics, meta_item, struct_def}; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index 16f754727b078..df92693d3246a 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use ast::{meta_item, item, expr, ident}; use codemap::span; diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs index 89b469575e54b..2e00bba27b3e3 100644 --- a/src/libsyntax/ext/deriving/to_str.rs +++ b/src/libsyntax/ext/deriving/to_str.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::{meta_item, item, expr}; use codemap::span; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/deriving/ty.rs b/src/libsyntax/ext/deriving/ty.rs index 99bc2d87b3095..f8f7dc8db5fd6 100644 --- a/src/libsyntax/ext/deriving/ty.rs +++ b/src/libsyntax/ext/deriving/ty.rs @@ -13,6 +13,8 @@ A mini version of ast::Ty, which is easier to use, and features an explicit `Self` type to use when specifying impls to be derived. */ +use core::prelude::*; + use ast; use ast::{expr,Generics,ident}; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/env.rs b/src/libsyntax/ext/env.rs index 32fbc9139998e..3e5fb939f6241 100644 --- a/src/libsyntax/ext/env.rs +++ b/src/libsyntax/ext/env.rs @@ -14,6 +14,8 @@ * interface. */ +use core::prelude::*; + use ast; use codemap::span; use ext::base::*; diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index b993162cfa3dd..c74a4dfb5cdfe 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::{blk_, attribute_, attr_outer, meta_word}; use ast::{crate, expr_, expr_mac, mac_invoc_tt}; use ast::{item_mac, stmt_, stmt_mac, stmt_expr, stmt_semi}; diff --git a/src/libsyntax/ext/fmt.rs b/src/libsyntax/ext/fmt.rs index 55d3d4ee8349d..987f7fc319abb 100644 --- a/src/libsyntax/ext/fmt.rs +++ b/src/libsyntax/ext/fmt.rs @@ -14,6 +14,8 @@ * compiler syntax extension plugin interface. */ +use core::prelude::*; + use ast; use codemap::span; use ext::base::*; diff --git a/src/libsyntax/ext/log_syntax.rs b/src/libsyntax/ext/log_syntax.rs index a3f6fb8e97d21..423ade835a075 100644 --- a/src/libsyntax/ext/log_syntax.rs +++ b/src/libsyntax/ext/log_syntax.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap; use ext::base::*; diff --git a/src/libsyntax/ext/pipes/ast_builder.rs b/src/libsyntax/ext/pipes/ast_builder.rs index 1f2e3f06a7310..6d6db23a3785e 100644 --- a/src/libsyntax/ext/pipes/ast_builder.rs +++ b/src/libsyntax/ext/pipes/ast_builder.rs @@ -13,6 +13,9 @@ // To start with, it will be use dummy spans, but it might someday do // something smarter. +use core::prelude::*; + +use abi::AbiSet; use ast::ident; use ast; use codemap::span; diff --git a/src/libsyntax/ext/pipes/check.rs b/src/libsyntax/ext/pipes/check.rs index c0b7f5bbb8426..694a7c1cf8411 100644 --- a/src/libsyntax/ext/pipes/check.rs +++ b/src/libsyntax/ext/pipes/check.rs @@ -29,6 +29,8 @@ that. */ +use core::prelude::*; + use ast; use codemap::span; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/pipes/liveness.rs b/src/libsyntax/ext/pipes/liveness.rs index 8d45e47d54ef7..9cdd35aaf3221 100644 --- a/src/libsyntax/ext/pipes/liveness.rs +++ b/src/libsyntax/ext/pipes/liveness.rs @@ -37,6 +37,8 @@ updating the states using rule (2) until there are no changes. */ +use core::prelude::*; + use ext::base::ExtCtxt; use ext::pipes::proto::{protocol_}; diff --git a/src/libsyntax/ext/pipes/parse_proto.rs b/src/libsyntax/ext/pipes/parse_proto.rs index 28c8c9a704d90..67ef3347ff71c 100644 --- a/src/libsyntax/ext/pipes/parse_proto.rs +++ b/src/libsyntax/ext/pipes/parse_proto.rs @@ -10,6 +10,8 @@ // Parsing pipes protocols from token trees. +use core::prelude::*; + use ast_util; use ext::pipes::proto::*; use parse::common::SeqSep; diff --git a/src/libsyntax/ext/pipes/pipec.rs b/src/libsyntax/ext/pipes/pipec.rs index 0482dffe6d44c..7ed375efc547c 100644 --- a/src/libsyntax/ext/pipes/pipec.rs +++ b/src/libsyntax/ext/pipes/pipec.rs @@ -10,6 +10,8 @@ // A protocol compiler for Rust. +use core::prelude::*; + use ast; use codemap::{dummy_sp, spanned}; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/pipes/proto.rs b/src/libsyntax/ext/pipes/proto.rs index 4471c5bb9b855..80e4520b09419 100644 --- a/src/libsyntax/ext/pipes/proto.rs +++ b/src/libsyntax/ext/pipes/proto.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap::span; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index 1c57d500c221a..9a5645a5b0cab 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap::{BytePos, Pos, span}; use ext::base::ExtCtxt; @@ -29,6 +31,8 @@ use parse; */ pub mod rt { + use core::prelude::*; + use ast; use ext::base::ExtCtxt; use parse; diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 30e6b7cfc65c9..73b84c2a5ab9a 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap; use codemap::{FileMap, Loc, Pos, ExpandedFrom, span}; diff --git a/src/libsyntax/ext/trace_macros.rs b/src/libsyntax/ext/trace_macros.rs index 25607a8bfa76f..185d2fac11be8 100644 --- a/src/libsyntax/ext/trace_macros.rs +++ b/src/libsyntax/ext/trace_macros.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap::span; use ext::base::ExtCtxt; diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index a34045a883eec..be79722373bda 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -9,6 +9,9 @@ // except according to those terms. // Earley-like parser for macros. + +use core::prelude::*; + use ast; use ast::{matcher, match_tok, match_seq, match_nonterminal, ident}; use codemap::{BytePos, mk_sp}; diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 3814243efc4c6..04ac311579fed 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use ast::{ident, matcher_, matcher, match_tok, match_nonterminal, match_seq}; use ast::{tt_delim}; diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index b13dc3f3c0fe7..3e63360fbec69 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use ast::{token_tree, tt_delim, tt_tok, tt_seq, tt_nonterminal,ident}; use codemap::{span, dummy_sp}; diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 8b657b13fa9d2..709463159c52c 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast::*; use ast; use codemap::{span, spanned}; diff --git a/src/libsyntax/parse/comments.rs b/src/libsyntax/parse/comments.rs index da7ad6ffeffcc..66d2d46cc584d 100644 --- a/src/libsyntax/parse/comments.rs +++ b/src/libsyntax/parse/comments.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap::{BytePos, CharPos, CodeMap, Pos}; use diagnostic; diff --git a/src/libsyntax/parse/common.rs b/src/libsyntax/parse/common.rs index 6e85b814b31e8..7182b80880ff9 100644 --- a/src/libsyntax/parse/common.rs +++ b/src/libsyntax/parse/common.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap::{BytePos, spanned}; use parse::lexer::reader; diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index 5340293bb0249..86284a3923a2a 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use codemap::{BytePos, CharPos, CodeMap, Pos, span}; use codemap; diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 0ce3ab4b3e171..34205e7b9abcb 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -17,6 +17,7 @@ Obsolete syntax that becomes too hard to parse can be removed. */ +use core::prelude::*; use ast::{expr, expr_lit, lit_nil, attribute}; use ast; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 4f81194acd781..0a2d0ed924edf 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use abi; use abi::AbiSet; use ast::{Sigil, BorrowedSigil, ManagedSigil, OwnedSigil}; diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 055336a6d9532..1153c361e69fa 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use ast; use ast_util; use parse::token; diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index 6b2ee61545e6d..4e2fd5592dfa0 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -60,6 +60,9 @@ * line (which it can't) and so naturally place the content on its own line to * avoid combining it with other lines and making matters even worse. */ + +use core::prelude::*; + #[deriving(Eq)] pub enum breaks { consistent, inconsistent, } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index b5acdf8599c98..9110becefbce9 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; use abi::AbiSet; use ast::{RegionTyParamBound, TraitTyParamBound, required, provided}; diff --git a/src/libsyntax/syntax.rc b/src/libsyntax/syntax.rc index 0650df576031b..1b9b7b2c8c389 100644 --- a/src/libsyntax/syntax.rc +++ b/src/libsyntax/syntax.rc @@ -23,7 +23,13 @@ #[allow(non_camel_case_types)]; #[deny(deprecated_pattern)]; -extern mod std; +#[no_core]; +#[no_std]; + +extern mod core(name = "std"); +extern mod std(name = "extra"); + +use core::prelude::*; pub mod util { pub mod interner; diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index 5d49c8cd75d86..e2736a00564bd 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -12,6 +12,11 @@ // allows bidirectional lookup; i.e. given a value, one can easily find the // type, and vice versa. +// allow the interner_key macro to escape this module: +#[macro_escape]; + +use core::prelude::*; + use core::cmp::Equiv; use core::hashmap::HashMap; use syntax::parse::token::StringRef; diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 4cfd54256f82e..a2b89243cfd1b 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use core::prelude::*; + use abi::AbiSet; use ast::*; use ast; From c532e033c9ee92d208a9bb2fac4c12d901932f42 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Sat, 18 May 2013 12:39:17 -0700 Subject: [PATCH 189/248] librustc: Change `std` to `extra` throughout libsyntax and librustc --- src/libextra/std.rc | 10 +++++-- src/librustc/back/link.rs | 4 +-- src/librustc/driver/driver.rs | 12 ++++----- src/librustc/front/test.rs | 26 +++++++++---------- src/librustc/metadata/csearch.rs | 2 +- src/librustc/metadata/cstore.rs | 4 +-- src/librustc/metadata/decoder.rs | 6 ++--- src/librustc/metadata/encoder.rs | 10 +++---- src/librustc/metadata/loader.rs | 2 +- src/librustc/middle/astencode.rs | 12 ++++----- src/librustc/middle/check_match.rs | 2 +- src/librustc/middle/lint.rs | 2 +- src/librustc/middle/trans/base.rs | 2 +- src/librustc/middle/trans/glue.rs | 2 +- src/librustc/middle/trans/type_use.rs | 4 +-- src/librustc/middle/ty.rs | 2 +- src/librustc/middle/typeck/check/method.rs | 2 +- src/librustc/middle/typeck/check/mod.rs | 2 +- .../middle/typeck/check/regionmanip.rs | 2 +- src/librustc/middle/typeck/infer/glb.rs | 2 +- src/librustc/middle/typeck/infer/lattice.rs | 2 +- src/librustc/middle/typeck/infer/lub.rs | 2 +- src/librustc/middle/typeck/infer/mod.rs | 4 +-- src/librustc/middle/typeck/infer/sub.rs | 4 +-- src/librustc/middle/typeck/infer/test.rs | 12 ++++----- src/librustc/middle/typeck/infer/unify.rs | 2 +- src/librustc/middle/typeck/mod.rs | 4 +-- src/librustc/rustc.rc | 9 ++++--- src/librustc/util/common.rs | 6 ++--- src/libsyntax/ast.rs | 10 +++---- src/libsyntax/attr.rs | 4 +-- src/libsyntax/codemap.rs | 2 +- src/libsyntax/diagnostic.rs | 2 +- src/libsyntax/ext/deriving/decodable.rs | 6 ++--- src/libsyntax/ext/deriving/encodable.rs | 12 ++++----- src/libsyntax/ext/deriving/generic.rs | 2 +- src/libsyntax/ext/deriving/mod.rs | 2 +- src/libsyntax/ext/pipes/liveness.rs | 2 +- src/libsyntax/parse/lexer.rs | 2 -- src/libsyntax/parse/mod.rs | 8 +++--- src/libsyntax/syntax.rc | 4 +++ 41 files changed, 111 insertions(+), 100 deletions(-) diff --git a/src/libextra/std.rc b/src/libextra/std.rc index 90672d221c5cb..777f45e84bcaa 100644 --- a/src/libextra/std.rc +++ b/src/libextra/std.rc @@ -119,10 +119,16 @@ pub mod test; pub mod serialize; // A curious inner-module that's not exported that contains the binding -// 'std' so that macro-expanded references to std::serialize and such -// can be resolved within libcore. +// 'extra' so that macro-expanded references to std::serialize and such +// can be resolved within libextra. #[doc(hidden)] // FIXME #3538 pub mod std { pub use serialize; pub use test; } +#[doc(hidden)] // FIXME #3538 +pub mod extra { + pub use serialize; + pub use test; +} + diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index 42ce18cf88b68..a5882450f67d0 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -125,9 +125,9 @@ pub mod jit { // We need to tell JIT where to resolve all linked // symbols from. The equivalent of -lstd, -lcore, etc. - // By default the JIT will resolve symbols from the std and + // By default the JIT will resolve symbols from the extra and // core linked into rustc. We don't want that, - // incase the user wants to use an older std library. + // incase the user wants to use an older extra library. let cstore = sess.cstore; for cstore::get_used_crate_files(cstore).each |cratepath| { diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index a3f47d398fb7c..4a9a12e7c0f24 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -30,9 +30,9 @@ use core::io; use core::os; use core::str; use core::vec; -use std::getopts::groups::{optopt, optmulti, optflag, optflagopt, getopts}; -use std::getopts::{opt_present}; -use std::getopts; +use extra::getopts::groups::{optopt, optmulti, optflag, optflagopt, getopts}; +use extra::getopts::{opt_present}; +use extra::getopts; use syntax::ast; use syntax::abi; use syntax::attr; @@ -200,7 +200,7 @@ pub fn compile_rest(sess: Session, crate = time(time_passes, ~"intrinsic injection", || front::intrinsic_inject::inject_intrinsic(sess, crate)); - crate = time(time_passes, ~"std injection", || + crate = time(time_passes, ~"extra injection", || front::std_inject::maybe_inject_libstd_ref(sess, crate)); let ast_map = time(time_passes, ~"ast indexing", || @@ -923,8 +923,8 @@ mod test { use driver::driver::{build_configuration, build_session}; use driver::driver::{build_session_options, optgroups, str_input}; - use std::getopts::groups::getopts; - use std::getopts; + use extra::getopts::groups::getopts; + use extra::getopts; use syntax::attr; use syntax::diagnostic; diff --git a/src/librustc/front/test.rs b/src/librustc/front/test.rs index 2bc648814a31b..e41f26aab083a 100644 --- a/src/librustc/front/test.rs +++ b/src/librustc/front/test.rs @@ -258,13 +258,13 @@ We're going to be building a module that looks more or less like: mod __test { #[!resolve_unexported] - extern mod std (name = "std", vers = "..."); + extern mod extra (name = "extra", vers = "..."); fn main() { #[main]; - std::test::test_main_static(::os::args(), tests) + extra::test::test_main_static(::os::args(), tests) } - static tests : &'static [std::test::TestDescAndFn] = &[ + static tests : &'static [extra::test::TestDescAndFn] = &[ ... the list of tests in the crate ... ]; } @@ -276,7 +276,7 @@ fn mk_std(cx: &TestCtxt) -> @ast::view_item { let vers = nospan(vers); let mi = ast::meta_name_value(@~"vers", vers); let mi = nospan(mi); - let id_std = cx.sess.ident_of("std"); + let id_std = cx.sess.ident_of("extra"); let vi = if is_std(cx) { ast::view_item_use( ~[@nospan(ast::view_path_simple(id_std, @@ -297,7 +297,7 @@ fn mk_std(cx: &TestCtxt) -> @ast::view_item { fn mk_test_module(cx: &TestCtxt) -> @ast::item { - // Link to std + // Link to extra let view_items = ~[mk_std(cx)]; // A constant vector of test descriptors. @@ -309,7 +309,7 @@ fn mk_test_module(cx: &TestCtxt) -> @ast::item { let mainfn = (quote_item!( pub fn main() { #[main]; - std::test::test_main_static(::os::args(), tests); + extra::test::test_main_static(::os::args(), tests); } )).get(); @@ -366,7 +366,7 @@ fn mk_tests(cx: &TestCtxt) -> @ast::item { let test_descs = mk_test_descs(cx); (quote_item!( - pub static tests : &'static [self::std::test::TestDescAndFn] = + pub static tests : &'static [self::extra::test::TestDescAndFn] = $test_descs ; )).get() @@ -376,7 +376,7 @@ fn is_std(cx: &TestCtxt) -> bool { let is_std = { let items = attr::find_linkage_metas(cx.crate.node.attrs); match attr::last_meta_item_value_str_by_name(items, "name") { - Some(@~"std") => true, + Some(@~"extra") => true, _ => false } }; @@ -437,9 +437,9 @@ fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::expr { }; let t_expr = if test.bench { - quote_expr!( self::std::test::StaticBenchFn($fn_expr) ) + quote_expr!( self::extra::test::StaticBenchFn($fn_expr) ) } else { - quote_expr!( self::std::test::StaticTestFn($fn_expr) ) + quote_expr!( self::extra::test::StaticTestFn($fn_expr) ) }; let ignore_expr = if test.ignore { @@ -455,9 +455,9 @@ fn mk_test_desc_and_fn_rec(cx: &TestCtxt, test: &Test) -> @ast::expr { }; let e = quote_expr!( - self::std::test::TestDescAndFn { - desc: self::std::test::TestDesc { - name: self::std::test::StaticTestName($name_expr), + self::extra::test::TestDescAndFn { + desc: self::extra::test::TestDesc { + name: self::extra::test::StaticTestName($name_expr), ignore: $ignore_expr, should_fail: $fail_expr }, diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index c887b2553f741..b35904dbdae36 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -18,7 +18,7 @@ use metadata::decoder; use metadata; use middle::{ty, resolve}; -use reader = std::ebml::reader; +use reader = extra::ebml::reader; use syntax::ast; use syntax::ast_map; use syntax::diagnostic::expect; diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 0c0f094731459..6cc211e0e99ab 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -18,7 +18,7 @@ use metadata::cstore; use metadata::decoder; use core::hashmap::HashMap; -use std; +use extra; use syntax::ast; use syntax::parse::token::ident_interner; @@ -152,7 +152,7 @@ pub fn get_dep_hashes(cstore: &CStore) -> ~[~str] { }); } - let sorted = do std::sort::merge_sort(result) |a, b| { + let sorted = do extra::sort::merge_sort(result) |a, b| { (a.name, a.vers, a.hash) <= (b.name, b.vers, b.hash) }; diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index ef9c945306264..de44b74528dcf 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -30,9 +30,9 @@ use core::io; use core::option; use core::str; use core::vec; -use std::ebml::reader; -use std::ebml; -use std::serialize::Decodable; +use extra::ebml::reader; +use extra::ebml; +use extra::serialize::Decodable; use syntax::ast_map; use syntax::attr; use syntax::diagnostic::span_handler; diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index e959983a98a10..715465a757784 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -22,11 +22,11 @@ use middle::ty; use middle; use util::ppaux::ty_to_str; -use std::flate; +use extra::flate; use core::hash::HashUtil; use core::hashmap::HashMap; -use std::serialize::Encodable; -use std; +use extra::serialize::Encodable; +use extra; use syntax::abi::AbiSet; use syntax::ast::*; use syntax::ast; @@ -39,7 +39,7 @@ use syntax::{ast_util, visit}; use syntax::opt_vec::OptVec; use syntax::opt_vec; use syntax; -use writer = std::ebml::writer; +use writer = extra::ebml::writer; // used by astencode: type abbrev_map = @mut HashMap; @@ -1288,7 +1288,7 @@ fn encode_crate_deps(ecx: @EncodeContext, }; // Sort by cnum - std::sort::quick_sort(deps, |kv1, kv2| kv1.cnum <= kv2.cnum); + extra::sort::quick_sort(deps, |kv1, kv2| kv1.cnum <= kv2.cnum); // Sanity-check the crate numbers let mut expected_cnum = 1; diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index c29a644c123f0..232101930ad28 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -23,7 +23,7 @@ use syntax::parse::token::ident_interner; use syntax::print::pprust; use syntax::{ast, attr}; -use std::flate; +use extra::flate; use core::os::consts::{macos, freebsd, linux, android, win32}; pub enum os { diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 3bade41d0321d..3ebcf72e48548 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -25,11 +25,11 @@ use middle::{ty, typeck, moves}; use middle; use util::ppaux::ty_to_str; -use std::ebml::reader; -use std::ebml; -use std::serialize; -use std::serialize::{Encoder, Encodable, EncoderHelpers, DecoderHelpers}; -use std::serialize::{Decoder, Decodable}; +use extra::ebml::reader; +use extra::ebml; +use extra::serialize; +use extra::serialize::{Encoder, Encodable, EncoderHelpers, DecoderHelpers}; +use extra::serialize::{Decoder, Decodable}; use syntax::ast; use syntax::ast_map; use syntax::ast_util::inlined_item_utils; @@ -39,7 +39,7 @@ use syntax::codemap; use syntax::fold::*; use syntax::fold; use syntax; -use writer = std::ebml::writer; +use writer = extra::ebml::writer; #[cfg(test)] use syntax::parse; #[cfg(test)] use syntax::print::pprust; diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index db5bdf85cb5d8..9d164f5eb401a 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -19,7 +19,7 @@ use middle::typeck::method_map; use middle::moves; use util::ppaux::ty_to_str; -use std::sort; +use extra::sort; use syntax::ast::*; use syntax::ast_util::{unguarded_pat, walk_pat}; use syntax::codemap::{span, dummy_sp, spanned}; diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 11d1f5bd7d2df..2b2f2df577b2e 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -17,7 +17,7 @@ use middle::pat_util; use util::ppaux::{ty_to_str}; use core::hashmap::HashMap; -use std::smallintmap::SmallIntMap; +use extra::smallintmap::SmallIntMap; use syntax::attr; use syntax::codemap::span; use syntax::codemap; diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 605bd72d8d7f1..f92acbaf5c68c 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -67,7 +67,7 @@ use util::ppaux::{Repr, ty_to_str}; use core::hash; use core::hashmap::{HashMap, HashSet}; use core::libc::c_uint; -use std::time; +use extra::time; use syntax::ast::ident; use syntax::ast_map::{path, path_elt_to_str, path_name}; use syntax::ast_util::{local_def, path_to_ident}; diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index 8dc97b5c35d83..d8c851127478e 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -36,7 +36,7 @@ use util::ppaux; use util::ppaux::ty_to_short_str; use core::libc::c_uint; -use std::time; +use extra::time; use syntax::ast; pub fn trans_free(cx: block, v: ValueRef) -> block { diff --git a/src/librustc/middle/trans/type_use.rs b/src/librustc/middle/trans/type_use.rs index 4a8adfba11c31..365b75b8dd43d 100644 --- a/src/librustc/middle/trans/type_use.rs +++ b/src/librustc/middle/trans/type_use.rs @@ -36,8 +36,8 @@ use middle::typeck; use core::option::{Some, None}; use core::uint; use core::vec; -use std::list::{List, Cons, Nil}; -use std::list; +use extra::list::{List, Cons, Nil}; +use extra::list; use syntax::ast; use syntax::ast::*; use syntax::ast_map; diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 734c9ac04775d..761096a019e20 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -30,7 +30,7 @@ use util::enum_set::{EnumSet, CLike}; use core::ptr::to_unsafe_ptr; use core::to_bytes; use core::hashmap::{HashMap, HashSet}; -use std::smallintmap::SmallIntMap; +use extra::smallintmap::SmallIntMap; use syntax::ast::*; use syntax::ast_util::is_local; use syntax::ast_util; diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index a34465db7cd43..68deb900886fb 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -96,7 +96,7 @@ use middle::typeck::check::regionmanip::replace_bound_regions_in_fn_sig; use util::common::indenter; use core::hashmap::HashSet; -use std::list::Nil; +use extra::list::Nil; use syntax::ast::{def_id, sty_value, sty_region, sty_box}; use syntax::ast::{sty_uniq, sty_static, node_id}; use syntax::ast::{m_const, m_mutbl, m_imm}; diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 226d7fa7651d7..6131280f90038 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -112,7 +112,7 @@ use util::ppaux; use core::cast::transmute; use core::hashmap::HashMap; use core::util::replace; -use std::list::Nil; +use extra::list::Nil; use syntax::abi::AbiSet; use syntax::ast::{provided, required}; use syntax::ast; diff --git a/src/librustc/middle/typeck/check/regionmanip.rs b/src/librustc/middle/typeck/check/regionmanip.rs index 89cf3df6fedf9..c1b33d317f1e3 100644 --- a/src/librustc/middle/typeck/check/regionmanip.rs +++ b/src/librustc/middle/typeck/check/regionmanip.rs @@ -19,7 +19,7 @@ use util::common::indenter; use util::ppaux::region_to_str; use util::ppaux; -use std::list::Cons; +use extra::list::Cons; // Helper functions related to manipulating region types. diff --git a/src/librustc/middle/typeck/infer/glb.rs b/src/librustc/middle/typeck/infer/glb.rs index 78989a1337634..d6e3f2dae5d48 100644 --- a/src/librustc/middle/typeck/infer/glb.rs +++ b/src/librustc/middle/typeck/infer/glb.rs @@ -30,7 +30,7 @@ use syntax::codemap::span; use util::common::{indent, indenter}; use util::ppaux::mt_to_str; -use std::list; +use extra::list; pub struct Glb(CombineFields); // "greatest lower bound" (common subtype) diff --git a/src/librustc/middle/typeck/infer/lattice.rs b/src/librustc/middle/typeck/infer/lattice.rs index 81befc5f65066..3640748b20b54 100644 --- a/src/librustc/middle/typeck/infer/lattice.rs +++ b/src/librustc/middle/typeck/infer/lattice.rs @@ -46,7 +46,7 @@ use middle::typeck::infer::sub::Sub; use middle::typeck::infer::to_str::InferStr; use util::common::indenter; -use std::list; +use extra::list; pub trait LatticeValue { fn sub(cf: &CombineFields, a: &Self, b: &Self) -> ures; diff --git a/src/librustc/middle/typeck/infer/lub.rs b/src/librustc/middle/typeck/infer/lub.rs index c906d3ef4951b..f5eb0bc26351a 100644 --- a/src/librustc/middle/typeck/infer/lub.rs +++ b/src/librustc/middle/typeck/infer/lub.rs @@ -24,7 +24,7 @@ use middle::typeck::isr_alist; use util::common::indent; use util::ppaux::mt_to_str; -use std::list; +use extra::list; use syntax::abi::AbiSet; use syntax::ast; use syntax::ast::{Many, Once, extern_fn, m_const, impure_fn}; diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/typeck/infer/mod.rs index 864f0e24eeb53..f2371e927b82f 100644 --- a/src/librustc/middle/typeck/infer/mod.rs +++ b/src/librustc/middle/typeck/infer/mod.rs @@ -267,8 +267,8 @@ use middle::typeck::isr_alist; use util::common::indent; use util::ppaux::{bound_region_to_str, ty_to_str, trait_ref_to_str}; -use std::list::Nil; -use std::smallintmap::SmallIntMap; +use extra::list::Nil; +use extra::smallintmap::SmallIntMap; use syntax::ast::{m_imm, m_mutbl}; use syntax::ast; use syntax::codemap; diff --git a/src/librustc/middle/typeck/infer/sub.rs b/src/librustc/middle/typeck/infer/sub.rs index 11fac4d5414c0..2578f7c855359 100644 --- a/src/librustc/middle/typeck/infer/sub.rs +++ b/src/librustc/middle/typeck/infer/sub.rs @@ -23,8 +23,8 @@ use middle::typeck::infer::to_str::InferStr; use util::common::{indent, indenter}; use util::ppaux::bound_region_to_str; -use std::list::Nil; -use std::list; +use extra::list::Nil; +use extra::list; use syntax::abi::AbiSet; use syntax::ast; use syntax::ast::{Onceness, m_const, purity}; diff --git a/src/librustc/middle/typeck/infer/test.rs b/src/librustc/middle/typeck/infer/test.rs index f2a72e07a5739..e39dd986c514b 100644 --- a/src/librustc/middle/typeck/infer/test.rs +++ b/src/librustc/middle/typeck/infer/test.rs @@ -23,12 +23,12 @@ use middle::lang_items::{LanguageItems, language_items}; use middle::ty::{FnTyBase, FnMeta, FnSig}; use util::ppaux::ty_to_str; -use std::getopts::groups::{optopt, optmulti, optflag, optflagopt, getopts}; -use std::getopts::groups; -use std::getopts::{opt_present}; -use std::getopts; -use std::getopts; -use std::oldmap::HashMap; +use extra::getopts::groups::{optopt, optmulti, optflag, optflagopt, getopts}; +use extra::getopts::groups; +use extra::getopts::{opt_present}; +use extra::getopts; +use extra::getopts; +use extra::oldmap::HashMap; use syntax::codemap::dummy_sp; use syntax::parse::parse_crate_from_source_str; use syntax::{ast, attr, parse}; diff --git a/src/librustc/middle/typeck/infer/unify.rs b/src/librustc/middle/typeck/infer/unify.rs index 39feedfce8bca..78739bd7b04f9 100644 --- a/src/librustc/middle/typeck/infer/unify.rs +++ b/src/librustc/middle/typeck/infer/unify.rs @@ -10,7 +10,7 @@ use core::prelude::*; -use std::smallintmap::SmallIntMap; +use extra::smallintmap::SmallIntMap; use middle::ty::{Vid, expected_found, IntVarValue}; use middle::ty; diff --git a/src/librustc/middle/typeck/mod.rs b/src/librustc/middle/typeck/mod.rs index 8684b1b03e865..f4900f5bfeb63 100644 --- a/src/librustc/middle/typeck/mod.rs +++ b/src/librustc/middle/typeck/mod.rs @@ -59,8 +59,8 @@ use util::ppaux::Repr; use util::ppaux; use core::hashmap::HashMap; -use std::list::List; -use std::list; +use extra::list::List; +use extra::list; use syntax::codemap::span; use syntax::print::pprust::*; use syntax::{ast, ast_map, abi}; diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index f1263be6b4b54..04375b45793b7 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -25,9 +25,12 @@ #[no_std]; extern mod core(name = "std"); -extern mod std(name = "extra"); +extern mod extra(name = "extra"); extern mod syntax; +// For deriving(Encodable) purposes... +extern mod std(name = "extra", vers = "0.7-pre"); + use core::prelude::*; use driver::driver::{host_triple, optgroups, early_error}; @@ -38,8 +41,8 @@ use driver::driver::{compile_input}; use driver::session; use middle::lint; -use std::getopts::{groups, opt_present}; -use std::getopts; +use extra::getopts::{groups, opt_present}; +use extra::getopts; use syntax::codemap; use syntax::diagnostic; diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 7bd8c6aadf23c..cbf1d0df09f68 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -15,13 +15,13 @@ use syntax::codemap::{span}; use syntax::visit; use core::hashmap::HashSet; -use std; +use extra; pub fn time(do_it: bool, what: ~str, thunk: &fn() -> T) -> T { if !do_it { return thunk(); } - let start = std::time::precise_time_s(); + let start = extra::time::precise_time_s(); let rv = thunk(); - let end = std::time::precise_time_s(); + let end = extra::time::precise_time_s(); io::println(fmt!("time: %3.3f s\t%s", end - start, what)); rv } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index f82d8d3798a61..e5771a5db2e95 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -18,12 +18,12 @@ use opt_vec::OptVec; use parse::token::get_ident_interner; use core::cast; +use core::hashmap::HashMap; use core::option::{Option}; -use core::to_bytes; use core::to_bytes::IterBytes; +use core::to_bytes; use core::to_str::ToStr; -use core::hashmap::HashMap; -use std::serialize::{Encodable, Decodable, Encoder, Decoder}; +use extra::serialize::{Encodable, Decodable, Encoder, Decoder}; // an identifier contains an index into the interner @@ -1117,7 +1117,7 @@ pub enum inlined_item { mod test { use core::option::{None, Option, Some}; use core::uint; - use std; + use extra; use codemap::*; use super::*; @@ -1206,7 +1206,7 @@ mod test { }, span: bogus_span}; // doesn't matter which encoder we use.... - let _f = (@e as @std::serialize::Encodable); + let _f = (@e as @extra::serialize::Encodable); } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 4ac4aeed63a10..6ac743d3844d2 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -20,7 +20,7 @@ use diagnostic::span_handler; use parse::comments::{doc_comment_style, strip_doc_comment_decoration}; use core::hashmap::HashSet; -use std; +use extra; /* Constructors */ @@ -258,7 +258,7 @@ pub fn last_meta_item_list_by_name(items: ~[@ast::meta_item], name: &str) pub fn sort_meta_items(items: &[@ast::meta_item]) -> ~[@ast::meta_item] { // This is sort of stupid here, converting to a vec of mutables and back let mut v = vec::to_owned(items); - do std::sort::quick_sort(v) |ma, mb| { + do extra::sort::quick_sort(v) |ma, mb| { get_meta_item_name(*ma) <= get_meta_item_name(*mb) } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 5f701c4be8b67..77a6137cd1719 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -24,7 +24,7 @@ source code snippets, etc. use core::prelude::*; use core::to_bytes; -use std::serialize::{Encodable, Decodable, Encoder, Decoder}; +use extra::serialize::{Encodable, Decodable, Encoder, Decoder}; pub trait Pos { fn from_uint(n: uint) -> Self; diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 528bc546fa30b..792b561f110c1 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -13,7 +13,7 @@ use core::prelude::*; use codemap::{Pos, span}; use codemap; -use std::term; +use extra::term; pub type Emitter = @fn(cmsp: Option<(@codemap::CodeMap, span)>, msg: &str, diff --git a/src/libsyntax/ext/deriving/decodable.rs b/src/libsyntax/ext/deriving/decodable.rs index f3ea6f28a0044..d1f1c4187d52e 100644 --- a/src/libsyntax/ext/deriving/decodable.rs +++ b/src/libsyntax/ext/deriving/decodable.rs @@ -53,7 +53,7 @@ fn create_derived_decodable_impl( cx.path_global( span, ~[ - cx.ident_of("std"), + cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Decoder"), ])))); @@ -66,7 +66,7 @@ fn create_derived_decodable_impl( span, true, ~[ - cx.ident_of("std"), + cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Decodable") ], @@ -150,7 +150,7 @@ fn call_substructure_decode_method( cx.path_global( span, ~[ - cx.ident_of("std"), + cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Decodable"), cx.ident_of("decode"), diff --git a/src/libsyntax/ext/deriving/encodable.rs b/src/libsyntax/ext/deriving/encodable.rs index 00f7b7a1ebd1c..6ca7d0b7b28c8 100644 --- a/src/libsyntax/ext/deriving/encodable.rs +++ b/src/libsyntax/ext/deriving/encodable.rs @@ -22,7 +22,7 @@ For example, a type like: would generate two implementations like: -impl Encodable for Node { +impl Encodable for Node { fn encode(&self, s: &S) { do s.emit_struct("Node", 1) { s.emit_field("id", 0, || s.emit_uint(self.id)) @@ -115,7 +115,7 @@ fn create_derived_encodable_impl( cx.path_global( span, ~[ - cx.ident_of("std"), + cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Encoder"), ])))); @@ -128,7 +128,7 @@ fn create_derived_encodable_impl( span, true, ~[ - cx.ident_of("std"), + cx.ident_of("extra"), cx.ident_of("serialize"), cx.ident_of("Encodable") ], @@ -411,10 +411,10 @@ fn expand_deriving_encodable_enum_method( #[cfg(test)] mod test { - extern mod std; + extern mod extra; use core::option::{None, Some}; - use std::serialize::Encodable; - use std::serialize::Encoder; + use extra::serialize::Encodable; + use extra::serialize::Encoder; // just adding the ones I want to test, for now: #[deriving(Eq)] diff --git a/src/libsyntax/ext/deriving/generic.rs b/src/libsyntax/ext/deriving/generic.rs index 49f7ea598644b..e250f970e62f5 100644 --- a/src/libsyntax/ext/deriving/generic.rs +++ b/src/libsyntax/ext/deriving/generic.rs @@ -202,7 +202,7 @@ pub struct TraitDef<'self> { /// other than the current trait additional_bounds: ~[Ty<'self>], - /// Any extra lifetimes and/or bounds, e.g. `D: std::serialize::Decoder` + /// Any extra lifetimes and/or bounds, e.g. `D: extra::serialize::Decoder` generics: LifetimeBounds<'self>, methods: ~[MethodDef<'self>] diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index e96682676bdd8..63ef871614909 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -13,7 +13,7 @@ The compiler code necessary to implement the #[deriving] extensions. FIXME (#2810)--Hygiene. Search for "__" strings (in other files too). -We also assume "std" is the standard library, and "core" is the core +We also assume "extra" is the standard library, and "core" is the core library. */ diff --git a/src/libsyntax/ext/pipes/liveness.rs b/src/libsyntax/ext/pipes/liveness.rs index 9cdd35aaf3221..f1f5a7f12b268 100644 --- a/src/libsyntax/ext/pipes/liveness.rs +++ b/src/libsyntax/ext/pipes/liveness.rs @@ -42,7 +42,7 @@ use core::prelude::*; use ext::base::ExtCtxt; use ext::pipes::proto::{protocol_}; -use std::bitv::Bitv; +use extra::bitv::Bitv; pub fn analyze(proto: @mut protocol_, _cx: @ExtCtxt) { debug!("initializing colive analysis"); diff --git a/src/libsyntax/parse/lexer.rs b/src/libsyntax/parse/lexer.rs index 86284a3923a2a..77637712c7f5b 100644 --- a/src/libsyntax/parse/lexer.rs +++ b/src/libsyntax/parse/lexer.rs @@ -20,8 +20,6 @@ use parse::token; pub use ext::tt::transcribe::{TtReader, new_tt_reader}; -//use std; - pub trait reader { fn is_eof(@mut self) -> bool; fn next_token(@mut self) -> TokenAndSpan; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 8eb7ca2923c25..eca999231cdf2 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -343,8 +343,8 @@ pub fn maybe_aborted(result : T, p: Parser) -> T { #[cfg(test)] mod test { use super::*; - use std::serialize::Encodable; - use std; + use extra::serialize::Encodable; + use extra; use core::io; use core::option::Some; use core::option::None; @@ -365,9 +365,9 @@ mod test { } - #[cfg(test)] fn to_json_str>(val: @E) -> ~str { + #[cfg(test)] fn to_json_str>(val: @E) -> ~str { do io::with_str_writer |writer| { - let mut encoder = std::json::Encoder(writer); + let mut encoder = extra::json::Encoder(writer); val.encode(&mut encoder); } } diff --git a/src/libsyntax/syntax.rc b/src/libsyntax/syntax.rc index 1b9b7b2c8c389..8ec281a6bc1f7 100644 --- a/src/libsyntax/syntax.rc +++ b/src/libsyntax/syntax.rc @@ -27,6 +27,10 @@ #[no_std]; extern mod core(name = "std"); +extern mod extra(name = "extra"); + +// For deriving(Encodable) purposes... +#[cfg(stage0)] extern mod std(name = "extra"); use core::prelude::*; From d5055f4e972ac37eb22490974f49e15ba50b1d53 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Sat, 18 May 2013 16:43:04 -0700 Subject: [PATCH 190/248] librustc: Make `std_inject` inject the name `std`, not `core` --- src/librustc/front/std_inject.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/librustc/front/std_inject.rs b/src/librustc/front/std_inject.rs index 616b1cb98157a..c8135abf33439 100644 --- a/src/librustc/front/std_inject.rs +++ b/src/librustc/front/std_inject.rs @@ -43,7 +43,7 @@ fn inject_libstd_ref(sess: Session, crate: @ast::crate) -> @ast::crate { let n1 = sess.next_node_id(); let vi1 = @ast::view_item { node: ast::view_item_extern_mod( - sess.ident_of("core"), ~[], n1), + sess.ident_of("std"), ~[], n1), attrs: ~[ spanned(ast::attribute_ { style: ast::attr_inner, @@ -79,7 +79,7 @@ fn inject_libstd_ref(sess: Session, crate: @ast::crate) -> @ast::crate { span: dummy_sp(), global: false, idents: ~[ - sess.ident_of("core"), + sess.ident_of("std"), sess.ident_of("prelude") ], rp: None, From b8be7e8329fdf819d413d0bf82146c138edff2bb Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Sun, 19 May 2013 11:16:30 -0700 Subject: [PATCH 191/248] libfuzzer: Rename `std` to `extra`. --- src/libfuzzer/ast_match.rs | 1 - src/libfuzzer/cycles.rs | 4 ++-- src/libfuzzer/fuzzer.rc | 2 +- src/libfuzzer/rand_util.rs | 2 +- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/libfuzzer/ast_match.rs b/src/libfuzzer/ast_match.rs index d0bbcc024815c..8a22f0a068975 100644 --- a/src/libfuzzer/ast_match.rs +++ b/src/libfuzzer/ast_match.rs @@ -10,7 +10,6 @@ use core::prelude::*; -use std; use vec; fn vec_equal(v: ~[T], diff --git a/src/libfuzzer/cycles.rs b/src/libfuzzer/cycles.rs index 5f7152f109f24..2256325fa4376 100644 --- a/src/libfuzzer/cycles.rs +++ b/src/libfuzzer/cycles.rs @@ -10,8 +10,8 @@ use core::prelude::*; -use std; -use std::rand; +use extra; +use extra::rand; use uint::range; // random uint less than n diff --git a/src/libfuzzer/fuzzer.rc b/src/libfuzzer/fuzzer.rc index aac6796f30c23..c993796639f14 100644 --- a/src/libfuzzer/fuzzer.rc +++ b/src/libfuzzer/fuzzer.rc @@ -23,7 +23,7 @@ #[no_std]; extern mod core(name = "std", vers = "0.7-pre"); -extern mod std(name = "extra", vers = "0.7-pre"); +extern mod extra(name = "extra", vers = "0.7-pre"); extern mod syntax(vers = "0.7-pre"); diff --git a/src/libfuzzer/rand_util.rs b/src/libfuzzer/rand_util.rs index 32197ba2195ec..168c6d4dd61a3 100644 --- a/src/libfuzzer/rand_util.rs +++ b/src/libfuzzer/rand_util.rs @@ -9,7 +9,7 @@ // except according to those terms. use core::prelude::*; -use std::rand; +use extra::rand; // random uint less than n fn under(r : rand::rng, n : uint) -> uint { From 14be4c23e46144026efaa1fa0155f6407326747e Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Sun, 19 May 2013 11:17:49 -0700 Subject: [PATCH 192/248] librustdoc: Rename `std` to `extra`. --- src/librustdoc/config.rs | 2 +- src/librustdoc/markdown_writer.rs | 2 +- src/librustdoc/rustdoc.rc | 6 +++--- src/librustdoc/sort_pass.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 85ceb6cccb749..22a5f668c70ee 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -14,7 +14,7 @@ use core::cell::Cell; use core::run; use core::run::ProgramOutput; use core::result::Result; -use std::getopts; +use extra::getopts; /// The type of document to output #[deriving(Eq)] diff --git a/src/librustdoc/markdown_writer.rs b/src/librustdoc/markdown_writer.rs index b585b294b0d3e..5a22a56b7a6f8 100644 --- a/src/librustdoc/markdown_writer.rs +++ b/src/librustdoc/markdown_writer.rs @@ -17,7 +17,7 @@ use doc; use core::libc; use core::run; use core::comm::*; -use std::future; +use extra::future; pub enum WriteInstr { Write(~str), diff --git a/src/librustdoc/rustdoc.rc b/src/librustdoc/rustdoc.rc index 9b73e393cb235..d4a25f6eb8bcc 100644 --- a/src/librustdoc/rustdoc.rc +++ b/src/librustdoc/rustdoc.rc @@ -24,7 +24,7 @@ #[no_std]; extern mod core(name = "std"); -extern mod std(name = "extra"); +extern mod extra(name = "extra"); extern mod rustc; extern mod syntax; @@ -145,9 +145,9 @@ fn run(config: Config) { } pub fn time(what: ~str, f: &fn() -> T) -> T { - let start = std::time::precise_time_s(); + let start = extra::time::precise_time_s(); let rv = f(); - let end = std::time::precise_time_s(); + let end = extra::time::precise_time_s(); info!("time: %3.3f s %s", end - start, what); rv } diff --git a/src/librustdoc/sort_pass.rs b/src/librustdoc/sort_pass.rs index 72abbd2bdbd05..2c545f7d2be07 100644 --- a/src/librustdoc/sort_pass.rs +++ b/src/librustdoc/sort_pass.rs @@ -19,7 +19,7 @@ use util::NominalOp; #[cfg(test)] use extract; -use std::sort; +use extra::sort; pub type ItemLtEqOp = @fn(v1: &doc::ItemTag, v2: &doc::ItemTag) -> bool; From 9200237b4d86cba8f3b222ff8957f79d54ecd0e1 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Mon, 20 May 2013 14:30:00 -0700 Subject: [PATCH 193/248] fuzzer: Change `core` to `std` in the fuzzer --- src/libfuzzer/ast_match.rs | 2 +- src/libfuzzer/fuzzer.rc | 13 ++++++++++--- src/libfuzzer/ivec_fuzz.rs | 2 +- src/libfuzzer/rand_util.rs | 4 ++-- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/libfuzzer/ast_match.rs b/src/libfuzzer/ast_match.rs index 8a22f0a068975..7d623919ff936 100644 --- a/src/libfuzzer/ast_match.rs +++ b/src/libfuzzer/ast_match.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::prelude::*; +use std::prelude::*; use vec; diff --git a/src/libfuzzer/fuzzer.rc b/src/libfuzzer/fuzzer.rc index c993796639f14..3be5593793347 100644 --- a/src/libfuzzer/fuzzer.rc +++ b/src/libfuzzer/fuzzer.rc @@ -22,13 +22,13 @@ #[no_std]; -extern mod core(name = "std", vers = "0.7-pre"); +extern mod std(name = "std", vers = "0.7-pre"); extern mod extra(name = "extra", vers = "0.7-pre"); extern mod syntax(vers = "0.7-pre"); -use core::prelude::*; -use core::run; +use std::prelude::*; +use std::run; use syntax::diagnostic; use syntax::parse::token::ident_interner; @@ -698,3 +698,10 @@ pub fn main() { error!("Fuzzer done"); } + +// For bootstrapping purposes... +pub mod core { + pub use std::cmp; + pub use std::sys; +} + diff --git a/src/libfuzzer/ivec_fuzz.rs b/src/libfuzzer/ivec_fuzz.rs index d0f83d4ba5428..8f019a14eedb3 100644 --- a/src/libfuzzer/ivec_fuzz.rs +++ b/src/libfuzzer/ivec_fuzz.rs @@ -28,7 +28,7 @@ vec_edits is not an iter because iters might go away. */ -use core::prelude::*; +use std::prelude::*; use vec::slice; use vec::len; diff --git a/src/libfuzzer/rand_util.rs b/src/libfuzzer/rand_util.rs index 168c6d4dd61a3..abc6b1cfc0af1 100644 --- a/src/libfuzzer/rand_util.rs +++ b/src/libfuzzer/rand_util.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::prelude::*; +use std::prelude::*; use extra::rand; // random uint less than n @@ -63,7 +63,7 @@ fn weighted_choice(r : rand::rng, v : ~[weighted]) -> T { return item; } } - core::unreachable(); + std::unreachable(); } fn weighted_vec(v : ~[weighted]) -> ~[T] { From c10e0cb9c984ece484a5c8c9c4c20369e2be499b Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Mon, 20 May 2013 15:20:16 -0700 Subject: [PATCH 194/248] syntax: Change syntax extensions to expand to `std::foo` instead of `core::foo` --- src/libextra/std.rc | 6 +++ src/librustc/rustc.rc | 3 ++ src/libstd/core.rc | 10 +++++ src/libsyntax/ext/deriving/clone.rs | 4 +- src/libsyntax/ext/deriving/cmp/eq.rs | 2 +- src/libsyntax/ext/deriving/cmp/ord.rs | 4 +- src/libsyntax/ext/deriving/cmp/totaleq.rs | 2 +- src/libsyntax/ext/deriving/cmp/totalord.rs | 8 ++-- src/libsyntax/ext/deriving/iter_bytes.rs | 4 +- src/libsyntax/ext/deriving/mod.rs | 2 +- src/libsyntax/ext/deriving/rand.rs | 6 +-- src/libsyntax/ext/deriving/to_str.rs | 4 +- src/libsyntax/ext/expand.rs | 26 ++++++------- src/libsyntax/ext/pipes/ast_builder.rs | 1 + src/libsyntax/ext/pipes/pipec.rs | 44 +++++++++++----------- src/libsyntax/syntax.rc | 2 + 16 files changed, 75 insertions(+), 53 deletions(-) diff --git a/src/libextra/std.rc b/src/libextra/std.rc index 777f45e84bcaa..7f9902dfc8c53 100644 --- a/src/libextra/std.rc +++ b/src/libextra/std.rc @@ -125,6 +125,12 @@ pub mod serialize; pub mod std { pub use serialize; pub use test; + + // For bootstrapping. + pub use core::clone; + pub use core::condition; + pub use core::cmp; + pub use core::sys; } #[doc(hidden)] // FIXME #3538 pub mod extra { diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index 04375b45793b7..2b392efaa859c 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -29,7 +29,10 @@ extern mod extra(name = "extra"); extern mod syntax; // For deriving(Encodable) purposes... +#[cfg(stage0)] extern mod std(name = "extra", vers = "0.7-pre"); +#[cfg(not(stage0))] +extern mod std(name = "std", vers = "0.7-pre"); use core::prelude::*; diff --git a/src/libstd/core.rc b/src/libstd/core.rc index f9c4612d043f6..0b9e09cfa8db4 100644 --- a/src/libstd/core.rc +++ b/src/libstd/core.rc @@ -225,4 +225,14 @@ mod core { pub use sys; pub use pipes; } +#[doc(hidden)] +mod std { + pub use clone; + pub use cmp; + pub use condition; + pub use option; + pub use kinds; + pub use sys; + pub use pipes; +} diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 69e15a8dd67c0..8d9abb186fd1c 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -22,7 +22,7 @@ pub fn expand_deriving_clone(cx: @ExtCtxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~["core", "clone", "Clone"]), + path: Path::new(~["std", "clone", "Clone"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ @@ -49,7 +49,7 @@ pub fn expand_deriving_deep_clone(cx: @ExtCtxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~["core", "clone", "DeepClone"]), + path: Path::new(~["std", "clone", "DeepClone"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ diff --git a/src/libsyntax/ext/deriving/cmp/eq.rs b/src/libsyntax/ext/deriving/cmp/eq.rs index 81434e8ec623b..67107b4218acf 100644 --- a/src/libsyntax/ext/deriving/cmp/eq.rs +++ b/src/libsyntax/ext/deriving/cmp/eq.rs @@ -46,7 +46,7 @@ pub fn expand_deriving_eq(cx: @ExtCtxt, ); let trait_def = TraitDef { - path: Path::new(~["core", "cmp", "Eq"]), + path: Path::new(~["std", "cmp", "Eq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ diff --git a/src/libsyntax/ext/deriving/cmp/ord.rs b/src/libsyntax/ext/deriving/cmp/ord.rs index 7e549c25665e3..8b8ee37691cb0 100644 --- a/src/libsyntax/ext/deriving/cmp/ord.rs +++ b/src/libsyntax/ext/deriving/cmp/ord.rs @@ -38,9 +38,9 @@ pub fn expand_deriving_ord(cx: @ExtCtxt, let trait_def = TraitDef { - path: Path::new(~["core", "cmp", "Ord"]), + path: Path::new(~["std", "cmp", "Ord"]), // XXX: Ord doesn't imply Eq yet - additional_bounds: ~[Literal(Path::new(~["core", "cmp", "Eq"]))], + additional_bounds: ~[Literal(Path::new(~["std", "cmp", "Eq"]))], generics: LifetimeBounds::empty(), methods: ~[ md!("lt", true, false), diff --git a/src/libsyntax/ext/deriving/cmp/totaleq.rs b/src/libsyntax/ext/deriving/cmp/totaleq.rs index 39764a72ece74..f07c894943868 100644 --- a/src/libsyntax/ext/deriving/cmp/totaleq.rs +++ b/src/libsyntax/ext/deriving/cmp/totaleq.rs @@ -27,7 +27,7 @@ pub fn expand_deriving_totaleq(cx: @ExtCtxt, } let trait_def = TraitDef { - path: Path::new(~["core", "cmp", "TotalEq"]), + path: Path::new(~["std", "cmp", "TotalEq"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ diff --git a/src/libsyntax/ext/deriving/cmp/totalord.rs b/src/libsyntax/ext/deriving/cmp/totalord.rs index 561a1577e7e6d..4c1c940927b9b 100644 --- a/src/libsyntax/ext/deriving/cmp/totalord.rs +++ b/src/libsyntax/ext/deriving/cmp/totalord.rs @@ -22,7 +22,7 @@ pub fn expand_deriving_totalord(cx: @ExtCtxt, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~["core", "cmp", "TotalOrd"]), + path: Path::new(~["std", "cmp", "TotalOrd"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ @@ -31,7 +31,7 @@ pub fn expand_deriving_totalord(cx: @ExtCtxt, generics: LifetimeBounds::empty(), explicit_self: borrowed_explicit_self(), args: ~[borrowed_self()], - ret_ty: Literal(Path::new(~["core", "cmp", "Ordering"])), + ret_ty: Literal(Path::new(~["std", "cmp", "Ordering"])), const_nonmatching: false, combine_substructure: cs_cmp } @@ -51,7 +51,7 @@ pub fn ordering_const(cx: @ExtCtxt, span: span, cnst: Ordering) -> @expr { }; cx.expr_path( cx.path_global(span, - ~[cx.ident_of("core"), + ~[cx.ident_of("std"), cx.ident_of("cmp"), cx.ident_of(cnst)])) } @@ -64,7 +64,7 @@ pub fn cs_cmp(cx: @ExtCtxt, span: span, false, |cx, span, old, new| { cx.expr_call_global(span, - ~[cx.ident_of("core"), + ~[cx.ident_of("std"), cx.ident_of("cmp"), cx.ident_of("lexical_ordering")], ~[old, new]) diff --git a/src/libsyntax/ext/deriving/iter_bytes.rs b/src/libsyntax/ext/deriving/iter_bytes.rs index 7a818a4e04f52..401b91227fc0d 100644 --- a/src/libsyntax/ext/deriving/iter_bytes.rs +++ b/src/libsyntax/ext/deriving/iter_bytes.rs @@ -21,7 +21,7 @@ pub fn expand_deriving_iter_bytes(cx: @ExtCtxt, mitem: @meta_item, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~["core", "to_bytes", "IterBytes"]), + path: Path::new(~["std", "to_bytes", "IterBytes"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ @@ -31,7 +31,7 @@ pub fn expand_deriving_iter_bytes(cx: @ExtCtxt, explicit_self: borrowed_explicit_self(), args: ~[ Literal(Path::new(~["bool"])), - Literal(Path::new(~["core", "to_bytes", "Cb"])) + Literal(Path::new(~["std", "to_bytes", "Cb"])) ], ret_ty: Literal(Path::new(~["bool"])), const_nonmatching: false, diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 63ef871614909..3159b6db0af39 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -13,7 +13,7 @@ The compiler code necessary to implement the #[deriving] extensions. FIXME (#2810)--Hygiene. Search for "__" strings (in other files too). -We also assume "extra" is the standard library, and "core" is the core +We also assume "extra" is the standard library, and "std" is the core library. */ diff --git a/src/libsyntax/ext/deriving/rand.rs b/src/libsyntax/ext/deriving/rand.rs index df92693d3246a..d62e4972fd1fd 100644 --- a/src/libsyntax/ext/deriving/rand.rs +++ b/src/libsyntax/ext/deriving/rand.rs @@ -23,7 +23,7 @@ pub fn expand_deriving_rand(cx: @ExtCtxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~["core", "rand", "Rand"]), + path: Path::new(~["std", "rand", "Rand"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ @@ -32,7 +32,7 @@ pub fn expand_deriving_rand(cx: @ExtCtxt, generics: LifetimeBounds { lifetimes: ~[], bounds: ~[("R", - ~[ Path::new(~["core", "rand", "Rng"]) ])] + ~[ Path::new(~["std", "rand", "Rng"]) ])] }, explicit_self: None, args: ~[ @@ -55,7 +55,7 @@ fn rand_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr { _ => cx.bug("Incorrect number of arguments to `rand` in `deriving(Rand)`") }; let rand_ident = ~[ - cx.ident_of("core"), + cx.ident_of("std"), cx.ident_of("rand"), cx.ident_of("Rand"), cx.ident_of("rand") diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs index 2e00bba27b3e3..52efabd4b9b87 100644 --- a/src/libsyntax/ext/deriving/to_str.rs +++ b/src/libsyntax/ext/deriving/to_str.rs @@ -22,7 +22,7 @@ pub fn expand_deriving_to_str(cx: @ExtCtxt, in_items: ~[@item]) -> ~[@item] { let trait_def = TraitDef { - path: Path::new(~["core", "to_str", "ToStr"]), + path: Path::new(~["std", "to_str", "ToStr"]), additional_bounds: ~[], generics: LifetimeBounds::empty(), methods: ~[ @@ -46,7 +46,7 @@ fn to_str_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr [self_obj] => { let self_addr = cx.expr_addr_of(span, self_obj); cx.expr_call_global(span, - ~[cx.ident_of("core"), + ~[cx.ident_of("std"), cx.ident_of("sys"), cx.ident_of("log_str")], ~[self_addr]) diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index c74a4dfb5cdfe..7fa235fc334b8 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -438,28 +438,28 @@ pub fn core_macros() -> ~str { fail!(\"explicit failure\") ); ($msg:expr) => ( - ::core::sys::FailWithCause::fail_with($msg, file!(), line!()) + ::std::sys::FailWithCause::fail_with($msg, file!(), line!()) ); ($( $arg:expr ),+) => ( - ::core::sys::FailWithCause::fail_with(fmt!( $($arg),+ ), file!(), line!()) + ::std::sys::FailWithCause::fail_with(fmt!( $($arg),+ ), file!(), line!()) ) ) macro_rules! assert( ($cond:expr) => { if !$cond { - ::core::sys::FailWithCause::fail_with( + ::std::sys::FailWithCause::fail_with( ~\"assertion failed: \" + stringify!($cond), file!(), line!()) } }; ($cond:expr, $msg:expr) => { if !$cond { - ::core::sys::FailWithCause::fail_with($msg, file!(), line!()) + ::std::sys::FailWithCause::fail_with($msg, file!(), line!()) } }; ($cond:expr, $( $arg:expr ),+) => { if !$cond { - ::core::sys::FailWithCause::fail_with(fmt!( $($arg),+ ), file!(), line!()) + ::std::sys::FailWithCause::fail_with(fmt!( $($arg),+ ), file!(), line!()) } } ) @@ -480,7 +480,7 @@ pub fn core_macros() -> ~str { macro_rules! assert_approx_eq ( ($given:expr , $expected:expr) => ( { - use core::cmp::ApproxEq; + use std::cmp::ApproxEq; let given_val = $given; let expected_val = $expected; @@ -496,7 +496,7 @@ pub fn core_macros() -> ~str { ); ($given:expr , $expected:expr , $epsilon:expr) => ( { - use core::cmp::ApproxEq; + use std::cmp::ApproxEq; let given_val = $given; let expected_val = $expected; @@ -518,11 +518,11 @@ pub fn core_macros() -> ~str { { pub $c:ident: $in:ty -> $out:ty; } => { pub mod $c { - fn key(_x: @::core::condition::Handler<$in,$out>) { } + fn key(_x: @::std::condition::Handler<$in,$out>) { } pub static cond : - ::core::condition::Condition<'static,$in,$out> = - ::core::condition::Condition { + ::std::condition::Condition<'static,$in,$out> = + ::std::condition::Condition { name: stringify!($c), key: key }; @@ -533,11 +533,11 @@ pub fn core_macros() -> ~str { // FIXME (#6009): remove mod's `pub` below once variant above lands. pub mod $c { - fn key(_x: @::core::condition::Handler<$in,$out>) { } + fn key(_x: @::std::condition::Handler<$in,$out>) { } pub static cond : - ::core::condition::Condition<'static,$in,$out> = - ::core::condition::Condition { + ::std::condition::Condition<'static,$in,$out> = + ::std::condition::Condition { name: stringify!($c), key: key }; diff --git a/src/libsyntax/ext/pipes/ast_builder.rs b/src/libsyntax/ext/pipes/ast_builder.rs index 6d6db23a3785e..545b5338ab107 100644 --- a/src/libsyntax/ext/pipes/ast_builder.rs +++ b/src/libsyntax/ext/pipes/ast_builder.rs @@ -63,3 +63,4 @@ impl append_types for @ast::Path { } } } + diff --git a/src/libsyntax/ext/pipes/pipec.rs b/src/libsyntax/ext/pipes/pipec.rs index 7ed375efc547c..1a7b7e55acea9 100644 --- a/src/libsyntax/ext/pipes/pipec.rs +++ b/src/libsyntax/ext/pipes/pipec.rs @@ -77,10 +77,10 @@ impl gen_send for message { }; body += ~"let mut b = pipe.reuse_buffer();\n"; - body += fmt!("let %s = ::core::pipes::SendPacketBuffered(\ + body += fmt!("let %s = ::std::pipes::SendPacketBuffered(\ &mut (b.buffer.data.%s));\n", sp, next.name); - body += fmt!("let %s = ::core::pipes::RecvPacketBuffered(\ + body += fmt!("let %s = ::std::pipes::RecvPacketBuffered(\ &mut (b.buffer.data.%s));\n", rp, next.name); } @@ -92,7 +92,7 @@ impl gen_send for message { (recv, recv) => "(c, s)" }; - body += fmt!("let %s = ::core::pipes::entangle();\n", pat); + body += fmt!("let %s = ::std::pipes::entangle();\n", pat); } body += fmt!("let message = %s(%s);\n", name, @@ -101,14 +101,14 @@ impl gen_send for message { ~"s"), ", ")); if !try { - body += fmt!("::core::pipes::send(pipe, message);\n"); + body += fmt!("::std::pipes::send(pipe, message);\n"); // return the new channel body += ~"c }"; } else { - body += fmt!("if ::core::pipes::send(pipe, message) {\n \ - ::core::pipes::rt::make_some(c) \ - } else { ::core::pipes::rt::make_none() } }"); + body += fmt!("if ::std::pipes::send(pipe, message) {\n \ + ::std::pipes::rt::make_some(c) \ + } else { ::std::pipes::rt::make_none() } }"); } let body = cx.parse_expr(body); @@ -160,14 +160,14 @@ impl gen_send for message { body += fmt!("let message = %s%s;\n", name, message_args); if !try { - body += fmt!("::core::pipes::send(pipe, message);\n"); + body += fmt!("::std::pipes::send(pipe, message);\n"); body += ~" }"; } else { - body += fmt!("if ::core::pipes::send(pipe, message) \ + body += fmt!("if ::std::pipes::send(pipe, message) \ { \ - ::core::pipes::rt::make_some(()) \ + ::std::pipes::rt::make_some(()) \ } else { \ - ::core::pipes::rt::make_none() \ + ::std::pipes::rt::make_none() \ } }"); } @@ -270,7 +270,7 @@ impl to_type_decls for state { self.span, self.data_name(), cx.ty_path( - path_global(~[cx.ident_of("core"), + path_global(~[cx.ident_of("std"), cx.ident_of("pipes"), cx.ident_of(dir.to_str() + "Packet")], dummy_sp()) @@ -288,7 +288,7 @@ impl to_type_decls for state { self.span, self.data_name(), cx.ty_path( - path_global(~[cx.ident_of("core"), + path_global(~[cx.ident_of("std"), cx.ident_of("pipes"), cx.ident_of(dir.to_str() + "PacketBuffered")], @@ -315,10 +315,10 @@ impl gen_init for protocol { let body = if !self.is_bounded() { match start_state.dir { - send => quote_expr!( ::core::pipes::entangle() ), + send => quote_expr!( ::std::pipes::entangle() ), recv => { quote_expr!({ - let (s, c) = ::core::pipes::entangle(); + let (s, c) = ::std::pipes::entangle(); (c, s) }) } @@ -338,7 +338,7 @@ impl gen_init for protocol { }; cx.parse_item(fmt!("pub fn init%s() -> (client::%s, server::%s)\ - { pub use core::pipes::HasBuffer; %s }", + { pub use std::pipes::HasBuffer; %s }", start_state.generics.to_source(cx), start_state.to_ty(cx).to_source(cx), start_state.to_ty(cx).to_source(cx), @@ -355,7 +355,7 @@ impl gen_init for protocol { ext_cx.field_imm(dummy_sp(), ext_cx.ident_of(s.name), quote_expr!( - ::core::pipes::mk_packet::<$fty>() + ::std::pipes::mk_packet::<$fty>() )) })) } @@ -363,8 +363,8 @@ impl gen_init for protocol { fn gen_init_bounded(&self, ext_cx: @ExtCtxt) -> @ast::expr { debug!("gen_init_bounded"); let buffer_fields = self.gen_buffer_init(ext_cx); - let buffer = quote_expr!(~::core::pipes::Buffer { - header: ::core::pipes::BufferHeader(), + let buffer = quote_expr!(~::std::pipes::Buffer { + header: ::std::pipes::BufferHeader(), data: $buffer_fields, }); @@ -376,12 +376,12 @@ impl gen_init for protocol { fmt!("data.%s.set_buffer(buffer)", s.name))), Some(ext_cx.parse_expr(fmt!( - "::core::ptr::to_mut_unsafe_ptr(&mut (data.%s))", + "::std::ptr::to_mut_unsafe_ptr(&mut (data.%s))", self.states[0].name))))); quote_expr!({ let buffer = $buffer; - do ::core::pipes::entangle_buffer(buffer) |buffer, data| { + do ::std::pipes::entangle_buffer(buffer) |buffer, data| { $entangle_body } }) @@ -416,7 +416,7 @@ impl gen_init for protocol { } let ty = s.to_ty(cx); - let fty = quote_ty!( ::core::pipes::Packet<$ty> ); + let fty = quote_ty!( ::std::pipes::Packet<$ty> ); @spanned { node: ast::struct_field_ { diff --git a/src/libsyntax/syntax.rc b/src/libsyntax/syntax.rc index 8ec281a6bc1f7..cb1c2269c1e0a 100644 --- a/src/libsyntax/syntax.rc +++ b/src/libsyntax/syntax.rc @@ -32,6 +32,8 @@ extern mod extra(name = "extra"); // For deriving(Encodable) purposes... #[cfg(stage0)] extern mod std(name = "extra"); +#[cfg(not(stage0))] +extern mod std(name = "std"); use core::prelude::*; From 1be40be613177d4849f42da284a3af74e1d58da2 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Mon, 20 May 2013 17:07:24 -0700 Subject: [PATCH 195/248] test: Update tests to use the new syntax. --- src/test/auxiliary/cci_capture_clause.rs | 2 +- src/test/auxiliary/cci_class_cast.rs | 2 +- src/test/auxiliary/issue-2526.rs | 2 +- src/test/auxiliary/issue-2631-a.rs | 4 ++-- .../trait_inheritance_overloading_xc.rs | 2 +- src/test/bench/core-map.rs | 16 +++++++------- src/test/bench/core-set.rs | 18 +++++++-------- src/test/bench/core-std.rs | 10 ++++----- src/test/bench/graph500-bfs.rs | 16 +++++++------- src/test/bench/msgsend-pipes-shared.rs | 12 +++++----- src/test/bench/msgsend-pipes.rs | 12 +++++----- src/test/bench/msgsend-ring-mutex-arcs.rs | 10 ++++----- src/test/bench/msgsend-ring-pipes.rs | 12 +++++----- src/test/bench/msgsend-ring-rw-arcs.rs | 10 ++++----- src/test/bench/noise.rs | 2 +- src/test/bench/pingpong.rs | 12 +++++----- src/test/bench/shootout-ackermann.rs | 2 +- src/test/bench/shootout-binarytrees.rs | 4 ++-- src/test/bench/shootout-chameneos-redux.rs | 8 +++---- src/test/bench/shootout-fannkuch-redux.rs | 6 ++--- src/test/bench/shootout-fasta-redux.rs | 10 ++++----- src/test/bench/shootout-fasta.rs | 4 ++-- src/test/bench/shootout-fibo.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 14 ++++++------ src/test/bench/shootout-k-nucleotide.rs | 20 ++++++++--------- src/test/bench/shootout-mandelbrot.rs | 8 +++---- src/test/bench/shootout-nbody.rs | 4 ++-- src/test/bench/shootout-pfib.rs | 12 +++++----- src/test/bench/shootout-pidigits.rs | 10 ++++----- src/test/bench/shootout-reverse-complement.rs | 12 +++++----- src/test/bench/shootout-spectralnorm.rs | 4 ++-- src/test/bench/std-smallintmap.rs | 12 +++++----- src/test/bench/sudoku.rs | 8 +++---- src/test/bench/task-perf-alloc-unwind.rs | 6 ++--- .../bench/task-perf-jargon-metal-smoke.rs | 2 +- src/test/bench/task-perf-linked-failure.rs | 2 +- src/test/bench/task-perf-one-million.rs | 2 +- .../compile-fail/arc-cant-nest-rw-arc-3177.rs | 4 ++-- .../arc-rw-cond-shouldnt-escape.rs | 4 ++-- .../arc-rw-read-mode-shouldnt-escape.rs | 4 ++-- .../arc-rw-state-shouldnt-escape.rs | 4 ++-- .../arc-rw-write-mode-cond-shouldnt-escape.rs | 4 ++-- .../arc-rw-write-mode-shouldnt-escape.rs | 4 ++-- .../borrowck-borrowed-uniq-rvalue.rs | 2 +- .../borrowck-insert-during-each.rs | 2 +- ...borrowck-loan-local-as-both-mut-and-imm.rs | 2 +- .../compile-fail/borrowck-move-by-capture.rs | 2 +- .../borrowck-vec-pattern-move-tail.rs | 2 +- .../compile-fail/core-tls-store-pointer.rs | 2 +- .../compile-fail/extfmt-not-enough-args.rs | 2 +- src/test/compile-fail/extfmt-too-many-args.rs | 2 +- src/test/compile-fail/fail-expr.rs | 2 +- src/test/compile-fail/fail-type-err.rs | 2 +- src/test/compile-fail/forget-init-unsafe.rs | 2 +- .../fully-qualified-type-name1.rs | 2 +- .../fully-qualified-type-name4.rs | 4 ++-- src/test/compile-fail/issue-2766-a.rs | 4 ++-- src/test/compile-fail/issue-3021-b.rs | 2 +- src/test/compile-fail/issue-3021-c.rs | 2 +- src/test/compile-fail/issue-3021-d.rs | 2 +- src/test/compile-fail/issue-3021.rs | 2 +- src/test/compile-fail/issue-3296.rs | 6 ++--- src/test/compile-fail/issue-3680.rs | 2 +- src/test/compile-fail/issue-3953.rs | 2 +- src/test/compile-fail/issue-511.rs | 4 ++-- src/test/compile-fail/issue-5358-1.rs | 2 +- src/test/compile-fail/issue-5358.rs | 2 +- src/test/compile-fail/lint-unused-imports.rs | 16 +++++++------- src/test/compile-fail/map-types.rs | 6 ++--- ...s-based-on-type-cyclic-types-issue-4821.rs | 2 +- .../compile-fail/mutable-huh-ptr-assign.rs | 2 +- src/test/compile-fail/name-clash-nullary.rs | 2 +- src/test/compile-fail/no-capture-arc.rs | 4 ++-- src/test/compile-fail/no-reuse-move-arc.rs | 4 ++-- src/test/compile-fail/no-send-res-ports.rs | 2 +- src/test/compile-fail/noexporttypeexe.rs | 2 +- src/test/compile-fail/pattern-tyvar-2.rs | 2 +- src/test/compile-fail/pattern-tyvar.rs | 2 +- src/test/compile-fail/qquote-1.rs | 2 +- src/test/compile-fail/qquote-2.rs | 4 ++-- .../compile-fail/regions-glb-free-free.rs | 2 +- src/test/compile-fail/seq-args.rs | 2 +- src/test/compile-fail/spawn-non-nil-fn.rs | 2 +- .../compile-fail/sync-cond-shouldnt-escape.rs | 4 ++-- .../sync-rwlock-cond-shouldnt-escape.rs | 4 ++-- .../sync-rwlock-read-mode-shouldnt-escape.rs | 4 ++-- ...-rwlock-write-mode-cond-shouldnt-escape.rs | 4 ++-- .../sync-rwlock-write-mode-shouldnt-escape.rs | 4 ++-- .../tag-that-dare-not-speak-its-name.rs | 4 ++-- src/test/compile-fail/use-meta-dup.rs | 2 +- src/test/compile-fail/use-meta-mismatch.rs | 4 ++-- src/test/compile-fail/view-items-at-top.rs | 4 ++-- src/test/run-fail/extern-fail.rs | 2 +- src/test/run-fail/fail-main.rs | 2 +- src/test/run-fail/fmt-fail.rs | 2 +- src/test/run-fail/for-each-loop-fail.rs | 2 +- src/test/run-fail/issue-2156.rs | 4 ++-- src/test/run-fail/issue-2444.rs | 4 ++-- src/test/run-fail/linked-failure.rs | 2 +- src/test/run-fail/morestack2.rs | 2 +- src/test/run-fail/morestack3.rs | 2 +- src/test/run-fail/morestack4.rs | 2 +- src/test/run-fail/run-unexported-tests.rs | 2 +- src/test/run-fail/spawnfail.rs | 2 +- src/test/run-fail/unwind-misc-1.rs | 2 +- src/test/run-fail/zip-different-lengths.rs | 4 ++-- src/test/run-pass-fulldeps/qquote.rs | 4 ++-- src/test/run-pass/alt-join.rs | 2 +- src/test/run-pass/alt-pattern-drop.rs | 16 +++++++------- src/test/run-pass/attr-before-view-item.rs | 2 +- src/test/run-pass/attr-before-view-item2.rs | 2 +- src/test/run-pass/auto-encode.rs | 16 +++++++------- src/test/run-pass/bind-by-move.rs | 4 ++-- src/test/run-pass/binops.rs | 10 ++++----- src/test/run-pass/bitv-perf-test.rs | 4 ++-- src/test/run-pass/block-arg-call-as.rs | 2 +- src/test/run-pass/block-vec-map_zip.rs | 2 +- src/test/run-pass/borrowck-mut-uniq.rs | 2 +- src/test/run-pass/c-stack-returning-int64.rs | 2 +- src/test/run-pass/capture_nil.rs | 2 +- src/test/run-pass/child-outlives-parent.rs | 2 +- .../class-cast-to-trait-cross-crate-2.rs | 2 +- .../class-impl-parameterized-trait.rs | 4 ++-- .../class-impl-very-parameterized-trait.rs | 4 ++-- .../class-implements-multiple-traits.rs | 4 ++-- .../run-pass/class-trait-bounded-param.rs | 4 ++-- src/test/run-pass/clone-with-exterior.rs | 4 ++-- src/test/run-pass/coherence-impl-in-fn.rs | 2 +- src/test/run-pass/comm.rs | 2 +- src/test/run-pass/core-export-f64-sqrt.rs | 2 +- src/test/run-pass/core-run-destroy.rs | 12 +++++----- src/test/run-pass/deriving-meta-multiple.rs | 2 +- src/test/run-pass/deriving-meta.rs | 2 +- ...deriving-self-lifetime-totalord-totaleq.rs | 2 +- src/test/run-pass/drop-trait-generic.rs | 2 +- src/test/run-pass/duplicate-use.rs | 6 ++--- src/test/run-pass/explicit-self-generic.rs | 2 +- src/test/run-pass/expr-repeat-vstore.rs | 2 +- src/test/run-pass/extern-mod-syntax.rs | 4 ++-- src/test/run-pass/float-nan.rs | 4 ++-- src/test/run-pass/fn-bare-size.rs | 2 +- src/test/run-pass/foreign-call-no-runtime.rs | 2 +- src/test/run-pass/foreign-fn-linkname.rs | 2 +- src/test/run-pass/foreign2.rs | 4 ++-- src/test/run-pass/getopts_ref.rs | 4 ++-- src/test/run-pass/hashmap-memory.rs | 4 ++-- src/test/run-pass/import-glob-crate.rs | 4 ++-- src/test/run-pass/import-in-block.rs | 6 ++--- src/test/run-pass/infinite-loops.rs | 2 +- src/test/run-pass/intrinsics-integer.rs | 2 +- src/test/run-pass/issue-1696.rs | 2 +- src/test/run-pass/issue-2101.rs | 6 ++--- src/test/run-pass/issue-2214.rs | 8 +++---- src/test/run-pass/issue-2383.rs | 4 ++-- src/test/run-pass/issue-2611.rs | 2 +- src/test/run-pass/issue-2631-b.rs | 2 +- src/test/run-pass/issue-2718.rs | 16 +++++++------- src/test/run-pass/issue-2804-2.rs | 2 +- src/test/run-pass/issue-2804.rs | 16 +++++++------- src/test/run-pass/issue-2904.rs | 4 ++-- src/test/run-pass/issue-2989.rs | 2 +- src/test/run-pass/issue-3026.rs | 2 +- src/test/run-pass/issue-3176.rs | 2 +- src/test/run-pass/issue-3424.rs | 4 ++-- src/test/run-pass/issue-3556.rs | 4 ++-- src/test/run-pass/issue-3559.rs | 6 ++--- src/test/run-pass/issue-3563-3.rs | 8 +++---- src/test/run-pass/issue-3574.rs | 2 +- src/test/run-pass/issue-3609.rs | 4 ++-- src/test/run-pass/issue-3656.rs | 2 +- src/test/run-pass/issue-4016.rs | 6 ++--- src/test/run-pass/issue-4036.rs | 6 ++--- src/test/run-pass/issue-4092.rs | 2 +- src/test/run-pass/issue-4241.rs | 6 ++--- src/test/run-pass/issue-4541.rs | 2 +- src/test/run-pass/item-attributes.rs | 6 ++--- src/test/run-pass/ivec-tag.rs | 2 +- .../log-knows-the-names-of-variants-in-std.rs | 4 ++-- src/test/run-pass/lots-a-fail.rs | 2 +- src/test/run-pass/mlist-cycle.rs | 6 ++--- src/test/run-pass/mod-view-items.rs | 2 +- ...nomorphized-callees-with-ty-params-3314.rs | 2 +- src/test/run-pass/morestack5.rs | 2 +- src/test/run-pass/morestack6.rs | 2 +- src/test/run-pass/move-3-unique.rs | 2 +- src/test/run-pass/move-3.rs | 2 +- src/test/run-pass/move-4-unique.rs | 2 +- src/test/run-pass/move-4.rs | 2 +- src/test/run-pass/mutable-alias-vec.rs | 2 +- src/test/run-pass/new-import-syntax.rs | 2 +- src/test/run-pass/new-style-constants.rs | 2 +- .../run-pass/new-style-fixed-length-vec.rs | 2 +- src/test/run-pass/newtype-struct-with-dtor.rs | 4 ++-- src/test/run-pass/non-boolean-pure-fns.rs | 4 ++-- .../nullable-pointer-iotareduction.rs | 2 +- src/test/run-pass/overload-index-operator.rs | 2 +- src/test/run-pass/pipe-bank-proto.rs | 4 ++-- src/test/run-pass/pipe-detect-term.rs | 10 ++++----- src/test/run-pass/pipe-peek.rs | 8 +++---- src/test/run-pass/pipe-pingpong-bounded.rs | 22 +++++++++---------- src/test/run-pass/pipe-pingpong-proto.rs | 6 ++--- .../run-pass/pipe-presentation-examples.rs | 6 ++--- src/test/run-pass/pipe-select.rs | 12 +++++----- src/test/run-pass/pipe-sleep.rs | 12 +++++----- src/test/run-pass/placement-new-arena.rs | 4 ++-- src/test/run-pass/reflect-visit-data.rs | 6 ++--- .../regions-infer-borrow-scope-addr-of.rs | 2 +- src/test/run-pass/ret-break-cont-in-block.rs | 2 +- src/test/run-pass/rt-sched-1.rs | 2 +- src/test/run-pass/send-iloop.rs | 2 +- src/test/run-pass/send-resource.rs | 2 +- src/test/run-pass/send-type-inference.rs | 2 +- src/test/run-pass/sendfn-spawn-with-fn-arg.rs | 2 +- .../run-pass/shape_intrinsic_tag_then_rec.rs | 6 ++--- src/test/run-pass/spawn-types.rs | 2 +- src/test/run-pass/spawn.rs | 2 +- src/test/run-pass/stat.rs | 6 ++--- src/test/run-pass/str-append.rs | 2 +- src/test/run-pass/str-multiline.rs | 2 +- src/test/run-pass/string-self-append.rs | 2 +- src/test/run-pass/swap-1.rs | 2 +- src/test/run-pass/swap-2.rs | 2 +- src/test/run-pass/swap-overlapping.rs | 2 +- src/test/run-pass/syntax-extension-fmt.rs | 2 +- src/test/run-pass/task-comm-0.rs | 6 ++--- src/test/run-pass/task-comm-10.rs | 2 +- src/test/run-pass/task-comm-11.rs | 2 +- src/test/run-pass/task-comm-12.rs | 2 +- src/test/run-pass/task-comm-13.rs | 2 +- src/test/run-pass/task-comm-15.rs | 2 +- src/test/run-pass/task-comm-17.rs | 2 +- src/test/run-pass/task-comm-3.rs | 4 ++-- src/test/run-pass/task-comm-5.rs | 2 +- src/test/run-pass/task-comm-6.rs | 2 +- src/test/run-pass/task-comm-7.rs | 2 +- src/test/run-pass/task-comm-9.rs | 2 +- src/test/run-pass/task-comm-chan-nil.rs | 2 +- src/test/run-pass/task-killjoin-rsrc.rs | 4 ++-- src/test/run-pass/task-life-0.rs | 2 +- src/test/run-pass/task-spawn-move-and-copy.rs | 2 +- src/test/run-pass/terminate-in-initializer.rs | 2 +- src/test/run-pass/test-ignore-cfg.rs | 2 +- src/test/run-pass/test-runner-hides-main.rs | 2 +- src/test/run-pass/threads.rs | 2 +- src/test/run-pass/trait-inheritance-num.rs | 6 ++--- src/test/run-pass/trait-inheritance-num0.rs | 2 +- src/test/run-pass/trait-inheritance-num1.rs | 4 ++-- src/test/run-pass/trait-inheritance-num2.rs | 4 ++-- src/test/run-pass/trait-inheritance-num3.rs | 4 ++-- src/test/run-pass/trait-inheritance-num5.rs | 4 ++-- .../trait-inheritance-overloading-simple.rs | 2 +- .../run-pass/trait-inheritance-overloading.rs | 2 +- src/test/run-pass/trait-to-str.rs | 4 ++-- src/test/run-pass/type-sizes.rs | 4 ++-- src/test/run-pass/unify-return-ty.rs | 2 +- src/test/run-pass/unique-kinds.rs | 2 +- src/test/run-pass/unique-send-2.rs | 2 +- src/test/run-pass/unique-send.rs | 2 +- src/test/run-pass/unique-swap.rs | 2 +- src/test/run-pass/unwind-box.rs | 2 +- src/test/run-pass/unwind-resource.rs | 4 ++-- src/test/run-pass/unwind-resource2.rs | 2 +- src/test/run-pass/unwind-unique.rs | 2 +- src/test/run-pass/use-crate-name-alias.rs | 2 +- src/test/run-pass/use.rs | 10 ++++----- src/test/run-pass/utf8_chars.rs | 2 +- src/test/run-pass/vec-matching-autoslice.rs | 10 ++++----- .../vec-matching-legal-tail-element-borrow.rs | 2 +- src/test/run-pass/vec-matching.rs | 10 ++++----- src/test/run-pass/vec-self-append.rs | 2 +- src/test/run-pass/vec-tail-matching.rs | 6 ++--- src/test/run-pass/weird-exprs.rs | 2 +- 272 files changed, 565 insertions(+), 565 deletions(-) diff --git a/src/test/auxiliary/cci_capture_clause.rs b/src/test/auxiliary/cci_capture_clause.rs index f2749ed1d0c05..13cc27e0e2785 100644 --- a/src/test/auxiliary/cci_capture_clause.rs +++ b/src/test/auxiliary/cci_capture_clause.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::*; +use std::comm::*; pub fn foo(x: T) -> Port { let (p, c) = stream(); diff --git a/src/test/auxiliary/cci_class_cast.rs b/src/test/auxiliary/cci_class_cast.rs index ae0407a5bed33..56808b0d58f8d 100644 --- a/src/test/auxiliary/cci_class_cast.rs +++ b/src/test/auxiliary/cci_class_cast.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::to_str::*; +use std::to_str::*; pub mod kitty { pub struct cat { diff --git a/src/test/auxiliary/issue-2526.rs b/src/test/auxiliary/issue-2526.rs index 0e9cf39929f1c..bbc0f1ad3e558 100644 --- a/src/test/auxiliary/issue-2526.rs +++ b/src/test/auxiliary/issue-2526.rs @@ -13,7 +13,7 @@ uuid = "54cc1bc9-02b8-447c-a227-75ebc923bc29")]; #[crate_type = "lib"]; -extern mod std; +extern mod extra; struct arc_destruct { _data: int, diff --git a/src/test/auxiliary/issue-2631-a.rs b/src/test/auxiliary/issue-2631-a.rs index bee754f5bd448..8afc032775590 100644 --- a/src/test/auxiliary/issue-2631-a.rs +++ b/src/test/auxiliary/issue-2631-a.rs @@ -11,9 +11,9 @@ #[link(name = "req")]; #[crate_type = "lib"]; -extern mod std; +extern mod extra; -use core::hashmap::HashMap; +use std::hashmap::HashMap; pub type header_map = HashMap<~str, @mut ~[@~str]>; diff --git a/src/test/auxiliary/trait_inheritance_overloading_xc.rs b/src/test/auxiliary/trait_inheritance_overloading_xc.rs index 1fb0db25b31a8..f938c9c56ed94 100644 --- a/src/test/auxiliary/trait_inheritance_overloading_xc.rs +++ b/src/test/auxiliary/trait_inheritance_overloading_xc.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::Eq; +use std::cmp::Eq; pub trait MyNum : Add + Sub + Mul + Eq { } diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index 0d951771d7014..7904041ea3cb3 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -8,14 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; -use core::io; -use std::time; -use std::treemap::TreeMap; -use core::hashmap::{HashMap, HashSet}; -use core::trie::TrieMap; -use core::rand::Rng; +use std::io; +use extra::time; +use extra::treemap::TreeMap; +use std::hashmap::{HashMap, HashSet}; +use std::trie::TrieMap; +use std::rand::Rng; fn timed(label: &str, f: &fn()) { let start = time::precise_time_s(); @@ -103,7 +103,7 @@ fn main() { let mut rand = vec::with_capacity(n_keys); { - let mut rng = core::rand::IsaacRng::new_seeded([1, 1, 1, 1, 1, 1, 1]); + let mut rng = std::rand::IsaacRng::new_seeded([1, 1, 1, 1, 1, 1, 1]); let mut set = HashSet::new(); while set.len() != n_keys { let next = rng.next() as uint; diff --git a/src/test/bench/core-set.rs b/src/test/bench/core-set.rs index bae21c6d4a325..86215e609eea2 100644 --- a/src/test/bench/core-set.rs +++ b/src/test/bench/core-set.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use core::hashmap::HashSet; -use std::bitv::BitvSet; -use std::treemap::TreeSet; +extern mod extra; +use std::hashmap::HashSet; +use extra::bitv::BitvSet; +use extra::treemap::TreeSet; struct Results { sequential_ints: float, @@ -24,9 +24,9 @@ struct Results { } fn timed(result: &mut float, op: &fn()) { - let start = std::time::precise_time_s(); + let start = extra::time::precise_time_s(); op(); - let end = std::time::precise_time_s(); + let end = extra::time::precise_time_s(); *result = (end - start); } @@ -168,7 +168,7 @@ fn main() { let mut results = empty_results(); results.bench_int(&mut rng, num_keys, max, || HashSet::new::()); results.bench_str(&mut rng, num_keys, || HashSet::new::<~str>()); - write_results("core::hashmap::HashSet", &results); + write_results("std::hashmap::HashSet", &results); } { @@ -176,13 +176,13 @@ fn main() { let mut results = empty_results(); results.bench_int(&mut rng, num_keys, max, || TreeSet::new::()); results.bench_str(&mut rng, num_keys, || TreeSet::new::<~str>()); - write_results("std::treemap::TreeSet", &results); + write_results("extra::treemap::TreeSet", &results); } { let mut rng = rand::IsaacRng::new_seeded(seed); let mut results = empty_results(); results.bench_int(&mut rng, num_keys, max, || BitvSet::new()); - write_results("std::bitv::BitvSet", &results); + write_results("extra::bitv::BitvSet", &results); } } diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index e6b3b3bbe20d3..024d4a0289779 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -8,13 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Microbenchmarks for various functions in core and std +// Microbenchmarks for various functions in std and extra -extern mod std; +extern mod extra; -use std::time::precise_time_s; -use core::rand::RngUtil; -use core::util; +use extra::time::precise_time_s; +use std::rand::RngUtil; +use std::util; macro_rules! bench ( ($id:ident) => (maybe_run_test(argv, stringify!($id).to_owned(), $id)) diff --git a/src/test/bench/graph500-bfs.rs b/src/test/bench/graph500-bfs.rs index 4be2cca0b4855..734b5a0006f90 100644 --- a/src/test/bench/graph500-bfs.rs +++ b/src/test/bench/graph500-bfs.rs @@ -16,14 +16,14 @@ An implementation of the Graph500 Breadth First Search problem in Rust. */ -extern mod std; -use std::arc; -use std::time; -use std::deque::Deque; -use std::par; -use core::hashmap::HashSet; -use core::int::abs; -use core::rand::RngUtil; +extern mod extra; +use extra::arc; +use extra::time; +use extra::deque::Deque; +use extra::par; +use std::hashmap::HashSet; +use std::int::abs; +use std::rand::RngUtil; type node_id = i64; type graph = ~[~[node_id]]; diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index d1be03e944ae1..e041f60705758 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -18,11 +18,11 @@ // different scalability characteristics compared to the select // version. -extern mod std; -use core::io::Writer; -use core::io::WriterUtil; +extern mod extra; +use std::io::Writer; +use std::io::WriterUtil; -use core::comm::{Port, Chan, SharedChan}; +use std::comm::{Port, Chan, SharedChan}; macro_rules! move_out ( { $x:expr } => { unsafe { let y = *ptr::to_unsafe_ptr(&($x)); y } } @@ -61,7 +61,7 @@ fn run(args: &[~str]) { let size = uint::from_str(args[1]).get(); let workers = uint::from_str(args[2]).get(); let num_bytes = 100; - let start = std::time::precise_time_s(); + let start = extra::time::precise_time_s(); let mut worker_results = ~[]; for uint::range(0, workers) |_i| { let to_child = to_child.clone(); @@ -87,7 +87,7 @@ fn run(args: &[~str]) { to_child.send(stop); move_out!(to_child); let result = from_child.recv(); - let end = std::time::precise_time_s(); + let end = extra::time::precise_time_s(); let elapsed = end - start; io::stdout().write_str(fmt!("Count is %?\n", result)); io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed)); diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index b72a38d4054bd..a854de0a828f7 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -14,11 +14,11 @@ // // I *think* it's the same, more or less. -extern mod std; -use core::io::Writer; -use core::io::WriterUtil; +extern mod extra; +use std::io::Writer; +use std::io::WriterUtil; -use core::comm::{Port, PortSet, Chan, stream}; +use std::comm::{Port, PortSet, Chan, stream}; macro_rules! move_out ( { $x:expr } => { unsafe { let y = *ptr::to_unsafe_ptr(&($x)); y } } @@ -57,7 +57,7 @@ fn run(args: &[~str]) { let size = uint::from_str(args[1]).get(); let workers = uint::from_str(args[2]).get(); let num_bytes = 100; - let start = std::time::precise_time_s(); + let start = extra::time::precise_time_s(); let mut worker_results = ~[]; for uint::range(0, workers) |_i| { let (from_parent_, to_child) = stream(); @@ -84,7 +84,7 @@ fn run(args: &[~str]) { to_child.send(stop); move_out!(to_child); let result = from_child.recv(); - let end = std::time::precise_time_s(); + let end = extra::time::precise_time_s(); let elapsed = end - start; io::stdout().write_str(fmt!("Count is %?\n", result)); io::stdout().write_str(fmt!("Test took %? seconds\n", elapsed)); diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index 2d234634cc8ba..ffca59e3e8fd4 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -15,11 +15,11 @@ // This also serves as a pipes test, because ARCs are implemented with pipes. -extern mod std; -use std::time; -use std::arc; -use std::future; -use core::cell::Cell; +extern mod extra; +use extra::time; +use extra::arc; +use extra::future; +use std::cell::Cell; // A poor man's pipe. type pipe = arc::MutexARC<~[uint]>; diff --git a/src/test/bench/msgsend-ring-pipes.rs b/src/test/bench/msgsend-ring-pipes.rs index f698b2c3c1137..7b6e94fa10b3e 100644 --- a/src/test/bench/msgsend-ring-pipes.rs +++ b/src/test/bench/msgsend-ring-pipes.rs @@ -16,13 +16,13 @@ // This version uses automatically compiled channel contracts. -extern mod std; +extern mod extra; -use core::cell::Cell; -use core::pipes::recv; -use core::util; -use std::time; -use std::future; +use std::cell::Cell; +use std::pipes::recv; +use std::util; +use extra::time; +use extra::future; proto! ring ( num:send { diff --git a/src/test/bench/msgsend-ring-rw-arcs.rs b/src/test/bench/msgsend-ring-rw-arcs.rs index 02415c4bcfce7..78f7c02a40bbd 100644 --- a/src/test/bench/msgsend-ring-rw-arcs.rs +++ b/src/test/bench/msgsend-ring-rw-arcs.rs @@ -15,12 +15,12 @@ // This also serves as a pipes test, because ARCs are implemented with pipes. -extern mod std; +extern mod extra; -use core::cell::Cell; -use std::time; -use std::arc; -use std::future; +use std::cell::Cell; +use extra::time; +use extra::arc; +use extra::future; // A poor man's pipe. type pipe = arc::RWARC<~[uint]>; diff --git a/src/test/bench/noise.rs b/src/test/bench/noise.rs index 992ce73a4bff7..cf1eae3d37b07 100644 --- a/src/test/bench/noise.rs +++ b/src/test/bench/noise.rs @@ -1,6 +1,6 @@ // Perlin noise benchmark from https://gist.github.com/1170424 -use core::rand::{Rng, RngUtil}; +use std::rand::{Rng, RngUtil}; struct Vec2 { x: f32, diff --git a/src/test/bench/pingpong.rs b/src/test/bench/pingpong.rs index cfad253cfed5b..970a970feb159 100644 --- a/src/test/bench/pingpong.rs +++ b/src/test/bench/pingpong.rs @@ -12,11 +12,11 @@ // xfail-pretty -extern mod std; +extern mod extra; -use core::cell::Cell; -use core::pipes::*; -use std::time::precise_time_s; +use std::cell::Cell; +use std::pipes::*; +use extra::time::precise_time_s; proto! pingpong ( ping: send { @@ -117,10 +117,10 @@ pub fn spawn_service_recv( client } -fn switch(endp: core::pipes::RecvPacketBuffered, +fn switch(endp: std::pipes::RecvPacketBuffered, f: &fn(v: Option) -> U) -> U { - f(core::pipes::try_recv(endp)) + f(std::pipes::try_recv(endp)) } // Here's the benchmark diff --git a/src/test/bench/shootout-ackermann.rs b/src/test/bench/shootout-ackermann.rs index c8ffad025fa68..4a81130567927 100644 --- a/src/test/bench/shootout-ackermann.rs +++ b/src/test/bench/shootout-ackermann.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn ack(m: int, n: int) -> int { if m == 0 { diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index c420e0cbb2fd0..e7aed911cb0a2 100644 --- a/src/test/bench/shootout-binarytrees.rs +++ b/src/test/bench/shootout-binarytrees.rs @@ -12,8 +12,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::arena; +extern mod extra; +use extra::arena; enum tree<'self> { nil, diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index 03d4525243272..0ccb9a16adae6 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -10,10 +10,10 @@ // chameneos -extern mod std; -use std::sort; -use core::cell::Cell; -use core::comm::*; +extern mod extra; +use extra::sort; +use std::cell::Cell; +use std::comm::*; fn print_complements() { let all = ~[Blue, Red, Yellow]; diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index cb32e0e496e95..a65bfe228b2d5 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -1,6 +1,6 @@ -use core::from_str::FromStr; -use core::i32::range; -use core::vec::MutableVector; +use std::from_str::FromStr; +use std::i32::range; +use std::vec::MutableVector; fn max(a: i32, b: i32) -> i32 { if a > b { diff --git a/src/test/bench/shootout-fasta-redux.rs b/src/test/bench/shootout-fasta-redux.rs index d6a0f4b8b255e..840f6fdb17bdc 100644 --- a/src/test/bench/shootout-fasta-redux.rs +++ b/src/test/bench/shootout-fasta-redux.rs @@ -1,8 +1,8 @@ -use core::cast::transmute; -use core::from_str::FromStr; -use core::libc::{FILE, STDOUT_FILENO, c_int, fdopen, fputc, fputs, fwrite, size_t}; -use core::uint::{min, range}; -use core::vec::bytes::copy_memory; +use std::cast::transmute; +use std::from_str::FromStr; +use std::libc::{FILE, STDOUT_FILENO, c_int, fdopen, fputc, fputs, fwrite, size_t}; +use std::uint::{min, range}; +use std::vec::bytes::copy_memory; static LINE_LEN: uint = 60; static LOOKUP_SIZE: uint = 4 * 1024; diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 7316b68f8bd42..f3de8bf01e9a2 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -15,8 +15,8 @@ * Computer Language Benchmarks Game * http://shootout.alioth.debian.org/ */ -extern mod std; -use core::rand::Rng; +extern mod extra; +use std::rand::Rng; fn LINE_LENGTH() -> uint { return 60u; } diff --git a/src/test/bench/shootout-fibo.rs b/src/test/bench/shootout-fibo.rs index b080aded8c45e..cfb8e0fe7c9eb 100644 --- a/src/test/bench/shootout-fibo.rs +++ b/src/test/bench/shootout-fibo.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn fib(n: int) -> int { if n < 2 { diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 3c32ec338b7ec..e0ffd3e4133d9 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -11,13 +11,13 @@ // xfail-pretty (extra blank line is inserted in vec::mapi call) // multi tasking k-nucleotide -extern mod std; -use std::sort; -use core::hashmap::HashMap; -use core::io::ReaderUtil; -use core::comm::{stream, Port, Chan}; -use core::cmp::Ord; -use core::util; +extern mod extra; +use extra::sort; +use std::hashmap::HashMap; +use std::io::ReaderUtil; +use std::comm::{stream, Port, Chan}; +use std::cmp::Ord; +use std::util; // given a map, print a sorted version of it fn sort_and_fmt(mm: &HashMap<~[u8], uint>, total: uint) -> ~str { diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index 1791af67ed040..a70e073007306 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -1,15 +1,15 @@ // xfail-test -extern mod std; - -use core::cast::transmute; -use core::i32::range; -use core::libc::{STDIN_FILENO, c_int, fdopen, fgets, fileno, fopen, fstat}; -use core::libc::{stat, strlen}; -use core::ptr::null; -use core::unstable::intrinsics::init; -use core::vec::{reverse, slice}; -use std::sort::quick_sort3; +extern mod extra; + +use std::cast::transmute; +use std::i32::range; +use std::libc::{STDIN_FILENO, c_int, fdopen, fgets, fileno, fopen, fstat}; +use std::libc::{stat, strlen}; +use std::ptr::null; +use std::unstable::intrinsics::init; +use std::vec::{reverse, slice}; +use extra::sort::quick_sort3; static LINE_LEN: uint = 80; static TABLE: [u8, ..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ]; diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 7d2b25792ec57..d4c3862fd7ea0 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -1,7 +1,7 @@ -use core::cast::transmute; -use core::from_str::FromStr; -use core::i32::range; -use core::libc::{STDOUT_FILENO, c_int, fdopen, fputc}; +use std::cast::transmute; +use std::from_str::FromStr; +use std::i32::range; +use std::libc::{STDOUT_FILENO, c_int, fdopen, fputc}; static ITER: uint = 50; static LIMIT: f64 = 2.0; diff --git a/src/test/bench/shootout-nbody.rs b/src/test/bench/shootout-nbody.rs index da06b36af67ee..a226d50dc27ae 100644 --- a/src/test/bench/shootout-nbody.rs +++ b/src/test/bench/shootout-nbody.rs @@ -1,5 +1,5 @@ -use core::from_str::FromStr; -use core::uint::range; +use std::from_str::FromStr; +use std::uint::range; static PI: f64 = 3.141592653589793; static SOLAR_MASS: f64 = 4.0 * PI * PI; diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 31945310eb32b..e201438a6ef76 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -19,14 +19,14 @@ */ -extern mod std; +extern mod extra; -use std::{time, getopts}; -use core::int::range; -use core::comm::*; -use core::io::WriterUtil; +use extra::{time, getopts}; +use std::int::range; +use std::comm::*; +use std::io::WriterUtil; -use core::result::{Ok, Err}; +use std::result::{Ok, Err}; fn fib(n: int) -> int { fn pfib(c: &Chan, n: int) { diff --git a/src/test/bench/shootout-pidigits.rs b/src/test/bench/shootout-pidigits.rs index cb7fa969be7a7..e84a4ea4327aa 100644 --- a/src/test/bench/shootout-pidigits.rs +++ b/src/test/bench/shootout-pidigits.rs @@ -1,10 +1,10 @@ // xfail-test -use core::cast::transmute; -use core::from_str::FromStr; -use core::libc::{STDOUT_FILENO, c_char, c_int, c_uint, c_void, fdopen, fputc}; -use core::libc::{fputs}; -use core::ptr::null; +use std::cast::transmute; +use std::from_str::FromStr; +use std::libc::{STDOUT_FILENO, c_char, c_int, c_uint, c_void, fdopen, fputc}; +use std::libc::{fputs}; +use std::ptr::null; struct mpz_t { _mp_alloc: c_int, diff --git a/src/test/bench/shootout-reverse-complement.rs b/src/test/bench/shootout-reverse-complement.rs index a9cb3c7636a9b..9893785ecfa22 100644 --- a/src/test/bench/shootout-reverse-complement.rs +++ b/src/test/bench/shootout-reverse-complement.rs @@ -1,12 +1,12 @@ // xfail-pretty // xfail-test -use core::cast::transmute; -use core::libc::{STDOUT_FILENO, c_int, fdopen, fgets, fopen, fputc, fwrite}; -use core::libc::{size_t}; -use core::ptr::null; -use core::vec::{capacity, reserve, reserve_at_least}; -use core::vec::raw::set_len; +use std::cast::transmute; +use std::libc::{STDOUT_FILENO, c_int, fdopen, fgets, fopen, fputc, fwrite}; +use std::libc::{size_t}; +use std::ptr::null; +use std::vec::{capacity, reserve, reserve_at_least}; +use std::vec::raw::set_len; static LINE_LEN: u32 = 80; diff --git a/src/test/bench/shootout-spectralnorm.rs b/src/test/bench/shootout-spectralnorm.rs index 6840384ca7c8a..a3beee7c90df7 100644 --- a/src/test/bench/shootout-spectralnorm.rs +++ b/src/test/bench/shootout-spectralnorm.rs @@ -1,5 +1,5 @@ -use core::from_str::FromStr; -use core::iter::ExtendedMutableIter; +use std::from_str::FromStr; +use std::iter::ExtendedMutableIter; #[inline] fn A(i: i32, j: i32) -> i32 { diff --git a/src/test/bench/std-smallintmap.rs b/src/test/bench/std-smallintmap.rs index 7b8aca2694e80..f1cd05e1d9e92 100644 --- a/src/test/bench/std-smallintmap.rs +++ b/src/test/bench/std-smallintmap.rs @@ -10,9 +10,9 @@ // Microbenchmark for the smallintmap library -extern mod std; -use std::smallintmap::SmallIntMap; -use core::io::WriterUtil; +extern mod extra; +use extra::smallintmap::SmallIntMap; +use std::io::WriterUtil; fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap) { for uint::range(min, max) |i| { @@ -43,11 +43,11 @@ fn main() { for uint::range(0u, rep) |_r| { let mut map = SmallIntMap::new(); - let start = std::time::precise_time_s(); + let start = extra::time::precise_time_s(); append_sequential(0u, max, &mut map); - let mid = std::time::precise_time_s(); + let mid = extra::time::precise_time_s(); check_sequential(0u, max, &map); - let end = std::time::precise_time_s(); + let end = extra::time::precise_time_s(); checkf += (end - mid) as float; appendf += (mid - start) as float; diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 4d8614b5eddb6..e3f02684bb06c 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -10,11 +10,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; -use core::io::{ReaderUtil, WriterUtil}; -use core::io; -use core::unstable::intrinsics::cttz16; +use std::io::{ReaderUtil, WriterUtil}; +use std::io; +use std::unstable::intrinsics::cttz16; // Computes a single solution to a given 9x9 sudoku // diff --git a/src/test/bench/task-perf-alloc-unwind.rs b/src/test/bench/task-perf-alloc-unwind.rs index 4a07193d8cd1d..a6d94c753548d 100644 --- a/src/test/bench/task-perf-alloc-unwind.rs +++ b/src/test/bench/task-perf-alloc-unwind.rs @@ -10,10 +10,10 @@ // xfail-win32 -extern mod std; +extern mod extra; -use std::list::{List, Cons, Nil}; -use std::time::precise_time_s; +use extra::list::{List, Cons, Nil}; +use extra::time::precise_time_s; enum UniqueList { ULNil, ULCons(~UniqueList) diff --git a/src/test/bench/task-perf-jargon-metal-smoke.rs b/src/test/bench/task-perf-jargon-metal-smoke.rs index a6eaf89231089..4600cf46892fe 100644 --- a/src/test/bench/task-perf-jargon-metal-smoke.rs +++ b/src/test/bench/task-perf-jargon-metal-smoke.rs @@ -17,7 +17,7 @@ // // The filename is a song reference; google it in quotes. -use core::cell::Cell; +use std::cell::Cell; fn child_generation(gens_left: uint, c: comm::Chan<()>) { // This used to be O(n^2) in the number of generations that ever existed. diff --git a/src/test/bench/task-perf-linked-failure.rs b/src/test/bench/task-perf-linked-failure.rs index aacdf678bbfe5..b8cba98c6fb0b 100644 --- a/src/test/bench/task-perf-linked-failure.rs +++ b/src/test/bench/task-perf-linked-failure.rs @@ -22,7 +22,7 @@ // Creates in the background 'num_tasks' tasks, all blocked forever. // Doesn't return until all such tasks are ready, but doesn't block forever itself. -use core::comm::*; +use std::comm::*; fn grandchild_group(num_tasks: uint) { let (po, ch) = stream(); diff --git a/src/test/bench/task-perf-one-million.rs b/src/test/bench/task-perf-one-million.rs index 8e1cbb9e17bdd..56e981b735d0d 100644 --- a/src/test/bench/task-perf-one-million.rs +++ b/src/test/bench/task-perf-one-million.rs @@ -10,7 +10,7 @@ // Test for concurrent tasks -use core::comm::*; +use std::comm::*; fn calc(children: uint, parent_wait_chan: &Chan>>) { diff --git a/src/test/compile-fail/arc-cant-nest-rw-arc-3177.rs b/src/test/compile-fail/arc-cant-nest-rw-arc-3177.rs index 7806436ef83b7..3dafb076afefb 100644 --- a/src/test/compile-fail/arc-cant-nest-rw-arc-3177.rs +++ b/src/test/compile-fail/arc-cant-nest-rw-arc-3177.rs @@ -10,8 +10,8 @@ // xfail-test // error-pattern: instantiating a type parameter with an incompatible type -extern mod std; -use std::arc::rw_arc; +extern mod extra; +use extra::arc::rw_arc; fn main() { let arc1 = ~rw_arc(true); diff --git a/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs index f59eb509156ac..82868647e57da 100644 --- a/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; fn main() { let x = ~arc::RWARC(1); let mut y = None; diff --git a/src/test/compile-fail/arc-rw-read-mode-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-read-mode-shouldnt-escape.rs index 85f60f34bdb80..6d4b774fd5f60 100644 --- a/src/test/compile-fail/arc-rw-read-mode-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-read-mode-shouldnt-escape.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; fn main() { let x = ~arc::RWARC(1); let mut y = None; diff --git a/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs index 22f5a8eac03d2..6bd32866f8989 100644 --- a/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; fn main() { let x = ~arc::RWARC(1); let mut y = None; diff --git a/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs index c8273cb016797..534475319033f 100644 --- a/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; fn main() { let x = ~arc::RWARC(1); let mut y = None; diff --git a/src/test/compile-fail/arc-rw-write-mode-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-write-mode-shouldnt-escape.rs index c7ae6a0dc6c52..decb7b8af9f3a 100644 --- a/src/test/compile-fail/arc-rw-write-mode-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-write-mode-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; fn main() { let x = ~arc::RWARC(1); let mut y = None; diff --git a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs index 887cb59930ebc..bd87a57af2570 100644 --- a/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs +++ b/src/test/compile-fail/borrowck-borrowed-uniq-rvalue.rs @@ -10,7 +10,7 @@ //buggy.rs -use core::hashmap::HashMap; +use std::hashmap::HashMap; fn main() { let mut buggy_map :HashMap = diff --git a/src/test/compile-fail/borrowck-insert-during-each.rs b/src/test/compile-fail/borrowck-insert-during-each.rs index 109753b38e70b..c9bd75039693f 100644 --- a/src/test/compile-fail/borrowck-insert-during-each.rs +++ b/src/test/compile-fail/borrowck-insert-during-each.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::HashSet; +use std::hashmap::HashSet; struct Foo { n: HashSet, diff --git a/src/test/compile-fail/borrowck-loan-local-as-both-mut-and-imm.rs b/src/test/compile-fail/borrowck-loan-local-as-both-mut-and-imm.rs index 6e8e3da143e4f..9ea4fe8aef416 100644 --- a/src/test/compile-fail/borrowck-loan-local-as-both-mut-and-imm.rs +++ b/src/test/compile-fail/borrowck-loan-local-as-both-mut-and-imm.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::either::{Either, Left, Right}; +use std::either::{Either, Left, Right}; fn f(x: &mut Either, y: &Either) -> int { match *y { diff --git a/src/test/compile-fail/borrowck-move-by-capture.rs b/src/test/compile-fail/borrowck-move-by-capture.rs index c199c8795756d..4e977442e1586 100644 --- a/src/test/compile-fail/borrowck-move-by-capture.rs +++ b/src/test/compile-fail/borrowck-move-by-capture.rs @@ -1,4 +1,4 @@ -extern mod std; +extern mod extra; fn main() { let foo = ~3; diff --git a/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs b/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs index 2898e312930fe..db8127d0854d2 100644 --- a/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs +++ b/src/test/compile-fail/borrowck-vec-pattern-move-tail.rs @@ -2,7 +2,7 @@ fn main() { let mut a = [1, 2, 3, 4]; let t = match a { [1, 2, ..tail] => tail, - _ => core::util::unreachable() + _ => std::util::unreachable() }; a[0] = 0; //~ ERROR cannot assign to `a[]` because it is borrowed t[0]; diff --git a/src/test/compile-fail/core-tls-store-pointer.rs b/src/test/compile-fail/core-tls-store-pointer.rs index fcb25069de6dd..63bbaf80177e1 100644 --- a/src/test/compile-fail/core-tls-store-pointer.rs +++ b/src/test/compile-fail/core-tls-store-pointer.rs @@ -10,7 +10,7 @@ // Testing that we can't store a borrowed pointer it task-local storage -use core::local_data::*; +use std::local_data::*; fn key(_x: @&int) { } diff --git a/src/test/compile-fail/extfmt-not-enough-args.rs b/src/test/compile-fail/extfmt-not-enough-args.rs index 5f078a288d929..f18ae748ee07f 100644 --- a/src/test/compile-fail/extfmt-not-enough-args.rs +++ b/src/test/compile-fail/extfmt-not-enough-args.rs @@ -10,6 +10,6 @@ // error-pattern:not enough arguments -extern mod std; +extern mod extra; fn main() { let s = fmt!("%s%s%s", "test", "test"); } diff --git a/src/test/compile-fail/extfmt-too-many-args.rs b/src/test/compile-fail/extfmt-too-many-args.rs index 3a16db6638b64..2a72dcf89889e 100644 --- a/src/test/compile-fail/extfmt-too-many-args.rs +++ b/src/test/compile-fail/extfmt-too-many-args.rs @@ -10,6 +10,6 @@ // error-pattern:too many arguments -extern mod std; +extern mod extra; fn main() { let s = fmt!("%s", "test", "test"); } diff --git a/src/test/compile-fail/fail-expr.rs b/src/test/compile-fail/fail-expr.rs index e17c8d6a182c5..98270bdc58383 100644 --- a/src/test/compile-fail/fail-expr.rs +++ b/src/test/compile-fail/fail-expr.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern:failed to find an implementation of trait core::sys::FailWithCause for int +// error-pattern:failed to find an implementation of trait std::sys::FailWithCause for int fn main() { fail!(5); } diff --git a/src/test/compile-fail/fail-type-err.rs b/src/test/compile-fail/fail-type-err.rs index fbfa85ea6f87f..b6755249bcf98 100644 --- a/src/test/compile-fail/fail-type-err.rs +++ b/src/test/compile-fail/fail-type-err.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern:failed to find an implementation of trait core::sys::FailWithCause for ~[int] +// error-pattern:failed to find an implementation of trait std::sys::FailWithCause for ~[int] fn main() { fail!(~[0i]); } diff --git a/src/test/compile-fail/forget-init-unsafe.rs b/src/test/compile-fail/forget-init-unsafe.rs index 2361b5ad6a9cf..25ab28b5fc067 100644 --- a/src/test/compile-fail/forget-init-unsafe.rs +++ b/src/test/compile-fail/forget-init-unsafe.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::unstable::intrinsics::{init, forget}; +use std::unstable::intrinsics::{init, forget}; // Test that the `forget` and `init` intrinsics are really unsafe pub fn main() { diff --git a/src/test/compile-fail/fully-qualified-type-name1.rs b/src/test/compile-fail/fully-qualified-type-name1.rs index c5e7fc82cc994..dd9833ad41fb1 100644 --- a/src/test/compile-fail/fully-qualified-type-name1.rs +++ b/src/test/compile-fail/fully-qualified-type-name1.rs @@ -13,5 +13,5 @@ fn main() { let x: Option; x = 5; - //~^ ERROR mismatched types: expected `core::option::Option` + //~^ ERROR mismatched types: expected `std::option::Option` } diff --git a/src/test/compile-fail/fully-qualified-type-name4.rs b/src/test/compile-fail/fully-qualified-type-name4.rs index a91d8284e71ef..f49eb5ee85aa8 100644 --- a/src/test/compile-fail/fully-qualified-type-name4.rs +++ b/src/test/compile-fail/fully-qualified-type-name4.rs @@ -10,11 +10,11 @@ // Test that we use fully-qualified type names in error messages. -use core::task::Task; +use std::task::Task; fn bar(x: uint) -> Task { return x; - //~^ ERROR mismatched types: expected `core::task::Task` + //~^ ERROR mismatched types: expected `std::task::Task` } fn main() { diff --git a/src/test/compile-fail/issue-2766-a.rs b/src/test/compile-fail/issue-2766-a.rs index 5b55cc772fde8..41527027c744b 100644 --- a/src/test/compile-fail/issue-2766-a.rs +++ b/src/test/compile-fail/issue-2766-a.rs @@ -11,8 +11,8 @@ pub mod stream { pub enum Stream { send(T, ::stream::server::Stream), } pub mod server { - use core::option; - use core::pipes; + use std::option; + use std::pipes; pub impl Stream { pub fn recv() -> extern fn(v: Stream) -> ::stream::Stream { diff --git a/src/test/compile-fail/issue-3021-b.rs b/src/test/compile-fail/issue-3021-b.rs index 3769154c9d948..f9f1a27e11b2c 100644 --- a/src/test/compile-fail/issue-3021-b.rs +++ b/src/test/compile-fail/issue-3021-b.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn siphash(k0 : u64) { diff --git a/src/test/compile-fail/issue-3021-c.rs b/src/test/compile-fail/issue-3021-c.rs index 4fc4c005cf611..a0b78a4bc79b1 100644 --- a/src/test/compile-fail/issue-3021-c.rs +++ b/src/test/compile-fail/issue-3021-c.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn siphash() { diff --git a/src/test/compile-fail/issue-3021-d.rs b/src/test/compile-fail/issue-3021-d.rs index 55c8e8aa51dd8..fd08d556befcf 100644 --- a/src/test/compile-fail/issue-3021-d.rs +++ b/src/test/compile-fail/issue-3021-d.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; trait siphash { fn result(&self) -> u64; diff --git a/src/test/compile-fail/issue-3021.rs b/src/test/compile-fail/issue-3021.rs index f2cf2d19a864e..0ca6173275cb2 100644 --- a/src/test/compile-fail/issue-3021.rs +++ b/src/test/compile-fail/issue-3021.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; trait SipHash { fn reset(&self); diff --git a/src/test/compile-fail/issue-3296.rs b/src/test/compile-fail/issue-3296.rs index 062ee8fd01e46..ba0ad02f91ccc 100644 --- a/src/test/compile-fail/issue-3296.rs +++ b/src/test/compile-fail/issue-3296.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std; +use extra; -struct Deserializer : std::serialization::deserializer{ //~ ERROR obsolete syntax: class traits +struct Deserializer : extra::serialization::deserializer{ //~ ERROR obsolete syntax: class traits x: () } @@ -18,7 +18,7 @@ struct Foo { a: () } -fn deserialize_foo<__D: std::serialization::deserializer>(__d: __D) { +fn deserialize_foo<__D: extra::serialization::deserializer>(__d: __D) { } fn main() { let des = Deserializer(); let foo = deserialize_foo(des); } diff --git a/src/test/compile-fail/issue-3680.rs b/src/test/compile-fail/issue-3680.rs index 18b5d290f3d6d..b453384c0c890 100644 --- a/src/test/compile-fail/issue-3680.rs +++ b/src/test/compile-fail/issue-3680.rs @@ -10,6 +10,6 @@ fn main() { match None { - Err(_) => () //~ ERROR mismatched types: expected `core::option::Option<>` but found `core::result::Result<,>` + Err(_) => () //~ ERROR mismatched types: expected `std::option::Option<>` but found `std::result::Result<,>` } } diff --git a/src/test/compile-fail/issue-3953.rs b/src/test/compile-fail/issue-3953.rs index b726f090e7db7..fc8e456f56b42 100644 --- a/src/test/compile-fail/issue-3953.rs +++ b/src/test/compile-fail/issue-3953.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::Eq; +use std::cmp::Eq; trait Hahaha: Eq + Eq + Eq + Eq + Eq + //~ ERROR Duplicate supertrait Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + diff --git a/src/test/compile-fail/issue-511.rs b/src/test/compile-fail/issue-511.rs index c872f89d88450..a053424b30d51 100644 --- a/src/test/compile-fail/issue-511.rs +++ b/src/test/compile-fail/issue-511.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use core::cmp::Eq; +extern mod extra; +use std::cmp::Eq; fn f(o: &mut Option) { assert!(*o == option::None); diff --git a/src/test/compile-fail/issue-5358-1.rs b/src/test/compile-fail/issue-5358-1.rs index 0b6e2fb0ff5f2..a3d25e7d2adca 100644 --- a/src/test/compile-fail/issue-5358-1.rs +++ b/src/test/compile-fail/issue-5358-1.rs @@ -12,7 +12,7 @@ struct S(Either); fn main() { match S(Left(5)) { - Right(_) => {} //~ ERROR mismatched types: expected `S` but found `core::either::Either + Right(_) => {} //~ ERROR mismatched types: expected `S` but found `std::either::Either _ => {} } } diff --git a/src/test/compile-fail/issue-5358.rs b/src/test/compile-fail/issue-5358.rs index 7d11a127f9ae8..8d4f463346693 100644 --- a/src/test/compile-fail/issue-5358.rs +++ b/src/test/compile-fail/issue-5358.rs @@ -12,6 +12,6 @@ struct S(Either); fn main() { match *S(Left(5)) { - S(_) => {} //~ ERROR mismatched types: expected `core::either::Either` but found a structure pattern + S(_) => {} //~ ERROR mismatched types: expected `std::either::Either` but found a structure pattern } } diff --git a/src/test/compile-fail/lint-unused-imports.rs b/src/test/compile-fail/lint-unused-imports.rs index dc5936777c9fe..201b2e9b98953 100644 --- a/src/test/compile-fail/lint-unused-imports.rs +++ b/src/test/compile-fail/lint-unused-imports.rs @@ -12,23 +12,23 @@ use cal = bar::c::cc; -use core::either::Right; //~ ERROR unused import +use std::either::Right; //~ ERROR unused import -use core::util::*; // shouldn't get errors for not using +use std::util::*; // shouldn't get errors for not using // everything imported // Should get errors for both 'Some' and 'None' -use core::option::{Some, None}; //~ ERROR unused import +use std::option::{Some, None}; //~ ERROR unused import //~^ ERROR unused import -use core::io::ReaderUtil; //~ ERROR unused import +use std::io::ReaderUtil; //~ ERROR unused import // Be sure that if we just bring some methods into scope that they're also // counted as being used. -use core::io::WriterUtil; +use std::io::WriterUtil; // Make sure this import is warned about when at least one of its imported names // is unused -use core::vec::{filter, map}; //~ ERROR unused import +use std::vec::{filter, map}; //~ ERROR unused import mod foo { pub struct Point{x: int, y: int} @@ -37,7 +37,7 @@ mod foo { mod bar { // Don't ignore on 'pub use' because we're not sure if it's used or not - pub use core::cmp::Eq; + pub use std::cmp::Eq; pub mod c { use foo::Point; @@ -47,7 +47,7 @@ mod bar { #[allow(unused_imports)] mod foo { - use core::cmp::Eq; + use std::cmp::Eq; } } diff --git a/src/test/compile-fail/map-types.rs b/src/test/compile-fail/map-types.rs index ebc5b015d2752..f5d6e95fe2f4d 100644 --- a/src/test/compile-fail/map-types.rs +++ b/src/test/compile-fail/map-types.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::container::Map; -use core::hashmap::HashMap; +use std::container::Map; +use std::hashmap::HashMap; // Test that trait types printed in error msgs include the type arguments. @@ -17,5 +17,5 @@ fn main() { let x: @Map<~str, ~str> = @HashMap::new::<~str, ~str>() as @Map<~str, ~str>; let y: @Map = @x; - //~^ ERROR mismatched types: expected `@core::container::Map` + //~^ ERROR mismatched types: expected `@std::container::Map` } diff --git a/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs b/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs index 2b9291ce3284c..7c01ddb6c9331 100644 --- a/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs +++ b/src/test/compile-fail/moves-based-on-type-cyclic-types-issue-4821.rs @@ -12,7 +12,7 @@ // temporary kinds wound up being stored in a cache and used later. // See middle::ty::type_contents() for more information. -extern mod std; +extern mod extra; struct List { key: int, next: Option<~List> } diff --git a/src/test/compile-fail/mutable-huh-ptr-assign.rs b/src/test/compile-fail/mutable-huh-ptr-assign.rs index c907eb4be49f8..4460da72e2059 100644 --- a/src/test/compile-fail/mutable-huh-ptr-assign.rs +++ b/src/test/compile-fail/mutable-huh-ptr-assign.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn main() { unsafe fn f(v: *const int) { diff --git a/src/test/compile-fail/name-clash-nullary.rs b/src/test/compile-fail/name-clash-nullary.rs index e64d651dab2b4..68f5d921d0239 100644 --- a/src/test/compile-fail/name-clash-nullary.rs +++ b/src/test/compile-fail/name-clash-nullary.rs @@ -9,7 +9,7 @@ // except according to those terms. // error-pattern:declaration of `None` shadows -use core::option::*; +use std::option::*; fn main() { let None: int = 42; diff --git a/src/test/compile-fail/no-capture-arc.rs b/src/test/compile-fail/no-capture-arc.rs index 4c206a949a238..132a5326a8846 100644 --- a/src/test/compile-fail/no-capture-arc.rs +++ b/src/test/compile-fail/no-capture-arc.rs @@ -10,8 +10,8 @@ // error-pattern: use of moved value -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; fn main() { let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; diff --git a/src/test/compile-fail/no-reuse-move-arc.rs b/src/test/compile-fail/no-reuse-move-arc.rs index 46eaded4527a3..8bed4e6da47d6 100644 --- a/src/test/compile-fail/no-reuse-move-arc.rs +++ b/src/test/compile-fail/no-reuse-move-arc.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; fn main() { let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; diff --git a/src/test/compile-fail/no-send-res-ports.rs b/src/test/compile-fail/no-send-res-ports.rs index c1071e5a8c4d9..951103bfbe369 100644 --- a/src/test/compile-fail/no-send-res-ports.rs +++ b/src/test/compile-fail/no-send-res-ports.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cell::Cell; +use std::cell::Cell; struct Port(@T); diff --git a/src/test/compile-fail/noexporttypeexe.rs b/src/test/compile-fail/noexporttypeexe.rs index 95428568e4c35..3add0134d002a 100644 --- a/src/test/compile-fail/noexporttypeexe.rs +++ b/src/test/compile-fail/noexporttypeexe.rs @@ -18,5 +18,5 @@ fn main() { // because the def_id associated with the type was // not convertible to a path. let x: int = noexporttypelib::foo(); - //~^ ERROR expected `int` but found `core::option::Option` + //~^ ERROR expected `int` but found `std::option::Option` } diff --git a/src/test/compile-fail/pattern-tyvar-2.rs b/src/test/compile-fail/pattern-tyvar-2.rs index 41529b3da93ed..537d095d2d7a3 100644 --- a/src/test/compile-fail/pattern-tyvar-2.rs +++ b/src/test/compile-fail/pattern-tyvar-2.rs @@ -10,7 +10,7 @@ // except according to those terms. -extern mod std; +extern mod extra; enum bar { t1((), Option<~[int]>), t2, } diff --git a/src/test/compile-fail/pattern-tyvar.rs b/src/test/compile-fail/pattern-tyvar.rs index 506c71f493ae3..4ca0aac35ee66 100644 --- a/src/test/compile-fail/pattern-tyvar.rs +++ b/src/test/compile-fail/pattern-tyvar.rs @@ -9,7 +9,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; // error-pattern: mismatched types diff --git a/src/test/compile-fail/qquote-1.rs b/src/test/compile-fail/qquote-1.rs index 1241190b5371f..156d09cedff6c 100644 --- a/src/test/compile-fail/qquote-1.rs +++ b/src/test/compile-fail/qquote-1.rs @@ -10,7 +10,7 @@ // xfail-test Can't use syntax crate here -extern mod std; +extern mod extra; extern mod syntax; use io::*; diff --git a/src/test/compile-fail/qquote-2.rs b/src/test/compile-fail/qquote-2.rs index 07500825a952b..2a593c51759c0 100644 --- a/src/test/compile-fail/qquote-2.rs +++ b/src/test/compile-fail/qquote-2.rs @@ -10,10 +10,10 @@ // xfail-test Can't use syntax crate here -extern mod std; +extern mod extra; extern mod syntax; -use std::io::*; +use extra::io::*; use syntax::diagnostic; use syntax::ast; diff --git a/src/test/compile-fail/regions-glb-free-free.rs b/src/test/compile-fail/regions-glb-free-free.rs index 61300b92afd09..dc3d414e91b4d 100644 --- a/src/test/compile-fail/regions-glb-free-free.rs +++ b/src/test/compile-fail/regions-glb-free-free.rs @@ -9,7 +9,7 @@ // except according to those terms. mod argparse { - extern mod std; + extern mod extra; pub struct Flag<'self> { name: &'self str, diff --git a/src/test/compile-fail/seq-args.rs b/src/test/compile-fail/seq-args.rs index 0d253d782832a..a6ab41a3d6b74 100644 --- a/src/test/compile-fail/seq-args.rs +++ b/src/test/compile-fail/seq-args.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn main() { trait seq { } diff --git a/src/test/compile-fail/spawn-non-nil-fn.rs b/src/test/compile-fail/spawn-non-nil-fn.rs index 00e3e612e8f5b..9dbef3692574b 100644 --- a/src/test/compile-fail/spawn-non-nil-fn.rs +++ b/src/test/compile-fail/spawn-non-nil-fn.rs @@ -10,6 +10,6 @@ // error-pattern: mismatched types -extern mod std; +extern mod extra; fn main() { task::spawn(|| -> int { 10 }); } diff --git a/src/test/compile-fail/sync-cond-shouldnt-escape.rs b/src/test/compile-fail/sync-cond-shouldnt-escape.rs index 964c2ce946b47..b22d4d3b2e2e3 100644 --- a/src/test/compile-fail/sync-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-cond-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::sync; +extern mod extra; +use extra::sync; fn main() { let m = ~sync::Mutex(); diff --git a/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs b/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs index 9cab2d3b05626..518e67800d763 100644 --- a/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::sync; +extern mod extra; +use extra::sync; fn main() { let x = ~sync::RWlock(); let mut y = None; diff --git a/src/test/compile-fail/sync-rwlock-read-mode-shouldnt-escape.rs b/src/test/compile-fail/sync-rwlock-read-mode-shouldnt-escape.rs index 4195d8700678b..4bec5fa270ab8 100644 --- a/src/test/compile-fail/sync-rwlock-read-mode-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-rwlock-read-mode-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: cannot infer an appropriate lifetime -extern mod std; -use std::sync; +extern mod extra; +use extra::sync; fn main() { let x = ~sync::RWlock(); let mut y = None; diff --git a/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs b/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs index 43ad693ccf8d8..09b83887bcfd1 100644 --- a/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::sync; +extern mod extra; +use extra::sync; fn main() { let x = ~sync::RWlock(); let mut y = None; diff --git a/src/test/compile-fail/sync-rwlock-write-mode-shouldnt-escape.rs b/src/test/compile-fail/sync-rwlock-write-mode-shouldnt-escape.rs index 525d334f4115d..679c4a72598ea 100644 --- a/src/test/compile-fail/sync-rwlock-write-mode-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-rwlock-write-mode-shouldnt-escape.rs @@ -9,8 +9,8 @@ // except according to those terms. // error-pattern: reference is not valid outside of its lifetime -extern mod std; -use std::sync; +extern mod extra; +use extra::sync; fn main() { let x = ~sync::RWlock(); let mut y = None; diff --git a/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs b/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs index f167ee3d5c48e..ebd3320d90126 100644 --- a/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs +++ b/src/test/compile-fail/tag-that-dare-not-speak-its-name.rs @@ -13,9 +13,9 @@ #[no_std]; -extern mod core; +extern mod std; -fn last(v: ~[&T]) -> core::option::Option { +fn last(v: ~[&T]) -> std::option::Option { fail!(); } diff --git a/src/test/compile-fail/use-meta-dup.rs b/src/test/compile-fail/use-meta-dup.rs index 805a853c315de..dd57382afbbb7 100644 --- a/src/test/compile-fail/use-meta-dup.rs +++ b/src/test/compile-fail/use-meta-dup.rs @@ -10,6 +10,6 @@ // error-pattern:duplicate meta item `name` -extern mod std(name = "std", name = "nonstd"); +extern mod extra(name = "extra", name = "nonstd"); fn main() { } diff --git a/src/test/compile-fail/use-meta-mismatch.rs b/src/test/compile-fail/use-meta-mismatch.rs index b643e9421f589..118fce8a891b6 100644 --- a/src/test/compile-fail/use-meta-mismatch.rs +++ b/src/test/compile-fail/use-meta-mismatch.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern:can't find crate for `std` +// error-pattern:can't find crate for `extra` -extern mod std(complex(meta(item))); +extern mod extra(complex(meta(item))); fn main() { } diff --git a/src/test/compile-fail/view-items-at-top.rs b/src/test/compile-fail/view-items-at-top.rs index 023be703cca77..fa03e0d5199fc 100644 --- a/src/test/compile-fail/view-items-at-top.rs +++ b/src/test/compile-fail/view-items-at-top.rs @@ -10,12 +10,12 @@ // xfail-test -extern mod std; +extern mod extra; fn f() { } -use std::net; //~ ERROR view items must be declared at the top +use extra::net; //~ ERROR view items must be declared at the top fn main() { } diff --git a/src/test/run-fail/extern-fail.rs b/src/test/run-fail/extern-fail.rs index d7ec9f088653f..15cc8a488673a 100644 --- a/src/test/run-fail/extern-fail.rs +++ b/src/test/run-fail/extern-fail.rs @@ -12,7 +12,7 @@ // Testing that runtime failure doesn't cause callbacks to abort abnormally. // Instead the failure will be delivered after the callbacks return. -use core::old_iter; +use std::old_iter; mod rustrt { pub extern { diff --git a/src/test/run-fail/fail-main.rs b/src/test/run-fail/fail-main.rs index beb0d38ea473b..f007e03041c14 100644 --- a/src/test/run-fail/fail-main.rs +++ b/src/test/run-fail/fail-main.rs @@ -9,5 +9,5 @@ // except according to those terms. // error-pattern:moop -extern mod std; +extern mod extra; fn main() { fail!("moop"); } diff --git a/src/test/run-fail/fmt-fail.rs b/src/test/run-fail/fmt-fail.rs index 10d8903838143..d34ca029023f3 100644 --- a/src/test/run-fail/fmt-fail.rs +++ b/src/test/run-fail/fmt-fail.rs @@ -9,6 +9,6 @@ // except according to those terms. // error-pattern:meh -extern mod std; +extern mod extra; fn main() { let str_var: ~str = ~"meh"; fail!(fmt!("%s", str_var)); } diff --git a/src/test/run-fail/for-each-loop-fail.rs b/src/test/run-fail/for-each-loop-fail.rs index 3ae387952a2d7..06422244af958 100644 --- a/src/test/run-fail/for-each-loop-fail.rs +++ b/src/test/run-fail/for-each-loop-fail.rs @@ -9,5 +9,5 @@ // except according to those terms. // error-pattern:moop -extern mod std; +extern mod extra; fn main() { for uint::range(0u, 10u) |_i| { fail!("moop"); } } diff --git a/src/test/run-fail/issue-2156.rs b/src/test/run-fail/issue-2156.rs index 9ca343e3866b8..de0b903b53c02 100644 --- a/src/test/run-fail/issue-2156.rs +++ b/src/test/run-fail/issue-2156.rs @@ -10,8 +10,8 @@ // error-pattern:explicit failure // Don't double free the string -extern mod std; -use core::io::ReaderUtil; +extern mod extra; +use std::io::ReaderUtil; fn main() { do io::with_str_reader(~"") |rdr| { diff --git a/src/test/run-fail/issue-2444.rs b/src/test/run-fail/issue-2444.rs index 04a0f47fc06fd..0ab1528e4fb75 100644 --- a/src/test/run-fail/issue-2444.rs +++ b/src/test/run-fail/issue-2444.rs @@ -10,8 +10,8 @@ // error-pattern:explicit failure -extern mod std; -use std::arc; +extern mod extra; +use extra::arc; enum e { e(arc::ARC) } diff --git a/src/test/run-fail/linked-failure.rs b/src/test/run-fail/linked-failure.rs index 054d6f697ae34..6a87e202d1382 100644 --- a/src/test/run-fail/linked-failure.rs +++ b/src/test/run-fail/linked-failure.rs @@ -11,7 +11,7 @@ // error-pattern:1 == 2 -extern mod std; +extern mod extra; fn child() { assert!((1 == 2)); } diff --git a/src/test/run-fail/morestack2.rs b/src/test/run-fail/morestack2.rs index d59fbae2f9f14..f829767edf19d 100644 --- a/src/test/run-fail/morestack2.rs +++ b/src/test/run-fail/morestack2.rs @@ -15,7 +15,7 @@ // See the hack in upcall_call_shim_on_c_stack where it messes // with the stack limit. -extern mod std; +extern mod extra; mod rustrt { pub extern { diff --git a/src/test/run-fail/morestack3.rs b/src/test/run-fail/morestack3.rs index 012e9d19b1218..6ab064f382738 100644 --- a/src/test/run-fail/morestack3.rs +++ b/src/test/run-fail/morestack3.rs @@ -12,7 +12,7 @@ // Just testing unwinding -extern mod std; +extern mod extra; fn getbig_and_fail(i: int) { let _r = and_then_get_big_again(5); diff --git a/src/test/run-fail/morestack4.rs b/src/test/run-fail/morestack4.rs index 6fc187491cf8c..e07c799710848 100644 --- a/src/test/run-fail/morestack4.rs +++ b/src/test/run-fail/morestack4.rs @@ -12,7 +12,7 @@ // Just testing unwinding -extern mod std; +extern mod extra; fn getbig_and_fail(i: int) { let r = and_then_get_big_again(5); diff --git a/src/test/run-fail/run-unexported-tests.rs b/src/test/run-fail/run-unexported-tests.rs index b055bf4ed9563..e9d3c41faa6cc 100644 --- a/src/test/run-fail/run-unexported-tests.rs +++ b/src/test/run-fail/run-unexported-tests.rs @@ -11,7 +11,7 @@ // error-pattern:runned an unexported test // compile-flags:--test -extern mod std; +extern mod extra; mod m { pub fn exported() { } diff --git a/src/test/run-fail/spawnfail.rs b/src/test/run-fail/spawnfail.rs index 8431f7bb74d98..fc4977308ae14 100644 --- a/src/test/run-fail/spawnfail.rs +++ b/src/test/run-fail/spawnfail.rs @@ -10,7 +10,7 @@ // xfail-win32 // error-pattern:explicit -extern mod std; +extern mod extra; // We don't want to see any invalid reads fn main() { diff --git a/src/test/run-fail/unwind-misc-1.rs b/src/test/run-fail/unwind-misc-1.rs index 7e3318f865228..e30054575d6a6 100644 --- a/src/test/run-fail/unwind-misc-1.rs +++ b/src/test/run-fail/unwind-misc-1.rs @@ -14,7 +14,7 @@ fn main() { let count = @mut 0u; - let mut map = core::hashmap::HashMap::new(); + let mut map = std::hashmap::HashMap::new(); let mut arr = ~[]; for uint::range(0u, 10u) |i| { arr += ~[@~"key stuff"]; diff --git a/src/test/run-fail/zip-different-lengths.rs b/src/test/run-fail/zip-different-lengths.rs index ae76c4ba6034b..355a2ce93ed9a 100644 --- a/src/test/run-fail/zip-different-lengths.rs +++ b/src/test/run-fail/zip-different-lengths.rs @@ -11,8 +11,8 @@ // In this case, the code should compile but // the assert should fail at runtime // error-pattern:assertion failed -extern mod std; -use core::vec::{same_length, zip}; +extern mod extra; +use std::vec::{same_length, zip}; fn enum_chars(start: u8, end: u8) -> ~[char] { assert!(start < end); diff --git a/src/test/run-pass-fulldeps/qquote.rs b/src/test/run-pass-fulldeps/qquote.rs index 53385e16759d1..9a3ba32390c72 100644 --- a/src/test/run-pass-fulldeps/qquote.rs +++ b/src/test/run-pass-fulldeps/qquote.rs @@ -10,10 +10,10 @@ // xfail-pretty -extern mod std; +extern mod extra; extern mod syntax; -use core::io::*; +use std::io::*; use syntax::diagnostic; use syntax::ast; diff --git a/src/test/run-pass/alt-join.rs b/src/test/run-pass/alt-join.rs index b9f25396b32c8..66b6476806094 100644 --- a/src/test/run-pass/alt-join.rs +++ b/src/test/run-pass/alt-join.rs @@ -9,7 +9,7 @@ // except according to those terms. -extern mod std; +extern mod extra; fn foo(y: Option) { let mut x: int; diff --git a/src/test/run-pass/alt-pattern-drop.rs b/src/test/run-pass/alt-pattern-drop.rs index d9f3f10a11b03..71bbb1768e892 100644 --- a/src/test/run-pass/alt-pattern-drop.rs +++ b/src/test/run-pass/alt-pattern-drop.rs @@ -14,7 +14,7 @@ enum t { make_t(@int), clam, } fn foo(s: @int) { - let count = ::core::sys::refcount(s); + let count = ::std::sys::refcount(s); let x: t = make_t(s); // ref up match x { @@ -24,20 +24,20 @@ fn foo(s: @int) { } _ => { debug!("?"); fail!(); } } - debug!(::core::sys::refcount(s)); - assert_eq!(::core::sys::refcount(s), count + 1u); - let _ = ::core::sys::refcount(s); // don't get bitten by last-use. + debug!(::std::sys::refcount(s)); + assert_eq!(::std::sys::refcount(s), count + 1u); + let _ = ::std::sys::refcount(s); // don't get bitten by last-use. } pub fn main() { let s: @int = @0; // ref up - let count = ::core::sys::refcount(s); + let count = ::std::sys::refcount(s); foo(s); // ref up then down - debug!("%u", ::core::sys::refcount(s)); - let count2 = ::core::sys::refcount(s); - let _ = ::core::sys::refcount(s); // don't get bitten by last-use. + debug!("%u", ::std::sys::refcount(s)); + let count2 = ::std::sys::refcount(s); + let _ = ::std::sys::refcount(s); // don't get bitten by last-use. assert_eq!(count, count2); } diff --git a/src/test/run-pass/attr-before-view-item.rs b/src/test/run-pass/attr-before-view-item.rs index aa5c3bb22a380..316f8fa0f61f4 100644 --- a/src/test/run-pass/attr-before-view-item.rs +++ b/src/test/run-pass/attr-before-view-item.rs @@ -11,7 +11,7 @@ // error-pattern:expected item #[foo = "bar"] -extern mod std; +extern mod extra; pub fn main() { } diff --git a/src/test/run-pass/attr-before-view-item2.rs b/src/test/run-pass/attr-before-view-item2.rs index e0d9a05b8aa2b..0721544aa0dc8 100644 --- a/src/test/run-pass/attr-before-view-item2.rs +++ b/src/test/run-pass/attr-before-view-item2.rs @@ -12,7 +12,7 @@ mod m { #[foo = "bar"] - extern mod std; + extern mod extra; } pub fn main() { diff --git a/src/test/run-pass/auto-encode.rs b/src/test/run-pass/auto-encode.rs index cfac8e8cd061f..0c2f24b5bf75b 100644 --- a/src/test/run-pass/auto-encode.rs +++ b/src/test/run-pass/auto-encode.rs @@ -12,18 +12,18 @@ #[forbid(deprecated_pattern)]; -extern mod std; +extern mod extra; // These tests used to be separate files, but I wanted to refactor all // the common code. -use EBReader = std::ebml::reader; -use EBWriter = std::ebml::writer; -use core::cmp::Eq; -use core::io::Writer; -use std::ebml; -use std::serialize::{Decodable, Encodable}; -use std::time; +use EBReader = extra::ebml::reader; +use EBWriter = extra::ebml::writer; +use std::cmp::Eq; +use std::io::Writer; +use extra::ebml; +use extra::serialize::{Decodable, Encodable}; +use extra::time; fn test_ebml) { unsafe { } } pub fn main() { diff --git a/src/test/run-pass/binops.rs b/src/test/run-pass/binops.rs index 9039730f11963..a7e910538c947 100644 --- a/src/test/run-pass/binops.rs +++ b/src/test/run-pass/binops.rs @@ -64,9 +64,9 @@ fn test_box() { fn test_ptr() { unsafe { - let p1: *u8 = ::core::cast::transmute(0); - let p2: *u8 = ::core::cast::transmute(0); - let p3: *u8 = ::core::cast::transmute(1); + let p1: *u8 = ::std::cast::transmute(0); + let p2: *u8 = ::std::cast::transmute(0); + let p3: *u8 = ::std::cast::transmute(1); assert_eq!(p1, p2); assert!(p1 != p3); @@ -107,8 +107,8 @@ fn test_class() { unsafe { error!("q = %x, r = %x", - (::core::cast::transmute::<*p, uint>(&q)), - (::core::cast::transmute::<*p, uint>(&r))); + (::std::cast::transmute::<*p, uint>(&q)), + (::std::cast::transmute::<*p, uint>(&r))); } assert_eq!(q, r); r.y = 17; diff --git a/src/test/run-pass/bitv-perf-test.rs b/src/test/run-pass/bitv-perf-test.rs index 2d47916d05040..c6edbfbe463d0 100644 --- a/src/test/run-pass/bitv-perf-test.rs +++ b/src/test/run-pass/bitv-perf-test.rs @@ -10,8 +10,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::bitv::*; +extern mod extra; +use extra::bitv::*; fn bitv_test() -> bool { let mut v1 = ~Bitv::new(31, false); diff --git a/src/test/run-pass/block-arg-call-as.rs b/src/test/run-pass/block-arg-call-as.rs index e27458327696e..d68b0be632eb3 100644 --- a/src/test/run-pass/block-arg-call-as.rs +++ b/src/test/run-pass/block-arg-call-as.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn asSendfn( f : ~fn()->uint ) -> uint { return f(); diff --git a/src/test/run-pass/block-vec-map_zip.rs b/src/test/run-pass/block-vec-map_zip.rs index b859dc91fba0c..4c37000113cf7 100644 --- a/src/test/run-pass/block-vec-map_zip.rs +++ b/src/test/run-pass/block-vec-map_zip.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { let v = diff --git a/src/test/run-pass/borrowck-mut-uniq.rs b/src/test/run-pass/borrowck-mut-uniq.rs index 023eaae0a7648..fa5ae98450726 100644 --- a/src/test/run-pass/borrowck-mut-uniq.rs +++ b/src/test/run-pass/borrowck-mut-uniq.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::util; +use std::util; struct Ints {sum: ~int, values: ~[int]} diff --git a/src/test/run-pass/c-stack-returning-int64.rs b/src/test/run-pass/c-stack-returning-int64.rs index ec204e7a4c23f..647c42cf891cb 100644 --- a/src/test/run-pass/c-stack-returning-int64.rs +++ b/src/test/run-pass/c-stack-returning-int64.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; mod libc { #[abi = "cdecl"] diff --git a/src/test/run-pass/capture_nil.rs b/src/test/run-pass/capture_nil.rs index 817891c114640..c9a1c031e84d0 100644 --- a/src/test/run-pass/capture_nil.rs +++ b/src/test/run-pass/capture_nil.rs @@ -24,7 +24,7 @@ // course preferable, as the value itself is // irrelevant). -use core::comm::*; +use std::comm::*; fn foo(x: ()) -> Port<()> { let (p, c) = stream::<()>(); diff --git a/src/test/run-pass/child-outlives-parent.rs b/src/test/run-pass/child-outlives-parent.rs index 4eb3cea3a2586..de933b53a18b0 100644 --- a/src/test/run-pass/child-outlives-parent.rs +++ b/src/test/run-pass/child-outlives-parent.rs @@ -10,7 +10,7 @@ // Reported as issue #126, child leaks the string. -extern mod std; +extern mod extra; fn child2(s: ~str) { } diff --git a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs index 8bedfef89d00d..393c9e2ece0f5 100644 --- a/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs +++ b/src/test/run-pass/class-cast-to-trait-cross-crate-2.rs @@ -11,7 +11,7 @@ // xfail-fast // aux-build:cci_class_cast.rs extern mod cci_class_cast; -use core::to_str::ToStr; +use std::to_str::ToStr; use cci_class_cast::kitty::*; fn print_out(thing: @ToStr, expected: ~str) { diff --git a/src/test/run-pass/class-impl-parameterized-trait.rs b/src/test/run-pass/class-impl-parameterized-trait.rs index 04784b5c51507..09967f0ab361d 100644 --- a/src/test/run-pass/class-impl-parameterized-trait.rs +++ b/src/test/run-pass/class-impl-parameterized-trait.rs @@ -11,8 +11,8 @@ // xfail-test // xfail-fast -extern mod std; -use std::oldmap::*; +extern mod extra; +use extra::oldmap::*; class cat : map { priv { diff --git a/src/test/run-pass/class-impl-very-parameterized-trait.rs b/src/test/run-pass/class-impl-very-parameterized-trait.rs index ae3d088c539c7..a73af840fe4e4 100644 --- a/src/test/run-pass/class-impl-very-parameterized-trait.rs +++ b/src/test/run-pass/class-impl-very-parameterized-trait.rs @@ -10,8 +10,8 @@ // xfail-fast -use core::container::{Container, Mutable, Map}; -use core::old_iter::BaseIter; +use std::container::{Container, Mutable, Map}; +use std::old_iter::BaseIter; enum cat_type { tuxedo, tabby, tortoiseshell } diff --git a/src/test/run-pass/class-implements-multiple-traits.rs b/src/test/run-pass/class-implements-multiple-traits.rs index 9545f5340df76..7a3045db91f1a 100644 --- a/src/test/run-pass/class-implements-multiple-traits.rs +++ b/src/test/run-pass/class-implements-multiple-traits.rs @@ -10,8 +10,8 @@ // xfail-test -extern mod std; -use std::oldmap::*; +extern mod extra; +use extra::oldmap::*; use vec::*; use dvec::{dvec, extensions}; diff --git a/src/test/run-pass/class-trait-bounded-param.rs b/src/test/run-pass/class-trait-bounded-param.rs index 0246946102bdc..75c62abcb0d55 100644 --- a/src/test/run-pass/class-trait-bounded-param.rs +++ b/src/test/run-pass/class-trait-bounded-param.rs @@ -10,8 +10,8 @@ // xfail-test -extern mod std; -use std::oldmap::{map, hashmap, int_hash}; +extern mod extra; +use extra::oldmap::{map, hashmap, int_hash}; class keys> : old_iter::base_iter { diff --git a/src/test/run-pass/clone-with-exterior.rs b/src/test/run-pass/clone-with-exterior.rs index 091f955aca01b..f6a7856dccccf 100644 --- a/src/test/run-pass/clone-with-exterior.rs +++ b/src/test/run-pass/clone-with-exterior.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use core::task::spawn; +extern mod extra; +use std::task::spawn; struct Pair { a: int, diff --git a/src/test/run-pass/coherence-impl-in-fn.rs b/src/test/run-pass/coherence-impl-in-fn.rs index 7643799df0637..707a7bf407659 100644 --- a/src/test/run-pass/coherence-impl-in-fn.rs +++ b/src/test/run-pass/coherence-impl-in-fn.rs @@ -10,7 +10,7 @@ pub fn main() { enum x { foo } - impl ::core::cmp::Eq for x { + impl ::std::cmp::Eq for x { fn eq(&self, other: &x) -> bool { (*self) as int == (*other) as int } diff --git a/src/test/run-pass/comm.rs b/src/test/run-pass/comm.rs index 510976c56463d..c307cf809b66d 100644 --- a/src/test/run-pass/comm.rs +++ b/src/test/run-pass/comm.rs @@ -9,7 +9,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::*; +use std::comm::*; pub fn main() { let (p, ch) = stream(); diff --git a/src/test/run-pass/core-export-f64-sqrt.rs b/src/test/run-pass/core-export-f64-sqrt.rs index d7ac91fe75c32..7e00d7efbe23b 100644 --- a/src/test/run-pass/core-export-f64-sqrt.rs +++ b/src/test/run-pass/core-export-f64-sqrt.rs @@ -14,5 +14,5 @@ pub fn main() { let digits: uint = 10 as uint; - ::core::io::println(float::to_str_digits(f64::sqrt(42.0f64) as float, digits)); + ::std::io::println(float::to_str_digits(f64::sqrt(42.0f64) as float, digits)); } diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index a4f3f59f46baa..b2f444d39e242 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -13,10 +13,10 @@ // NB: These tests kill child processes. Valgrind sees these children as leaking // memory, which makes for some *confusing* logs. That's why these are here -// instead of in core. +// instead of in std. -use core::run; -use core::run::*; +use std::run; +use std::run::*; #[test] fn test_destroy_once() { @@ -47,9 +47,9 @@ fn test_destroy_actually_kills(force: bool) { #[cfg(windows)] fn process_exists(pid: libc::pid_t) -> bool { - use core::libc::types::os::arch::extra::DWORD; - use core::libc::funcs::extra::kernel32::{CloseHandle, GetExitCodeProcess, OpenProcess}; - use core::libc::consts::os::extra::{FALSE, PROCESS_QUERY_INFORMATION, STILL_ACTIVE }; + use std::libc::types::os::arch::extra::DWORD; + use std::libc::funcs::extra::kernel32::{CloseHandle, GetExitCodeProcess, OpenProcess}; + use std::libc::consts::os::extra::{FALSE, PROCESS_QUERY_INFORMATION, STILL_ACTIVE }; unsafe { let proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid as DWORD); diff --git a/src/test/run-pass/deriving-meta-multiple.rs b/src/test/run-pass/deriving-meta-multiple.rs index d94b6fcb41584..f0b2d2ec827bb 100644 --- a/src/test/run-pass/deriving-meta-multiple.rs +++ b/src/test/run-pass/deriving-meta-multiple.rs @@ -19,7 +19,7 @@ struct Foo { } pub fn main() { - use core::hash::{Hash, HashUtil}; // necessary for IterBytes check + use std::hash::{Hash, HashUtil}; // necessary for IterBytes check let a = Foo {bar: 4, baz: -3}; diff --git a/src/test/run-pass/deriving-meta.rs b/src/test/run-pass/deriving-meta.rs index efb202028f3b9..aef671ba757aa 100644 --- a/src/test/run-pass/deriving-meta.rs +++ b/src/test/run-pass/deriving-meta.rs @@ -17,7 +17,7 @@ struct Foo { } pub fn main() { - use core::hash::{Hash, HashUtil}; // necessary for IterBytes check + use std::hash::{Hash, HashUtil}; // necessary for IterBytes check let a = Foo {bar: 4, baz: -3}; diff --git a/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs b/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs index b0b03d8419b8c..2d42088fc140a 100644 --- a/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs +++ b/src/test/run-pass/deriving-self-lifetime-totalord-totaleq.rs @@ -10,7 +10,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::{Less,Equal,Greater}; +use std::cmp::{Less,Equal,Greater}; #[deriving(TotalEq,TotalOrd)] struct A<'self> { diff --git a/src/test/run-pass/drop-trait-generic.rs b/src/test/run-pass/drop-trait-generic.rs index 65c3faac2b304..6c565604fceec 100644 --- a/src/test/run-pass/drop-trait-generic.rs +++ b/src/test/run-pass/drop-trait-generic.rs @@ -13,7 +13,7 @@ struct S { } #[unsafe_destructor] -impl ::core::ops::Drop for S { +impl ::std::ops::Drop for S { fn finalize(&self) { io::println("bye"); } diff --git a/src/test/run-pass/duplicate-use.rs b/src/test/run-pass/duplicate-use.rs index f81b33105e63e..35d5d2ffe8a31 100644 --- a/src/test/run-pass/duplicate-use.rs +++ b/src/test/run-pass/duplicate-use.rs @@ -9,10 +9,10 @@ // except according to those terms. // xfail-test -extern mod std; +extern mod extra; -use list = std::oldmap::chained; -use std::list; +use list = extra::oldmap::chained; +use extra::list; pub fn main() { let _x: list::T = list::mk(); diff --git a/src/test/run-pass/explicit-self-generic.rs b/src/test/run-pass/explicit-self-generic.rs index ad8af0ce63995..c500201d65de3 100644 --- a/src/test/run-pass/explicit-self-generic.rs +++ b/src/test/run-pass/explicit-self-generic.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; /** * A function that returns a hash of a value diff --git a/src/test/run-pass/expr-repeat-vstore.rs b/src/test/run-pass/expr-repeat-vstore.rs index e48abc5753492..5758793602209 100644 --- a/src/test/run-pass/expr-repeat-vstore.rs +++ b/src/test/run-pass/expr-repeat-vstore.rs @@ -1,4 +1,4 @@ -use core::io::println; +use std::io::println; fn main() { let v: ~[int] = ~[ 1, ..5 ]; diff --git a/src/test/run-pass/extern-mod-syntax.rs b/src/test/run-pass/extern-mod-syntax.rs index c98b5ebc23854..0db61fc8cd506 100644 --- a/src/test/run-pass/extern-mod-syntax.rs +++ b/src/test/run-pass/extern-mod-syntax.rs @@ -10,8 +10,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::json::Object; +extern mod extra; +use extra::json::Object; pub fn main() { io::println("Hello world!"); diff --git a/src/test/run-pass/float-nan.rs b/src/test/run-pass/float-nan.rs index 4ea1604a18cbe..29a180db1855d 100644 --- a/src/test/run-pass/float-nan.rs +++ b/src/test/run-pass/float-nan.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; -use core::num::Float; +use std::num::Float; pub fn main() { let nan = Float::NaN::(); diff --git a/src/test/run-pass/fn-bare-size.rs b/src/test/run-pass/fn-bare-size.rs index 424d829b5ea7b..dc47dda420cea 100644 --- a/src/test/run-pass/fn-bare-size.rs +++ b/src/test/run-pass/fn-bare-size.rs @@ -10,7 +10,7 @@ // xfail-test -extern mod std; +extern mod extra; pub fn main() { // Bare functions should just be a pointer diff --git a/src/test/run-pass/foreign-call-no-runtime.rs b/src/test/run-pass/foreign-call-no-runtime.rs index 6f94b16331532..67efca194d527 100644 --- a/src/test/run-pass/foreign-call-no-runtime.rs +++ b/src/test/run-pass/foreign-call-no-runtime.rs @@ -1,4 +1,4 @@ -use core::unstable::run_in_bare_thread; +use std::unstable::run_in_bare_thread; extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) diff --git a/src/test/run-pass/foreign-fn-linkname.rs b/src/test/run-pass/foreign-fn-linkname.rs index 3b00b329feb9d..15e14e3abe5a8 100644 --- a/src/test/run-pass/foreign-fn-linkname.rs +++ b/src/test/run-pass/foreign-fn-linkname.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; mod libc { #[nolink] diff --git a/src/test/run-pass/foreign2.rs b/src/test/run-pass/foreign2.rs index f83d21e17149c..2745ae4014b41 100644 --- a/src/test/run-pass/foreign2.rs +++ b/src/test/run-pass/foreign2.rs @@ -24,8 +24,8 @@ mod libc { #[abi = "cdecl"] #[nolink] pub extern { - pub fn write(fd: int, buf: *u8, count: ::core::libc::size_t) - -> ::core::libc::ssize_t; + pub fn write(fd: int, buf: *u8, count: ::std::libc::size_t) + -> ::std::libc::ssize_t; } } diff --git a/src/test/run-pass/getopts_ref.rs b/src/test/run-pass/getopts_ref.rs index afd018de3bb39..5abef9e5f8913 100644 --- a/src/test/run-pass/getopts_ref.rs +++ b/src/test/run-pass/getopts_ref.rs @@ -10,9 +10,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; -use std::getopts::*; +use extra::getopts::*; pub fn main() { let args = ~[]; diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index c6ae2047147b1..fb82e93047da8 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -19,8 +19,8 @@ pub fn map(filename: ~str, emit: map_reduce::putter) { emit(filename, ~"1"); } mod map_reduce { - use core::hashmap::HashMap; - use core::comm::*; + use std::hashmap::HashMap; + use std::comm::*; pub type putter = @fn(~str, ~str); diff --git a/src/test/run-pass/import-glob-crate.rs b/src/test/run-pass/import-glob-crate.rs index de25ec42c29f1..0e95ee25c4243 100644 --- a/src/test/run-pass/import-glob-crate.rs +++ b/src/test/run-pass/import-glob-crate.rs @@ -11,8 +11,8 @@ // except according to those terms. -extern mod std; -use core::vec::*; +extern mod extra; +use std::vec::*; pub fn main() { let mut v = from_elem(0u, 0); diff --git a/src/test/run-pass/import-in-block.rs b/src/test/run-pass/import-in-block.rs index 659b7b5be6f65..9537162e1c803 100644 --- a/src/test/run-pass/import-in-block.rs +++ b/src/test/run-pass/import-in-block.rs @@ -9,10 +9,10 @@ // except according to those terms. pub fn main() { - use core::vec::from_fn; - debug!(::core::vec::len(from_fn(2, |i| i))); + use std::vec::from_fn; + debug!(::std::vec::len(from_fn(2, |i| i))); { - use core::vec::*; + use std::vec::*; debug!(len(~[2])); } } diff --git a/src/test/run-pass/infinite-loops.rs b/src/test/run-pass/infinite-loops.rs index b2ed6d95c206a..dea0df2e52b34 100644 --- a/src/test/run-pass/infinite-loops.rs +++ b/src/test/run-pass/infinite-loops.rs @@ -14,7 +14,7 @@ */ // xfail-test -extern mod std; +extern mod extra; fn loopy(n: int) { if n > 0 { do spawn { loopy(n - 1) }; do spawn { loopy(n - 1) }; } diff --git a/src/test/run-pass/intrinsics-integer.rs b/src/test/run-pass/intrinsics-integer.rs index e4d84808673c0..6be47b1e88b3d 100644 --- a/src/test/run-pass/intrinsics-integer.rs +++ b/src/test/run-pass/intrinsics-integer.rs @@ -10,7 +10,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; mod rusti { #[abi = "rust-intrinsic"] diff --git a/src/test/run-pass/issue-1696.rs b/src/test/run-pass/issue-1696.rs index 5b40d0abff818..d531217e550b6 100644 --- a/src/test/run-pass/issue-1696.rs +++ b/src/test/run-pass/issue-1696.rs @@ -10,7 +10,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::HashMap; +use std::hashmap::HashMap; pub fn main() { let mut m = HashMap::new(); diff --git a/src/test/run-pass/issue-2101.rs b/src/test/run-pass/issue-2101.rs index 4564e08914712..423888c1cf5b6 100644 --- a/src/test/run-pass/issue-2101.rs +++ b/src/test/run-pass/issue-2101.rs @@ -9,9 +9,9 @@ // except according to those terms. // xfail-test -extern mod std; -use std::arena; -use std::arena::Arena; +extern mod extra; +use extra::arena; +use extra::arena::Arena; enum hold { s(str) } diff --git a/src/test/run-pass/issue-2214.rs b/src/test/run-pass/issue-2214.rs index 8e4309e08e49c..93cc8c292b152 100644 --- a/src/test/run-pass/issue-2214.rs +++ b/src/test/run-pass/issue-2214.rs @@ -10,9 +10,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cast; -use core::libc::{c_double, c_int}; -use core::f64::*; +use std::cast; +use std::libc::{c_double, c_int}; +use std::f64::*; fn to_c_int(v: &mut int) -> &mut c_int { unsafe { @@ -27,7 +27,7 @@ fn lgamma(n: c_double, value: &mut int) -> c_double { } mod m { - use core::libc::{c_double, c_int}; + use std::libc::{c_double, c_int}; #[link_name = "m"] #[abi = "cdecl"] diff --git a/src/test/run-pass/issue-2383.rs b/src/test/run-pass/issue-2383.rs index a7afa1d6f3494..9d8701688024c 100644 --- a/src/test/run-pass/issue-2383.rs +++ b/src/test/run-pass/issue-2383.rs @@ -10,8 +10,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::deque::Deque; +extern mod extra; +use extra::deque::Deque; pub fn main() { let mut q = Deque::new(); diff --git a/src/test/run-pass/issue-2611.rs b/src/test/run-pass/issue-2611.rs index f24605339ad77..3d4bed4b62fc7 100644 --- a/src/test/run-pass/issue-2611.rs +++ b/src/test/run-pass/issue-2611.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::old_iter::BaseIter; +use std::old_iter::BaseIter; trait FlatMapToVec { fn flat_map_to_vec>(&self, op: &fn(&A) -> IB) -> ~[B]; diff --git a/src/test/run-pass/issue-2631-b.rs b/src/test/run-pass/issue-2631-b.rs index f6e40fa247d5e..3ceae1030562d 100644 --- a/src/test/run-pass/issue-2631-b.rs +++ b/src/test/run-pass/issue-2631-b.rs @@ -14,7 +14,7 @@ extern mod req; use req::*; -use core::hashmap::HashMap; +use std::hashmap::HashMap; pub fn main() { let v = ~[@~"hi"]; diff --git a/src/test/run-pass/issue-2718.rs b/src/test/run-pass/issue-2718.rs index 55be1056ecaea..48599b2a5383b 100644 --- a/src/test/run-pass/issue-2718.rs +++ b/src/test/run-pass/issue-2718.rs @@ -10,12 +10,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::util; +use std::util; // tjc: I don't know why pub mod pipes { - use core::util; - use core::cast::{forget, transmute}; + use std::util; + use std::cast::{forget, transmute}; pub struct Stuff { state: state, @@ -54,7 +54,7 @@ pub mod pipes { pub fn atomic_xchg_rel(_dst: &mut int, _src: int) -> int { fail!(); } } - // We should consider moving this to ::core::unsafe, although I + // We should consider moving this to ::std::unsafe, although I // suspect graydon would want us to use void pointers instead. pub unsafe fn uniquify(x: *T) -> ~T { unsafe { cast::transmute(x) } @@ -219,9 +219,9 @@ pub mod pipes { } pub mod pingpong { - use core::cast; - use core::ptr; - use core::util; + use std::cast; + use std::ptr; + use std::util; pub struct ping(::pipes::send_packet); pub struct pong(::pipes::send_packet); @@ -253,7 +253,7 @@ pub mod pingpong { } pub mod client { - use core::option; + use std::option; use pingpong; pub type ping = ::pipes::send_packet; diff --git a/src/test/run-pass/issue-2804-2.rs b/src/test/run-pass/issue-2804-2.rs index b25e4095b185e..917839a5401e2 100644 --- a/src/test/run-pass/issue-2804-2.rs +++ b/src/test/run-pass/issue-2804-2.rs @@ -13,7 +13,7 @@ // Minimized version of issue-2804.rs. Both check that callee IDs don't // clobber the previous node ID in a macro expr -use core::hashmap::HashMap; +use std::hashmap::HashMap; fn add_interfaces(managed_ip: ~str, device: HashMap<~str, int>) { error!("%s, %?", managed_ip, device.get(&~"interfaces")); diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index 4614c26fa5fc8..bb2dbb9fe21ff 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -10,9 +10,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use core::hashmap::HashMap; -use std::json; +extern mod extra; +use std::hashmap::HashMap; +use extra::json; enum object { bool_value(bool), @@ -23,7 +23,7 @@ fn lookup(table: ~json::Object, key: ~str, default: ~str) -> ~str { match table.find(&key) { - option::Some(&std::json::String(copy s)) => + option::Some(&extra::json::String(copy s)) => { copy s } @@ -39,11 +39,11 @@ fn lookup(table: ~json::Object, key: ~str, default: ~str) -> ~str } } -fn add_interface(store: int, managed_ip: ~str, data: std::json::Json) -> (~str, object) +fn add_interface(store: int, managed_ip: ~str, data: extra::json::Json) -> (~str, object) { match &data { - &std::json::Object(copy interface) => + &extra::json::Object(copy interface) => { let name = lookup(copy interface, ~"ifDescr", ~""); let label = fmt!("%s-%s", managed_ip, name); @@ -58,11 +58,11 @@ fn add_interface(store: int, managed_ip: ~str, data: std::json::Json) -> (~str, } } -fn add_interfaces(store: int, managed_ip: ~str, device: HashMap<~str, std::json::Json>) -> ~[(~str, object)] +fn add_interfaces(store: int, managed_ip: ~str, device: HashMap<~str, extra::json::Json>) -> ~[(~str, object)] { match device.get(&~"interfaces") { - &std::json::List(ref interfaces) => + &extra::json::List(ref interfaces) => { do interfaces.map |interface| { add_interface(store, copy managed_ip, copy *interface) diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index 9ea8caef7bc21..1cb8a74e5a4fe 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -12,9 +12,9 @@ /// Map representation -extern mod std; +extern mod extra; -use core::io::ReaderUtil; +use std::io::ReaderUtil; enum square { bot, diff --git a/src/test/run-pass/issue-2989.rs b/src/test/run-pass/issue-2989.rs index 5aaa3e595e100..8ef67840ba3cf 100644 --- a/src/test/run-pass/issue-2989.rs +++ b/src/test/run-pass/issue-2989.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; trait methods { fn to_bytes(&self) -> ~[u8]; diff --git a/src/test/run-pass/issue-3026.rs b/src/test/run-pass/issue-3026.rs index 16e9b4753f830..a4b37f0ba0f0b 100644 --- a/src/test/run-pass/issue-3026.rs +++ b/src/test/run-pass/issue-3026.rs @@ -10,7 +10,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::HashMap; +use std::hashmap::HashMap; pub fn main() { let mut buggy_map: HashMap = HashMap::new::(); diff --git a/src/test/run-pass/issue-3176.rs b/src/test/run-pass/issue-3176.rs index d22c7e82ad5de..54094a0c008a3 100644 --- a/src/test/run-pass/issue-3176.rs +++ b/src/test/run-pass/issue-3176.rs @@ -10,7 +10,7 @@ // xfail-fast -use core::comm::{Select2, Selectable}; +use std::comm::{Select2, Selectable}; pub fn main() { let (p,c) = comm::stream(); diff --git a/src/test/run-pass/issue-3424.rs b/src/test/run-pass/issue-3424.rs index 70a01f8cf02d2..a6eb5097b36fc 100644 --- a/src/test/run-pass/issue-3424.rs +++ b/src/test/run-pass/issue-3424.rs @@ -11,8 +11,8 @@ // except according to those terms. // rustc --test ignores2.rs && ./ignores2 -extern mod std; -use core::path::{Path}; +extern mod extra; +use std::path::{Path}; type rsrc_loader = ~fn(path: &Path) -> result::Result<~str, ~str>; diff --git a/src/test/run-pass/issue-3556.rs b/src/test/run-pass/issue-3556.rs index ff2fa80102bfc..ca67f1dae431b 100644 --- a/src/test/run-pass/issue-3556.rs +++ b/src/test/run-pass/issue-3556.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use core::io::WriterUtil; +extern mod extra; +use std::io::WriterUtil; enum Token { Text(@~str), diff --git a/src/test/run-pass/issue-3559.rs b/src/test/run-pass/issue-3559.rs index b3f3aed9ea1f9..9665da11b9334 100644 --- a/src/test/run-pass/issue-3559.rs +++ b/src/test/run-pass/issue-3559.rs @@ -11,9 +11,9 @@ // except according to those terms. // rustc --test map_to_str.rs && ./map_to_str -extern mod std; +extern mod extra; -use core::io::{WriterUtil}; +use std::io::{WriterUtil}; fn check_strs(actual: &str, expected: &str) -> bool { @@ -27,7 +27,7 @@ fn check_strs(actual: &str, expected: &str) -> bool fn tester() { - let mut table = core::hashmap::HashMap::new(); + let mut table = std::hashmap::HashMap::new(); table.insert(@~"one", 1); table.insert(@~"two", 2); assert!(check_strs(table.to_str(), ~"xxx")); // not sure what expected should be diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index 96925a97a1016..bfdf4aa053daf 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -12,15 +12,15 @@ // Demonstrates traits, impls, operator overloading, non-copyable struct, unit testing. // To run execute: rustc --test shapes.rs && ./shapes -// Rust's core library is tightly bound to the language itself so it is automatically linked in. -// However the std library is designed to be optional (for code that must run on constrained +// Rust's std library is tightly bound to the language itself so it is automatically linked in. +// However the extra library is designed to be optional (for code that must run on constrained // environments like embedded devices or special environments like kernel code) so it must // be explicitly linked in. -extern mod std; +extern mod extra; // Extern mod controls linkage. Use controls the visibility of names to modules that are // already linked in. Using WriterUtil allows us to use the write_line method. -use core::io::WriterUtil; +use std::io::WriterUtil; // Represents a position on a canvas. struct Point { diff --git a/src/test/run-pass/issue-3574.rs b/src/test/run-pass/issue-3574.rs index db937e745037a..dc1ce95cfae54 100644 --- a/src/test/run-pass/issue-3574.rs +++ b/src/test/run-pass/issue-3574.rs @@ -9,7 +9,7 @@ // except according to those terms. // rustc --test match_borrowed_str.rs.rs && ./match_borrowed_str.rs -extern mod std; +extern mod extra; fn compare(x: &str, y: &str) -> bool { diff --git a/src/test/run-pass/issue-3609.rs b/src/test/run-pass/issue-3609.rs index 6c26ac3f65e1c..a1aced7b5df0a 100644 --- a/src/test/run-pass/issue-3609.rs +++ b/src/test/run-pass/issue-3609.rs @@ -1,6 +1,6 @@ -extern mod std; +extern mod extra; -use core::comm::Chan; +use std::comm::Chan; type RingBuffer = ~[float]; type SamplesFn = ~fn(samples: &RingBuffer); diff --git a/src/test/run-pass/issue-3656.rs b/src/test/run-pass/issue-3656.rs index 895e90beef4aa..96cf88a0e2b5e 100644 --- a/src/test/run-pass/issue-3656.rs +++ b/src/test/run-pass/issue-3656.rs @@ -13,7 +13,7 @@ // Incorrect struct size computation in the FFI, because of not taking // the alignment of elements into account. -use core::libc::*; +use std::libc::*; struct KEYGEN { hash_algorithm: [c_uint, ..2], diff --git a/src/test/run-pass/issue-4016.rs b/src/test/run-pass/issue-4016.rs index 2384b0e859393..4e65a7063e7f0 100644 --- a/src/test/run-pass/issue-4016.rs +++ b/src/test/run-pass/issue-4016.rs @@ -9,11 +9,11 @@ // except according to those terms. // xfail-test -extern mod std; +extern mod extra; use hashmap; -use std::json; -use std::serialization::{Deserializable, deserialize}; +use extra::json; +use extra::serialization::{Deserializable, deserialize}; trait JD : Deserializable { } //type JD = Deserializable; diff --git a/src/test/run-pass/issue-4036.rs b/src/test/run-pass/issue-4036.rs index 8b514b11625e4..ad82071259593 100644 --- a/src/test/run-pass/issue-4036.rs +++ b/src/test/run-pass/issue-4036.rs @@ -11,9 +11,9 @@ // Issue #4036: Test for an issue that arose around fixing up type inference // byproducts in vtable records. -extern mod std; -use self::std::json; -use self::std::serialize; +extern mod extra; +use self::extra::json; +use self::extra::serialize; pub fn main() { let json = json::from_str("[1]").unwrap(); diff --git a/src/test/run-pass/issue-4092.rs b/src/test/run-pass/issue-4092.rs index e129e0a88687a..919c1f7ad184d 100644 --- a/src/test/run-pass/issue-4092.rs +++ b/src/test/run-pass/issue-4092.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::hashmap::HashMap; +use std::hashmap::HashMap; pub fn main() { let mut x = HashMap::new(); diff --git a/src/test/run-pass/issue-4241.rs b/src/test/run-pass/issue-4241.rs index 5503441771c45..4aa604160d933 100644 --- a/src/test/run-pass/issue-4241.rs +++ b/src/test/run-pass/issue-4241.rs @@ -9,11 +9,11 @@ // except according to those terms. // xfail-test -extern mod std; +extern mod extra; -use std::net::tcp::TcpSocketBuf; +use extra::net::tcp::TcpSocketBuf; -use core::io::{ReaderUtil,WriterUtil}; +use std::io::{ReaderUtil,WriterUtil}; enum Result { Nil, diff --git a/src/test/run-pass/issue-4541.rs b/src/test/run-pass/issue-4541.rs index 37e91cf1eb22a..24a8adfcb1a53 100644 --- a/src/test/run-pass/issue-4541.rs +++ b/src/test/run-pass/issue-4541.rs @@ -10,7 +10,7 @@ // xfail-test fn parse_args() -> ~str { - let args = core::os::args(); + let args = std::os::args(); let mut n = 0; while n < args.len() { diff --git a/src/test/run-pass/item-attributes.rs b/src/test/run-pass/item-attributes.rs index c616d46a8336c..5a1d54c48b5d2 100644 --- a/src/test/run-pass/item-attributes.rs +++ b/src/test/run-pass/item-attributes.rs @@ -17,10 +17,10 @@ #[attr4(attr5)]; // Special linkage attributes for the crate -#[link(name = "std", +#[link(name = "extra", vers = "0.1", uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297", - url = "http://rust-lang.org/src/std")]; + url = "http://rust-lang.org/src/extra")]; // These are are attributes of the following mod #[attr1 = "val"] @@ -148,7 +148,7 @@ mod test_attr_inner_then_outer_multi { } mod test_distinguish_syntax_ext { - extern mod std; + extern mod extra; pub fn f() { fmt!("test%s", ~"s"); diff --git a/src/test/run-pass/ivec-tag.rs b/src/test/run-pass/ivec-tag.rs index 017d90cbcd736..5b1102a1917b5 100644 --- a/src/test/run-pass/ivec-tag.rs +++ b/src/test/run-pass/ivec-tag.rs @@ -1,4 +1,4 @@ -use core::comm::*; +use std::comm::*; fn producer(c: &Chan<~[u8]>) { c.send( 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 2cddc51042277..ae2ae6dbf9ce0 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 @@ -10,8 +10,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::list; +extern mod extra; +use extra::list; enum foo { a(uint), diff --git a/src/test/run-pass/lots-a-fail.rs b/src/test/run-pass/lots-a-fail.rs index ed9e6e540305d..4eb0cd81bc320 100644 --- a/src/test/run-pass/lots-a-fail.rs +++ b/src/test/run-pass/lots-a-fail.rs @@ -9,7 +9,7 @@ // except according to those terms. // xfail-win32 leaks -extern mod std; +extern mod extra; fn die() { fail!(); diff --git a/src/test/run-pass/mlist-cycle.rs b/src/test/run-pass/mlist-cycle.rs index a67f1574f64af..cb33feef539ef 100644 --- a/src/test/run-pass/mlist-cycle.rs +++ b/src/test/run-pass/mlist-cycle.rs @@ -10,9 +10,9 @@ // xfail-test // -*- rust -*- -extern mod core; -use core::gc; -use core::gc::rustrt; +extern mod std; +use std::gc; +use std::gc::rustrt; struct cell {c: @list} diff --git a/src/test/run-pass/mod-view-items.rs b/src/test/run-pass/mod-view-items.rs index 7dbcb72f1eaf3..2fc2d4b371605 100644 --- a/src/test/run-pass/mod-view-items.rs +++ b/src/test/run-pass/mod-view-items.rs @@ -17,7 +17,7 @@ // begin failing. mod m { - use core::vec; + use std::vec; pub fn f() -> ~[int] { vec::from_elem(1u, 0) } } diff --git a/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs b/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs index 90b3e623f5ed6..efbf9302117ff 100644 --- a/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs +++ b/src/test/run-pass/monomorphized-callees-with-ty-params-3314.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; trait Serializer { } diff --git a/src/test/run-pass/morestack5.rs b/src/test/run-pass/morestack5.rs index e1561db8b9162..492196ed7f0d5 100644 --- a/src/test/run-pass/morestack5.rs +++ b/src/test/run-pass/morestack5.rs @@ -10,7 +10,7 @@ // This test will call __morestack with various minimum stack sizes -extern mod std; +extern mod extra; fn getbig(i: int) { if i != 0 { diff --git a/src/test/run-pass/morestack6.rs b/src/test/run-pass/morestack6.rs index dafdd0fba48c3..79c66ba72b0c7 100644 --- a/src/test/run-pass/morestack6.rs +++ b/src/test/run-pass/morestack6.rs @@ -54,7 +54,7 @@ fn runtest2(f: extern fn(), frame_backoff: u32, last_stk: *u8) -> u32 { } pub fn main() { - use core::rand::Rng; + use std::rand::Rng; let fns = ~[ calllink01, calllink02, diff --git a/src/test/run-pass/move-3-unique.rs b/src/test/run-pass/move-3-unique.rs index dcd4cc9a7ea06..7b71fc4f86ecb 100644 --- a/src/test/run-pass/move-3-unique.rs +++ b/src/test/run-pass/move-3-unique.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; struct Triple { x: int, y: int, z: int } diff --git a/src/test/run-pass/move-3.rs b/src/test/run-pass/move-3.rs index 42955b9472127..64519034ebe7a 100644 --- a/src/test/run-pass/move-3.rs +++ b/src/test/run-pass/move-3.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; struct Triple { x: int, y: int, z: int } diff --git a/src/test/run-pass/move-4-unique.rs b/src/test/run-pass/move-4-unique.rs index 2ed3523ef86ab..48621cf03be6a 100644 --- a/src/test/run-pass/move-4-unique.rs +++ b/src/test/run-pass/move-4-unique.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; struct Triple {a: int, b: int, c: int} diff --git a/src/test/run-pass/move-4.rs b/src/test/run-pass/move-4.rs index cd88b67936155..2f0f256ba78e8 100644 --- a/src/test/run-pass/move-4.rs +++ b/src/test/run-pass/move-4.rs @@ -9,7 +9,7 @@ // except according to those terms. -extern mod std; +extern mod extra; struct Triple { a: int, b: int, c: int } diff --git a/src/test/run-pass/mutable-alias-vec.rs b/src/test/run-pass/mutable-alias-vec.rs index 42c623ec41c58..b058df7fc7a0f 100644 --- a/src/test/run-pass/mutable-alias-vec.rs +++ b/src/test/run-pass/mutable-alias-vec.rs @@ -11,7 +11,7 @@ // -*- rust -*- -extern mod std; +extern mod extra; fn grow(v: &mut ~[int]) { *v += ~[1]; } diff --git a/src/test/run-pass/new-import-syntax.rs b/src/test/run-pass/new-import-syntax.rs index 1390ae5f7ebe0..c7497bf3de525 100644 --- a/src/test/run-pass/new-import-syntax.rs +++ b/src/test/run-pass/new-import-syntax.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::io::println; +use std::io::println; pub fn main() { println("Hello world!"); diff --git a/src/test/run-pass/new-style-constants.rs b/src/test/run-pass/new-style-constants.rs index 6fe4a88d07183..2da532422c0cb 100644 --- a/src/test/run-pass/new-style-constants.rs +++ b/src/test/run-pass/new-style-constants.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::io::println; +use std::io::println; static FOO: int = 3; diff --git a/src/test/run-pass/new-style-fixed-length-vec.rs b/src/test/run-pass/new-style-fixed-length-vec.rs index 6eea23f6b2b06..41704c252c8db 100644 --- a/src/test/run-pass/new-style-fixed-length-vec.rs +++ b/src/test/run-pass/new-style-fixed-length-vec.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::io::println; +use std::io::println; static FOO: [int, ..3] = [1, 2, 3]; diff --git a/src/test/run-pass/newtype-struct-with-dtor.rs b/src/test/run-pass/newtype-struct-with-dtor.rs index eb3b74553b7ba..0e36f27aa9292 100644 --- a/src/test/run-pass/newtype-struct-with-dtor.rs +++ b/src/test/run-pass/newtype-struct-with-dtor.rs @@ -1,5 +1,5 @@ -use core::libc::c_int; -use core::libc; +use std::libc::c_int; +use std::libc; pub struct Fd(c_int); diff --git a/src/test/run-pass/non-boolean-pure-fns.rs b/src/test/run-pass/non-boolean-pure-fns.rs index 58ac4fc576d9b..c08f52cba1597 100644 --- a/src/test/run-pass/non-boolean-pure-fns.rs +++ b/src/test/run-pass/non-boolean-pure-fns.rs @@ -10,9 +10,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; -use std::list::*; +use extra::list::*; fn pure_length_go(ls: @List, acc: uint) -> uint { match *ls { Nil => { acc } Cons(_, tl) => { pure_length_go(tl, acc + 1u) } } diff --git a/src/test/run-pass/nullable-pointer-iotareduction.rs b/src/test/run-pass/nullable-pointer-iotareduction.rs index 6ec2054996335..b63870dcfb631 100644 --- a/src/test/run-pass/nullable-pointer-iotareduction.rs +++ b/src/test/run-pass/nullable-pointer-iotareduction.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::{option, cast}; +use std::{option, cast}; // Iota-reduction is a rule in the Calculus of (Co-)Inductive Constructions, // which "says that a destructor applied to an object built from a constructor diff --git a/src/test/run-pass/overload-index-operator.rs b/src/test/run-pass/overload-index-operator.rs index 497c17d04590e..1838cfe25198a 100644 --- a/src/test/run-pass/overload-index-operator.rs +++ b/src/test/run-pass/overload-index-operator.rs @@ -11,7 +11,7 @@ // Test overloading of the `[]` operator. In particular test that it // takes its argument *by reference*. -use core::ops::Index; +use std::ops::Index; struct AssociationList { pairs: ~[AssociationPair] diff --git a/src/test/run-pass/pipe-bank-proto.rs b/src/test/run-pass/pipe-bank-proto.rs index 26395e7307f9c..83031b4670450 100644 --- a/src/test/run-pass/pipe-bank-proto.rs +++ b/src/test/run-pass/pipe-bank-proto.rs @@ -15,8 +15,8 @@ // // http://theincredibleholk.wordpress.com/2012/07/06/rusty-pipes/ -use core::pipes; -use core::pipes::try_recv; +use std::pipes; +use std::pipes::try_recv; pub type username = ~str; pub type password = ~str; diff --git a/src/test/run-pass/pipe-detect-term.rs b/src/test/run-pass/pipe-detect-term.rs index 55e43075204cc..d922eef5dbb1d 100644 --- a/src/test/run-pass/pipe-detect-term.rs +++ b/src/test/run-pass/pipe-detect-term.rs @@ -14,12 +14,12 @@ // xfail-win32 -extern mod std; -use std::timer::sleep; -use std::uv; +extern mod extra; +use extra::timer::sleep; +use extra::uv; -use core::cell::Cell; -use core::pipes::{try_recv, recv}; +use std::cell::Cell; +use std::pipes::{try_recv, recv}; proto! oneshot ( waiting:send { diff --git a/src/test/run-pass/pipe-peek.rs b/src/test/run-pass/pipe-peek.rs index 985eaecdc781b..149e81204f474 100644 --- a/src/test/run-pass/pipe-peek.rs +++ b/src/test/run-pass/pipe-peek.rs @@ -10,10 +10,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::timer::sleep; -use std::uv; -use core::pipes; +extern mod extra; +use extra::timer::sleep; +use extra::uv; +use std::pipes; proto! oneshot ( waiting:send { diff --git a/src/test/run-pass/pipe-pingpong-bounded.rs b/src/test/run-pass/pipe-pingpong-bounded.rs index 3c37371a5371c..b4c92dc0614bb 100644 --- a/src/test/run-pass/pipe-pingpong-bounded.rs +++ b/src/test/run-pass/pipe-pingpong-bounded.rs @@ -14,15 +14,15 @@ // experiment with what code the compiler should generate for bounded // protocols. -use core::cell::Cell; +use std::cell::Cell; // This was generated initially by the pipe compiler, but it's been // modified in hopefully straightforward ways. mod pingpong { - use core::pipes; - use core::pipes::*; - use core::ptr; + use std::pipes; + use std::pipes::*; + use std::ptr; pub struct Packets { ping: Packet, @@ -46,9 +46,9 @@ mod pingpong { pub struct ping(server::pong); pub struct pong(client::ping); pub mod client { - use core::pipes; - use core::pipes::*; - use core::ptr; + use std::pipes; + use std::pipes::*; + use std::ptr; pub fn ping(mut pipe: ping) -> pong { { @@ -66,9 +66,9 @@ mod pingpong { ::pingpong::Packets>; } pub mod server { - use core::pipes; - use core::pipes::*; - use core::ptr; + use std::pipes; + use std::pipes::*; + use std::ptr; pub type ping = pipes::RecvPacketBuffered<::pingpong::ping, ::pingpong::Packets>; @@ -88,7 +88,7 @@ mod pingpong { } mod test { - use core::pipes::recv; + use std::pipes::recv; use pingpong::{ping, pong}; pub fn client(chan: ::pingpong::client::ping) { diff --git a/src/test/run-pass/pipe-pingpong-proto.rs b/src/test/run-pass/pipe-pingpong-proto.rs index 5978438ef7635..95502b14c5314 100644 --- a/src/test/run-pass/pipe-pingpong-proto.rs +++ b/src/test/run-pass/pipe-pingpong-proto.rs @@ -12,8 +12,8 @@ // An example to make sure the protocol parsing syntax extension works. -use core::cell::Cell; -use core::option; +use std::cell::Cell; +use std::option; proto! pingpong ( ping:send { @@ -26,7 +26,7 @@ proto! pingpong ( ) mod test { - use core::pipes::recv; + use std::pipes::recv; use pingpong::{ping, pong}; pub fn client(chan: ::pingpong::client::ping) { diff --git a/src/test/run-pass/pipe-presentation-examples.rs b/src/test/run-pass/pipe-presentation-examples.rs index fcfd77dab0aa3..54cf8ba9c0acb 100644 --- a/src/test/run-pass/pipe-presentation-examples.rs +++ b/src/test/run-pass/pipe-presentation-examples.rs @@ -21,7 +21,7 @@ use double_buffer::client::*; use double_buffer::give_buffer; -use core::comm::Selectable; +use std::comm::Selectable; macro_rules! select_if ( { @@ -37,7 +37,7 @@ macro_rules! select_if ( ], )* } => { if $index == $count { - match core::pipes::try_recv($port) { + match std::pipes::try_recv($port) { $(Some($message($($($x,)+)* next)) => { let $next = next; $e @@ -71,7 +71,7 @@ macro_rules! select ( -> $next:ident $e:expr),+ } )+ } => ({ - let index = core::comm::selecti([$(($port).header()),+]); + let index = std::comm::selecti([$(($port).header()),+]); select_if!(index, 0, $( $port => [ $($message$(($($x),+))dont_type_this* -> $next $e),+ ], )+) diff --git a/src/test/run-pass/pipe-select.rs b/src/test/run-pass/pipe-select.rs index 7e0a59f57fc5a..a386c3a2e05e0 100644 --- a/src/test/run-pass/pipe-select.rs +++ b/src/test/run-pass/pipe-select.rs @@ -13,13 +13,13 @@ // xfail-pretty // xfail-win32 -extern mod std; -use std::timer::sleep; -use std::uv; +extern mod extra; +use extra::timer::sleep; +use extra::uv; -use core::cell::Cell; -use core::pipes; -use core::pipes::*; +use std::cell::Cell; +use std::pipes; +use std::pipes::*; proto! oneshot ( waiting:send { diff --git a/src/test/run-pass/pipe-sleep.rs b/src/test/run-pass/pipe-sleep.rs index da49a4303a6d7..674ad5f340563 100644 --- a/src/test/run-pass/pipe-sleep.rs +++ b/src/test/run-pass/pipe-sleep.rs @@ -10,12 +10,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::timer::sleep; -use std::uv; -use core::cell::Cell; -use core::pipes; -use core::pipes::*; +extern mod extra; +use extra::timer::sleep; +use extra::uv; +use std::cell::Cell; +use std::pipes; +use std::pipes::*; proto! oneshot ( waiting:send { diff --git a/src/test/run-pass/placement-new-arena.rs b/src/test/run-pass/placement-new-arena.rs index ac5bc4f62d9ea..1dafbca22f72d 100644 --- a/src/test/run-pass/placement-new-arena.rs +++ b/src/test/run-pass/placement-new-arena.rs @@ -10,8 +10,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; -use std::arena; +extern mod extra; +use extra::arena; pub fn main() { let mut arena = arena::Arena(); diff --git a/src/test/run-pass/reflect-visit-data.rs b/src/test/run-pass/reflect-visit-data.rs index 5255c13bead62..9663beb279e5b 100644 --- a/src/test/run-pass/reflect-visit-data.rs +++ b/src/test/run-pass/reflect-visit-data.rs @@ -10,9 +10,9 @@ // xfail-fast -use core::bool; -use core::libc::c_void; -use core::vec::UnboxedVecRepr; +use std::bool; +use std::libc::c_void; +use std::vec::UnboxedVecRepr; use intrinsic::{TyDesc, get_tydesc, visit_tydesc, TyVisitor, Opaque}; #[doc = "High-level interfaces to `intrinsic::visit_ty` reflection system."] diff --git a/src/test/run-pass/regions-infer-borrow-scope-addr-of.rs b/src/test/run-pass/regions-infer-borrow-scope-addr-of.rs index a87a899cafeaf..33d147c22b612 100644 --- a/src/test/run-pass/regions-infer-borrow-scope-addr-of.rs +++ b/src/test/run-pass/regions-infer-borrow-scope-addr-of.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::util; +use std::util; pub fn main() { let mut x = 4; diff --git a/src/test/run-pass/ret-break-cont-in-block.rs b/src/test/run-pass/ret-break-cont-in-block.rs index f1b1267faa78a..9a547bd4bdf46 100644 --- a/src/test/run-pass/ret-break-cont-in-block.rs +++ b/src/test/run-pass/ret-break-cont-in-block.rs @@ -10,7 +10,7 @@ // xfail-fast -use core::cmp::Eq; +use std::cmp::Eq; fn iter(v: ~[T], it: &fn(&T) -> bool) -> bool { let mut i = 0u, l = v.len(); diff --git a/src/test/run-pass/rt-sched-1.rs b/src/test/run-pass/rt-sched-1.rs index 17c5994634fe3..a60b24987c85b 100644 --- a/src/test/run-pass/rt-sched-1.rs +++ b/src/test/run-pass/rt-sched-1.rs @@ -10,7 +10,7 @@ // Tests of the runtime's scheduler interface -use core::comm::*; +use std::comm::*; pub type sched_id = int; pub type task_id = *libc::c_void; diff --git a/src/test/run-pass/send-iloop.rs b/src/test/run-pass/send-iloop.rs index 18f4fd27858ba..ed0a5263035bf 100644 --- a/src/test/run-pass/send-iloop.rs +++ b/src/test/run-pass/send-iloop.rs @@ -9,7 +9,7 @@ // except according to those terms. // xfail-win32 -extern mod std; +extern mod extra; fn die() { fail!(); diff --git a/src/test/run-pass/send-resource.rs b/src/test/run-pass/send-resource.rs index 6bda62be621d6..17789e0b50942 100644 --- a/src/test/run-pass/send-resource.rs +++ b/src/test/run-pass/send-resource.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::*; +use std::comm::*; struct test { f: int, diff --git a/src/test/run-pass/send-type-inference.rs b/src/test/run-pass/send-type-inference.rs index 734ef70a4b8d0..bdb1fbaf42261 100644 --- a/src/test/run-pass/send-type-inference.rs +++ b/src/test/run-pass/send-type-inference.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::*; +use std::comm::*; // tests that ctrl's type gets inferred properly struct Command { diff --git a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs index 9816849d80826..19e853199273e 100644 --- a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs +++ b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cell::Cell; +use std::cell::Cell; pub fn main() { test05(); } diff --git a/src/test/run-pass/shape_intrinsic_tag_then_rec.rs b/src/test/run-pass/shape_intrinsic_tag_then_rec.rs index 25ac00d174f34..f29d0c6f108c6 100644 --- a/src/test/run-pass/shape_intrinsic_tag_then_rec.rs +++ b/src/test/run-pass/shape_intrinsic_tag_then_rec.rs @@ -14,9 +14,9 @@ // on x86_64: when there is a enum embedded in an // interior record which is then itself interior to // something else, shape calculations were off. -extern mod std; -use std::list; -use std::list::list; +extern mod extra; +use extra::list; +use extra::list::list; enum opt_span { diff --git a/src/test/run-pass/spawn-types.rs b/src/test/run-pass/spawn-types.rs index eb1c082f2f2e6..58b7b8c09a5a0 100644 --- a/src/test/run-pass/spawn-types.rs +++ b/src/test/run-pass/spawn-types.rs @@ -14,7 +14,7 @@ Arnold. */ -use core::comm::*; +use std::comm::*; type ctx = Chan; diff --git a/src/test/run-pass/spawn.rs b/src/test/run-pass/spawn.rs index 9a5131ef23000..fef00549fa771 100644 --- a/src/test/run-pass/spawn.rs +++ b/src/test/run-pass/spawn.rs @@ -10,7 +10,7 @@ // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { diff --git a/src/test/run-pass/stat.rs b/src/test/run-pass/stat.rs index 2e081f364e768..f9216135038a8 100644 --- a/src/test/run-pass/stat.rs +++ b/src/test/run-pass/stat.rs @@ -10,9 +10,9 @@ // xfail-fast -extern mod std; -use core::io::WriterUtil; -use std::tempfile; +extern mod extra; +use std::io::WriterUtil; +use extra::tempfile; pub fn main() { let dir = tempfile::mkdtemp(&Path("."), "").unwrap(); diff --git a/src/test/run-pass/str-append.rs b/src/test/run-pass/str-append.rs index d8cc8716e11c9..4fdf7dde031a7 100644 --- a/src/test/run-pass/str-append.rs +++ b/src/test/run-pass/str-append.rs @@ -11,7 +11,7 @@ // -*- rust -*- -extern mod std; +extern mod extra; fn test1() { let mut s: ~str = ~"hello"; diff --git a/src/test/run-pass/str-multiline.rs b/src/test/run-pass/str-multiline.rs index 90a7583dec951..28c2cd7a41acd 100644 --- a/src/test/run-pass/str-multiline.rs +++ b/src/test/run-pass/str-multiline.rs @@ -11,7 +11,7 @@ // -*- rust -*- -extern mod std; +extern mod extra; pub fn main() { let a: ~str = ~"this \ diff --git a/src/test/run-pass/string-self-append.rs b/src/test/run-pass/string-self-append.rs index 8c15a8c689279..6fe383a64a21a 100644 --- a/src/test/run-pass/string-self-append.rs +++ b/src/test/run-pass/string-self-append.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { // Make sure we properly handle repeated self-appends. diff --git a/src/test/run-pass/swap-1.rs b/src/test/run-pass/swap-1.rs index ed69fa41d711f..1c0c05cc16d3c 100644 --- a/src/test/run-pass/swap-1.rs +++ b/src/test/run-pass/swap-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::util; +use std::util; pub fn main() { let mut x = 3; let mut y = 7; diff --git a/src/test/run-pass/swap-2.rs b/src/test/run-pass/swap-2.rs index 738460def923a..52092b994f96f 100644 --- a/src/test/run-pass/swap-2.rs +++ b/src/test/run-pass/swap-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::util; +use std::util; pub fn main() { let mut a: ~[int] = ~[0, 1, 2, 3, 4, 5, 6]; diff --git a/src/test/run-pass/swap-overlapping.rs b/src/test/run-pass/swap-overlapping.rs index 05f943bf928ca..1f1b121d362a7 100644 --- a/src/test/run-pass/swap-overlapping.rs +++ b/src/test/run-pass/swap-overlapping.rs @@ -10,7 +10,7 @@ // Issue #5041 - avoid overlapping memcpy when src and dest of a swap are the same -use core::util; +use std::util; pub fn main() { let mut test = TestDescAndFn { diff --git a/src/test/run-pass/syntax-extension-fmt.rs b/src/test/run-pass/syntax-extension-fmt.rs index 936c71dc0f3c3..67573fce2cd26 100644 --- a/src/test/run-pass/syntax-extension-fmt.rs +++ b/src/test/run-pass/syntax-extension-fmt.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn test(actual: ~str, expected: ~str) { debug!(actual.clone()); diff --git a/src/test/run-pass/task-comm-0.rs b/src/test/run-pass/task-comm-0.rs index bd5575f61549d..90812f9a7f868 100644 --- a/src/test/run-pass/task-comm-0.rs +++ b/src/test/run-pass/task-comm-0.rs @@ -10,10 +10,10 @@ // xfail-fast -extern mod std; +extern mod extra; -use core::comm::Chan; -use core::comm::Port; +use std::comm::Chan; +use std::comm::Port; pub fn main() { test05(); } diff --git a/src/test/run-pass/task-comm-10.rs b/src/test/run-pass/task-comm-10.rs index fa3ead8dfe65c..b4b9592329b51 100644 --- a/src/test/run-pass/task-comm-10.rs +++ b/src/test/run-pass/task-comm-10.rs @@ -10,7 +10,7 @@ // xfail-fast -extern mod std; +extern mod extra; fn start(c: &comm::Chan>) { let (p, ch) = comm::stream(); diff --git a/src/test/run-pass/task-comm-11.rs b/src/test/run-pass/task-comm-11.rs index b2012fbd2dd5e..2c6baf91862cb 100644 --- a/src/test/run-pass/task-comm-11.rs +++ b/src/test/run-pass/task-comm-11.rs @@ -10,7 +10,7 @@ // xfail-fast -extern mod std; +extern mod extra; fn start(c: &comm::Chan>) { let (p, ch) = comm::stream(); diff --git a/src/test/run-pass/task-comm-12.rs b/src/test/run-pass/task-comm-12.rs index 0f0b82d7c21df..9ecbbaeaee2e4 100644 --- a/src/test/run-pass/task-comm-12.rs +++ b/src/test/run-pass/task-comm-12.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { test00(); } diff --git a/src/test/run-pass/task-comm-13.rs b/src/test/run-pass/task-comm-13.rs index f22328a3e1b32..f10aa46ae6e37 100644 --- a/src/test/run-pass/task-comm-13.rs +++ b/src/test/run-pass/task-comm-13.rs @@ -10,7 +10,7 @@ // xfail-fast -extern mod std; +extern mod extra; fn start(c: &comm::Chan, start: int, number_of_messages: int) { let mut i: int = 0; diff --git a/src/test/run-pass/task-comm-15.rs b/src/test/run-pass/task-comm-15.rs index 308627720622c..3941f84666606 100644 --- a/src/test/run-pass/task-comm-15.rs +++ b/src/test/run-pass/task-comm-15.rs @@ -11,7 +11,7 @@ // xfail-fast // xfail-win32 -extern mod std; +extern mod extra; fn start(c: &comm::Chan, i0: int) { let mut i = i0; diff --git a/src/test/run-pass/task-comm-17.rs b/src/test/run-pass/task-comm-17.rs index 58fa65b7fe7a1..25bddc7fe944e 100644 --- a/src/test/run-pass/task-comm-17.rs +++ b/src/test/run-pass/task-comm-17.rs @@ -12,7 +12,7 @@ // This test is specifically about spawning temporary closures. -extern mod std; +extern mod extra; fn f() { } diff --git a/src/test/run-pass/task-comm-3.rs b/src/test/run-pass/task-comm-3.rs index 1a3dc678d4211..faa1d8a69b1a6 100644 --- a/src/test/run-pass/task-comm-3.rs +++ b/src/test/run-pass/task-comm-3.rs @@ -10,8 +10,8 @@ // xfail-fast -extern mod std; -use core::comm::Chan; +extern mod extra; +use std::comm::Chan; pub fn main() { debug!("===== WITHOUT THREADS ====="); test00(); } diff --git a/src/test/run-pass/task-comm-5.rs b/src/test/run-pass/task-comm-5.rs index b6a517a6f8141..22ca343ff17d7 100644 --- a/src/test/run-pass/task-comm-5.rs +++ b/src/test/run-pass/task-comm-5.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { test00(); } diff --git a/src/test/run-pass/task-comm-6.rs b/src/test/run-pass/task-comm-6.rs index 38fdc2dc33e9a..16d6f53ad86e0 100644 --- a/src/test/run-pass/task-comm-6.rs +++ b/src/test/run-pass/task-comm-6.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::Chan; +use std::comm::Chan; pub fn main() { test00(); } diff --git a/src/test/run-pass/task-comm-7.rs b/src/test/run-pass/task-comm-7.rs index 227f8aadecdf4..3cc1127fbbf66 100644 --- a/src/test/run-pass/task-comm-7.rs +++ b/src/test/run-pass/task-comm-7.rs @@ -10,7 +10,7 @@ // xfail-fast -extern mod std; +extern mod extra; pub fn main() { test00(); } diff --git a/src/test/run-pass/task-comm-9.rs b/src/test/run-pass/task-comm-9.rs index f13377369651f..41e91097d2730 100644 --- a/src/test/run-pass/task-comm-9.rs +++ b/src/test/run-pass/task-comm-9.rs @@ -10,7 +10,7 @@ // xfail-fast -extern mod std; +extern mod extra; pub fn main() { test00(); } diff --git a/src/test/run-pass/task-comm-chan-nil.rs b/src/test/run-pass/task-comm-chan-nil.rs index ec534a6650042..64b587eff9a01 100644 --- a/src/test/run-pass/task-comm-chan-nil.rs +++ b/src/test/run-pass/task-comm-chan-nil.rs @@ -10,7 +10,7 @@ // except according to those terms. -extern mod std; +extern mod extra; // rustboot can't transmit nils across channels because they don't have // any size, but rustc currently can because they do have size. Whether diff --git a/src/test/run-pass/task-killjoin-rsrc.rs b/src/test/run-pass/task-killjoin-rsrc.rs index 879f668577f86..4b89ddc4a6c0b 100644 --- a/src/test/run-pass/task-killjoin-rsrc.rs +++ b/src/test/run-pass/task-killjoin-rsrc.rs @@ -13,8 +13,8 @@ // A port of task-killjoin to use a class with a dtor to manage // the join. -use core::cell::Cell; -use core::comm::*; +use std::cell::Cell; +use std::comm::*; struct notify { ch: Chan, v: @mut bool, diff --git a/src/test/run-pass/task-life-0.rs b/src/test/run-pass/task-life-0.rs index 9885c5d6f3fc0..0ec62ff85410b 100644 --- a/src/test/run-pass/task-life-0.rs +++ b/src/test/run-pass/task-life-0.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { task::spawn(|| child(~"Hello") ); } diff --git a/src/test/run-pass/task-spawn-move-and-copy.rs b/src/test/run-pass/task-spawn-move-and-copy.rs index f67cc0d51af04..3e17c5d992ce2 100644 --- a/src/test/run-pass/task-spawn-move-and-copy.rs +++ b/src/test/run-pass/task-spawn-move-and-copy.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::*; +use std::comm::*; pub fn main() { let (p, ch) = stream::(); diff --git a/src/test/run-pass/terminate-in-initializer.rs b/src/test/run-pass/terminate-in-initializer.rs index cb169c3a6389d..0e1bf1e90622d 100644 --- a/src/test/run-pass/terminate-in-initializer.rs +++ b/src/test/run-pass/terminate-in-initializer.rs @@ -12,7 +12,7 @@ // Issue #787 // Don't try to clean up uninitialized locals -extern mod std; +extern mod extra; fn test_break() { loop { let x: @int = break; } } diff --git a/src/test/run-pass/test-ignore-cfg.rs b/src/test/run-pass/test-ignore-cfg.rs index 304c9e5ccb9c3..536dd78bba1f2 100644 --- a/src/test/run-pass/test-ignore-cfg.rs +++ b/src/test/run-pass/test-ignore-cfg.rs @@ -11,7 +11,7 @@ // compile-flags: --test --cfg ignorecfg // xfail-fast -extern mod std; +extern mod extra; #[test] #[ignore(cfg(ignorecfg))] diff --git a/src/test/run-pass/test-runner-hides-main.rs b/src/test/run-pass/test-runner-hides-main.rs index 74b63e4dd27d4..3f1e9fe4c5197 100644 --- a/src/test/run-pass/test-runner-hides-main.rs +++ b/src/test/run-pass/test-runner-hides-main.rs @@ -11,7 +11,7 @@ // compile-flags:--test // xfail-fast -extern mod std; +extern mod extra; // Building as a test runner means that a synthetic main will be run, // not ours diff --git a/src/test/run-pass/threads.rs b/src/test/run-pass/threads.rs index a72d3dd40f4ca..47b49513a60cb 100644 --- a/src/test/run-pass/threads.rs +++ b/src/test/run-pass/threads.rs @@ -10,7 +10,7 @@ // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { let mut i = 10; diff --git a/src/test/run-pass/trait-inheritance-num.rs b/src/test/run-pass/trait-inheritance-num.rs index 9135b458f95eb..87de3a2be1496 100644 --- a/src/test/run-pass/trait-inheritance-num.rs +++ b/src/test/run-pass/trait-inheritance-num.rs @@ -10,10 +10,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; -use core::cmp::{Eq, Ord}; -use core::num::NumCast; +use std::cmp::{Eq, Ord}; +use std::num::NumCast; pub trait NumExt: Num + NumCast + Eq + Ord {} diff --git a/src/test/run-pass/trait-inheritance-num0.rs b/src/test/run-pass/trait-inheritance-num0.rs index 3e31b8067f9c3..ae285f3bc958b 100644 --- a/src/test/run-pass/trait-inheritance-num0.rs +++ b/src/test/run-pass/trait-inheritance-num0.rs @@ -12,7 +12,7 @@ // Extending Num and using inherited static methods -use core::num::NumCast; +use std::num::NumCast; trait Num { fn from_int(i: int) -> Self; diff --git a/src/test/run-pass/trait-inheritance-num1.rs b/src/test/run-pass/trait-inheritance-num1.rs index 25741518f66eb..d22a8154a5b25 100644 --- a/src/test/run-pass/trait-inheritance-num1.rs +++ b/src/test/run-pass/trait-inheritance-num1.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::Ord; -use core::num::NumCast; +use std::cmp::Ord; +use std::num::NumCast; pub trait NumExt: Num + NumCast + Ord { } diff --git a/src/test/run-pass/trait-inheritance-num2.rs b/src/test/run-pass/trait-inheritance-num2.rs index 2963a815e0519..ff9c792af29b1 100644 --- a/src/test/run-pass/trait-inheritance-num2.rs +++ b/src/test/run-pass/trait-inheritance-num2.rs @@ -12,9 +12,9 @@ // A more complex example of numeric extensions -extern mod std; +extern mod extra; -use core::cmp::{Eq, Ord}; +use std::cmp::{Eq, Ord}; pub trait TypeExt {} diff --git a/src/test/run-pass/trait-inheritance-num3.rs b/src/test/run-pass/trait-inheritance-num3.rs index 667fd335ac4a4..98fa6a5ebf1d6 100644 --- a/src/test/run-pass/trait-inheritance-num3.rs +++ b/src/test/run-pass/trait-inheritance-num3.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::{Eq, Ord}; -use core::num::NumCast; +use std::cmp::{Eq, Ord}; +use std::num::NumCast; pub trait NumExt: Eq + Ord + Num + NumCast {} diff --git a/src/test/run-pass/trait-inheritance-num5.rs b/src/test/run-pass/trait-inheritance-num5.rs index f1897636c8aa6..f56eca693ea53 100644 --- a/src/test/run-pass/trait-inheritance-num5.rs +++ b/src/test/run-pass/trait-inheritance-num5.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::{Eq, Ord}; -use core::num::NumCast; +use std::cmp::{Eq, Ord}; +use std::num::NumCast; pub trait NumExt: Eq + Num + NumCast {} diff --git a/src/test/run-pass/trait-inheritance-overloading-simple.rs b/src/test/run-pass/trait-inheritance-overloading-simple.rs index 2e9b60303c6c3..041452176e0e3 100644 --- a/src/test/run-pass/trait-inheritance-overloading-simple.rs +++ b/src/test/run-pass/trait-inheritance-overloading-simple.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::Eq; +use std::cmp::Eq; trait MyNum : Eq { } diff --git a/src/test/run-pass/trait-inheritance-overloading.rs b/src/test/run-pass/trait-inheritance-overloading.rs index 82c9091147dc4..302d3d87df909 100644 --- a/src/test/run-pass/trait-inheritance-overloading.rs +++ b/src/test/run-pass/trait-inheritance-overloading.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::Eq; +use std::cmp::Eq; trait MyNum : Add + Sub + Mul + Eq { } diff --git a/src/test/run-pass/trait-to-str.rs b/src/test/run-pass/trait-to-str.rs index 9726eed58043e..ff01efc027eb1 100644 --- a/src/test/run-pass/trait-to-str.rs +++ b/src/test/run-pass/trait-to-str.rs @@ -12,9 +12,9 @@ #[no_std]; -extern mod core; +extern mod std; -use core::{str, int, vec}; +use std::{str, int, vec}; trait to_str { fn to_str(&self) -> ~str; diff --git a/src/test/run-pass/type-sizes.rs b/src/test/run-pass/type-sizes.rs index adb3ae9557be1..5695254cdbffb 100644 --- a/src/test/run-pass/type-sizes.rs +++ b/src/test/run-pass/type-sizes.rs @@ -8,8 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod core; -use core::sys::size_of; +extern mod std; +use std::sys::size_of; struct t {a: u8, b: i8} struct u {a: u8, b: i8, c: u8} diff --git a/src/test/run-pass/unify-return-ty.rs b/src/test/run-pass/unify-return-ty.rs index 820d42ab14d57..2f686d21b96b7 100644 --- a/src/test/run-pass/unify-return-ty.rs +++ b/src/test/run-pass/unify-return-ty.rs @@ -11,7 +11,7 @@ // Tests that the tail expr in null() has its type // unified with the type *T, and so the type variable // in that type gets resolved. -extern mod std; +extern mod extra; fn null() -> *T { unsafe { diff --git a/src/test/run-pass/unique-kinds.rs b/src/test/run-pass/unique-kinds.rs index dbbd238cbac22..b3ce71dcbff5d 100644 --- a/src/test/run-pass/unique-kinds.rs +++ b/src/test/run-pass/unique-kinds.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::cmp::Eq; +use std::cmp::Eq; fn sendable() { diff --git a/src/test/run-pass/unique-send-2.rs b/src/test/run-pass/unique-send-2.rs index 9b522490f988a..3684a6ef7883d 100644 --- a/src/test/run-pass/unique-send-2.rs +++ b/src/test/run-pass/unique-send-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::*; +use std::comm::*; fn child(c: &SharedChan<~uint>, i: uint) { c.send(~i); diff --git a/src/test/run-pass/unique-send.rs b/src/test/run-pass/unique-send.rs index a611992d7eee5..05012f789c38f 100644 --- a/src/test/run-pass/unique-send.rs +++ b/src/test/run-pass/unique-send.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::comm::*; +use std::comm::*; pub fn main() { let (p, c) = stream(); diff --git a/src/test/run-pass/unique-swap.rs b/src/test/run-pass/unique-swap.rs index fa3aeb5d4218d..a372e4a4d98a6 100644 --- a/src/test/run-pass/unique-swap.rs +++ b/src/test/run-pass/unique-swap.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::util; +use std::util; pub fn main() { let mut i = ~100; diff --git a/src/test/run-pass/unwind-box.rs b/src/test/run-pass/unwind-box.rs index 90e8d41d26a2d..5184ffb8d239e 100644 --- a/src/test/run-pass/unwind-box.rs +++ b/src/test/run-pass/unwind-box.rs @@ -9,7 +9,7 @@ // except according to those terms. // xfail-win32 -extern mod std; +extern mod extra; fn f() { let a = @0; diff --git a/src/test/run-pass/unwind-resource.rs b/src/test/run-pass/unwind-resource.rs index 4c7b2e6370242..012b12ea99e78 100644 --- a/src/test/run-pass/unwind-resource.rs +++ b/src/test/run-pass/unwind-resource.rs @@ -9,9 +9,9 @@ // except according to those terms. // xfail-win32 -extern mod std; +extern mod extra; -use core::comm::*; +use std::comm::*; struct complainer { c: SharedChan, diff --git a/src/test/run-pass/unwind-resource2.rs b/src/test/run-pass/unwind-resource2.rs index 993acc2264f68..0d7c717cd36af 100644 --- a/src/test/run-pass/unwind-resource2.rs +++ b/src/test/run-pass/unwind-resource2.rs @@ -9,7 +9,7 @@ // except according to those terms. // xfail-win32 -extern mod std; +extern mod extra; struct complainer { c: @int, diff --git a/src/test/run-pass/unwind-unique.rs b/src/test/run-pass/unwind-unique.rs index 8b0850cff774d..f5f5209fa5477 100644 --- a/src/test/run-pass/unwind-unique.rs +++ b/src/test/run-pass/unwind-unique.rs @@ -9,7 +9,7 @@ // except according to those terms. // xfail-win32 -extern mod std; +extern mod extra; fn f() { let a = ~0; diff --git a/src/test/run-pass/use-crate-name-alias.rs b/src/test/run-pass/use-crate-name-alias.rs index ea9dcc2f56279..4954de3919ffe 100644 --- a/src/test/run-pass/use-crate-name-alias.rs +++ b/src/test/run-pass/use-crate-name-alias.rs @@ -9,6 +9,6 @@ // except according to those terms. // Issue #1706 -extern mod stdlib(name="std"); +extern mod stdlib(name="extra"); pub fn main() {} diff --git a/src/test/run-pass/use.rs b/src/test/run-pass/use.rs index 11f9e7641e17b..d73eb6641fadf 100644 --- a/src/test/run-pass/use.rs +++ b/src/test/run-pass/use.rs @@ -11,16 +11,16 @@ // except according to those terms. #[no_std]; -extern mod core; -extern mod zed(name = "core"); -extern mod bar(name = "core", vers = "0.7-pre"); +extern mod std; +extern mod zed(name = "std"); +extern mod bar(name = "std", vers = "0.7-pre"); -use core::str; +use std::str; use x = zed::str; mod baz { pub use bar::str; - pub use x = core::str; + pub use x = std::str; } pub fn main() { } diff --git a/src/test/run-pass/utf8_chars.rs b/src/test/run-pass/utf8_chars.rs index fd98723c2f6ca..23dddf5992577 100644 --- a/src/test/run-pass/utf8_chars.rs +++ b/src/test/run-pass/utf8_chars.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; pub fn main() { // Chars of 1, 2, 3, and 4 bytes diff --git a/src/test/run-pass/vec-matching-autoslice.rs b/src/test/run-pass/vec-matching-autoslice.rs index 6757ef46951e9..d04deeac52e31 100644 --- a/src/test/run-pass/vec-matching-autoslice.rs +++ b/src/test/run-pass/vec-matching-autoslice.rs @@ -1,22 +1,22 @@ pub fn main() { let x = @[1, 2, 3]; match x { - [2, .._] => ::core::util::unreachable(), + [2, .._] => ::std::util::unreachable(), [1, ..tail] => { assert_eq!(tail, [2, 3]); } - [_] => ::core::util::unreachable(), - [] => ::core::util::unreachable() + [_] => ::std::util::unreachable(), + [] => ::std::util::unreachable() } let y = (~[(1, true), (2, false)], 0.5); match y { - ([_, _, _], 0.5) => ::core::util::unreachable(), + ([_, _, _], 0.5) => ::std::util::unreachable(), ([(1, a), (b, false), ..tail], _) => { assert_eq!(a, true); assert_eq!(b, 2); assert!(tail.is_empty()); } - ([..tail], _) => ::core::util::unreachable() + ([..tail], _) => ::std::util::unreachable() } } diff --git a/src/test/run-pass/vec-matching-legal-tail-element-borrow.rs b/src/test/run-pass/vec-matching-legal-tail-element-borrow.rs index 561d5555f128a..acd9a9664f78d 100644 --- a/src/test/run-pass/vec-matching-legal-tail-element-borrow.rs +++ b/src/test/run-pass/vec-matching-legal-tail-element-borrow.rs @@ -3,7 +3,7 @@ pub fn main() { if !x.is_empty() { let el = match x { [1, ..ref tail] => &tail[0], - _ => ::core::util::unreachable() + _ => ::std::util::unreachable() }; io::println(fmt!("%d", *el)); } diff --git a/src/test/run-pass/vec-matching.rs b/src/test/run-pass/vec-matching.rs index e4ca51368b29b..5e906fa265994 100644 --- a/src/test/run-pass/vec-matching.rs +++ b/src/test/run-pass/vec-matching.rs @@ -1,14 +1,14 @@ fn a() { let x = [1]; match x { - [_, _, _, _, _, .._] => ::core::util::unreachable(), - [.._, _, _, _, _] => ::core::util::unreachable(), - [_, .._, _, _] => ::core::util::unreachable(), - [_, _] => ::core::util::unreachable(), + [_, _, _, _, _, .._] => ::std::util::unreachable(), + [.._, _, _, _, _] => ::std::util::unreachable(), + [_, .._, _, _] => ::std::util::unreachable(), + [_, _] => ::std::util::unreachable(), [a] => { assert_eq!(a, 1); } - [] => ::core::util::unreachable() + [] => ::std::util::unreachable() } } diff --git a/src/test/run-pass/vec-self-append.rs b/src/test/run-pass/vec-self-append.rs index 30f6befe69c5d..ef661c7ed6723 100644 --- a/src/test/run-pass/vec-self-append.rs +++ b/src/test/run-pass/vec-self-append.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern mod std; +extern mod extra; fn test_heap_to_heap() { // a spills onto the heap diff --git a/src/test/run-pass/vec-tail-matching.rs b/src/test/run-pass/vec-tail-matching.rs index 6a98ed678b264..cf4aebbd08270 100644 --- a/src/test/run-pass/vec-tail-matching.rs +++ b/src/test/run-pass/vec-tail-matching.rs @@ -17,19 +17,19 @@ pub fn main() { match tail { [Foo { _ }, _, Foo { _ }, ..tail] => { - ::core::util::unreachable(); + ::std::util::unreachable(); } [Foo { string: a }, Foo { string: b }] => { assert_eq!(a, ~"bar"); assert_eq!(b, ~"baz"); } _ => { - ::core::util::unreachable(); + ::std::util::unreachable(); } } } _ => { - ::core::util::unreachable(); + ::std::util::unreachable(); } } } diff --git a/src/test/run-pass/weird-exprs.rs b/src/test/run-pass/weird-exprs.rs index f226f315ff9ee..5a585c8c10e81 100644 --- a/src/test/run-pass/weird-exprs.rs +++ b/src/test/run-pass/weird-exprs.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::util; +use std::util; // Just a grab bag of stuff that you wouldn't want to actually write. From ee52865c8848657e737e3c2071728b062ec9c8de Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Tue, 21 May 2013 17:24:31 -0700 Subject: [PATCH 196/248] test: Update tests and import the prelude in some more places. --- src/libextra/arc.rs | 1 + src/libextra/dlist.rs | 2 ++ src/libextra/fileinput.rs | 2 ++ src/libextra/flatpipes.rs | 2 ++ src/libextra/json.rs | 2 ++ src/libextra/net_tcp.rs | 2 ++ src/libextra/num/bigint.rs | 4 ++++ src/libextra/num/rational.rs | 2 ++ src/libextra/priority_queue.rs | 24 +++++++++---------- src/libextra/smallintmap.rs | 2 ++ src/libextra/sort.rs | 9 +++++++ src/libextra/std.rc | 2 ++ src/libextra/sync.rs | 1 + src/libextra/tempfile.rs | 2 ++ src/libextra/timer.rs | 2 ++ src/libextra/treemap.rs | 3 +++ src/libextra/uv_ll.rs | 1 + .../auxiliary/extern-crosscrate-source.rs | 4 +--- src/test/run-pass/const-cast.rs | 2 +- src/test/run-pass/const-cross-crate-extern.rs | 2 +- src/test/run-pass/const-extern-function.rs | 2 +- src/test/run-pass/extern-call-deep.rs | 4 +--- src/test/run-pass/extern-call-deep2.rs | 4 +--- src/test/run-pass/extern-call-scrub.rs | 4 +--- src/test/run-pass/extern-call.rs | 4 +--- src/test/run-pass/extern-stress.rs | 4 +--- src/test/run-pass/extern-take-value.rs | 8 +++---- src/test/run-pass/extern-yield.rs | 4 +--- src/test/run-pass/foreign-call-no-runtime.rs | 4 +--- 29 files changed, 66 insertions(+), 43 deletions(-) diff --git a/src/libextra/arc.rs b/src/libextra/arc.rs index 087b28ec01e6d..648089a552475 100644 --- a/src/libextra/arc.rs +++ b/src/libextra/arc.rs @@ -511,6 +511,7 @@ pub impl<'self, T:Const + Owned> RWReadMode<'self, T> { #[cfg(test)] mod tests { + use core::prelude::*; use arc::*; use arc; diff --git a/src/libextra/dlist.rs b/src/libextra/dlist.rs index c3ef1f25ad933..75249b9f467ad 100644 --- a/src/libextra/dlist.rs +++ b/src/libextra/dlist.rs @@ -534,6 +534,8 @@ impl BaseIter for @mut DList { #[cfg(test)] mod tests { + use core::prelude::*; + use super::*; #[test] diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index a9024592426fd..ec2c73251ba12 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -405,6 +405,8 @@ pub fn input_vec_state(files: ~[Option], #[cfg(test)] mod test { + use core::prelude::*; + use core::io::WriterUtil; use super::{FileInput, pathify, input_vec, input_vec_state}; diff --git a/src/libextra/flatpipes.rs b/src/libextra/flatpipes.rs index 7c97cabd58910..76361db7d76cf 100644 --- a/src/libextra/flatpipes.rs +++ b/src/libextra/flatpipes.rs @@ -866,6 +866,8 @@ mod test { // Tests that the different backends behave the same when the // binary streaming protocol is broken mod broken_protocol { + use core::prelude::*; + use flatpipes::{BytePort, FlatPort}; use flatpipes::flatteners::PodUnflattener; use flatpipes::pod; diff --git a/src/libextra/json.rs b/src/libextra/json.rs index f56da368008d6..6656c896e74c3 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -1327,6 +1327,8 @@ impl to_str::ToStr for Error { #[cfg(test)] mod tests { + use core::prelude::*; + use super::*; use core::hashmap::HashMap; diff --git a/src/libextra/net_tcp.rs b/src/libextra/net_tcp.rs index d0a1385b706a5..894488e47e123 100644 --- a/src/libextra/net_tcp.rs +++ b/src/libextra/net_tcp.rs @@ -1440,6 +1440,8 @@ struct TcpBufferedSocketData { #[cfg(test)] mod test { + use core::prelude::*; + use net::ip; use net::tcp::{GenericListenErr, TcpConnectErrData, TcpListenErrData}; use net::tcp::{connect, accept, read, listen, TcpSocket, socket_buf}; diff --git a/src/libextra/num/bigint.rs b/src/libextra/num/bigint.rs index fa7621462ef70..776172262b742 100644 --- a/src/libextra/num/bigint.rs +++ b/src/libextra/num/bigint.rs @@ -1145,6 +1145,8 @@ pub impl BigInt { #[cfg(test)] mod biguint_tests { + use core::prelude::*; + use super::*; use core::num::{IntConvertible, Zero, One, FromStrRadix}; use core::cmp::{Less, Equal, Greater}; @@ -1611,6 +1613,8 @@ mod biguint_tests { #[cfg(test)] mod bigint_tests { + use core::prelude::*; + use super::*; use core::cmp::{Less, Equal, Greater}; use core::num::{IntConvertible, Zero, One, FromStrRadix}; diff --git a/src/libextra/num/rational.rs b/src/libextra/num/rational.rs index d26ef06ebce17..de114a35e36be 100644 --- a/src/libextra/num/rational.rs +++ b/src/libextra/num/rational.rs @@ -284,6 +284,8 @@ impl #[cfg(test)] mod test { + use core::prelude::*; + use super::*; use core::num::{Zero,One,FromStrRadix,IntConvertible}; use core::from_str::FromStr; diff --git a/src/libextra/priority_queue.rs b/src/libextra/priority_queue.rs index 6d41cd653ebff..a4fc30cedcdaa 100644 --- a/src/libextra/priority_queue.rs +++ b/src/libextra/priority_queue.rs @@ -185,13 +185,13 @@ pub impl PriorityQueue { mod tests { use sort::merge_sort; use core::cmp::le; - use priority_queue::PriorityQueue::{from_vec, new}; + use priority_queue::PriorityQueue; #[test] fn test_top_and_pop() { let data = ~[2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1]; let mut sorted = merge_sort(data, le); - let mut heap = from_vec(data); + let mut heap = PriorityQueue::from_vec(data); while !heap.is_empty() { assert_eq!(heap.top(), sorted.last()); assert_eq!(heap.pop(), sorted.pop()); @@ -200,7 +200,7 @@ mod tests { #[test] fn test_push() { - let mut heap = from_vec(~[2, 4, 9]); + let mut heap = PriorityQueue::from_vec(~[2, 4, 9]); assert_eq!(heap.len(), 3); assert!(*heap.top() == 9); heap.push(11); @@ -222,7 +222,7 @@ mod tests { #[test] fn test_push_unique() { - let mut heap = from_vec(~[~2, ~4, ~9]); + let mut heap = PriorityQueue::from_vec(~[~2, ~4, ~9]); assert_eq!(heap.len(), 3); assert!(*heap.top() == ~9); heap.push(~11); @@ -244,7 +244,7 @@ mod tests { #[test] fn test_push_pop() { - let mut heap = from_vec(~[5, 5, 2, 1, 3]); + let mut heap = PriorityQueue::from_vec(~[5, 5, 2, 1, 3]); assert_eq!(heap.len(), 5); assert_eq!(heap.push_pop(6), 6); assert_eq!(heap.len(), 5); @@ -258,7 +258,7 @@ mod tests { #[test] fn test_replace() { - let mut heap = from_vec(~[5, 5, 2, 1, 3]); + let mut heap = PriorityQueue::from_vec(~[5, 5, 2, 1, 3]); assert_eq!(heap.len(), 5); assert_eq!(heap.replace(6), 5); assert_eq!(heap.len(), 5); @@ -271,7 +271,7 @@ mod tests { } fn check_to_vec(data: ~[int]) { - let heap = from_vec(copy data); + let heap = PriorityQueue::from_vec(copy data); assert_eq!(merge_sort((copy heap).to_vec(), le), merge_sort(data, le)); assert_eq!(heap.to_sorted_vec(), merge_sort(data, le)); } @@ -296,27 +296,27 @@ mod tests { #[test] #[should_fail] #[ignore(cfg(windows))] - fn test_empty_pop() { let mut heap = new::(); heap.pop(); } + fn test_empty_pop() { let mut heap = PriorityQueue::new::(); heap.pop(); } #[test] fn test_empty_maybe_pop() { - let mut heap = new::(); + let mut heap = PriorityQueue::new::(); assert!(heap.maybe_pop().is_none()); } #[test] #[should_fail] #[ignore(cfg(windows))] - fn test_empty_top() { let empty = new::(); empty.top(); } + fn test_empty_top() { let empty = PriorityQueue::new::(); empty.top(); } #[test] fn test_empty_maybe_top() { - let empty = new::(); + let empty = PriorityQueue::new::(); assert!(empty.maybe_top().is_none()); } #[test] #[should_fail] #[ignore(cfg(windows))] - fn test_empty_replace() { let mut heap = new(); heap.replace(5); } + fn test_empty_replace() { let mut heap = PriorityQueue::new(); heap.replace(5); } } diff --git a/src/libextra/smallintmap.rs b/src/libextra/smallintmap.rs index 3e5e62894dfc9..b2a98845b2f65 100644 --- a/src/libextra/smallintmap.rs +++ b/src/libextra/smallintmap.rs @@ -267,6 +267,8 @@ pub impl SmallIntSet { #[cfg(test)] mod tests { + use core::prelude::*; + use super::SmallIntMap; #[test] diff --git a/src/libextra/sort.rs b/src/libextra/sort.rs index 2c4020e776c21..388f321d9ea87 100644 --- a/src/libextra/sort.rs +++ b/src/libextra/sort.rs @@ -746,6 +746,8 @@ fn shift_vec(dest: &mut [T], #[cfg(test)] mod test_qsort3 { + use core::prelude::*; + use sort::*; use core::vec; @@ -788,6 +790,8 @@ mod test_qsort3 { #[cfg(test)] mod test_qsort { + use core::prelude::*; + use sort::*; use core::int; @@ -852,6 +856,7 @@ mod test_qsort { #[cfg(test)] mod tests { + use core::prelude::*; use sort::*; @@ -920,6 +925,8 @@ mod tests { #[cfg(test)] mod test_tim_sort { + use core::prelude::*; + use sort::tim_sort; use core::rand::RngUtil; @@ -1011,6 +1018,8 @@ mod test_tim_sort { #[cfg(test)] mod big_tests { + use core::prelude::*; + use sort::*; use core::rand::RngUtil; diff --git a/src/libextra/std.rc b/src/libextra/std.rc index 7f9902dfc8c53..a23a547634242 100644 --- a/src/libextra/std.rc +++ b/src/libextra/std.rc @@ -36,6 +36,8 @@ extern mod core(name = "std", vers = "0.7-pre"); use core::{str, unstable}; use core::str::{StrSlice, OwnedStr}; +pub use core::os; + pub mod uv_ll; // General io and system-services modules diff --git a/src/libextra/sync.rs b/src/libextra/sync.rs index dc7f891b2593d..9e0ebc0222102 100644 --- a/src/libextra/sync.rs +++ b/src/libextra/sync.rs @@ -711,6 +711,7 @@ pub impl<'self> RWlockReadMode<'self> { #[cfg(test)] mod tests { + use core::prelude::*; use sync::*; diff --git a/src/libextra/tempfile.rs b/src/libextra/tempfile.rs index d7ee326f2ffb5..be9b920c592bf 100644 --- a/src/libextra/tempfile.rs +++ b/src/libextra/tempfile.rs @@ -27,6 +27,8 @@ pub fn mkdtemp(tmpdir: &Path, suffix: &str) -> Option { #[cfg(test)] mod tests { + use core::prelude::*; + use tempfile::mkdtemp; use tempfile; use core::os; diff --git a/src/libextra/timer.rs b/src/libextra/timer.rs index 6a36d674279a2..75caf1a4829e0 100644 --- a/src/libextra/timer.rs +++ b/src/libextra/timer.rs @@ -175,6 +175,8 @@ extern fn delayed_send_close_cb(handle: *uv::ll::uv_timer_t) { #[cfg(test)] mod test { + use core::prelude::*; + use timer::*; use uv; use core::cell::Cell; diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index f4257070e1984..973d1faa9a6e5 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -699,6 +699,8 @@ fn remove(node: &mut Option<~TreeNode>, #[cfg(test)] mod test_treemap { + use core::prelude::*; + use core::iterator::*; use super::*; use core::rand::RngUtil; @@ -1017,6 +1019,7 @@ mod test_treemap { #[cfg(test)] mod test_set { + use core::prelude::*; use core::iterator::*; use super::*; diff --git a/src/libextra/uv_ll.rs b/src/libextra/uv_ll.rs index 014dea220292f..5be8dd514de43 100644 --- a/src/libextra/uv_ll.rs +++ b/src/libextra/uv_ll.rs @@ -1224,6 +1224,7 @@ pub unsafe fn addrinfo_as_sockaddr_in6(input: *addrinfo) -> *sockaddr_in6 { #[cfg(test)] mod test { + use core::prelude::*; use core::comm::{SharedChan, stream, GenericChan, GenericPort}; use super::*; diff --git a/src/test/auxiliary/extern-crosscrate-source.rs b/src/test/auxiliary/extern-crosscrate-source.rs index c7e8e89913595..3c81c787a09a2 100644 --- a/src/test/auxiliary/extern-crosscrate-source.rs +++ b/src/test/auxiliary/extern-crosscrate-source.rs @@ -15,9 +15,7 @@ pub mod rustrt { pub extern { - pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/const-cast.rs b/src/test/run-pass/const-cast.rs index 2f7ccfe2a3a23..1c8e92b91cd1b 100644 --- a/src/test/run-pass/const-cast.rs +++ b/src/test/run-pass/const-cast.rs @@ -10,7 +10,7 @@ extern fn foo() {} -static x: extern "C" fn() = foo; +static x: *u8 = foo; static y: *libc::c_void = x as *libc::c_void; static a: &'static int = &10; static b: *int = a as *int; diff --git a/src/test/run-pass/const-cross-crate-extern.rs b/src/test/run-pass/const-cross-crate-extern.rs index 66db6c824bc01..5281c21762689 100644 --- a/src/test/run-pass/const-cross-crate-extern.rs +++ b/src/test/run-pass/const-cross-crate-extern.rs @@ -13,7 +13,7 @@ extern mod cci_const; use cci_const::bar; -static foo: extern "C" fn() = bar; +static foo: *u8 = bar; pub fn main() { assert_eq!(foo, cci_const::bar); diff --git a/src/test/run-pass/const-extern-function.rs b/src/test/run-pass/const-extern-function.rs index 513f93a676056..9a8104cb14f71 100644 --- a/src/test/run-pass/const-extern-function.rs +++ b/src/test/run-pass/const-extern-function.rs @@ -10,7 +10,7 @@ extern fn foopy() {} -static f: extern "C" fn() = foopy; +static f: *u8 = foopy; static s: S = S { f: foopy }; struct S { diff --git a/src/test/run-pass/extern-call-deep.rs b/src/test/run-pass/extern-call-deep.rs index 2e95873b60df4..6831048bee41d 100644 --- a/src/test/run-pass/extern-call-deep.rs +++ b/src/test/run-pass/extern-call-deep.rs @@ -10,9 +10,7 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-call-deep2.rs b/src/test/run-pass/extern-call-deep2.rs index 6ad1c531d9a19..4c5d4218b1fce 100644 --- a/src/test/run-pass/extern-call-deep2.rs +++ b/src/test/run-pass/extern-call-deep2.rs @@ -10,9 +10,7 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-call-scrub.rs b/src/test/run-pass/extern-call-scrub.rs index 2caf4cbf2bc74..5c4d594476ff3 100644 --- a/src/test/run-pass/extern-call-scrub.rs +++ b/src/test/run-pass/extern-call-scrub.rs @@ -14,9 +14,7 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-call.rs b/src/test/run-pass/extern-call.rs index 6c36c4aa8f629..ec335cf8a82b8 100644 --- a/src/test/run-pass/extern-call.rs +++ b/src/test/run-pass/extern-call.rs @@ -10,9 +10,7 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-stress.rs b/src/test/run-pass/extern-stress.rs index b12295ab57684..4257f2b2435f5 100644 --- a/src/test/run-pass/extern-stress.rs +++ b/src/test/run-pass/extern-stress.rs @@ -13,9 +13,7 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/extern-take-value.rs b/src/test/run-pass/extern-take-value.rs index c3fe458802d4b..542686c9099f1 100644 --- a/src/test/run-pass/extern-take-value.rs +++ b/src/test/run-pass/extern-take-value.rs @@ -15,10 +15,10 @@ extern fn g() { } pub fn main() { - // extern functions are extern function types - let a: extern "C" fn() = f; - let b: extern "C" fn() = f; - let c: extern "C" fn() = g; + // extern functions are *u8 types + let a: *u8 = f; + let b: *u8 = f; + let c: *u8 = g; assert_eq!(a, b); assert!(a != c); diff --git a/src/test/run-pass/extern-yield.rs b/src/test/run-pass/extern-yield.rs index 16b1c7cd6f40f..b0c44030a1724 100644 --- a/src/test/run-pass/extern-yield.rs +++ b/src/test/run-pass/extern-yield.rs @@ -10,9 +10,7 @@ mod rustrt { pub extern { - pub fn rust_dbg_call(cb: extern "C" fn(data: libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } } diff --git a/src/test/run-pass/foreign-call-no-runtime.rs b/src/test/run-pass/foreign-call-no-runtime.rs index 67efca194d527..6ff8b24ab8336 100644 --- a/src/test/run-pass/foreign-call-no-runtime.rs +++ b/src/test/run-pass/foreign-call-no-runtime.rs @@ -1,9 +1,7 @@ use std::unstable::run_in_bare_thread; extern { - pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) - -> libc::uintptr_t, - data: libc::uintptr_t) -> libc::uintptr_t; + pub fn rust_dbg_call(cb: *u8, data: libc::uintptr_t) -> libc::uintptr_t; } pub fn main() { From 18df18c817b5e109710c58f512a2cc5ad14fa8b2 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Tue, 21 May 2013 18:24:42 -0700 Subject: [PATCH 197/248] libstd: Fix merge fallout. --- src/librustc/metadata/csearch.rs | 12 - src/librustc/metadata/decoder.rs | 8 - .../middle/borrowck/gather_loans/lifetime.rs | 2 + .../middle/borrowck/gather_loans/mod.rs | 2 + .../borrowck/gather_loans/restrictions.rs | 2 + src/librustc/middle/borrowck/mod.rs | 2 + src/librustc/middle/resolve.rs | 1 + src/{libcore => libstd}/rt/comm.rs | 0 src/libstd/rt/global_heap.rs | 87 ++++ src/{libcore => libstd}/rt/io/mock.rs | 0 src/{libcore => libstd}/rt/local.rs | 0 src/{libcore => libstd}/rt/local_ptr.rs | 0 src/{libcore => libstd}/rt/logging.rs | 0 src/{libcore => libstd}/rt/message_queue.rs | 0 src/{libcore => libstd}/rt/rc.rs | 0 src/{libcore => libstd}/rt/sched.rs | 0 src/{libcore => libstd}/rt/tube.rs | 0 src/{libcore => libstd}/rt/uv/idle.rs | 0 src/{libcore => libstd}/rt/uv/timer.rs | 0 src/libstd/rt/uv/uvio.rs | 492 ++++++++++++++++++ src/libstd/rt/uv/uvll.rs | 452 ++++++++++++++++ src/libsyntax/opt_vec.rs | 2 + 22 files changed, 1042 insertions(+), 20 deletions(-) rename src/{libcore => libstd}/rt/comm.rs (100%) create mode 100644 src/libstd/rt/global_heap.rs rename src/{libcore => libstd}/rt/io/mock.rs (100%) rename src/{libcore => libstd}/rt/local.rs (100%) rename src/{libcore => libstd}/rt/local_ptr.rs (100%) rename src/{libcore => libstd}/rt/logging.rs (100%) rename src/{libcore => libstd}/rt/message_queue.rs (100%) rename src/{libcore => libstd}/rt/rc.rs (100%) rename src/{libcore => libstd}/rt/sched.rs (100%) rename src/{libcore => libstd}/rt/tube.rs (100%) rename src/{libcore => libstd}/rt/uv/idle.rs (100%) rename src/{libcore => libstd}/rt/uv/timer.rs (100%) create mode 100644 src/libstd/rt/uv/uvio.rs create mode 100644 src/libstd/rt/uv/uvll.rs diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index b35904dbdae36..57d6c46d9f38b 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -54,18 +54,6 @@ pub fn each_lang_item(cstore: @mut cstore::CStore, } /// Iterates over all the paths in the given crate. -#[cfg(stage0)] -pub fn each_path(cstore: @mut cstore::CStore, - cnum: ast::crate_num, - f: &fn(&str, decoder::def_like, ast::visibility) -> bool) { - let crate_data = cstore::get_crate_data(cstore, cnum); - let get_crate_data: decoder::GetCrateDataCb = |cnum| { - cstore::get_crate_data(cstore, cnum) - }; - decoder::each_path(cstore.intr, crate_data, get_crate_data, f) -} -/// Iterates over all the paths in the given crate. -#[cfg(not(stage0))] pub fn each_path(cstore: @mut cstore::CStore, cnum: ast::crate_num, f: &fn(&str, decoder::def_like, ast::visibility) -> bool) diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index de44b74528dcf..2cc0382269ebc 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -566,14 +566,6 @@ pub fn _each_path(intr: @ident_interner, return broken; } -#[cfg(stage0)] -pub fn each_path(intr: @ident_interner, - cdata: cmd, - get_crate_data: GetCrateDataCb, - f: &fn(&str, def_like, ast::visibility) -> bool) { - _each_path(intr, cdata, get_crate_data, f); -} -#[cfg(not(stage0))] pub fn each_path(intr: @ident_interner, cdata: cmd, get_crate_data: GetCrateDataCb, diff --git a/src/librustc/middle/borrowck/gather_loans/lifetime.rs b/src/librustc/middle/borrowck/gather_loans/lifetime.rs index f91fdfe232c23..f7b30e22f0110 100644 --- a/src/librustc/middle/borrowck/gather_loans/lifetime.rs +++ b/src/librustc/middle/borrowck/gather_loans/lifetime.rs @@ -11,6 +11,8 @@ //! This module implements the check that the lifetime of a borrow //! does not exceed the lifetime of the value being borrowed. +use core::prelude::*; + use middle::borrowck::*; use mc = middle::mem_categorization; use middle::ty; diff --git a/src/librustc/middle/borrowck/gather_loans/mod.rs b/src/librustc/middle/borrowck/gather_loans/mod.rs index 3d2c318a87e2c..a422d99b6f5cf 100644 --- a/src/librustc/middle/borrowck/gather_loans/mod.rs +++ b/src/librustc/middle/borrowck/gather_loans/mod.rs @@ -16,6 +16,8 @@ // their associated scopes. In phase two, checking loans, we will then make // sure that all of these loans are honored. +use core::prelude::*; + use middle::borrowck::*; use mc = middle::mem_categorization; use middle::pat_util; diff --git a/src/librustc/middle/borrowck/gather_loans/restrictions.rs b/src/librustc/middle/borrowck/gather_loans/restrictions.rs index ff6ad87846c7d..42b1c40a4b3c4 100644 --- a/src/librustc/middle/borrowck/gather_loans/restrictions.rs +++ b/src/librustc/middle/borrowck/gather_loans/restrictions.rs @@ -10,6 +10,8 @@ //! Computes the restrictions that result from a borrow. +use core::prelude::*; + use middle::borrowck::*; use mc = middle::mem_categorization; use middle::ty; diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index bc3db4602b03c..39479e726f8b6 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -10,6 +10,8 @@ /*! See doc.rs for a thorough explanation of the borrow checker */ +use core::prelude::*; + use mc = middle::mem_categorization; use middle::ty; use middle::typeck; diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index b2ef0c46afb08..6a6746ab20bd9 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -22,6 +22,7 @@ use middle::lint::unused_imports; use middle::pat_util::pat_bindings; use syntax::ast::*; +use syntax::ast; use syntax::ast_util::{def_id_of_def, local_def}; use syntax::ast_util::{path_to_ident, walk_pat, trait_method_to_ty_method}; use syntax::ast_util::{Privacy, Public, Private}; diff --git a/src/libcore/rt/comm.rs b/src/libstd/rt/comm.rs similarity index 100% rename from src/libcore/rt/comm.rs rename to src/libstd/rt/comm.rs diff --git a/src/libstd/rt/global_heap.rs b/src/libstd/rt/global_heap.rs new file mode 100644 index 0000000000000..ce7ff87b44580 --- /dev/null +++ b/src/libstd/rt/global_heap.rs @@ -0,0 +1,87 @@ +// Copyright 2012 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 sys::{TypeDesc, size_of}; +use libc::{c_void, size_t, uintptr_t}; +use c_malloc = libc::malloc; +use c_free = libc::free; +use managed::raw::{BoxHeaderRepr, BoxRepr}; +use cast::transmute; +use unstable::intrinsics::{atomic_xadd,atomic_xsub}; +use ptr::null; +use intrinsic::TyDesc; + +pub unsafe fn malloc(td: *TypeDesc, size: uint) -> *c_void { + assert!(td.is_not_null()); + + let total_size = get_box_size(size, (*td).align); + let p = c_malloc(total_size as size_t); + assert!(p.is_not_null()); + + // FIXME #3475: Converting between our two different tydesc types + let td: *TyDesc = transmute(td); + + let box: &mut BoxRepr = transmute(p); + box.header.ref_count = -1; // Exchange values not ref counted + box.header.type_desc = td; + box.header.prev = null(); + box.header.next = null(); + + let exchange_count = &mut *exchange_count_ptr(); + atomic_xadd(exchange_count, 1); + + return transmute(box); +} +/** +Thin wrapper around libc::malloc, none of the box header +stuff in exchange_alloc::malloc +*/ +pub unsafe fn malloc_raw(size: uint) -> *c_void { + let p = c_malloc(size as size_t); + if p.is_null() { + fail!("Failure in malloc_raw: result ptr is null"); + } + p +} + +pub unsafe fn free(ptr: *c_void) { + let exchange_count = &mut *exchange_count_ptr(); + atomic_xsub(exchange_count, 1); + + assert!(ptr.is_not_null()); + c_free(ptr); +} +///Thin wrapper around libc::free, as with exchange_alloc::malloc_raw +pub unsafe fn free_raw(ptr: *c_void) { + c_free(ptr); +} + +fn get_box_size(body_size: uint, body_align: uint) -> uint { + let header_size = size_of::(); + // FIXME (#2699): This alignment calculation is suspicious. Is it right? + let total_size = align_to(header_size, body_align) + body_size; + return total_size; +} + +// Rounds |size| to the nearest |alignment|. Invariant: |alignment| is a power +// of two. +fn align_to(size: uint, align: uint) -> uint { + assert!(align != 0); + (size + align - 1) & !(align - 1) +} + +fn exchange_count_ptr() -> *mut int { + // XXX: Need mutable globals + unsafe { transmute(&rust_exchange_count) } +} + +extern { + static rust_exchange_count: uintptr_t; +} diff --git a/src/libcore/rt/io/mock.rs b/src/libstd/rt/io/mock.rs similarity index 100% rename from src/libcore/rt/io/mock.rs rename to src/libstd/rt/io/mock.rs diff --git a/src/libcore/rt/local.rs b/src/libstd/rt/local.rs similarity index 100% rename from src/libcore/rt/local.rs rename to src/libstd/rt/local.rs diff --git a/src/libcore/rt/local_ptr.rs b/src/libstd/rt/local_ptr.rs similarity index 100% rename from src/libcore/rt/local_ptr.rs rename to src/libstd/rt/local_ptr.rs diff --git a/src/libcore/rt/logging.rs b/src/libstd/rt/logging.rs similarity index 100% rename from src/libcore/rt/logging.rs rename to src/libstd/rt/logging.rs diff --git a/src/libcore/rt/message_queue.rs b/src/libstd/rt/message_queue.rs similarity index 100% rename from src/libcore/rt/message_queue.rs rename to src/libstd/rt/message_queue.rs diff --git a/src/libcore/rt/rc.rs b/src/libstd/rt/rc.rs similarity index 100% rename from src/libcore/rt/rc.rs rename to src/libstd/rt/rc.rs diff --git a/src/libcore/rt/sched.rs b/src/libstd/rt/sched.rs similarity index 100% rename from src/libcore/rt/sched.rs rename to src/libstd/rt/sched.rs diff --git a/src/libcore/rt/tube.rs b/src/libstd/rt/tube.rs similarity index 100% rename from src/libcore/rt/tube.rs rename to src/libstd/rt/tube.rs diff --git a/src/libcore/rt/uv/idle.rs b/src/libstd/rt/uv/idle.rs similarity index 100% rename from src/libcore/rt/uv/idle.rs rename to src/libstd/rt/uv/idle.rs diff --git a/src/libcore/rt/uv/timer.rs b/src/libstd/rt/uv/timer.rs similarity index 100% rename from src/libcore/rt/uv/timer.rs rename to src/libstd/rt/uv/timer.rs diff --git a/src/libstd/rt/uv/uvio.rs b/src/libstd/rt/uv/uvio.rs new file mode 100644 index 0000000000000..cacd67314ebac --- /dev/null +++ b/src/libstd/rt/uv/uvio.rs @@ -0,0 +1,492 @@ +// 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. + +use option::*; +use result::*; +use ops::Drop; +use cell::{Cell, empty_cell}; +use cast::transmute; +use clone::Clone; +use rt::io::IoError; +use rt::io::net::ip::IpAddr; +use rt::uv::*; +use rt::uv::idle::IdleWatcher; +use rt::rtio::*; +use rt::sched::Scheduler; +use rt::io::{standard_error, OtherIoError}; +use rt::tube::Tube; +use rt::local::Local; + +#[cfg(test)] use container::Container; +#[cfg(test)] use uint; +#[cfg(test)] use unstable::run_in_bare_thread; +#[cfg(test)] use rt::test::*; + +pub struct UvEventLoop { + uvio: UvIoFactory +} + +pub impl UvEventLoop { + fn new() -> UvEventLoop { + UvEventLoop { + uvio: UvIoFactory(Loop::new()) + } + } + + /// A convenience constructor + fn new_scheduler() -> Scheduler { + Scheduler::new(~UvEventLoop::new()) + } +} + +impl Drop for UvEventLoop { + fn finalize(&self) { + // XXX: Need mutable finalizer + let this = unsafe { + transmute::<&UvEventLoop, &mut UvEventLoop>(self) + }; + this.uvio.uv_loop().close(); + } +} + +impl EventLoop for UvEventLoop { + + fn run(&mut self) { + self.uvio.uv_loop().run(); + } + + fn callback(&mut self, f: ~fn()) { + let mut idle_watcher = IdleWatcher::new(self.uvio.uv_loop()); + do idle_watcher.start |idle_watcher, status| { + assert!(status.is_none()); + let mut idle_watcher = idle_watcher; + idle_watcher.stop(); + idle_watcher.close(||()); + f(); + } + } + + fn callback_ms(&mut self, ms: u64, f: ~fn()) { + let mut timer = TimerWatcher::new(self.uvio.uv_loop()); + do timer.start(ms, 0) |timer, status| { + assert!(status.is_none()); + timer.close(||()); + f(); + } + } + + fn io<'a>(&'a mut self) -> Option<&'a mut IoFactoryObject> { + Some(&mut self.uvio) + } +} + +#[test] +fn test_callback_run_once() { + do run_in_bare_thread { + let mut event_loop = UvEventLoop::new(); + let mut count = 0; + let count_ptr: *mut int = &mut count; + do event_loop.callback { + unsafe { *count_ptr += 1 } + } + event_loop.run(); + assert_eq!(count, 1); + } +} + +pub struct UvIoFactory(Loop); + +pub impl UvIoFactory { + fn uv_loop<'a>(&'a mut self) -> &'a mut Loop { + match self { &UvIoFactory(ref mut ptr) => ptr } + } +} + +impl IoFactory for UvIoFactory { + // Connect to an address and return a new stream + // NB: This blocks the task waiting on the connection. + // It would probably be better to return a future + fn tcp_connect(&mut self, addr: IpAddr) -> Result<~RtioTcpStreamObject, IoError> { + // Create a cell in the task to hold the result. We will fill + // the cell before resuming the task. + let result_cell = empty_cell(); + let result_cell_ptr: *Cell> = &result_cell; + + let scheduler = Local::take::(); + assert!(scheduler.in_task_context()); + + // Block this task and take ownership, switch to scheduler context + do scheduler.deschedule_running_task_and_then |task| { + + rtdebug!("connect: entered scheduler context"); + do Local::borrow:: |scheduler| { + assert!(!scheduler.in_task_context()); + } + let mut tcp_watcher = TcpWatcher::new(self.uv_loop()); + let task_cell = Cell(task); + + // Wait for a connection + do tcp_watcher.connect(addr) |stream_watcher, status| { + rtdebug!("connect: in connect callback"); + if status.is_none() { + rtdebug!("status is none"); + let res = Ok(~UvTcpStream { watcher: stream_watcher }); + + // Store the stream in the task's stack + unsafe { (*result_cell_ptr).put_back(res); } + + // Context switch + let scheduler = Local::take::(); + scheduler.resume_task_immediately(task_cell.take()); + } else { + rtdebug!("status is some"); + let task_cell = Cell(task_cell.take()); + do stream_watcher.close { + let res = Err(uv_error_to_io_error(status.get())); + unsafe { (*result_cell_ptr).put_back(res); } + let scheduler = Local::take::(); + scheduler.resume_task_immediately(task_cell.take()); + } + }; + } + } + + assert!(!result_cell.is_empty()); + return result_cell.take(); + } + + fn tcp_bind(&mut self, addr: IpAddr) -> Result<~RtioTcpListenerObject, IoError> { + let mut watcher = TcpWatcher::new(self.uv_loop()); + match watcher.bind(addr) { + Ok(_) => Ok(~UvTcpListener::new(watcher)), + Err(uverr) => { + let scheduler = Local::take::(); + do scheduler.deschedule_running_task_and_then |task| { + let task_cell = Cell(task); + do watcher.as_stream().close { + let scheduler = Local::take::(); + scheduler.resume_task_immediately(task_cell.take()); + } + } + Err(uv_error_to_io_error(uverr)) + } + } + } +} + +// FIXME #6090: Prefer newtype structs but Drop doesn't work +pub struct UvTcpListener { + watcher: TcpWatcher, + listening: bool, + incoming_streams: Tube> +} + +impl UvTcpListener { + fn new(watcher: TcpWatcher) -> UvTcpListener { + UvTcpListener { + watcher: watcher, + listening: false, + incoming_streams: Tube::new() + } + } + + fn watcher(&self) -> TcpWatcher { self.watcher } +} + +impl Drop for UvTcpListener { + fn finalize(&self) { + let watcher = self.watcher(); + let scheduler = Local::take::(); + do scheduler.deschedule_running_task_and_then |task| { + let task_cell = Cell(task); + do watcher.as_stream().close { + let scheduler = Local::take::(); + scheduler.resume_task_immediately(task_cell.take()); + } + } + } +} + +impl RtioTcpListener for UvTcpListener { + + fn accept(&mut self) -> Result<~RtioTcpStreamObject, IoError> { + rtdebug!("entering listen"); + + if self.listening { + return self.incoming_streams.recv(); + } + + self.listening = true; + + let server_tcp_watcher = self.watcher(); + let incoming_streams_cell = Cell(self.incoming_streams.clone()); + + let incoming_streams_cell = Cell(incoming_streams_cell.take()); + let mut server_tcp_watcher = server_tcp_watcher; + do server_tcp_watcher.listen |server_stream_watcher, status| { + let maybe_stream = if status.is_none() { + let mut server_stream_watcher = server_stream_watcher; + let mut loop_ = server_stream_watcher.event_loop(); + let client_tcp_watcher = TcpWatcher::new(&mut loop_); + let client_tcp_watcher = client_tcp_watcher.as_stream(); + // XXX: Need's to be surfaced in interface + server_stream_watcher.accept(client_tcp_watcher); + Ok(~UvTcpStream { watcher: client_tcp_watcher }) + } else { + Err(standard_error(OtherIoError)) + }; + + let mut incoming_streams = incoming_streams_cell.take(); + incoming_streams.send(maybe_stream); + incoming_streams_cell.put_back(incoming_streams); + } + + return self.incoming_streams.recv(); + } +} + +// FIXME #6090: Prefer newtype structs but Drop doesn't work +pub struct UvTcpStream { + watcher: StreamWatcher +} + +impl UvTcpStream { + fn watcher(&self) -> StreamWatcher { self.watcher } +} + +impl Drop for UvTcpStream { + fn finalize(&self) { + rtdebug!("closing tcp stream"); + let watcher = self.watcher(); + let scheduler = Local::take::(); + do scheduler.deschedule_running_task_and_then |task| { + let task_cell = Cell(task); + do watcher.close { + let scheduler = Local::take::(); + scheduler.resume_task_immediately(task_cell.take()); + } + } + } +} + +impl RtioTcpStream for UvTcpStream { + fn read(&mut self, buf: &mut [u8]) -> Result { + let result_cell = empty_cell(); + let result_cell_ptr: *Cell> = &result_cell; + + let scheduler = Local::take::(); + assert!(scheduler.in_task_context()); + let watcher = self.watcher(); + let buf_ptr: *&mut [u8] = &buf; + do scheduler.deschedule_running_task_and_then |task| { + rtdebug!("read: entered scheduler context"); + do Local::borrow:: |scheduler| { + assert!(!scheduler.in_task_context()); + } + let mut watcher = watcher; + let task_cell = Cell(task); + // XXX: We shouldn't reallocate these callbacks every + // call to read + let alloc: AllocCallback = |_| unsafe { + slice_to_uv_buf(*buf_ptr) + }; + do watcher.read_start(alloc) |watcher, nread, _buf, status| { + + // Stop reading so that no read callbacks are + // triggered before the user calls `read` again. + // XXX: Is there a performance impact to calling + // stop here? + let mut watcher = watcher; + watcher.read_stop(); + + let result = if status.is_none() { + assert!(nread >= 0); + Ok(nread as uint) + } else { + Err(uv_error_to_io_error(status.unwrap())) + }; + + unsafe { (*result_cell_ptr).put_back(result); } + + let scheduler = Local::take::(); + scheduler.resume_task_immediately(task_cell.take()); + } + } + + assert!(!result_cell.is_empty()); + return result_cell.take(); + } + + fn write(&mut self, buf: &[u8]) -> Result<(), IoError> { + let result_cell = empty_cell(); + let result_cell_ptr: *Cell> = &result_cell; + let scheduler = Local::take::(); + assert!(scheduler.in_task_context()); + let watcher = self.watcher(); + let buf_ptr: *&[u8] = &buf; + do scheduler.deschedule_running_task_and_then |task| { + let mut watcher = watcher; + let task_cell = Cell(task); + let buf = unsafe { slice_to_uv_buf(*buf_ptr) }; + do watcher.write(buf) |_watcher, status| { + let result = if status.is_none() { + Ok(()) + } else { + Err(uv_error_to_io_error(status.unwrap())) + }; + + unsafe { (*result_cell_ptr).put_back(result); } + + let scheduler = Local::take::(); + scheduler.resume_task_immediately(task_cell.take()); + } + } + + assert!(!result_cell.is_empty()); + return result_cell.take(); + } +} + +#[test] +fn test_simple_io_no_connect() { + do run_in_newsched_task { + unsafe { + let io = Local::unsafe_borrow::(); + let addr = next_test_ip4(); + let maybe_chan = (*io).tcp_connect(addr); + assert!(maybe_chan.is_err()); + } + } +} + +#[test] +fn test_simple_tcp_server_and_client() { + do run_in_newsched_task { + let addr = next_test_ip4(); + + // Start the server first so it's listening when we connect + do spawntask_immediately { + unsafe { + let io = Local::unsafe_borrow::(); + let mut listener = (*io).tcp_bind(addr).unwrap(); + let mut stream = listener.accept().unwrap(); + let mut buf = [0, .. 2048]; + let nread = stream.read(buf).unwrap(); + assert_eq!(nread, 8); + for uint::range(0, nread) |i| { + rtdebug!("%u", buf[i] as uint); + assert_eq!(buf[i], i as u8); + } + } + } + + do spawntask_immediately { + unsafe { + let io = Local::unsafe_borrow::(); + let mut stream = (*io).tcp_connect(addr).unwrap(); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + } + } + } +} + +#[test] #[ignore(reason = "busted")] +fn test_read_and_block() { + do run_in_newsched_task { + let addr = next_test_ip4(); + + do spawntask_immediately { + let io = unsafe { Local::unsafe_borrow::() }; + let mut listener = unsafe { (*io).tcp_bind(addr).unwrap() }; + let mut stream = listener.accept().unwrap(); + let mut buf = [0, .. 2048]; + + let expected = 32; + let mut current = 0; + let mut reads = 0; + + while current < expected { + let nread = stream.read(buf).unwrap(); + for uint::range(0, nread) |i| { + let val = buf[i] as uint; + assert_eq!(val, current % 8); + current += 1; + } + reads += 1; + + let scheduler = Local::take::(); + // Yield to the other task in hopes that it + // will trigger a read callback while we are + // not ready for it + do scheduler.deschedule_running_task_and_then |task| { + let task = Cell(task); + do Local::borrow:: |scheduler| { + scheduler.enqueue_task(task.take()); + } + } + } + + // Make sure we had multiple reads + assert!(reads > 1); + } + + do spawntask_immediately { + unsafe { + let io = Local::unsafe_borrow::(); + let mut stream = (*io).tcp_connect(addr).unwrap(); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + stream.write([0, 1, 2, 3, 4, 5, 6, 7]); + } + } + + } +} + +#[test] +fn test_read_read_read() { + do run_in_newsched_task { + let addr = next_test_ip4(); + static MAX: uint = 500000; + + do spawntask_immediately { + unsafe { + let io = Local::unsafe_borrow::(); + let mut listener = (*io).tcp_bind(addr).unwrap(); + let mut stream = listener.accept().unwrap(); + let buf = [1, .. 2048]; + let mut total_bytes_written = 0; + while total_bytes_written < MAX { + stream.write(buf); + total_bytes_written += buf.len(); + } + } + } + + do spawntask_immediately { + unsafe { + let io = Local::unsafe_borrow::(); + let mut stream = (*io).tcp_connect(addr).unwrap(); + let mut buf = [0, .. 2048]; + let mut total_bytes_read = 0; + while total_bytes_read < MAX { + let nread = stream.read(buf).unwrap(); + rtdebug!("read %u bytes", nread as uint); + total_bytes_read += nread; + for uint::range(0, nread) |i| { + assert_eq!(buf[i], 1); + } + } + rtdebug!("read %u bytes total", total_bytes_read as uint); + } + } + } +} diff --git a/src/libstd/rt/uv/uvll.rs b/src/libstd/rt/uv/uvll.rs new file mode 100644 index 0000000000000..ddc9040d73091 --- /dev/null +++ b/src/libstd/rt/uv/uvll.rs @@ -0,0 +1,452 @@ +// Copyright 2012 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. + +/*! + * Low-level bindings to the libuv library. + * + * This module contains a set of direct, 'bare-metal' wrappers around + * the libuv C-API. + * + * We're not bothering yet to redefine uv's structs as Rust structs + * because they are quite large and change often between versions. + * The maintenance burden is just too high. Instead we use the uv's + * `uv_handle_size` and `uv_req_size` to find the correct size of the + * structs and allocate them on the heap. This can be revisited later. + * + * There are also a collection of helper functions to ease interacting + * with the low-level API. + * + * As new functionality, existant in uv.h, is added to the rust stdlib, + * the mappings should be added in this module. + */ + +#[allow(non_camel_case_types)]; // C types + +use libc::{size_t, c_int, c_uint, c_void, c_char, uintptr_t}; +use libc::{malloc, free}; +use prelude::*; + +pub static UNKNOWN: c_int = -1; +pub static OK: c_int = 0; +pub static EOF: c_int = 1; +pub static EADDRINFO: c_int = 2; +pub static EACCES: c_int = 3; +pub static ECONNREFUSED: c_int = 12; +pub static ECONNRESET: c_int = 13; +pub static EPIPE: c_int = 36; + +pub struct uv_err_t { + code: c_int, + sys_errno_: c_int +} + +pub struct uv_buf_t { + base: *u8, + len: libc::size_t, +} + +pub type uv_handle_t = c_void; +pub type uv_loop_t = c_void; +pub type uv_idle_t = c_void; +pub type uv_tcp_t = c_void; +pub type uv_connect_t = c_void; +pub type uv_write_t = c_void; +pub type uv_async_t = c_void; +pub type uv_timer_t = c_void; +pub type uv_stream_t = c_void; +pub type uv_fs_t = c_void; + +pub type uv_idle_cb = *u8; + +pub type sockaddr_in = c_void; +pub type sockaddr_in6 = c_void; + +#[deriving(Eq)] +pub enum uv_handle_type { + UV_UNKNOWN_HANDLE, + UV_ASYNC, + UV_CHECK, + UV_FS_EVENT, + UV_FS_POLL, + UV_HANDLE, + UV_IDLE, + UV_NAMED_PIPE, + UV_POLL, + UV_PREPARE, + UV_PROCESS, + UV_STREAM, + UV_TCP, + UV_TIMER, + UV_TTY, + UV_UDP, + UV_SIGNAL, + UV_FILE, + UV_HANDLE_TYPE_MAX +} + +#[deriving(Eq)] +pub enum uv_req_type { + UV_UNKNOWN_REQ, + UV_REQ, + UV_CONNECT, + UV_WRITE, + UV_SHUTDOWN, + UV_UDP_SEND, + UV_FS, + UV_WORK, + UV_GETADDRINFO, + UV_REQ_TYPE_MAX +} + +pub unsafe fn malloc_handle(handle: uv_handle_type) -> *c_void { + assert!(handle != UV_UNKNOWN_HANDLE && handle != UV_HANDLE_TYPE_MAX); + let size = rust_uv_handle_size(handle as uint); + let p = malloc(size); + assert!(p.is_not_null()); + return p; +} + +pub unsafe fn free_handle(v: *c_void) { + free(v) +} + +pub unsafe fn malloc_req(req: uv_req_type) -> *c_void { + assert!(req != UV_UNKNOWN_REQ && req != UV_REQ_TYPE_MAX); + let size = rust_uv_req_size(req as uint); + let p = malloc(size); + assert!(p.is_not_null()); + return p; +} + +pub unsafe fn free_req(v: *c_void) { + free(v) +} + +#[test] +fn handle_sanity_check() { + unsafe { + assert_eq!(UV_HANDLE_TYPE_MAX as uint, rust_uv_handle_type_max()); + } +} + +#[test] +fn request_sanity_check() { + unsafe { + assert_eq!(UV_REQ_TYPE_MAX as uint, rust_uv_req_type_max()); + } +} + +pub unsafe fn loop_new() -> *c_void { + return rust_uv_loop_new(); +} + +pub unsafe fn loop_delete(loop_handle: *c_void) { + rust_uv_loop_delete(loop_handle); +} + +pub unsafe fn run(loop_handle: *c_void) { + rust_uv_run(loop_handle); +} + +pub unsafe fn close(handle: *T, cb: *u8) { + rust_uv_close(handle as *c_void, cb); +} + +pub unsafe fn walk(loop_handle: *c_void, cb: *u8, arg: *c_void) { + rust_uv_walk(loop_handle, cb, arg); +} + +pub unsafe fn idle_new() -> *uv_idle_t { + rust_uv_idle_new() +} + +pub unsafe fn idle_delete(handle: *uv_idle_t) { + rust_uv_idle_delete(handle) +} + +pub unsafe fn idle_init(loop_handle: *uv_loop_t, handle: *uv_idle_t) -> c_int { + rust_uv_idle_init(loop_handle, handle) +} + +pub unsafe fn idle_start(handle: *uv_idle_t, cb: uv_idle_cb) -> c_int { + rust_uv_idle_start(handle, cb) +} + +pub unsafe fn idle_stop(handle: *uv_idle_t) -> c_int { + rust_uv_idle_stop(handle) +} + +pub unsafe fn tcp_init(loop_handle: *c_void, handle: *uv_tcp_t) -> c_int { + return rust_uv_tcp_init(loop_handle, handle); +} + +// FIXME ref #2064 +pub unsafe fn tcp_connect(connect_ptr: *uv_connect_t, + tcp_handle_ptr: *uv_tcp_t, + addr_ptr: *sockaddr_in, + after_connect_cb: *u8) -> c_int { + return rust_uv_tcp_connect(connect_ptr, tcp_handle_ptr, + after_connect_cb, addr_ptr); +} +// FIXME ref #2064 +pub unsafe fn tcp_connect6(connect_ptr: *uv_connect_t, + tcp_handle_ptr: *uv_tcp_t, + addr_ptr: *sockaddr_in6, + after_connect_cb: *u8) -> c_int { + return rust_uv_tcp_connect6(connect_ptr, tcp_handle_ptr, + after_connect_cb, addr_ptr); +} +// FIXME ref #2064 +pub unsafe fn tcp_bind(tcp_server_ptr: *uv_tcp_t, addr_ptr: *sockaddr_in) -> c_int { + return rust_uv_tcp_bind(tcp_server_ptr, addr_ptr); +} +// FIXME ref #2064 +pub unsafe fn tcp_bind6(tcp_server_ptr: *uv_tcp_t, addr_ptr: *sockaddr_in6) -> c_int { + return rust_uv_tcp_bind6(tcp_server_ptr, addr_ptr); +} + +pub unsafe fn tcp_getpeername(tcp_handle_ptr: *uv_tcp_t, name: *sockaddr_in) -> c_int { + return rust_uv_tcp_getpeername(tcp_handle_ptr, name); +} + +pub unsafe fn tcp_getpeername6(tcp_handle_ptr: *uv_tcp_t, name: *sockaddr_in6) ->c_int { + return rust_uv_tcp_getpeername6(tcp_handle_ptr, name); +} + +pub unsafe fn listen(stream: *T, backlog: c_int, cb: *u8) -> c_int { + return rust_uv_listen(stream as *c_void, backlog, cb); +} + +pub unsafe fn accept(server: *c_void, client: *c_void) -> c_int { + return rust_uv_accept(server as *c_void, client as *c_void); +} + +pub unsafe fn write(req: *uv_write_t, stream: *T, buf_in: &[uv_buf_t], cb: *u8) -> c_int { + let buf_ptr = vec::raw::to_ptr(buf_in); + let buf_cnt = buf_in.len() as i32; + return rust_uv_write(req as *c_void, stream as *c_void, buf_ptr, buf_cnt, cb); +} +pub unsafe fn read_start(stream: *uv_stream_t, on_alloc: *u8, on_read: *u8) -> c_int { + return rust_uv_read_start(stream as *c_void, on_alloc, on_read); +} + +pub unsafe fn read_stop(stream: *uv_stream_t) -> c_int { + return rust_uv_read_stop(stream as *c_void); +} + +pub unsafe fn last_error(loop_handle: *c_void) -> uv_err_t { + return rust_uv_last_error(loop_handle); +} + +pub unsafe fn strerror(err: *uv_err_t) -> *c_char { + return rust_uv_strerror(err); +} +pub unsafe fn err_name(err: *uv_err_t) -> *c_char { + return rust_uv_err_name(err); +} + +pub unsafe fn async_init(loop_handle: *c_void, async_handle: *uv_async_t, cb: *u8) -> c_int { + return rust_uv_async_init(loop_handle, async_handle, cb); +} + +pub unsafe fn async_send(async_handle: *uv_async_t) { + return rust_uv_async_send(async_handle); +} +pub unsafe fn buf_init(input: *u8, len: uint) -> uv_buf_t { + let out_buf = uv_buf_t { base: ptr::null(), len: 0 as size_t }; + let out_buf_ptr = ptr::to_unsafe_ptr(&out_buf); + rust_uv_buf_init(out_buf_ptr, input, len as size_t); + return out_buf; +} + +pub unsafe fn timer_init(loop_ptr: *c_void, timer_ptr: *uv_timer_t) -> c_int { + return rust_uv_timer_init(loop_ptr, timer_ptr); +} +pub unsafe fn timer_start(timer_ptr: *uv_timer_t, cb: *u8, timeout: u64, + repeat: u64) -> c_int { + return rust_uv_timer_start(timer_ptr, cb, timeout, repeat); +} +pub unsafe fn timer_stop(timer_ptr: *uv_timer_t) -> c_int { + return rust_uv_timer_stop(timer_ptr); +} + +pub unsafe fn malloc_ip4_addr(ip: &str, port: int) -> *sockaddr_in { + do str::as_c_str(ip) |ip_buf| { + rust_uv_ip4_addrp(ip_buf as *u8, port as libc::c_int) + } +} +pub unsafe fn malloc_ip6_addr(ip: &str, port: int) -> *sockaddr_in6 { + do str::as_c_str(ip) |ip_buf| { + rust_uv_ip6_addrp(ip_buf as *u8, port as libc::c_int) + } +} + +pub unsafe fn free_ip4_addr(addr: *sockaddr_in) { + rust_uv_free_ip4_addr(addr); +} + +pub unsafe fn free_ip6_addr(addr: *sockaddr_in6) { + rust_uv_free_ip6_addr(addr); +} + +// data access helpers +pub unsafe fn get_loop_for_uv_handle(handle: *T) -> *c_void { + return rust_uv_get_loop_for_uv_handle(handle as *c_void); +} +pub unsafe fn get_stream_handle_from_connect_req(connect: *uv_connect_t) -> *uv_stream_t { + return rust_uv_get_stream_handle_from_connect_req(connect); +} +pub unsafe fn get_stream_handle_from_write_req(write_req: *uv_write_t) -> *uv_stream_t { + return rust_uv_get_stream_handle_from_write_req(write_req); +} +pub unsafe fn get_data_for_uv_loop(loop_ptr: *c_void) -> *c_void { + rust_uv_get_data_for_uv_loop(loop_ptr) +} +pub unsafe fn set_data_for_uv_loop(loop_ptr: *c_void, data: *c_void) { + rust_uv_set_data_for_uv_loop(loop_ptr, data); +} +pub unsafe fn get_data_for_uv_handle(handle: *T) -> *c_void { + return rust_uv_get_data_for_uv_handle(handle as *c_void); +} +pub unsafe fn set_data_for_uv_handle(handle: *T, data: *U) { + rust_uv_set_data_for_uv_handle(handle as *c_void, data as *c_void); +} +pub unsafe fn get_data_for_req(req: *T) -> *c_void { + return rust_uv_get_data_for_req(req as *c_void); +} +pub unsafe fn set_data_for_req(req: *T, data: *U) { + rust_uv_set_data_for_req(req as *c_void, data as *c_void); +} +pub unsafe fn get_base_from_buf(buf: uv_buf_t) -> *u8 { + return rust_uv_get_base_from_buf(buf); +} +pub unsafe fn get_len_from_buf(buf: uv_buf_t) -> size_t { + return rust_uv_get_len_from_buf(buf); +} +pub unsafe fn malloc_buf_base_of(suggested_size: size_t) -> *u8 { + return rust_uv_malloc_buf_base_of(suggested_size); +} +pub unsafe fn free_base_of_buf(buf: uv_buf_t) { + rust_uv_free_base_of_buf(buf); +} + +pub unsafe fn get_last_err_info(uv_loop: *c_void) -> ~str { + let err = last_error(uv_loop); + let err_ptr = ptr::to_unsafe_ptr(&err); + let err_name = str::raw::from_c_str(err_name(err_ptr)); + let err_msg = str::raw::from_c_str(strerror(err_ptr)); + return fmt!("LIBUV ERROR: name: %s msg: %s", + err_name, err_msg); +} + +pub unsafe fn get_last_err_data(uv_loop: *c_void) -> uv_err_data { + let err = last_error(uv_loop); + let err_ptr = ptr::to_unsafe_ptr(&err); + let err_name = str::raw::from_c_str(err_name(err_ptr)); + let err_msg = str::raw::from_c_str(strerror(err_ptr)); + uv_err_data { err_name: err_name, err_msg: err_msg } +} + +pub struct uv_err_data { + err_name: ~str, + err_msg: ~str, +} + +extern { + + fn rust_uv_handle_size(type_: uintptr_t) -> size_t; + fn rust_uv_req_size(type_: uintptr_t) -> size_t; + fn rust_uv_handle_type_max() -> uintptr_t; + fn rust_uv_req_type_max() -> uintptr_t; + + // libuv public API + fn rust_uv_loop_new() -> *c_void; + fn rust_uv_loop_delete(lp: *c_void); + fn rust_uv_run(loop_handle: *c_void); + fn rust_uv_close(handle: *c_void, cb: *u8); + fn rust_uv_walk(loop_handle: *c_void, cb: *u8, arg: *c_void); + + fn rust_uv_idle_new() -> *uv_idle_t; + fn rust_uv_idle_delete(handle: *uv_idle_t); + fn rust_uv_idle_init(loop_handle: *uv_loop_t, handle: *uv_idle_t) -> c_int; + fn rust_uv_idle_start(handle: *uv_idle_t, cb: uv_idle_cb) -> c_int; + fn rust_uv_idle_stop(handle: *uv_idle_t) -> c_int; + + fn rust_uv_async_send(handle: *uv_async_t); + fn rust_uv_async_init(loop_handle: *c_void, + async_handle: *uv_async_t, + cb: *u8) -> c_int; + fn rust_uv_tcp_init(loop_handle: *c_void, handle_ptr: *uv_tcp_t) -> c_int; + // FIXME ref #2604 .. ? + fn rust_uv_buf_init(out_buf: *uv_buf_t, base: *u8, len: size_t); + fn rust_uv_last_error(loop_handle: *c_void) -> uv_err_t; + // FIXME ref #2064 + fn rust_uv_strerror(err: *uv_err_t) -> *c_char; + // FIXME ref #2064 + fn rust_uv_err_name(err: *uv_err_t) -> *c_char; + fn rust_uv_ip4_addrp(ip: *u8, port: c_int) -> *sockaddr_in; + fn rust_uv_ip6_addrp(ip: *u8, port: c_int) -> *sockaddr_in6; + fn rust_uv_free_ip4_addr(addr: *sockaddr_in); + fn rust_uv_free_ip6_addr(addr: *sockaddr_in6); + fn rust_uv_ip4_name(src: *sockaddr_in, dst: *u8, size: size_t) -> c_int; + fn rust_uv_ip6_name(src: *sockaddr_in6, dst: *u8, size: size_t) -> c_int; + fn rust_uv_ip4_port(src: *sockaddr_in) -> c_uint; + fn rust_uv_ip6_port(src: *sockaddr_in6) -> c_uint; + // FIXME ref #2064 + fn rust_uv_tcp_connect(connect_ptr: *uv_connect_t, + tcp_handle_ptr: *uv_tcp_t, + after_cb: *u8, + addr: *sockaddr_in) -> c_int; + // FIXME ref #2064 + fn rust_uv_tcp_bind(tcp_server: *uv_tcp_t, addr: *sockaddr_in) -> c_int; + // FIXME ref #2064 + fn rust_uv_tcp_connect6(connect_ptr: *uv_connect_t, + tcp_handle_ptr: *uv_tcp_t, + after_cb: *u8, + addr: *sockaddr_in6) -> c_int; + // FIXME ref #2064 + fn rust_uv_tcp_bind6(tcp_server: *uv_tcp_t, addr: *sockaddr_in6) -> c_int; + fn rust_uv_tcp_getpeername(tcp_handle_ptr: *uv_tcp_t, + name: *sockaddr_in) -> c_int; + fn rust_uv_tcp_getpeername6(tcp_handle_ptr: *uv_tcp_t, + name: *sockaddr_in6) ->c_int; + fn rust_uv_listen(stream: *c_void, backlog: c_int, cb: *u8) -> c_int; + fn rust_uv_accept(server: *c_void, client: *c_void) -> c_int; + fn rust_uv_write(req: *c_void, + stream: *c_void, + buf_in: *uv_buf_t, + buf_cnt: c_int, + cb: *u8) -> c_int; + fn rust_uv_read_start(stream: *c_void, + on_alloc: *u8, + on_read: *u8) -> c_int; + fn rust_uv_read_stop(stream: *c_void) -> c_int; + fn rust_uv_timer_init(loop_handle: *c_void, + timer_handle: *uv_timer_t) -> c_int; + fn rust_uv_timer_start(timer_handle: *uv_timer_t, + cb: *u8, + timeout: libc::uint64_t, + repeat: libc::uint64_t) -> c_int; + fn rust_uv_timer_stop(handle: *uv_timer_t) -> c_int; + + fn rust_uv_malloc_buf_base_of(sug_size: size_t) -> *u8; + fn rust_uv_free_base_of_buf(buf: uv_buf_t); + fn rust_uv_get_stream_handle_from_connect_req(connect_req: *uv_connect_t) -> *uv_stream_t; + fn rust_uv_get_stream_handle_from_write_req(write_req: *uv_write_t) -> *uv_stream_t; + fn rust_uv_get_loop_for_uv_handle(handle: *c_void) -> *c_void; + fn rust_uv_get_data_for_uv_loop(loop_ptr: *c_void) -> *c_void; + fn rust_uv_set_data_for_uv_loop(loop_ptr: *c_void, data: *c_void); + fn rust_uv_get_data_for_uv_handle(handle: *c_void) -> *c_void; + fn rust_uv_set_data_for_uv_handle(handle: *c_void, data: *c_void); + fn rust_uv_get_data_for_req(req: *c_void) -> *c_void; + fn rust_uv_set_data_for_req(req: *c_void, data: *c_void); + fn rust_uv_get_base_from_buf(buf: uv_buf_t) -> *u8; + fn rust_uv_get_len_from_buf(buf: uv_buf_t) -> size_t; +} diff --git a/src/libsyntax/opt_vec.rs b/src/libsyntax/opt_vec.rs index e3f1e9e1328c5..791f7444b6226 100644 --- a/src/libsyntax/opt_vec.rs +++ b/src/libsyntax/opt_vec.rs @@ -16,6 +16,8 @@ * other useful things like `push()` and `len()`. */ +use core::prelude::*; + use core::old_iter; use core::old_iter::BaseIter; From 3a66d732bb3d4b90796d39a5bc58921cea955c60 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Wed, 22 May 2013 11:02:40 -0700 Subject: [PATCH 198/248] libsyntax: Fix more merge fallout. --- src/libextra/flate.rs | 2 ++ src/libsyntax/ext/build.rs | 4 ++-- src/libuv | 2 +- src/test/run-pass/core-rt-smoke.rs | 4 ++-- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/libextra/flate.rs b/src/libextra/flate.rs index c968bb5768d8b..1f57383140ba2 100644 --- a/src/libextra/flate.rs +++ b/src/libextra/flate.rs @@ -14,6 +14,8 @@ Simple compression */ +use core::prelude::*; + use core::libc::{c_void, size_t, c_int}; use core::libc; use core::vec; diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 58ea03ffceefe..7be8742d1c250 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -299,7 +299,7 @@ impl AstBuilder for @ExtCtxt { self.path_all(dummy_sp(), true, ~[ - self.ident_of("core"), + self.ident_of("std"), self.ident_of("option"), self.ident_of("Option") ], @@ -537,7 +537,7 @@ impl AstBuilder for @ExtCtxt { self.expr_call_global( span, ~[ - self.ident_of("core"), + self.ident_of("std"), self.ident_of("sys"), self.ident_of("FailWithCause"), self.ident_of("fail_with"), diff --git a/src/libuv b/src/libuv index 218ab86721eef..dfae9c3e958dc 160000 --- a/src/libuv +++ b/src/libuv @@ -1 +1 @@ -Subproject commit 218ab86721eefd7b7e97fa6d9f95a80a1fa8686c +Subproject commit dfae9c3e958dc086d9c0ab068cd76d196c95a433 diff --git a/src/test/run-pass/core-rt-smoke.rs b/src/test/run-pass/core-rt-smoke.rs index 3a0b4b6d40da9..5873e7c746028 100644 --- a/src/test/run-pass/core-rt-smoke.rs +++ b/src/test/run-pass/core-rt-smoke.rs @@ -14,7 +14,7 @@ #[start] fn start(argc: int, argv: **u8, crate_map: *u8) -> int { - do core::rt::start(argc, argv, crate_map) { + do std::rt::start(argc, argv, crate_map) { debug!("creating my own runtime is joy"); } -} \ No newline at end of file +} From a5ca58ae3444985c4c629767e2a9071a2d7729c6 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Wed, 22 May 2013 18:14:11 -0700 Subject: [PATCH 199/248] libextra: Allow unnecessary allocations --- src/libextra/std.rc | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libextra/std.rc b/src/libextra/std.rc index a23a547634242..2a18f021e7897 100644 --- a/src/libextra/std.rc +++ b/src/libextra/std.rc @@ -27,6 +27,7 @@ not required in or otherwise suitable for the core library. #[crate_type = "lib"]; #[deny(non_camel_case_types)]; +#[allow(unnecessary_allocation)]; #[no_core]; #[no_std]; From 18fca3e2e5541a3ce4d25ba84a28d4f5ad3db969 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Wed, 22 May 2013 19:59:22 -0700 Subject: [PATCH 200/248] librustc: Add some missing `use core::prelude::*;` in the test cases --- src/librustc/back/rpath.rs | 2 ++ src/librustc/driver/driver.rs | 2 ++ src/librustc/util/enum_set.rs | 3 +++ src/librustdoc/attr_parser.rs | 1 + src/librustdoc/attr_pass.rs | 2 ++ src/librustdoc/config.rs | 1 + src/librustdoc/desc_to_brief_pass.rs | 2 ++ src/librustdoc/markdown_index_pass.rs | 2 ++ src/librustdoc/markdown_pass.rs | 2 ++ src/librustdoc/markdown_writer.rs | 2 ++ src/librustdoc/sectionalize_pass.rs | 2 ++ src/librustdoc/text_pass.rs | 2 ++ src/librustdoc/tystr_pass.rs | 2 ++ 13 files changed, 25 insertions(+) diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index f3e01a00e38aa..026b2944a624f 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -195,6 +195,8 @@ pub fn minimize_rpaths(rpaths: &[Path]) -> ~[Path] { #[cfg(unix)] mod test { + use core::prelude::*; + // FIXME(#2119): the outer attribute should be #[cfg(unix, test)], then // these redundant #[cfg(test)] blocks can be removed #[cfg(test)] diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 4a9a12e7c0f24..4298cb5b15b31 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -920,6 +920,8 @@ pub fn list_metadata(sess: Session, path: &Path, out: @io::Writer) { #[cfg(test)] mod test { + use core::prelude::*; + use driver::driver::{build_configuration, build_session}; use driver::driver::{build_session_options, optgroups, str_input}; diff --git a/src/librustc/util/enum_set.rs b/src/librustc/util/enum_set.rs index 048b602e81888..d31d943db0701 100644 --- a/src/librustc/util/enum_set.rs +++ b/src/librustc/util/enum_set.rs @@ -98,7 +98,10 @@ impl BitAnd, EnumSet> for EnumSet { #[cfg(test)] mod test { + use core::prelude::*; + use core::iter; + use util::enum_set::*; #[deriving(Eq)] diff --git a/src/librustdoc/attr_parser.rs b/src/librustdoc/attr_parser.rs index 92e2973acb6f6..99bdf2284595f 100644 --- a/src/librustdoc/attr_parser.rs +++ b/src/librustdoc/attr_parser.rs @@ -70,6 +70,7 @@ pub fn parse_hidden(attrs: ~[ast::attribute]) -> bool { #[cfg(test)] mod test { + use core::prelude::*; use syntax::ast; use syntax; use super::{parse_hidden, parse_crate, parse_desc}; diff --git a/src/librustdoc/attr_pass.rs b/src/librustdoc/attr_pass.rs index e49e9b27d41ed..1e6d6d7bd89c7 100644 --- a/src/librustdoc/attr_pass.rs +++ b/src/librustdoc/attr_pass.rs @@ -234,6 +234,8 @@ fn fold_impl( #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use attr_pass::run; use doc; diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 22a5f668c70ee..39c72686a4d97 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -242,6 +242,7 @@ pub fn maybe_find_pandoc( #[cfg(test)] mod test { + use core::prelude::*; use config::*; use core::run::ProgramOutput; diff --git a/src/librustdoc/desc_to_brief_pass.rs b/src/librustdoc/desc_to_brief_pass.rs index 1066f9e924a04..d74be0580f49a 100644 --- a/src/librustdoc/desc_to_brief_pass.rs +++ b/src/librustdoc/desc_to_brief_pass.rs @@ -182,6 +182,8 @@ pub fn paragraphs(s: &str) -> ~[~str] { #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use attr_pass; use super::{extract, paragraphs, run}; diff --git a/src/librustdoc/markdown_index_pass.rs b/src/librustdoc/markdown_index_pass.rs index 9d55452acdfda..f2467d7ad2257 100644 --- a/src/librustdoc/markdown_index_pass.rs +++ b/src/librustdoc/markdown_index_pass.rs @@ -164,6 +164,8 @@ pub fn pandoc_header_id(header: &str) -> ~str { #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use attr_pass; use config; diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index ff7955768d333..e0fb88ff703c7 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -505,6 +505,8 @@ fn put_struct( #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use attr_pass; use config; diff --git a/src/librustdoc/markdown_writer.rs b/src/librustdoc/markdown_writer.rs index 5a22a56b7a6f8..3e90c1a53f4a5 100644 --- a/src/librustdoc/markdown_writer.rs +++ b/src/librustdoc/markdown_writer.rs @@ -261,6 +261,8 @@ fn future_writer() -> (Writer, future::Future<~str>) { #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use doc; use extract; diff --git a/src/librustdoc/sectionalize_pass.rs b/src/librustdoc/sectionalize_pass.rs index 6333e2878793f..4220a2bef78dd 100644 --- a/src/librustdoc/sectionalize_pass.rs +++ b/src/librustdoc/sectionalize_pass.rs @@ -162,6 +162,8 @@ fn parse_header(line: ~str) -> Option<~str> { #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use attr_pass; use doc; diff --git a/src/librustdoc/text_pass.rs b/src/librustdoc/text_pass.rs index e6c6118a76589..61f66c43521a8 100644 --- a/src/librustdoc/text_pass.rs +++ b/src/librustdoc/text_pass.rs @@ -139,6 +139,8 @@ fn fold_impl( #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use attr_pass; use desc_to_brief_pass; diff --git a/src/librustdoc/tystr_pass.rs b/src/librustdoc/tystr_pass.rs index 941faf32d3675..051825d46e1b3 100644 --- a/src/librustdoc/tystr_pass.rs +++ b/src/librustdoc/tystr_pass.rs @@ -347,6 +347,8 @@ fn strip_struct_extra_stuff(item: @ast::item) -> @ast::item { #[cfg(test)] mod test { + use core::prelude::*; + use astsrv; use doc; use extract; From be0110989e1e0b14c901876d373220567165b23e Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Thu, 23 May 2013 08:32:36 -0700 Subject: [PATCH 201/248] etc: Fix test combiner for core->std/std->extra change. rs=burningtree --- src/etc/combine-tests.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/etc/combine-tests.py b/src/etc/combine-tests.py index 93989f8e4a901..130acca28bfb2 100755 --- a/src/etc/combine-tests.py +++ b/src/etc/combine-tests.py @@ -49,10 +49,10 @@ def scrub(b): d = open("tmp/run_pass_stage2_driver.rs", "w") d.write("// AUTO-GENERATED FILE: DO NOT EDIT\n") -d.write("extern mod std;\n") +d.write("extern mod extra;\n") d.write("extern mod run_pass_stage2;\n") d.write("use run_pass_stage2::*;\n") -d.write("use core::io::WriterUtil;\n"); +d.write("use std::io::WriterUtil;\n"); d.write("fn main() {\n"); d.write(" let out = io::stdout();\n"); i = 0 From 6e2b082adc84c22ea3b023f4f08d7b21857fc399 Mon Sep 17 00:00:00 2001 From: Patrick Walton Date: Thu, 23 May 2013 08:33:30 -0700 Subject: [PATCH 202/248] libextra: Add missing core::prelude import. rs=burningtree --- src/libextra/smallintmap.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/libextra/smallintmap.rs b/src/libextra/smallintmap.rs index b2a98845b2f65..069368d3feaa8 100644 --- a/src/libextra/smallintmap.rs +++ b/src/libextra/smallintmap.rs @@ -362,6 +362,8 @@ mod tests { #[cfg(test)] mod test_set { + use core::prelude::*; + use super::SmallIntSet; #[test] From 34cfd2183b1d46ccec97691870a3bcceee5ee367 Mon Sep 17 00:00:00 2001 From: Ted Horst Date: Thu, 23 May 2013 15:06:29 -0500 Subject: [PATCH 203/248] more testing fallout from core->std/std->extra move --- doc/rust.md | 70 +++++++++++------------ doc/tutorial-ffi.md | 12 ++-- doc/tutorial-tasks.md | 90 +++++++++++++++--------------- doc/tutorial.md | 116 +++++++++++++++++++-------------------- src/etc/extract-tests.py | 4 +- src/librusti/rusti.rc | 1 + src/librustpkg/tests.rs | 1 + 7 files changed, 148 insertions(+), 146 deletions(-) diff --git a/doc/rust.md b/doc/rust.md index bb0438016b843..1d5a685a6a2cb 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -17,14 +17,14 @@ This document does not serve as a tutorial introduction to the language. Background familiarity with the language is assumed. A separate [tutorial] document is available to help acquire such background familiarity. -This document also does not serve as a reference to the [core] or [standard] +This document also does not serve as a reference to the [standard] or [extra] libraries included in the language distribution. Those libraries are documented separately by extracting documentation attributes from their source code. [tutorial]: tutorial.html -[core]: core/index.html [standard]: std/index.html +[extra]: extra/index.html ## Disclaimer @@ -441,7 +441,7 @@ expression context, the final namespace qualifier is omitted. Two examples of paths with type arguments: ~~~~ -# use core::hashmap::HashMap; +# use std::hashmap::HashMap; # fn f() { # fn id(t: T) -> T { t } type t = HashMap; // Type arguments used in a type expression @@ -768,9 +768,9 @@ Three examples of `extern mod` declarations: ~~~~~~~~{.xfail-test} extern mod pcre (uuid = "54aba0f8-a7b1-4beb-92f1-4cf625264841"); -extern mod std; // equivalent to: extern mod std ( name = "std" ); +extern mod extra; // equivalent to: extern mod extra ( name = "extra" ); -extern mod ruststd (name = "std"); // linking to 'std' under another name +extern mod rustextra (name = "extra"); // linking to 'extra' under another name ~~~~~~~~ ##### Use declarations @@ -802,19 +802,19 @@ Use declarations support a number of convenient shortcuts: An example of `use` declarations: ~~~~ -use core::float::sin; -use core::str::{slice, contains}; -use core::option::Some; +use std::float::sin; +use std::str::{slice, contains}; +use std::option::Some; fn main() { - // Equivalent to 'info!(core::float::sin(1.0));' + // Equivalent to 'info!(std::float::sin(1.0));' info!(sin(1.0)); - // Equivalent to 'info!(core::option::Some(1.0));' + // Equivalent to 'info!(std::option::Some(1.0));' info!(Some(1.0)); // Equivalent to - // 'info!(core::str::contains(core::str::slice("foo", 0, 1), "oo"));' + // 'info!(std::str::contains(std::str::slice("foo", 0, 1), "oo"));' info!(contains(slice("foo", 0, 1), "oo")); } ~~~~ @@ -1327,7 +1327,7 @@ with the exception that they may not have a body and are instead terminated by a semicolon. ~~~ -# use core::libc::{c_char, FILE}; +# use std::libc::{c_char, FILE}; # #[nolink] extern { @@ -1436,7 +1436,7 @@ Some primitive Rust operations are defined in Rust code, rather than being implemented directly in C or assembly language. The definitions of these operations have to be easy for the compiler to find. The `lang` attribute makes it possible to declare these operations. -For example, the `str` module in the Rust core library defines the string equality function: +For example, the `str` module in the Rust standard library defines the string equality function: ~~~ {.xfail-test} #[lang="str_eq"] @@ -1562,7 +1562,7 @@ impl Eq for Foo { Supported traits for `deriving` are: * Comparison traits: `Eq`, `TotalEq`, `Ord`, `TotalOrd`. -* Serialization: `Encodable`, `Decodable`. These require `std`. +* Serialization: `Encodable`, `Decodable`. These require `extra`. * `Clone` and `DeepClone`, to perform (deep) copies. * `IterBytes`, to iterate over the bytes in a data type. * `Rand`, to create a random instance of a data type. @@ -1885,25 +1885,25 @@ Binary operators expressions are given in terms of #### Arithmetic operators Binary arithmetic expressions are syntactic sugar for calls to built-in traits, -defined in the `core::ops` module of the `core` library. +defined in the `std::ops` module of the `std` library. This means that arithmetic operators can be overridden for user-defined types. The default meaning of the operators on standard types is given here. `+` : Addition and vector/string concatenation. - Calls the `add` method on the `core::ops::Add` trait. + Calls the `add` method on the `std::ops::Add` trait. `-` : Subtraction. - Calls the `sub` method on the `core::ops::Sub` trait. + Calls the `sub` method on the `std::ops::Sub` trait. `*` : Multiplication. - Calls the `mul` method on the `core::ops::Mul` trait. + Calls the `mul` method on the `std::ops::Mul` trait. `/` : Quotient. - Calls the `div` method on the `core::ops::Div` trait. + Calls the `div` method on the `std::ops::Div` trait. `%` : Remainder. - Calls the `rem` method on the `core::ops::Rem` trait. + Calls the `rem` method on the `std::ops::Rem` trait. #### Bitwise operators @@ -1914,19 +1914,19 @@ The default meaning of the operators on standard types is given here. `&` : And. - Calls the `bitand` method of the `core::ops::BitAnd` trait. + Calls the `bitand` method of the `std::ops::BitAnd` trait. `|` : Inclusive or. - Calls the `bitor` method of the `core::ops::BitOr` trait. + Calls the `bitor` method of the `std::ops::BitOr` trait. `^` : Exclusive or. - Calls the `bitxor` method of the `core::ops::BitXor` trait. + Calls the `bitxor` method of the `std::ops::BitXor` trait. `<<` : Logical left shift. - Calls the `shl` method of the `core::ops::Shl` trait. + Calls the `shl` method of the `std::ops::Shl` trait. `>>` : Logical right shift. - Calls the `shr` method of the `core::ops::Shr` trait. + Calls the `shr` method of the `std::ops::Shr` trait. #### Lazy boolean operators @@ -1947,22 +1947,22 @@ The default meaning of the operators on standard types is given here. `==` : Equal to. - Calls the `eq` method on the `core::cmp::Eq` trait. + Calls the `eq` method on the `std::cmp::Eq` trait. `!=` : Unequal to. - Calls the `ne` method on the `core::cmp::Eq` trait. + Calls the `ne` method on the `std::cmp::Eq` trait. `<` : Less than. - Calls the `lt` method on the `core::cmp::Ord` trait. + Calls the `lt` method on the `std::cmp::Ord` trait. `>` : Greater than. - Calls the `gt` method on the `core::cmp::Ord` trait. + Calls the `gt` method on the `std::cmp::Ord` trait. `<=` : Less than or equal. - Calls the `le` method on the `core::cmp::Ord` trait. + Calls the `le` method on the `std::cmp::Ord` trait. `>=` : Greater than or equal. - Calls the `ge` method on the `core::cmp::Ord` trait. + Calls the `ge` method on the `std::cmp::Ord` trait. #### Type cast expressions @@ -2121,11 +2121,11 @@ then the expression completes. Some examples of call expressions: ~~~~ -# use core::from_str::FromStr::from_str; +# use std::from_str::FromStr; # fn add(x: int, y: int) -> int { 0 } let x: int = add(1, 2); -let pi = from_str::("3.14"); +let pi = FromStr::from_str::("3.14"); ~~~~ ### Lambda expressions @@ -3168,7 +3168,7 @@ execute, after which it is *descheduled* at a loop-edge or similar preemption point, and another task within is scheduled, pseudo-randomly. An executing task can yield control at any time, by making a library call to -`core::task::yield`, which deschedules it immediately. Entering any other +`std::task::yield`, which deschedules it immediately. Entering any other non-executing state (blocked, dead) similarly deschedules the task. @@ -3181,7 +3181,7 @@ run-time. It is smaller and simpler than many modern language runtimes. It is tightly integrated into the language's execution model of memory, tasks, communication and logging. -> **Note:** The runtime library will merge with the `core` library in future versions of Rust. +> **Note:** The runtime library will merge with the `std` library in future versions of Rust. ### Memory allocation diff --git a/doc/tutorial-ffi.md b/doc/tutorial-ffi.md index b2c2a8824eee6..33a8cd230bb2f 100644 --- a/doc/tutorial-ffi.md +++ b/doc/tutorial-ffi.md @@ -12,7 +12,7 @@ The following is a minimal example of calling a foreign function which will comp installed: ~~~~ {.xfail-test} -use core::libc::size_t; +use std::libc::size_t; #[link_args = "-lsnappy"] extern { @@ -42,7 +42,7 @@ runtime. The `extern` block can be extended to cover the entire snappy API: ~~~~ {.xfail-test} -use core::libc::{c_int, size_t}; +use std::libc::{c_int, size_t}; #[link_args = "-lsnappy"] extern { @@ -149,9 +149,9 @@ A type with the same functionality as owned boxes can be implemented by wrapping `malloc` and `free`: ~~~~ -use core::libc::{c_void, size_t, malloc, free}; -use core::unstable::intrinsics; -use core::util; +use std::libc::{c_void, size_t, malloc, free}; +use std::unstable::intrinsics; +use std::util; // a wrapper around the handle returned by the foreign code pub struct Unique { @@ -161,7 +161,7 @@ pub struct Unique { pub impl Unique { fn new(value: T) -> Unique { unsafe { - let ptr = malloc(core::sys::size_of::() as size_t) as *mut T; + let ptr = malloc(std::sys::size_of::() as size_t) as *mut T; assert!(!ptr::is_null(ptr)); // `*ptr` is uninitialized, and `*ptr = value` would attempt to destroy it intrinsics::move_val_init(&mut *ptr, value); diff --git a/doc/tutorial-tasks.md b/doc/tutorial-tasks.md index c9e0377dd132c..320385c89a652 100644 --- a/doc/tutorial-tasks.md +++ b/doc/tutorial-tasks.md @@ -39,40 +39,40 @@ data through the global _exchange heap_. While Rust's type system provides the building blocks needed for safe and efficient tasks, all of the task functionality itself is implemented -in the core and standard libraries, which are still under development +in the standard and extra libraries, which are still under development and do not always present a consistent or complete interface. For your reference, these are the standard modules involved in Rust concurrency at this writing: -* [`core::task`] - All code relating to tasks and task scheduling, -* [`core::comm`] - The message passing interface, -* [`core::pipes`] - The underlying messaging infrastructure, -* [`std::comm`] - Additional messaging types based on `core::pipes`, -* [`std::sync`] - More exotic synchronization tools, including locks, -* [`std::arc`] - The ARC (atomically reference counted) type, +* [`std::task`] - All code relating to tasks and task scheduling, +* [`std::comm`] - The message passing interface, +* [`std::pipes`] - The underlying messaging infrastructure, +* [`extra::comm`] - Additional messaging types based on `std::pipes`, +* [`extra::sync`] - More exotic synchronization tools, including locks, +* [`extra::arc`] - The ARC (atomically reference counted) type, for safely sharing immutable data, -* [`std::future`] - A type representing values that may be computed concurrently and retrieved at a later time. +* [`extra::future`] - A type representing values that may be computed concurrently and retrieved at a later time. -[`core::task`]: core/task.html -[`core::comm`]: core/comm.html -[`core::pipes`]: core/pipes.html +[`std::task`]: std/task.html [`std::comm`]: std/comm.html -[`std::sync`]: std/sync.html -[`std::arc`]: std/arc.html -[`std::future`]: std/future.html +[`std::pipes`]: std/pipes.html +[`extra::comm`]: extra/comm.html +[`extra::sync`]: extra/sync.html +[`extra::arc`]: extra/arc.html +[`extra::future`]: extra/future.html # Basics The programming interface for creating and managing tasks lives -in the `task` module of the `core` library, and is thus available to all +in the `task` module of the `std` library, and is thus available to all Rust code by default. At its simplest, creating a task is a matter of calling the `spawn` function with a closure argument. `spawn` executes the closure in the new task. ~~~~ -# use core::io::println; -# use core::task::spawn; +# use std::io::println; +# use std::task::spawn; // Print something profound in a different task using a named function fn print_message() { println("I am running in a different task!"); } @@ -90,7 +90,7 @@ do spawn { In Rust, there is nothing special about creating tasks: a task is not a concept that appears in the language semantics. Instead, Rust's type system provides all the tools necessary to implement safe concurrency: particularly, -_owned types_. The language leaves the implementation details to the core +_owned types_. The language leaves the implementation details to the standard library. The `spawn` function has a very simple type signature: `fn spawn(f: @@ -101,8 +101,8 @@ execution. Like any closure, the function passed to `spawn` may capture an environment that it carries across tasks. ~~~ -# use core::io::println; -# use core::task::spawn; +# use std::io::println; +# use std::task::spawn; # fn generate_task_number() -> int { 0 } // Generate some state locally let child_task_number = generate_task_number(); @@ -118,8 +118,8 @@ in parallel. Thus, on a multicore machine, running the following code should interleave the output in vaguely random order. ~~~ -# use core::io::print; -# use core::task::spawn; +# use std::io::print; +# use std::task::spawn; for int::range(0, 20) |child_task_number| { do spawn { @@ -147,8 +147,8 @@ endpoint. Consider the following example of calculating two results concurrently: ~~~~ -# use core::task::spawn; -# use core::comm::{stream, Port, Chan}; +# use std::task::spawn; +# use std::comm::{stream, Port, Chan}; let (port, chan): (Port, Chan) = stream(); @@ -169,7 +169,7 @@ stream for sending and receiving integers (the left-hand side of the `let`, a tuple into its component parts). ~~~~ -# use core::comm::{stream, Chan, Port}; +# use std::comm::{stream, Chan, Port}; let (port, chan): (Port, Chan) = stream(); ~~~~ @@ -178,8 +178,8 @@ which will wait to receive the data on the port. The next statement spawns the child task. ~~~~ -# use core::task::spawn; -# use core::comm::stream; +# use std::task::spawn; +# use std::comm::stream; # fn some_expensive_computation() -> int { 42 } # let (port, chan) = stream(); do spawn || { @@ -199,7 +199,7 @@ computation, then waits for the child's result to arrive on the port: ~~~~ -# use core::comm::{stream}; +# use std::comm::{stream}; # fn some_other_expensive_computation() {} # let (port, chan) = stream::(); # chan.send(0); @@ -214,8 +214,8 @@ example needed to compute multiple results across a number of tasks? The following program is ill-typed: ~~~ {.xfail-test} -# use core::task::{spawn}; -# use core::comm::{stream, Port, Chan}; +# use std::task::{spawn}; +# use std::comm::{stream, Port, Chan}; # fn some_expensive_computation() -> int { 42 } let (port, chan) = stream(); @@ -234,8 +234,8 @@ Instead we can use a `SharedChan`, a type that allows a single `Chan` to be shared by multiple senders. ~~~ -# use core::task::spawn; -# use core::comm::{stream, SharedChan}; +# use std::task::spawn; +# use std::comm::{stream, SharedChan}; let (port, chan) = stream(); let chan = SharedChan::new(chan); @@ -267,8 +267,8 @@ illustrate the point. For reference, written with multiple streams, it might look like the example below. ~~~ -# use core::task::spawn; -# use core::comm::stream; +# use std::task::spawn; +# use std::comm::stream; // Create a vector of ports, one for each child task let ports = do vec::from_fn(3) |init_val| { @@ -285,7 +285,7 @@ let result = ports.foldl(0, |accum, port| *accum + port.recv() ); ~~~ ## Futures -With `std::future`, rust has a mechanism for requesting a computation and getting the result +With `extra::future`, rust has a mechanism for requesting a computation and getting the result later. The basic example below illustrates this. @@ -296,7 +296,7 @@ fn fib(n: uint) -> uint { 12586269025 } -let mut delayed_fib = std::future::spawn (|| fib(50) ); +let mut delayed_fib = extra::future::spawn (|| fib(50) ); make_a_sandwich(); println(fmt!("fib(50) = %?", delayed_fib.get())) ~~~ @@ -319,7 +319,7 @@ fn partial_sum(start: uint) -> f64 { } fn main() { - let mut futures = vec::from_fn(1000, |ind| do std::future::spawn { partial_sum(ind) }); + let mut futures = vec::from_fn(1000, |ind| do extra::future::spawn { partial_sum(ind) }); let mut final_res = 0f64; for futures.each_mut |ft| { @@ -344,7 +344,7 @@ All tasks are, by default, _linked_ to each other. That means that the fates of all tasks are intertwined: if one fails, so do all the others. ~~~ -# use core::task::spawn; +# use std::task::spawn; # fn do_some_work() { loop { task::yield() } } # do task::try { // Create a child task that fails @@ -384,7 +384,7 @@ enum. If the child task terminates successfully, `try` will return an `Ok` result; if the child task fails, `try` will return an `Error` result. -[`Result`]: core/result.html +[`Result`]: std/result.html > ***Note:*** A failed task does not currently produce a useful error > value (`try` always returns `Err(())`). In the @@ -428,8 +428,8 @@ internally, with additional logic to wait for the child task to finish before returning. Hence: ~~~ -# use core::comm::{stream, Chan, Port}; -# use core::task::{spawn, try}; +# use std::comm::{stream, Chan, Port}; +# use std::task::{spawn, try}; # fn sleep_forever() { loop { task::yield() } } # do task::try { let (receiver, sender): (Port, Chan) = stream(); @@ -493,7 +493,7 @@ fail!(); A very common thing to do is to spawn a child task where the parent and child both need to exchange messages with each other. The -function `std::comm::DuplexStream()` supports this pattern. We'll +function `extra::comm::DuplexStream()` supports this pattern. We'll look briefly at how to use it. To see how `DuplexStream()` works, we will create a child task @@ -502,7 +502,7 @@ the string in response. The child terminates when it receives `0`. Here is the function that implements the child task: ~~~~ -# use std::comm::DuplexStream; +# use extra::comm::DuplexStream; fn stringifier(channel: &DuplexStream<~str, uint>) { let mut value: uint; loop { @@ -524,8 +524,8 @@ response itself is simply the stringified version of the received value, Here is the code for the parent task: ~~~~ -# use core::task::spawn; -# use std::comm::DuplexStream; +# use std::task::spawn; +# use extra::comm::DuplexStream; # fn stringifier(channel: &DuplexStream<~str, uint>) { # let mut value: uint; # loop { diff --git a/doc/tutorial.md b/doc/tutorial.md index cb7caeeb8109f..ad9431ef60ca9 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -730,7 +730,7 @@ fn point_from_direction(dir: Direction) -> Point { Enum variants may also be structs. For example: ~~~~ -# use core::float; +# use std::float; # struct Point { x: float, y: float } # fn square(x: float) -> float { x * x } enum Shape { @@ -1366,11 +1366,11 @@ let exchange_crayons: ~str = ~"Black, BlizzardBlue, Blue"; ~~~ Both vectors and strings support a number of useful -[methods](#functions-and-methods), defined in [`core::vec`] -and [`core::str`]. Here are some examples. +[methods](#functions-and-methods), defined in [`std::vec`] +and [`std::str`]. Here are some examples. -[`core::vec`]: core/vec.html -[`core::str`]: core/str.html +[`std::vec`]: std/vec.html +[`std::str`]: std/str.html ~~~ # enum Crayon { @@ -1583,7 +1583,7 @@ words, it is a function that takes an owned closure that takes no arguments. ~~~~ -use core::task::spawn; +use std::task::spawn; do spawn() || { debug!("I'm a task, whatever"); @@ -1595,7 +1595,7 @@ lists back to back. Since that is so unsightly, empty argument lists may be omitted from `do` expressions. ~~~~ -# use core::task::spawn; +# use std::task::spawn; do spawn { debug!("Kablam!"); } @@ -1629,7 +1629,7 @@ fn each(v: &[int], op: &fn(v: &int) -> bool) { And using this function to iterate over a vector: ~~~~ -# use each = core::vec::each; +# use each = std::vec::each; each([2, 4, 8, 5, 16], |n| { if *n % 2 != 0 { println("found odd number!"); @@ -1645,7 +1645,7 @@ out of the loop, you just write `break`. To skip ahead to the next iteration, write `loop`. ~~~~ -# use each = core::vec::each; +# use each = std::vec::each; for each([2, 4, 8, 5, 16]) |n| { if *n % 2 != 0 { println("found odd number!"); @@ -1660,7 +1660,7 @@ normally allowed in closures, in a block that appears as the body of a the enclosing function, not just the loop body. ~~~~ -# use each = core::vec::each; +# use each = std::vec::each; fn contains(v: &[int], elt: int) -> bool { for each(v) |x| { if (*x == elt) { return true; } @@ -1675,7 +1675,7 @@ In these situations it can be convenient to lean on Rust's argument patterns to bind `x` to the actual value, not the pointer. ~~~~ -# use each = core::vec::each; +# use each = std::vec::each; # fn contains(v: &[int], elt: int) -> bool { for each(v) |&x| { if (x == elt) { return true; } @@ -1810,8 +1810,8 @@ impl Circle { To call such a method, just prefix it with the type name and a double colon: ~~~~ -# use core::float::consts::pi; -# use core::float::sqrt; +# use std::float::consts::pi; +# use std::float::sqrt; struct Circle { radius: float } impl Circle { fn new(area: float) -> Circle { Circle { radius: sqrt(area / pi) } } @@ -1857,7 +1857,7 @@ illegal to copy and pass by value. Generic `type`, `struct`, and `enum` declarations follow the same pattern: ~~~~ -# use core::hashmap::HashMap; +# use std::hashmap::HashMap; type Set = HashMap; struct Stack { @@ -2081,8 +2081,8 @@ name and a double colon. The compiler uses type inference to decide which implementation to use. ~~~~ -# use core::float::consts::pi; -# use core::float::sqrt; +# use std::float::consts::pi; +# use std::float::sqrt; trait Shape { fn new(area: float) -> Self; } struct Circle { radius: float } struct Square { length: float } @@ -2238,8 +2238,8 @@ trait Circle : Shape { fn radius(&self) -> float; } Now, we can implement `Circle` on a type only if we also implement `Shape`. ~~~~ -# use core::float::consts::pi; -# use core::float::sqrt; +# use std::float::consts::pi; +# use std::float::sqrt; # trait Shape { fn area(&self) -> float; } # trait Circle : Shape { fn radius(&self) -> float; } # struct Point { x: float, y: float } @@ -2274,8 +2274,8 @@ fn radius_times_area(c: T) -> float { Likewise, supertrait methods may also be called on trait objects. ~~~ {.xfail-test} -# use core::float::consts::pi; -# use core::float::sqrt; +# use std::float::consts::pi; +# use std::float::sqrt; # trait Shape { fn area(&self) -> float; } # trait Circle : Shape { fn radius(&self) -> float; } # struct Point { x: float, y: float } @@ -2292,7 +2292,7 @@ let nonsense = mycircle.radius() * mycircle.area(); ## Deriving implementations for traits -A small number of traits in `core` and `std` can have implementations +A small number of traits in `std` and `std` can have implementations that can be automatically derived. These instances are specified by placing the `deriving` attribute on a data type declaration. For example, the following will mean that `Circle` has an implementation @@ -2541,17 +2541,17 @@ as well as an inscrutable string of alphanumerics. These are both part of Rust's library versioning scheme. The alphanumerics are a hash representing the crate metadata. -## The core library +## The std library -The Rust core library provides runtime features required by the language, +The Rust std library provides runtime features required by the language, including the task scheduler and memory allocators, as well as library support for Rust built-in types, platform abstractions, and other commonly used features. -[`core`] includes modules corresponding to each of the integer types, each of +[`std`] includes modules corresponding to each of the integer types, each of the floating point types, the [`bool`] type, [tuples], [characters], [strings], [vectors], [managed boxes], [owned boxes], -and unsafe and borrowed [pointers]. Additionally, `core` provides +and unsafe and borrowed [pointers]. Additionally, `std` provides some pervasive types ([`option`] and [`result`]), [task] creation and [communication] primitives, platform abstractions ([`os`] and [`path`]), basic @@ -2561,47 +2561,47 @@ common traits ([`kinds`], [`ops`], [`cmp`], [`num`], ### Core injection and the Rust prelude -`core` is imported at the topmost level of every crate by default, as +`std` is imported at the topmost level of every crate by default, as if the first line of each crate was - extern mod core; + extern mod std; -This means that the contents of core can be accessed from from any context -with the `core::` path prefix, as in `use core::vec`, `use core::task::spawn`, +This means that the contents of std can be accessed from from any context +with the `std::` path prefix, as in `use std::vec`, `use std::task::spawn`, etc. -Additionally, `core` contains a `prelude` module that reexports many of the -most common core modules, types and traits. The contents of the prelude are +Additionally, `std` contains a `prelude` module that reexports many of the +most common std modules, types and traits. The contents of the prelude are imported into every *module* by default. Implicitly, all modules behave as if they contained the following prologue: - use core::prelude::*; - -[`core`]: core/index.html -[`bool`]: core/bool.html -[tuples]: core/tuple.html -[characters]: core/char.html -[strings]: core/str.html -[vectors]: core/vec.html -[managed boxes]: core/managed.html -[owned boxes]: core/owned.html -[pointers]: core/ptr.html -[`option`]: core/option.html -[`result`]: core/result.html -[task]: core/task.html -[communication]: core/comm.html -[`os`]: core/os.html -[`path`]: core/path.html -[`io`]: core/io.html -[containers]: core/container.html -[`hashmap`]: core/hashmap.html -[`kinds`]: core/kinds.html -[`ops`]: core/ops.html -[`cmp`]: core/cmp.html -[`num`]: core/num.html -[`to_str`]: core/to_str.html -[`clone`]: core/clone.html -[`libc`]: core/libc.html + use std::prelude::*; + +[`std`]: std/index.html +[`bool`]: std/bool.html +[tuples]: std/tuple.html +[characters]: std/char.html +[strings]: std/str.html +[vectors]: std/vec.html +[managed boxes]: std/managed.html +[owned boxes]: std/owned.html +[pointers]: std/ptr.html +[`option`]: std/option.html +[`result`]: std/result.html +[task]: std/task.html +[communication]: std/comm.html +[`os`]: std/os.html +[`path`]: std/path.html +[`io`]: std/io.html +[containers]: std/container.html +[`hashmap`]: std/hashmap.html +[`kinds`]: std/kinds.html +[`ops`]: std/ops.html +[`cmp`]: std/cmp.html +[`num`]: std/num.html +[`to_str`]: std/to_str.html +[`clone`]: std/clone.html +[`libc`]: std/libc.html # What next? diff --git a/src/etc/extract-tests.py b/src/etc/extract-tests.py index 12740a5616b8d..0260789adfc23 100644 --- a/src/etc/extract-tests.py +++ b/src/etc/extract-tests.py @@ -57,8 +57,8 @@ if not ignore: if not re.search(r"\bfn main\b", block): block = "fn main() {\n" + block + "\n}\n" - if not re.search(r"\bextern mod std\b", block): - block = "extern mod std;\n" + block + if not re.search(r"\bextern mod extra\b", block): + block = "extern mod extra;\n" + block block = """#[ forbid(ctypes) ]; #[ forbid(deprecated_pattern) ]; #[ forbid(implicit_copies) ]; diff --git a/src/librusti/rusti.rc b/src/librusti/rusti.rc index c79714bba3682..d99e6f5085d46 100644 --- a/src/librusti/rusti.rc +++ b/src/librusti/rusti.rc @@ -431,6 +431,7 @@ pub fn main() { #[cfg(test)] mod tests { use super::*; + use core::io; fn repl() -> Repl { Repl { diff --git a/src/librustpkg/tests.rs b/src/librustpkg/tests.rs index 2574ba4e76228..55bc302d9a17e 100644 --- a/src/librustpkg/tests.rs +++ b/src/librustpkg/tests.rs @@ -13,6 +13,7 @@ use context::Ctx; use core::hashmap::HashMap; use core::path::Path; +use core::prelude::*; use std::tempfile::mkdtemp; use util::{PkgId, default_version}; use path_util::{target_executable_in_workspace, target_library_in_workspace, From d213443a67c8dbef562ad207c62308e57c230511 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 23 May 2013 15:22:04 -0700 Subject: [PATCH 204/248] rustc: Check for null before dropping ~objects. #5192 --- src/librustc/middle/trans/glue.rs | 31 ++++++++++++++----------- src/test/run-pass/unique-object-move.rs | 24 +++++++++++++++++++ 2 files changed, 41 insertions(+), 14 deletions(-) create mode 100644 src/test/run-pass/unique-object-move.rs diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index d8c851127478e..ed46ab0ce3797 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -546,20 +546,23 @@ pub fn make_drop_glue(bcx: block, v0: ValueRef, t: ty::t) { decr_refcnt_maybe_free(bcx, llbox, ty::mk_opaque_box(ccx.tcx)) } ty::ty_trait(_, _, ty::UniqTraitStore, _) => { - let lluniquevalue = GEPi(bcx, v0, [0, abi::trt_field_box]); - let llvtable = Load(bcx, GEPi(bcx, v0, [0, abi::trt_field_vtable])); - - // Cast the vtable to a pointer to a pointer to a tydesc. - let llvtable = PointerCast(bcx, - llvtable, - T_ptr(T_ptr(ccx.tydesc_type))); - let lltydesc = Load(bcx, llvtable); - call_tydesc_glue_full(bcx, - lluniquevalue, - lltydesc, - abi::tydesc_field_free_glue, - None); - bcx + let lluniquevalue = GEPi(bcx, v0, [0, abi::trt_field_box]); + // Only drop the value when it is non-null + do with_cond(bcx, IsNotNull(bcx, Load(bcx, lluniquevalue))) |bcx| { + let llvtable = Load(bcx, GEPi(bcx, v0, [0, abi::trt_field_vtable])); + + // Cast the vtable to a pointer to a pointer to a tydesc. + let llvtable = PointerCast(bcx, + llvtable, + T_ptr(T_ptr(ccx.tydesc_type))); + let lltydesc = Load(bcx, llvtable); + call_tydesc_glue_full(bcx, + lluniquevalue, + lltydesc, + abi::tydesc_field_free_glue, + None); + bcx + } } ty::ty_opaque_closure_ptr(ck) => { closure::make_opaque_cbox_drop_glue(bcx, ck, v0) diff --git a/src/test/run-pass/unique-object-move.rs b/src/test/run-pass/unique-object-move.rs new file mode 100644 index 0000000000000..540de1652138b --- /dev/null +++ b/src/test/run-pass/unique-object-move.rs @@ -0,0 +1,24 @@ +// Copyright 2012 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. + +// Issue #5192 + +pub trait EventLoop { } + +pub struct UvEventLoop { + uvio: int +} + +impl EventLoop for UvEventLoop { } + +pub fn main() { + let loop_: ~EventLoop = ~UvEventLoop { uvio: 0 } as ~EventLoop; + let loop2_ = loop_; +} \ No newline at end of file From 7f642f3d85c8c9886983cbabadedf4a2dbbd6fc6 Mon Sep 17 00:00:00 2001 From: Brian Anderson Date: Thu, 23 May 2013 15:36:38 -0700 Subject: [PATCH 205/248] rustc: Give glue symbols meaningful names Instead of `glue_drop1234` it's `Type::::glue_drop1234` Haven't done any performance testing. --- src/librustc/back/link.rs | 11 +++++++++++ src/librustc/middle/trans/glue.rs | 14 ++------------ 2 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index f999c20a7d0ec..6ae1893d37275 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -721,6 +721,17 @@ pub fn mangle_internal_name_by_type_only(ccx: @CrateContext, path_name(ccx.sess.ident_of(hash))]); } +pub fn mangle_internal_name_by_type_and_seq(ccx: @CrateContext, + t: ty::t, + name: &str) -> ~str { + let s = ppaux::ty_to_str(ccx.tcx, t); + let hash = get_symbol_hash(ccx, t); + return mangle(ccx.sess, + ~[path_name(ccx.sess.ident_of(s)), + path_name(ccx.sess.ident_of(hash)), + path_name((ccx.names)(name))]); +} + pub fn mangle_internal_name_by_path_and_seq(ccx: @CrateContext, path: path, flav: &str) -> ~str { diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index 048acdc07a120..aa8e05235f0db 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -669,12 +669,7 @@ pub fn declare_tydesc(ccx: @CrateContext, t: ty::t) -> @mut tydesc_info { let llsize = llsize_of(ccx, llty); let llalign = llalign_of(ccx, llty); let addrspace = declare_tydesc_addrspace(ccx, t); - // FIXME #6574: this triggers duplicate LLVM symbols - let name = @(if false /*ccx.sess.opts.debuginfo*/ { - mangle_internal_name_by_type_only(ccx, t, "tydesc") - } else { - mangle_internal_name_by_seq(ccx, "tydesc") - }); + let name = @mangle_internal_name_by_type_and_seq(ccx, t, "tydesc"); note_unique_llvm_symbol(ccx, name); debug!("+++ declare_tydesc %s %s", ppaux::ty_to_str(ccx.tcx, t), *name); let gvar = str::as_c_str(*name, |buf| { @@ -703,12 +698,7 @@ pub fn declare_generic_glue(ccx: @CrateContext, t: ty::t, llfnty: TypeRef, name: ~str) -> ValueRef { let _icx = ccx.insn_ctxt("declare_generic_glue"); let name = name; - // FIXME #6574 this triggers duplicate LLVM symbols - let fn_nm = @(if false /*ccx.sess.opts.debuginfo*/ { - mangle_internal_name_by_type_only(ccx, t, (~"glue_" + name)) - } else { - mangle_internal_name_by_seq(ccx, (~"glue_" + name)) - }); + let fn_nm = @mangle_internal_name_by_type_and_seq(ccx, t, (~"glue_" + name)); debug!("%s is for type %s", *fn_nm, ppaux::ty_to_str(ccx.tcx, t)); note_unique_llvm_symbol(ccx, fn_nm); let llfn = decl_cdecl_fn(ccx.llmod, *fn_nm, llfnty); From 1965d7295775b93d56f6daea96a6d2f6e8f242da Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Wed, 22 May 2013 17:02:14 -0700 Subject: [PATCH 206/248] core: remove iter_bytes helper functions --- src/librustc/middle/trans/common.rs | 18 +- src/librustc/middle/ty.rs | 155 ++++++++++-------- .../middle/typeck/infer/region_inference.rs | 21 ++- src/libstd/to_bytes.rs | 36 ---- src/libsyntax/ast.rs | 22 ++- src/libsyntax/ast_util.rs | 2 +- src/libsyntax/codemap.rs | 12 +- 7 files changed, 137 insertions(+), 129 deletions(-) diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index fac155a70024d..d56690f4b6a48 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -1367,13 +1367,21 @@ pub type mono_id = @mono_id_; impl to_bytes::IterBytes for mono_param_id { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { - mono_precise(t, ref mids) => - to_bytes::iter_bytes_3(&0u8, &ty::type_id(t), mids, lsb0, f), + mono_precise(t, ref mids) => { + 0u8.iter_bytes(lsb0, f) && + ty::type_id(t).iter_bytes(lsb0, f) && + mids.iter_bytes(lsb0, f) + } mono_any => 1u8.iter_bytes(lsb0, f), - mono_repr(ref a, ref b, ref c, ref d) => - to_bytes::iter_bytes_5(&2u8, a, b, c, d, lsb0, f) + mono_repr(ref a, ref b, ref c, ref d) => { + 2u8.iter_bytes(lsb0, f) && + a.iter_bytes(lsb0, f) && + b.iter_bytes(lsb0, f) && + c.iter_bytes(lsb0, f) && + d.iter_bytes(lsb0, f) + } } } } @@ -1386,7 +1394,7 @@ impl to_bytes::IterBytes for MonoDataClass { impl to_bytes::IterBytes for mono_id_ { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.def, &self.params, lsb0, f) + self.def.iter_bytes(lsb0, f) && self.params.iter_bytes(lsb0, f) } } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 761096a019e20..621ce48a4fd08 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -137,7 +137,9 @@ type creader_cache = @mut HashMap; impl to_bytes::IterBytes for creader_cache_key { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_3(&self.cnum, &self.pos, &self.len, lsb0, f) + self.cnum.iter_bytes(lsb0, f) && + self.pos.iter_bytes(lsb0, f) && + self.len.iter_bytes(lsb0, f) } } @@ -392,14 +394,19 @@ pub struct FnSig { impl to_bytes::IterBytes for BareFnTy { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_3(&self.purity, &self.abis, &self.sig, lsb0, f) + self.purity.iter_bytes(lsb0, f) && + self.abis.iter_bytes(lsb0, f) && + self.sig.iter_bytes(lsb0, f) } } impl to_bytes::IterBytes for ClosureTy { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_5(&self.purity, &self.sigil, &self.onceness, - &self.region, &self.sig, lsb0, f) + self.purity.iter_bytes(lsb0, f) && + self.sigil.iter_bytes(lsb0, f) && + self.onceness.iter_bytes(lsb0, f) && + self.region.iter_bytes(lsb0, f) && + self.sig.iter_bytes(lsb0, f) } } @@ -717,9 +724,15 @@ pub enum InferTy { impl to_bytes::IterBytes for InferTy { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { - TyVar(ref tv) => to_bytes::iter_bytes_2(&0u8, tv, lsb0, f), - IntVar(ref iv) => to_bytes::iter_bytes_2(&1u8, iv, lsb0, f), - FloatVar(ref fv) => to_bytes::iter_bytes_2(&2u8, fv, lsb0, f), + TyVar(ref tv) => { + 0u8.iter_bytes(lsb0, f) && tv.iter_bytes(lsb0, f) + } + IntVar(ref iv) => { + 1u8.iter_bytes(lsb0, f) && iv.iter_bytes(lsb0, f) + } + FloatVar(ref fv) => { + 2u8.iter_bytes(lsb0, f) && fv.iter_bytes(lsb0, f) + } } } } @@ -733,8 +746,12 @@ pub enum InferRegion { impl to_bytes::IterBytes for InferRegion { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { - ReVar(ref rv) => to_bytes::iter_bytes_2(&0u8, rv, lsb0, f), - ReSkolemized(ref v, _) => to_bytes::iter_bytes_2(&1u8, v, lsb0, f) + ReVar(ref rv) => { + 0u8.iter_bytes(lsb0, f) && rv.iter_bytes(lsb0, f) + } + ReSkolemized(ref v, _) => { + 1u8.iter_bytes(lsb0, f) && v.iter_bytes(lsb0, f) + } } } } @@ -2626,119 +2643,115 @@ impl cmp::TotalEq for bound_region { impl to_bytes::IterBytes for vstore { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { - vstore_fixed(ref u) => - to_bytes::iter_bytes_2(&0u8, u, lsb0, f), - - vstore_uniq => 1u8.iter_bytes(lsb0, f), - vstore_box => 2u8.iter_bytes(lsb0, f), + vstore_fixed(ref u) => { + 0u8.iter_bytes(lsb0, f) && u.iter_bytes(lsb0, f) + } + vstore_uniq => 1u8.iter_bytes(lsb0, f), + vstore_box => 2u8.iter_bytes(lsb0, f), - vstore_slice(ref r) => - to_bytes::iter_bytes_2(&3u8, r, lsb0, f), + vstore_slice(ref r) => { + 3u8.iter_bytes(lsb0, f) && r.iter_bytes(lsb0, f) + } } } } impl to_bytes::IterBytes for substs { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_3(&self.self_r, - &self.self_ty, - &self.tps, lsb0, f) + self.self_r.iter_bytes(lsb0, f) && + self.self_ty.iter_bytes(lsb0, f) && + self.tps.iter_bytes(lsb0, f) } } impl to_bytes::IterBytes for mt { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.ty, - &self.mutbl, lsb0, f) + self.ty.iter_bytes(lsb0, f) && self.mutbl.iter_bytes(lsb0, f) } } impl to_bytes::IterBytes for field { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.ident, - &self.mt, lsb0, f) + self.ident.iter_bytes(lsb0, f) && self.mt.iter_bytes(lsb0, f) } } impl to_bytes::IterBytes for FnSig { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.inputs, - &self.output, - lsb0, f) + self.inputs.iter_bytes(lsb0, f) && self.output.iter_bytes(lsb0, f) } } impl to_bytes::IterBytes for sty { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { - ty_nil => 0u8.iter_bytes(lsb0, f), - ty_bool => 1u8.iter_bytes(lsb0, f), + ty_nil => 0u8.iter_bytes(lsb0, f), + ty_bool => 1u8.iter_bytes(lsb0, f), - ty_int(ref t) => - to_bytes::iter_bytes_2(&2u8, t, lsb0, f), + ty_int(ref t) => 2u8.iter_bytes(lsb0, f) && t.iter_bytes(lsb0, f), - ty_uint(ref t) => - to_bytes::iter_bytes_2(&3u8, t, lsb0, f), + ty_uint(ref t) => 3u8.iter_bytes(lsb0, f) && t.iter_bytes(lsb0, f), - ty_float(ref t) => - to_bytes::iter_bytes_2(&4u8, t, lsb0, f), + ty_float(ref t) => 4u8.iter_bytes(lsb0, f) && t.iter_bytes(lsb0, f), - ty_estr(ref v) => - to_bytes::iter_bytes_2(&5u8, v, lsb0, f), + ty_estr(ref v) => 5u8.iter_bytes(lsb0, f) && v.iter_bytes(lsb0, f), - ty_enum(ref did, ref substs) => - to_bytes::iter_bytes_3(&6u8, did, substs, lsb0, f), + ty_enum(ref did, ref substs) => { + 6u8.iter_bytes(lsb0, f) && + did.iter_bytes(lsb0, f) && + substs.iter_bytes(lsb0, f) + } - ty_box(ref mt) => - to_bytes::iter_bytes_2(&7u8, mt, lsb0, f), + ty_box(ref mt) => 7u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f), - ty_evec(ref mt, ref v) => - to_bytes::iter_bytes_3(&8u8, mt, v, lsb0, f), + ty_evec(ref mt, ref v) => { + 8u8.iter_bytes(lsb0, f) && + mt.iter_bytes(lsb0, f) && + v.iter_bytes(lsb0, f) + } - ty_unboxed_vec(ref mt) => - to_bytes::iter_bytes_2(&9u8, mt, lsb0, f), + ty_unboxed_vec(ref mt) => 9u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f), - ty_tup(ref ts) => - to_bytes::iter_bytes_2(&10u8, ts, lsb0, f), + ty_tup(ref ts) => 10u8.iter_bytes(lsb0, f) && ts.iter_bytes(lsb0, f), - ty_bare_fn(ref ft) => - to_bytes::iter_bytes_2(&12u8, ft, lsb0, f), + ty_bare_fn(ref ft) => 12u8.iter_bytes(lsb0, f) && ft.iter_bytes(lsb0, f), - ty_self(ref did) => to_bytes::iter_bytes_2(&13u8, did, lsb0, f), + ty_self(ref did) => 13u8.iter_bytes(lsb0, f) && did.iter_bytes(lsb0, f), - ty_infer(ref v) => - to_bytes::iter_bytes_2(&14u8, v, lsb0, f), + ty_infer(ref v) => 14u8.iter_bytes(lsb0, f) && v.iter_bytes(lsb0, f), - ty_param(ref p) => - to_bytes::iter_bytes_2(&15u8, p, lsb0, f), + ty_param(ref p) => 15u8.iter_bytes(lsb0, f) && p.iter_bytes(lsb0, f), - ty_type => 16u8.iter_bytes(lsb0, f), - ty_bot => 17u8.iter_bytes(lsb0, f), + ty_type => 16u8.iter_bytes(lsb0, f), + ty_bot => 17u8.iter_bytes(lsb0, f), - ty_ptr(ref mt) => - to_bytes::iter_bytes_2(&18u8, mt, lsb0, f), + ty_ptr(ref mt) => 18u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f), - ty_uniq(ref mt) => - to_bytes::iter_bytes_2(&19u8, mt, lsb0, f), + ty_uniq(ref mt) => 19u8.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f), - ty_trait(ref did, ref substs, ref v, ref mutbl) => - to_bytes::iter_bytes_5(&20u8, did, substs, v, mutbl, lsb0, f), + ty_trait(ref did, ref substs, ref v, ref mutbl) => { + 20u8.iter_bytes(lsb0, f) && + did.iter_bytes(lsb0, f) && + substs.iter_bytes(lsb0, f) && + v.iter_bytes(lsb0, f) && + mutbl.iter_bytes(lsb0, f) + } - ty_opaque_closure_ptr(ref ck) => - to_bytes::iter_bytes_2(&21u8, ck, lsb0, f), + ty_opaque_closure_ptr(ref ck) => 21u8.iter_bytes(lsb0, f) && ck.iter_bytes(lsb0, f), - ty_opaque_box => 22u8.iter_bytes(lsb0, f), + ty_opaque_box => 22u8.iter_bytes(lsb0, f), - ty_struct(ref did, ref substs) => - to_bytes::iter_bytes_3(&23u8, did, substs, lsb0, f), + ty_struct(ref did, ref substs) => { + 23u8.iter_bytes(lsb0, f) && did.iter_bytes(lsb0, f) && substs.iter_bytes(lsb0, f) + } - ty_rptr(ref r, ref mt) => - to_bytes::iter_bytes_3(&24u8, r, mt, lsb0, f), + ty_rptr(ref r, ref mt) => { + 24u8.iter_bytes(lsb0, f) && r.iter_bytes(lsb0, f) && mt.iter_bytes(lsb0, f) + } - ty_err => 25u8.iter_bytes(lsb0, f), + ty_err => 25u8.iter_bytes(lsb0, f), - ty_closure(ref ct) => - to_bytes::iter_bytes_2(&26u8, ct, lsb0, f), + ty_closure(ref ct) => 26u8.iter_bytes(lsb0, f) && ct.iter_bytes(lsb0, f), } } } diff --git a/src/librustc/middle/typeck/infer/region_inference.rs b/src/librustc/middle/typeck/infer/region_inference.rs index 14a79108f0646..556fcfeac99a5 100644 --- a/src/librustc/middle/typeck/infer/region_inference.rs +++ b/src/librustc/middle/typeck/infer/region_inference.rs @@ -564,14 +564,23 @@ enum Constraint { impl to_bytes::IterBytes for Constraint { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { - ConstrainVarSubVar(ref v0, ref v1) => - to_bytes::iter_bytes_3(&0u8, v0, v1, lsb0, f), + ConstrainVarSubVar(ref v0, ref v1) => { + 0u8.iter_bytes(lsb0, f) && + v0.iter_bytes(lsb0, f) && + v1.iter_bytes(lsb0, f) + } - ConstrainRegSubVar(ref ra, ref va) => - to_bytes::iter_bytes_3(&1u8, ra, va, lsb0, f), + ConstrainRegSubVar(ref ra, ref va) => { + 1u8.iter_bytes(lsb0, f) && + ra.iter_bytes(lsb0, f) && + va.iter_bytes(lsb0, f) + } - ConstrainVarSubReg(ref va, ref ra) => - to_bytes::iter_bytes_3(&2u8, va, ra, lsb0, f) + ConstrainVarSubReg(ref va, ref ra) => { + 2u8.iter_bytes(lsb0, f) && + va.iter_bytes(lsb0, f) && + ra.iter_bytes(lsb0, f) + } } } } diff --git a/src/libstd/to_bytes.rs b/src/libstd/to_bytes.rs index 5b66e94c1b456..20b45dfb2cc6a 100644 --- a/src/libstd/to_bytes.rs +++ b/src/libstd/to_bytes.rs @@ -236,42 +236,6 @@ impl IterBytes for @[A] { } } -// NOTE: remove all of these after a snapshot, the new for-loop iteration -// protocol makes these unnecessary. - -#[inline(always)] -pub fn iter_bytes_2(a: &A, b: &B, - lsb0: bool, z: Cb) -> bool { - a.iter_bytes(lsb0, z) && b.iter_bytes(lsb0, z) -} - -pub fn iter_bytes_3(a: &A, b: &B, c: &C, lsb0: bool, z: Cb) -> bool { - a.iter_bytes(lsb0, z) && b.iter_bytes(lsb0, z) && c.iter_bytes(lsb0, z) -} - -pub fn iter_bytes_4(a: &A, b: &B, c: &C, - d: &D, - lsb0: bool, z: Cb) -> bool { - a.iter_bytes(lsb0, z) && b.iter_bytes(lsb0, z) && c.iter_bytes(lsb0, z) && - d.iter_bytes(lsb0, z) -} - -pub fn iter_bytes_5(a: &A, b: &B, c: &C, - d: &D, e: &E, - lsb0: bool, z: Cb) -> bool { - a.iter_bytes(lsb0, z) && b.iter_bytes(lsb0, z) && c.iter_bytes(lsb0, z) && - d.iter_bytes(lsb0, z) && e.iter_bytes(lsb0, z) -} - impl<'self> IterBytes for &'self str { #[inline(always)] fn iter_bytes(&self, _lsb0: bool, f: Cb) -> bool { diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index e5771a5db2e95..9ab6f13bb4bcf 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -112,7 +112,9 @@ pub struct Lifetime { impl to_bytes::IterBytes for Lifetime { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_3(&self.id, &self.span, &self.ident, lsb0, f) + self.id.iter_bytes(lsb0, f) && + self.span.iter_bytes(lsb0, f) && + self.ident.iter_bytes(lsb0, f) } } @@ -266,7 +268,9 @@ impl to_bytes::IterBytes for binding_mode { match *self { bind_by_copy => 0u8.iter_bytes(lsb0, f), - bind_by_ref(ref m) => to_bytes::iter_bytes_2(&1u8, m, lsb0, f), + bind_by_ref(ref m) => { + 1u8.iter_bytes(lsb0, f) && m.iter_bytes(lsb0, f) + } bind_infer => 2u8.iter_bytes(lsb0, f), } @@ -788,7 +792,7 @@ pub enum ty_ { impl to_bytes::IterBytes for Ty { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.span.lo, &self.span.hi, lsb0, f) + self.span.lo.iter_bytes(lsb0, f) && self.span.hi.iter_bytes(lsb0, f) } } @@ -876,9 +880,15 @@ impl to_bytes::IterBytes for explicit_self_ { match *self { sty_static => 0u8.iter_bytes(lsb0, f), sty_value => 1u8.iter_bytes(lsb0, f), - sty_region(ref lft, ref mutbl) => to_bytes::iter_bytes_3(&2u8, &lft, mutbl, lsb0, f), - sty_box(ref mutbl) => to_bytes::iter_bytes_2(&3u8, mutbl, lsb0, f), - sty_uniq(ref mutbl) => to_bytes::iter_bytes_2(&4u8, mutbl, lsb0, f), + sty_region(ref lft, ref mutbl) => { + 2u8.iter_bytes(lsb0, f) && lft.iter_bytes(lsb0, f) && mutbl.iter_bytes(lsb0, f) + } + sty_box(ref mutbl) => { + 3u8.iter_bytes(lsb0, f) && mutbl.iter_bytes(lsb0, f) + } + sty_uniq(ref mutbl) => { + 4u8.iter_bytes(lsb0, f) && mutbl.iter_bytes(lsb0, f) + } } } } diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 283203059c888..59743b6e8927f 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -197,7 +197,7 @@ pub fn is_call_expr(e: @expr) -> bool { impl to_bytes::IterBytes for def_id { #[inline(always)] fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.crate, &self.node, lsb0, f) + self.crate.iter_bytes(lsb0, f) && self.node.iter_bytes(lsb0, f) } } diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 77a6137cd1719..42117e3b73cf3 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -140,7 +140,9 @@ impl Decodable for span { impl to_bytes::IterBytes for span { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_3(&self.lo, &self.hi, &self.expn_info, lsb0, f) + self.lo.iter_bytes(lsb0, f) && + self.hi.iter_bytes(lsb0, f) && + self.expn_info.iter_bytes(lsb0, f) } } @@ -193,7 +195,7 @@ pub struct NameAndSpan {name: ~str, span: Option} impl to_bytes::IterBytes for NameAndSpan { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.name, &self.span, lsb0, f) + self.name.iter_bytes(lsb0, f) && self.span.iter_bytes(lsb0, f) } } @@ -204,7 +206,7 @@ pub struct CallInfo { impl to_bytes::IterBytes for CallInfo { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { - to_bytes::iter_bytes_2(&self.call_site, &self.callee, lsb0, f) + self.call_site.iter_bytes(lsb0, f) && self.callee.iter_bytes(lsb0, f) } } @@ -216,7 +218,9 @@ pub enum ExpnInfo { impl to_bytes::IterBytes for ExpnInfo { fn iter_bytes(&self, lsb0: bool, f: to_bytes::Cb) -> bool { match *self { - ExpandedFrom(ref call_info) => to_bytes::iter_bytes_2(&0u8, call_info, lsb0, f) + ExpandedFrom(ref call_info) => { + 0u8.iter_bytes(lsb0, f) && call_info.iter_bytes(lsb0, f) + } } } } From dc970c13f476ef086066a47829185ac83645c61f Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 09:39:17 -0700 Subject: [PATCH 207/248] cleanup warnings from libstd --- src/libstd/cast.rs | 1 - src/libstd/hash.rs | 2 +- src/libstd/io.rs | 28 +- src/libstd/num/f32.rs | 1 - src/libstd/num/f64.rs | 1 - src/libstd/num/float.rs | 140 ++++---- src/libstd/num/int-template.rs | 96 +++--- src/libstd/num/uint-template.rs | 64 ++-- src/libstd/os.rs | 46 +-- src/libstd/rand.rs | 18 +- src/libstd/rt/comm.rs | 2 +- src/libstd/rt/io/extensions.rs | 6 +- src/libstd/rt/local.rs | 8 +- src/libstd/rt/sched.rs | 1 - src/libstd/rt/task.rs | 1 - src/libstd/str.rs | 545 ++++++++++++++++---------------- src/libstd/str/ascii.rs | 4 +- src/libstd/vec.rs | 147 ++++----- 18 files changed, 545 insertions(+), 566 deletions(-) diff --git a/src/libstd/cast.rs b/src/libstd/cast.rs index e3336e24a6e1a..cde22afd34a83 100644 --- a/src/libstd/cast.rs +++ b/src/libstd/cast.rs @@ -11,7 +11,6 @@ //! Unsafe casting functions use sys; -use unstable; use unstable::intrinsics; /// Casts the value at `src` to U. The two types must have the same length. diff --git a/src/libstd/hash.rs b/src/libstd/hash.rs index 69312f3a97b8c..f46c8ab7ecc6e 100644 --- a/src/libstd/hash.rs +++ b/src/libstd/hash.rs @@ -488,7 +488,7 @@ mod tests { assert!(f == i && f == v); buf += ~[t as u8]; - stream_inc.input(~[t as u8]); + stream_inc.input([t as u8]); t += 1; } diff --git a/src/libstd/io.rs b/src/libstd/io.rs index aa312742e3ecd..4ce4ea108e58c 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -1839,7 +1839,7 @@ mod tests { { let out: @io::Writer = result::get( - &io::file_writer(tmpfile, ~[io::Create, io::Truncate])); + &io::file_writer(tmpfile, [io::Create, io::Truncate])); out.write_str(frood); } let inp: @io::Reader = result::get(&io::file_reader(tmpfile)); @@ -1850,7 +1850,7 @@ mod tests { #[test] fn test_readchars_empty() { - do io::with_str_reader(~"") |inp| { + do io::with_str_reader("") |inp| { let res : ~[char] = inp.read_chars(128); assert_eq!(res.len(), 0); } @@ -1858,7 +1858,7 @@ mod tests { #[test] fn test_read_line_utf8() { - do io::with_str_reader(~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤") |inp| { + do io::with_str_reader("生锈的汤匙切肉汤hello生锈的汤匙切肉汤") |inp| { let line = inp.read_line(); assert_eq!(line, ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤"); } @@ -1866,15 +1866,15 @@ mod tests { #[test] fn test_read_lines() { - do io::with_str_reader(~"a\nb\nc\n") |inp| { + do io::with_str_reader("a\nb\nc\n") |inp| { assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]); } - do io::with_str_reader(~"a\nb\nc") |inp| { + do io::with_str_reader("a\nb\nc") |inp| { assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]); } - do io::with_str_reader(~"") |inp| { + do io::with_str_reader("") |inp| { assert!(inp.read_lines().is_empty()); } } @@ -1909,7 +1909,7 @@ mod tests { #[test] fn test_readchar() { - do io::with_str_reader(~"生") |inp| { + do io::with_str_reader("生") |inp| { let res : char = inp.read_char(); assert_eq!(res as int, 29983); } @@ -1917,7 +1917,7 @@ mod tests { #[test] fn test_readchar_empty() { - do io::with_str_reader(~"") |inp| { + do io::with_str_reader("") |inp| { let res : char = inp.read_char(); assert_eq!(res as int, -1); } @@ -1966,7 +1966,7 @@ mod tests { #[test] fn file_writer_bad_name() { - match io::file_writer(&Path("?/?"), ~[]) { + match io::file_writer(&Path("?/?"), []) { result::Err(copy e) => { assert!(str::starts_with(e, "error opening")); } @@ -1987,15 +1987,15 @@ mod tests { #[test] fn bytes_buffer_overwrite() { let wr = BytesWriter(); - wr.write(~[0u8, 1u8, 2u8, 3u8]); + wr.write([0u8, 1u8, 2u8, 3u8]); assert!(*wr.bytes == ~[0u8, 1u8, 2u8, 3u8]); wr.seek(-2, SeekCur); - wr.write(~[4u8, 5u8, 6u8, 7u8]); + wr.write([4u8, 5u8, 6u8, 7u8]); assert!(*wr.bytes == ~[0u8, 1u8, 4u8, 5u8, 6u8, 7u8]); wr.seek(-2, SeekEnd); - wr.write(~[8u8]); + wr.write([8u8]); wr.seek(1, SeekSet); - wr.write(~[9u8]); + wr.write([9u8]); assert!(*wr.bytes == ~[0u8, 9u8, 4u8, 5u8, 8u8, 7u8]); } @@ -2085,7 +2085,7 @@ mod tests { } } -#[test] + #[test] fn test_read_write_f32() { let path = Path("tmp/lib-io-test-read-write-f32.tmp"); let f:f32 = 8.1250; diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index d5dc0dd4730e1..c6d183c6fb841 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -951,7 +951,6 @@ impl num::FromStrRadix for f32 { mod tests { use f32::*; use num::*; - use super::*; use prelude::*; #[test] diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index 6e2496e2e4561..262e4176c911d 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -993,7 +993,6 @@ impl num::FromStrRadix for f64 { mod tests { use f64::*; use num::*; - use super::*; use prelude::*; #[test] diff --git a/src/libstd/num/float.rs b/src/libstd/num/float.rs index 681aafaab8884..d04f12f6bd3c6 100644 --- a/src/libstd/num/float.rs +++ b/src/libstd/num/float.rs @@ -1251,101 +1251,101 @@ mod tests { #[test] pub fn test_from_str() { - assert_eq!(from_str(~"3"), Some(3.)); - assert_eq!(from_str(~"3.14"), Some(3.14)); - assert_eq!(from_str(~"+3.14"), Some(3.14)); - assert_eq!(from_str(~"-3.14"), Some(-3.14)); - assert_eq!(from_str(~"2.5E10"), Some(25000000000.)); - assert_eq!(from_str(~"2.5e10"), Some(25000000000.)); - assert_eq!(from_str(~"25000000000.E-10"), Some(2.5)); - assert_eq!(from_str(~"."), Some(0.)); - assert_eq!(from_str(~".e1"), Some(0.)); - assert_eq!(from_str(~".e-1"), Some(0.)); - assert_eq!(from_str(~"5."), Some(5.)); - assert_eq!(from_str(~".5"), Some(0.5)); - assert_eq!(from_str(~"0.5"), Some(0.5)); - assert_eq!(from_str(~"-.5"), Some(-0.5)); - assert_eq!(from_str(~"-5"), Some(-5.)); - assert_eq!(from_str(~"inf"), Some(infinity)); - assert_eq!(from_str(~"+inf"), Some(infinity)); - assert_eq!(from_str(~"-inf"), Some(neg_infinity)); + assert_eq!(from_str("3"), Some(3.)); + assert_eq!(from_str("3.14"), Some(3.14)); + assert_eq!(from_str("+3.14"), Some(3.14)); + assert_eq!(from_str("-3.14"), Some(-3.14)); + assert_eq!(from_str("2.5E10"), Some(25000000000.)); + assert_eq!(from_str("2.5e10"), Some(25000000000.)); + assert_eq!(from_str("25000000000.E-10"), Some(2.5)); + assert_eq!(from_str("."), Some(0.)); + assert_eq!(from_str(".e1"), Some(0.)); + assert_eq!(from_str(".e-1"), Some(0.)); + assert_eq!(from_str("5."), Some(5.)); + assert_eq!(from_str(".5"), Some(0.5)); + assert_eq!(from_str("0.5"), Some(0.5)); + assert_eq!(from_str("-.5"), Some(-0.5)); + assert_eq!(from_str("-5"), Some(-5.)); + assert_eq!(from_str("inf"), Some(infinity)); + assert_eq!(from_str("+inf"), Some(infinity)); + assert_eq!(from_str("-inf"), Some(neg_infinity)); // note: NaN != NaN, hence this slightly complex test - match from_str(~"NaN") { + match from_str("NaN") { Some(f) => assert!(f.is_NaN()), None => fail!() } // note: -0 == 0, hence these slightly more complex tests - match from_str(~"-0") { + match from_str("-0") { Some(v) if v.is_zero() => assert!(v.is_negative()), _ => fail!() } - match from_str(~"0") { + match from_str("0") { Some(v) if v.is_zero() => assert!(v.is_positive()), _ => fail!() } - assert!(from_str(~"").is_none()); - assert!(from_str(~"x").is_none()); - assert!(from_str(~" ").is_none()); - assert!(from_str(~" ").is_none()); - assert!(from_str(~"e").is_none()); - assert!(from_str(~"E").is_none()); - assert!(from_str(~"E1").is_none()); - assert!(from_str(~"1e1e1").is_none()); - assert!(from_str(~"1e1.1").is_none()); - assert!(from_str(~"1e1-1").is_none()); + assert!(from_str("").is_none()); + assert!(from_str("x").is_none()); + assert!(from_str(" ").is_none()); + assert!(from_str(" ").is_none()); + assert!(from_str("e").is_none()); + assert!(from_str("E").is_none()); + assert!(from_str("E1").is_none()); + assert!(from_str("1e1e1").is_none()); + assert!(from_str("1e1.1").is_none()); + assert!(from_str("1e1-1").is_none()); } #[test] pub fn test_from_str_hex() { - assert_eq!(from_str_hex(~"a4"), Some(164.)); - assert_eq!(from_str_hex(~"a4.fe"), Some(164.9921875)); - assert_eq!(from_str_hex(~"-a4.fe"), Some(-164.9921875)); - assert_eq!(from_str_hex(~"+a4.fe"), Some(164.9921875)); - assert_eq!(from_str_hex(~"ff0P4"), Some(0xff00 as float)); - assert_eq!(from_str_hex(~"ff0p4"), Some(0xff00 as float)); - assert_eq!(from_str_hex(~"ff0p-4"), Some(0xff as float)); - assert_eq!(from_str_hex(~"."), Some(0.)); - assert_eq!(from_str_hex(~".p1"), Some(0.)); - assert_eq!(from_str_hex(~".p-1"), Some(0.)); - assert_eq!(from_str_hex(~"f."), Some(15.)); - assert_eq!(from_str_hex(~".f"), Some(0.9375)); - assert_eq!(from_str_hex(~"0.f"), Some(0.9375)); - assert_eq!(from_str_hex(~"-.f"), Some(-0.9375)); - assert_eq!(from_str_hex(~"-f"), Some(-15.)); - assert_eq!(from_str_hex(~"inf"), Some(infinity)); - assert_eq!(from_str_hex(~"+inf"), Some(infinity)); - assert_eq!(from_str_hex(~"-inf"), Some(neg_infinity)); + assert_eq!(from_str_hex("a4"), Some(164.)); + assert_eq!(from_str_hex("a4.fe"), Some(164.9921875)); + assert_eq!(from_str_hex("-a4.fe"), Some(-164.9921875)); + assert_eq!(from_str_hex("+a4.fe"), Some(164.9921875)); + assert_eq!(from_str_hex("ff0P4"), Some(0xff00 as float)); + assert_eq!(from_str_hex("ff0p4"), Some(0xff00 as float)); + assert_eq!(from_str_hex("ff0p-4"), Some(0xff as float)); + assert_eq!(from_str_hex("."), Some(0.)); + assert_eq!(from_str_hex(".p1"), Some(0.)); + assert_eq!(from_str_hex(".p-1"), Some(0.)); + assert_eq!(from_str_hex("f."), Some(15.)); + assert_eq!(from_str_hex(".f"), Some(0.9375)); + assert_eq!(from_str_hex("0.f"), Some(0.9375)); + assert_eq!(from_str_hex("-.f"), Some(-0.9375)); + assert_eq!(from_str_hex("-f"), Some(-15.)); + assert_eq!(from_str_hex("inf"), Some(infinity)); + assert_eq!(from_str_hex("+inf"), Some(infinity)); + assert_eq!(from_str_hex("-inf"), Some(neg_infinity)); // note: NaN != NaN, hence this slightly complex test - match from_str_hex(~"NaN") { + match from_str_hex("NaN") { Some(f) => assert!(f.is_NaN()), None => fail!() } // note: -0 == 0, hence these slightly more complex tests - match from_str_hex(~"-0") { + match from_str_hex("-0") { Some(v) if v.is_zero() => assert!(v.is_negative()), _ => fail!() } - match from_str_hex(~"0") { + match from_str_hex("0") { Some(v) if v.is_zero() => assert!(v.is_positive()), _ => fail!() } - assert_eq!(from_str_hex(~"e"), Some(14.)); - assert_eq!(from_str_hex(~"E"), Some(14.)); - assert_eq!(from_str_hex(~"E1"), Some(225.)); - assert_eq!(from_str_hex(~"1e1e1"), Some(123361.)); - assert_eq!(from_str_hex(~"1e1.1"), Some(481.0625)); - - assert!(from_str_hex(~"").is_none()); - assert!(from_str_hex(~"x").is_none()); - assert!(from_str_hex(~" ").is_none()); - assert!(from_str_hex(~" ").is_none()); - assert!(from_str_hex(~"p").is_none()); - assert!(from_str_hex(~"P").is_none()); - assert!(from_str_hex(~"P1").is_none()); - assert!(from_str_hex(~"1p1p1").is_none()); - assert!(from_str_hex(~"1p1.1").is_none()); - assert!(from_str_hex(~"1p1-1").is_none()); + assert_eq!(from_str_hex("e"), Some(14.)); + assert_eq!(from_str_hex("E"), Some(14.)); + assert_eq!(from_str_hex("E1"), Some(225.)); + assert_eq!(from_str_hex("1e1e1"), Some(123361.)); + assert_eq!(from_str_hex("1e1.1"), Some(481.0625)); + + assert!(from_str_hex("").is_none()); + assert!(from_str_hex("x").is_none()); + assert!(from_str_hex(" ").is_none()); + assert!(from_str_hex(" ").is_none()); + assert!(from_str_hex("p").is_none()); + assert!(from_str_hex("P").is_none()); + assert!(from_str_hex("P1").is_none()); + assert!(from_str_hex("1p1p1").is_none()); + assert!(from_str_hex("1p1.1").is_none()); + assert!(from_str_hex("1p1-1").is_none()); } #[test] @@ -1375,8 +1375,8 @@ mod tests { #[test] pub fn test_from_str_radix() { - assert_eq!(from_str_radix(~"10", 36u), Some(36.)); - assert_eq!(from_str_radix(~"1000.001", 2u), Some(8.125)); + assert_eq!(from_str_radix("10", 36u), Some(36.)); + assert_eq!(from_str_radix("1000.001", 2u), Some(8.125)); } #[test] diff --git a/src/libstd/num/int-template.rs b/src/libstd/num/int-template.rs index 3c31a7d574518..068f553ea6b57 100644 --- a/src/libstd/num/int-template.rs +++ b/src/libstd/num/int-template.rs @@ -755,45 +755,45 @@ mod tests { #[test] fn test_from_str() { - assert_eq!(from_str(~"0"), Some(0 as T)); - assert_eq!(from_str(~"3"), Some(3 as T)); - assert_eq!(from_str(~"10"), Some(10 as T)); - assert_eq!(i32::from_str(~"123456789"), Some(123456789 as i32)); - assert_eq!(from_str(~"00100"), Some(100 as T)); + assert_eq!(from_str("0"), Some(0 as T)); + assert_eq!(from_str("3"), Some(3 as T)); + assert_eq!(from_str("10"), Some(10 as T)); + assert_eq!(i32::from_str("123456789"), Some(123456789 as i32)); + assert_eq!(from_str("00100"), Some(100 as T)); - assert_eq!(from_str(~"-1"), Some(-1 as T)); - assert_eq!(from_str(~"-3"), Some(-3 as T)); - assert_eq!(from_str(~"-10"), Some(-10 as T)); - assert_eq!(i32::from_str(~"-123456789"), Some(-123456789 as i32)); - assert_eq!(from_str(~"-00100"), Some(-100 as T)); + assert_eq!(from_str("-1"), Some(-1 as T)); + assert_eq!(from_str("-3"), Some(-3 as T)); + assert_eq!(from_str("-10"), Some(-10 as T)); + assert_eq!(i32::from_str("-123456789"), Some(-123456789 as i32)); + assert_eq!(from_str("-00100"), Some(-100 as T)); - assert!(from_str(~" ").is_none()); - assert!(from_str(~"x").is_none()); + assert!(from_str(" ").is_none()); + assert!(from_str("x").is_none()); } #[test] fn test_parse_bytes() { use str::to_bytes; - assert_eq!(parse_bytes(to_bytes(~"123"), 10u), Some(123 as T)); - assert_eq!(parse_bytes(to_bytes(~"1001"), 2u), Some(9 as T)); - assert_eq!(parse_bytes(to_bytes(~"123"), 8u), Some(83 as T)); - assert_eq!(i32::parse_bytes(to_bytes(~"123"), 16u), Some(291 as i32)); - assert_eq!(i32::parse_bytes(to_bytes(~"ffff"), 16u), Some(65535 as i32)); - assert_eq!(i32::parse_bytes(to_bytes(~"FFFF"), 16u), Some(65535 as i32)); - assert_eq!(parse_bytes(to_bytes(~"z"), 36u), Some(35 as T)); - assert_eq!(parse_bytes(to_bytes(~"Z"), 36u), Some(35 as T)); - - assert_eq!(parse_bytes(to_bytes(~"-123"), 10u), Some(-123 as T)); - assert_eq!(parse_bytes(to_bytes(~"-1001"), 2u), Some(-9 as T)); - assert_eq!(parse_bytes(to_bytes(~"-123"), 8u), Some(-83 as T)); - assert_eq!(i32::parse_bytes(to_bytes(~"-123"), 16u), Some(-291 as i32)); - assert_eq!(i32::parse_bytes(to_bytes(~"-ffff"), 16u), Some(-65535 as i32)); - assert_eq!(i32::parse_bytes(to_bytes(~"-FFFF"), 16u), Some(-65535 as i32)); - assert_eq!(parse_bytes(to_bytes(~"-z"), 36u), Some(-35 as T)); - assert_eq!(parse_bytes(to_bytes(~"-Z"), 36u), Some(-35 as T)); - - assert!(parse_bytes(to_bytes(~"Z"), 35u).is_none()); - assert!(parse_bytes(to_bytes(~"-9"), 2u).is_none()); + assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123 as T)); + assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9 as T)); + assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83 as T)); + assert_eq!(i32::parse_bytes(to_bytes("123"), 16u), Some(291 as i32)); + assert_eq!(i32::parse_bytes(to_bytes("ffff"), 16u), Some(65535 as i32)); + assert_eq!(i32::parse_bytes(to_bytes("FFFF"), 16u), Some(65535 as i32)); + assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35 as T)); + assert_eq!(parse_bytes(to_bytes("Z"), 36u), Some(35 as T)); + + assert_eq!(parse_bytes(to_bytes("-123"), 10u), Some(-123 as T)); + assert_eq!(parse_bytes(to_bytes("-1001"), 2u), Some(-9 as T)); + assert_eq!(parse_bytes(to_bytes("-123"), 8u), Some(-83 as T)); + assert_eq!(i32::parse_bytes(to_bytes("-123"), 16u), Some(-291 as i32)); + assert_eq!(i32::parse_bytes(to_bytes("-ffff"), 16u), Some(-65535 as i32)); + assert_eq!(i32::parse_bytes(to_bytes("-FFFF"), 16u), Some(-65535 as i32)); + assert_eq!(parse_bytes(to_bytes("-z"), 36u), Some(-35 as T)); + assert_eq!(parse_bytes(to_bytes("-Z"), 36u), Some(-35 as T)); + + assert!(parse_bytes(to_bytes("Z"), 35u).is_none()); + assert!(parse_bytes(to_bytes("-9"), 2u).is_none()); } #[test] @@ -836,36 +836,36 @@ mod tests { #[test] fn test_int_from_str_overflow() { let mut i8_val: i8 = 127_i8; - assert_eq!(i8::from_str(~"127"), Some(i8_val)); - assert!(i8::from_str(~"128").is_none()); + assert_eq!(i8::from_str("127"), Some(i8_val)); + assert!(i8::from_str("128").is_none()); i8_val += 1 as i8; - assert_eq!(i8::from_str(~"-128"), Some(i8_val)); - assert!(i8::from_str(~"-129").is_none()); + assert_eq!(i8::from_str("-128"), Some(i8_val)); + assert!(i8::from_str("-129").is_none()); let mut i16_val: i16 = 32_767_i16; - assert_eq!(i16::from_str(~"32767"), Some(i16_val)); - assert!(i16::from_str(~"32768").is_none()); + assert_eq!(i16::from_str("32767"), Some(i16_val)); + assert!(i16::from_str("32768").is_none()); i16_val += 1 as i16; - assert_eq!(i16::from_str(~"-32768"), Some(i16_val)); - assert!(i16::from_str(~"-32769").is_none()); + assert_eq!(i16::from_str("-32768"), Some(i16_val)); + assert!(i16::from_str("-32769").is_none()); let mut i32_val: i32 = 2_147_483_647_i32; - assert_eq!(i32::from_str(~"2147483647"), Some(i32_val)); - assert!(i32::from_str(~"2147483648").is_none()); + assert_eq!(i32::from_str("2147483647"), Some(i32_val)); + assert!(i32::from_str("2147483648").is_none()); i32_val += 1 as i32; - assert_eq!(i32::from_str(~"-2147483648"), Some(i32_val)); - assert!(i32::from_str(~"-2147483649").is_none()); + assert_eq!(i32::from_str("-2147483648"), Some(i32_val)); + assert!(i32::from_str("-2147483649").is_none()); let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; - assert_eq!(i64::from_str(~"9223372036854775807"), Some(i64_val)); - assert!(i64::from_str(~"9223372036854775808").is_none()); + assert_eq!(i64::from_str("9223372036854775807"), Some(i64_val)); + assert!(i64::from_str("9223372036854775808").is_none()); i64_val += 1 as i64; - assert_eq!(i64::from_str(~"-9223372036854775808"), Some(i64_val)); - assert!(i64::from_str(~"-9223372036854775809").is_none()); + assert_eq!(i64::from_str("-9223372036854775808"), Some(i64_val)); + assert!(i64::from_str("-9223372036854775809").is_none()); } #[test] diff --git a/src/libstd/num/uint-template.rs b/src/libstd/num/uint-template.rs index 66ff16cbeb1ef..9784fe24206c3 100644 --- a/src/libstd/num/uint-template.rs +++ b/src/libstd/num/uint-template.rs @@ -472,29 +472,29 @@ mod tests { #[test] pub fn test_from_str() { - assert_eq!(from_str(~"0"), Some(0u as T)); - assert_eq!(from_str(~"3"), Some(3u as T)); - assert_eq!(from_str(~"10"), Some(10u as T)); - assert_eq!(u32::from_str(~"123456789"), Some(123456789 as u32)); - assert_eq!(from_str(~"00100"), Some(100u as T)); + assert_eq!(from_str("0"), Some(0u as T)); + assert_eq!(from_str("3"), Some(3u as T)); + assert_eq!(from_str("10"), Some(10u as T)); + assert_eq!(u32::from_str("123456789"), Some(123456789 as u32)); + assert_eq!(from_str("00100"), Some(100u as T)); - assert!(from_str(~"").is_none()); - assert!(from_str(~" ").is_none()); - assert!(from_str(~"x").is_none()); + assert!(from_str("").is_none()); + assert!(from_str(" ").is_none()); + assert!(from_str("x").is_none()); } #[test] pub fn test_parse_bytes() { use str::to_bytes; - assert_eq!(parse_bytes(to_bytes(~"123"), 10u), Some(123u as T)); - assert_eq!(parse_bytes(to_bytes(~"1001"), 2u), Some(9u as T)); - assert_eq!(parse_bytes(to_bytes(~"123"), 8u), Some(83u as T)); - assert_eq!(u16::parse_bytes(to_bytes(~"123"), 16u), Some(291u as u16)); - assert_eq!(u16::parse_bytes(to_bytes(~"ffff"), 16u), Some(65535u as u16)); - assert_eq!(parse_bytes(to_bytes(~"z"), 36u), Some(35u as T)); + assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123u as T)); + assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9u as T)); + assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83u as T)); + assert_eq!(u16::parse_bytes(to_bytes("123"), 16u), Some(291u as u16)); + assert_eq!(u16::parse_bytes(to_bytes("ffff"), 16u), Some(65535u as u16)); + assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35u as T)); - assert!(parse_bytes(to_bytes(~"Z"), 10u).is_none()); - assert!(parse_bytes(to_bytes(~"_"), 2u).is_none()); + assert!(parse_bytes(to_bytes("Z"), 10u).is_none()); + assert!(parse_bytes(to_bytes("_"), 2u).is_none()); } #[test] @@ -527,36 +527,36 @@ mod tests { #[test] fn test_uint_from_str_overflow() { let mut u8_val: u8 = 255_u8; - assert_eq!(u8::from_str(~"255"), Some(u8_val)); - assert!(u8::from_str(~"256").is_none()); + assert_eq!(u8::from_str("255"), Some(u8_val)); + assert!(u8::from_str("256").is_none()); u8_val += 1 as u8; - assert_eq!(u8::from_str(~"0"), Some(u8_val)); - assert!(u8::from_str(~"-1").is_none()); + assert_eq!(u8::from_str("0"), Some(u8_val)); + assert!(u8::from_str("-1").is_none()); let mut u16_val: u16 = 65_535_u16; - assert_eq!(u16::from_str(~"65535"), Some(u16_val)); - assert!(u16::from_str(~"65536").is_none()); + assert_eq!(u16::from_str("65535"), Some(u16_val)); + assert!(u16::from_str("65536").is_none()); u16_val += 1 as u16; - assert_eq!(u16::from_str(~"0"), Some(u16_val)); - assert!(u16::from_str(~"-1").is_none()); + assert_eq!(u16::from_str("0"), Some(u16_val)); + assert!(u16::from_str("-1").is_none()); let mut u32_val: u32 = 4_294_967_295_u32; - assert_eq!(u32::from_str(~"4294967295"), Some(u32_val)); - assert!(u32::from_str(~"4294967296").is_none()); + assert_eq!(u32::from_str("4294967295"), Some(u32_val)); + assert!(u32::from_str("4294967296").is_none()); u32_val += 1 as u32; - assert_eq!(u32::from_str(~"0"), Some(u32_val)); - assert!(u32::from_str(~"-1").is_none()); + assert_eq!(u32::from_str("0"), Some(u32_val)); + assert!(u32::from_str("-1").is_none()); let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; - assert_eq!(u64::from_str(~"18446744073709551615"), Some(u64_val)); - assert!(u64::from_str(~"18446744073709551616").is_none()); + assert_eq!(u64::from_str("18446744073709551615"), Some(u64_val)); + assert!(u64::from_str("18446744073709551616").is_none()); u64_val += 1 as u64; - assert_eq!(u64::from_str(~"0"), Some(u64_val)); - assert!(u64::from_str(~"-1").is_none()); + assert_eq!(u64::from_str("0"), Some(u64_val)); + assert!(u64::from_str("-1").is_none()); } #[test] diff --git a/src/libstd/os.rs b/src/libstd/os.rs index b2a30e50992c8..a82f1c9891696 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -1444,14 +1444,14 @@ mod tests { #[test] fn test_setenv() { let n = make_rand_name(); - setenv(n, ~"VALUE"); + setenv(n, "VALUE"); assert_eq!(getenv(n), option::Some(~"VALUE")); } #[test] fn test_unsetenv() { let n = make_rand_name(); - setenv(n, ~"VALUE"); + setenv(n, "VALUE"); unsetenv(n); assert_eq!(getenv(n), option::None); } @@ -1461,10 +1461,10 @@ mod tests { #[ignore] fn test_setenv_overwrite() { let n = make_rand_name(); - setenv(n, ~"1"); - setenv(n, ~"2"); + setenv(n, "1"); + setenv(n, "2"); assert_eq!(getenv(n), option::Some(~"2")); - setenv(n, ~""); + setenv(n, ""); assert_eq!(getenv(n), option::Some(~"")); } @@ -1515,7 +1515,7 @@ mod tests { let n = make_rand_name(); let mut e = env(); - setenv(n, ~"VALUE"); + setenv(n, "VALUE"); assert!(!vec::contains(e, &(copy n, ~"VALUE"))); e = env(); @@ -1526,7 +1526,7 @@ mod tests { fn test() { assert!((!Path("test-path").is_absolute)); - debug!(~"Current working directory: " + getcwd().to_str()); + debug!("Current working directory: %s", getcwd().to_str()); debug!(make_absolute(&Path("test-path"))); debug!(make_absolute(&Path("/usr/bin"))); @@ -1535,43 +1535,43 @@ mod tests { #[test] #[cfg(unix)] fn homedir() { - let oldhome = getenv(~"HOME"); + let oldhome = getenv("HOME"); - setenv(~"HOME", ~"/home/MountainView"); + setenv("HOME", "/home/MountainView"); assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); - setenv(~"HOME", ~""); + setenv("HOME", ""); assert!(os::homedir().is_none()); - for oldhome.each |s| { setenv(~"HOME", *s) } + for oldhome.each |s| { setenv("HOME", *s) } } #[test] #[cfg(windows)] fn homedir() { - let oldhome = getenv(~"HOME"); - let olduserprofile = getenv(~"USERPROFILE"); + let oldhome = getenv("HOME"); + let olduserprofile = getenv("USERPROFILE"); - setenv(~"HOME", ~""); - setenv(~"USERPROFILE", ~""); + setenv("HOME", ""); + setenv("USERPROFILE", ""); assert!(os::homedir().is_none()); - setenv(~"HOME", ~"/home/MountainView"); + setenv("HOME", "/home/MountainView"); assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); - setenv(~"HOME", ~""); + setenv("HOME", ""); - setenv(~"USERPROFILE", ~"/home/MountainView"); + setenv("USERPROFILE", "/home/MountainView"); assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); - setenv(~"HOME", ~"/home/MountainView"); - setenv(~"USERPROFILE", ~"/home/PaloAlto"); + setenv("HOME", "/home/MountainView"); + setenv("USERPROFILE", "/home/PaloAlto"); assert_eq!(os::homedir(), Some(Path("/home/MountainView"))); - oldhome.each(|s| {setenv(~"HOME", *s);true}); - olduserprofile.each(|s| {setenv(~"USERPROFILE", *s);true}); + oldhome.each(|s| { setenv("HOME", *s); true }); + olduserprofile.each(|s| { setenv("USERPROFILE", *s); true }); } #[test] @@ -1646,7 +1646,7 @@ mod tests { fail!("%s doesn't exist", in.to_str()); } assert!((rs)); - let rslt = run::run_program(~"diff", ~[in.to_str(), out.to_str()]); + let rslt = run::run_program("diff", [in.to_str(), out.to_str()]); assert_eq!(rslt, 0); assert_eq!(out.get_mode(), in_mode); assert!((remove_file(&in))); diff --git a/src/libstd/rand.rs b/src/libstd/rand.rs index 84dd7d187e4b1..09d0a38e16d49 100644 --- a/src/libstd/rand.rs +++ b/src/libstd/rand.rs @@ -988,10 +988,10 @@ mod tests { #[test] fn test_choose_weighted() { let mut r = rng(); - assert!(r.choose_weighted(~[ + assert!(r.choose_weighted([ Weighted { weight: 1u, item: 42 }, ]) == 42); - assert!(r.choose_weighted(~[ + assert!(r.choose_weighted([ Weighted { weight: 0u, item: 42 }, Weighted { weight: 1u, item: 43 }, ]) == 43); @@ -1000,10 +1000,10 @@ mod tests { #[test] fn test_choose_weighted_option() { let mut r = rng(); - assert!(r.choose_weighted_option(~[ + assert!(r.choose_weighted_option([ Weighted { weight: 1u, item: 42 }, ]) == Some(42)); - assert!(r.choose_weighted_option(~[ + assert!(r.choose_weighted_option([ Weighted { weight: 0u, item: 42 }, Weighted { weight: 1u, item: 43 }, ]) == Some(43)); @@ -1015,8 +1015,8 @@ mod tests { fn test_weighted_vec() { let mut r = rng(); let empty: ~[int] = ~[]; - assert_eq!(r.weighted_vec(~[]), empty); - assert!(r.weighted_vec(~[ + assert_eq!(r.weighted_vec([]), empty); + assert!(r.weighted_vec([ Weighted { weight: 0u, item: 3u }, Weighted { weight: 1u, item: 2u }, Weighted { weight: 2u, item: 1u }, @@ -1027,15 +1027,15 @@ mod tests { fn test_shuffle() { let mut r = rng(); let empty: ~[int] = ~[]; - assert_eq!(r.shuffle(~[]), empty); - assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]); + assert_eq!(r.shuffle([]), empty); + assert_eq!(r.shuffle([1, 1, 1]), ~[1, 1, 1]); } #[test] fn test_task_rng() { let mut r = task_rng(); r.gen::(); - assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]); + assert_eq!(r.shuffle([1, 1, 1]), ~[1, 1, 1]); assert_eq!(r.gen_uint_range(0u, 1u), 0u); } diff --git a/src/libstd/rt/comm.rs b/src/libstd/rt/comm.rs index 576a402b70919..54db03b6069c2 100644 --- a/src/libstd/rt/comm.rs +++ b/src/libstd/rt/comm.rs @@ -474,7 +474,7 @@ mod test { #[test] fn oneshot_single_thread_peek_open() { do run_in_newsched_task { - let (port, chan) = oneshot::(); + let (port, _) = oneshot::(); assert!(!port.peek()); } } diff --git a/src/libstd/rt/io/extensions.rs b/src/libstd/rt/io/extensions.rs index ceff2ecd77de0..fcbf31e87f2c0 100644 --- a/src/libstd/rt/io/extensions.rs +++ b/src/libstd/rt/io/extensions.rs @@ -587,12 +587,10 @@ fn extend_sign(val: u64, nbytes: uint) -> i64 { #[cfg(test)] mod test { - use super::{ReaderUtil, ReaderByteConversions, WriterByteConversions}; - use u64; - use i32; + use super::ReaderUtil; use option::{Some, None}; use cell::Cell; - use rt::io::mem::{MemReader, MemWriter}; + use rt::io::mem::MemReader; use rt::io::mock::MockReader; use rt::io::{read_error, placeholder_error}; diff --git a/src/libstd/rt/local.rs b/src/libstd/rt/local.rs index 64a384ddff0b9..313123c38b58d 100644 --- a/src/libstd/rt/local.rs +++ b/src/libstd/rt/local.rs @@ -33,7 +33,7 @@ impl Local for Scheduler { } impl Local for Task { - fn put(value: ~Task) { abort!("unimpl") } + fn put(_value: ~Task) { abort!("unimpl") } fn take() -> ~Task { abort!("unimpl") } fn exists() -> bool { abort!("unimpl") } fn borrow(f: &fn(&mut Task)) { @@ -71,10 +71,10 @@ impl Local for Task { // XXX: This formulation won't work once ~IoFactoryObject is a real trait pointer impl Local for IoFactoryObject { - fn put(value: ~IoFactoryObject) { abort!("unimpl") } + fn put(_value: ~IoFactoryObject) { abort!("unimpl") } fn take() -> ~IoFactoryObject { abort!("unimpl") } fn exists() -> bool { abort!("unimpl") } - fn borrow(f: &fn(&mut IoFactoryObject)) { abort!("unimpl") } + fn borrow(_f: &fn(&mut IoFactoryObject)) { abort!("unimpl") } unsafe fn unsafe_borrow() -> *mut IoFactoryObject { let sched = Local::unsafe_borrow::(); let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); @@ -115,4 +115,4 @@ mod test { } let _scheduler: ~Scheduler = Local::take(); } -} \ No newline at end of file +} diff --git a/src/libstd/rt/sched.rs b/src/libstd/rt/sched.rs index 50c6a894093f3..2d9cdaddc8433 100644 --- a/src/libstd/rt/sched.rs +++ b/src/libstd/rt/sched.rs @@ -20,7 +20,6 @@ use super::context::Context; use super::task::Task; use rt::local_ptr; use rt::local::Local; -use rt::rtio::IoFactoryObject; /// The Scheduler is responsible for coordinating execution of Coroutines /// on a single thread. When the scheduler is running it is owned by diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index 0314137fc7f92..cf4967b12b304 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -16,7 +16,6 @@ use prelude::*; use libc::{c_void, uintptr_t}; use cast::transmute; -use super::sched::Scheduler; use rt::local::Local; use super::local_heap::LocalHeap; use rt::logging::StdErrLogger; diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 53169554ec5e7..3dae1291e0315 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -2794,31 +2794,31 @@ mod tests { #[test] fn test_len() { - assert_eq!(len(~""), 0u); - assert_eq!(len(~"hello world"), 11u); - assert_eq!(len(~"\x63"), 1u); - assert_eq!(len(~"\xa2"), 2u); - assert_eq!(len(~"\u03c0"), 2u); - assert_eq!(len(~"\u2620"), 3u); - assert_eq!(len(~"\U0001d11e"), 4u); + assert_eq!(len(""), 0u); + assert_eq!(len("hello world"), 11u); + assert_eq!(len("\x63"), 1u); + assert_eq!(len("\xa2"), 2u); + assert_eq!(len("\u03c0"), 2u); + assert_eq!(len("\u2620"), 3u); + assert_eq!(len("\U0001d11e"), 4u); - assert_eq!(char_len(~""), 0u); - assert_eq!(char_len(~"hello world"), 11u); - assert_eq!(char_len(~"\x63"), 1u); - assert_eq!(char_len(~"\xa2"), 1u); - assert_eq!(char_len(~"\u03c0"), 1u); - assert_eq!(char_len(~"\u2620"), 1u); - assert_eq!(char_len(~"\U0001d11e"), 1u); - assert_eq!(char_len(~"ประเทศไทย中华Việt Nam"), 19u); + assert_eq!(char_len(""), 0u); + assert_eq!(char_len("hello world"), 11u); + assert_eq!(char_len("\x63"), 1u); + assert_eq!(char_len("\xa2"), 1u); + assert_eq!(char_len("\u03c0"), 1u); + assert_eq!(char_len("\u2620"), 1u); + assert_eq!(char_len("\U0001d11e"), 1u); + assert_eq!(char_len("ประเทศไทย中华Việt Nam"), 19u); } #[test] fn test_rfind_char() { - assert_eq!(rfind_char(~"hello", 'l'), Some(3u)); - assert_eq!(rfind_char(~"hello", 'o'), Some(4u)); - assert_eq!(rfind_char(~"hello", 'h'), Some(0u)); - assert!(rfind_char(~"hello", 'z').is_none()); - assert_eq!(rfind_char(~"ประเทศไทย中华Việt Nam", '华'), Some(30u)); + assert_eq!(rfind_char("hello", 'l'), Some(3u)); + assert_eq!(rfind_char("hello", 'o'), Some(4u)); + assert_eq!(rfind_char("hello", 'h'), Some(0u)); + assert!(rfind_char("hello", 'z').is_none()); + assert_eq!(rfind_char("ประเทศไทย中华Việt Nam", '华'), Some(30u)); } #[test] @@ -2848,66 +2848,66 @@ mod tests { #[test] fn test_split_char() { fn t(s: &str, c: char, u: &[~str]) { - debug!(~"split_byte: " + s); + debug!("split_byte: %?", s); let mut v = ~[]; for each_split_char(s, c) |s| { v.push(s.to_owned()) } debug!("split_byte to: %?", v); assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"abc.hello.there", '.', ~[~"abc", ~"hello", ~"there"]); - t(~".hello.there", '.', ~[~"", ~"hello", ~"there"]); - t(~"...hello.there.", '.', ~[~"", ~"", ~"", ~"hello", ~"there", ~""]); + t("abc.hello.there", '.', [~"abc", ~"hello", ~"there"]); + t(".hello.there", '.', [~"", ~"hello", ~"there"]); + t("...hello.there.", '.', [~"", ~"", ~"", ~"hello", ~"there", ~""]); - t(~"", 'z', ~[~""]); - t(~"z", 'z', ~[~"",~""]); - t(~"ok", 'z', ~[~"ok"]); + t("", 'z', [~""]); + t("z", 'z', [~"",~""]); + t("ok", 'z', [~"ok"]); } #[test] fn test_split_char_2() { fn t(s: &str, c: char, u: &[~str]) { - debug!(~"split_byte: " + s); + debug!("split_byte: %?", s); let mut v = ~[]; for each_split_char(s, c) |s| { v.push(s.to_owned()) } debug!("split_byte to: %?", v); assert!(vec::all2(v, u, |a,b| a == b)); } - let data = ~"ประเทศไทย中华Việt Nam"; - t(data, 'V', ~[~"ประเทศไทย中华", ~"iệt Nam"]); - t(data, 'ท', ~[~"ประเ", ~"ศไ", ~"ย中华Việt Nam"]); + let data = "ประเทศไทย中华Việt Nam"; + t(data, 'V', [~"ประเทศไทย中华", ~"iệt Nam"]); + t(data, 'ท', [~"ประเ", ~"ศไ", ~"ย中华Việt Nam"]); } #[test] fn test_splitn_char() { fn t(s: &str, c: char, n: uint, u: &[~str]) { - debug!(~"splitn_byte: " + s); + debug!("splitn_byte: %?", s); let mut v = ~[]; for each_splitn_char(s, c, n) |s| { v.push(s.to_owned()) } debug!("split_byte to: %?", v); debug!("comparing vs. %?", u); assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"abc.hello.there", '.', 0u, ~[~"abc.hello.there"]); - t(~"abc.hello.there", '.', 1u, ~[~"abc", ~"hello.there"]); - t(~"abc.hello.there", '.', 2u, ~[~"abc", ~"hello", ~"there"]); - t(~"abc.hello.there", '.', 3u, ~[~"abc", ~"hello", ~"there"]); - t(~".hello.there", '.', 0u, ~[~".hello.there"]); - t(~".hello.there", '.', 1u, ~[~"", ~"hello.there"]); - t(~"...hello.there.", '.', 3u, ~[~"", ~"", ~"", ~"hello.there."]); - t(~"...hello.there.", '.', 5u, ~[~"", ~"", ~"", ~"hello", ~"there", ~""]); + t("abc.hello.there", '.', 0u, [~"abc.hello.there"]); + t("abc.hello.there", '.', 1u, [~"abc", ~"hello.there"]); + t("abc.hello.there", '.', 2u, [~"abc", ~"hello", ~"there"]); + t("abc.hello.there", '.', 3u, [~"abc", ~"hello", ~"there"]); + t(".hello.there", '.', 0u, [~".hello.there"]); + t(".hello.there", '.', 1u, [~"", ~"hello.there"]); + t("...hello.there.", '.', 3u, [~"", ~"", ~"", ~"hello.there."]); + t("...hello.there.", '.', 5u, [~"", ~"", ~"", ~"hello", ~"there", ~""]); - t(~"", 'z', 5u, ~[~""]); - t(~"z", 'z', 5u, ~[~"",~""]); - t(~"ok", 'z', 5u, ~[~"ok"]); - t(~"z", 'z', 0u, ~[~"z"]); - t(~"w.x.y", '.', 0u, ~[~"w.x.y"]); - t(~"w.x.y", '.', 1u, ~[~"w",~"x.y"]); + t("", 'z', 5u, [~""]); + t("z", 'z', 5u, [~"",~""]); + t("ok", 'z', 5u, [~"ok"]); + t("z", 'z', 0u, [~"z"]); + t("w.x.y", '.', 0u, [~"w.x.y"]); + t("w.x.y", '.', 1u, [~"w",~"x.y"]); } #[test] - fn test_splitn_char_2 () { + fn test_splitn_char_2() { fn t(s: &str, c: char, n: uint, u: &[~str]) { - debug!(~"splitn_byte: " + s); + debug!("splitn_byte: %?", s); let mut v = ~[]; for each_splitn_char(s, c, n) |s| { v.push(s.to_owned()) } debug!("split_byte to: %?", v); @@ -2915,60 +2915,59 @@ mod tests { assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"ประเทศไทย中华Việt Nam", '华', 1u, ~[~"ประเทศไทย中", ~"Việt Nam"]); - t(~"zzXXXzYYYzWWWz", 'z', 3u, ~[~"", ~"", ~"XXX", ~"YYYzWWWz"]); - t(~"z", 'z', 5u, ~[~"",~""]); - t(~"", 'z', 5u, ~[~""]); - t(~"ok", 'z', 5u, ~[~"ok"]); + t("ประเทศไทย中华Việt Nam", '华', 1u, [~"ประเทศไทย中", ~"Việt Nam"]); + t("zzXXXzYYYzWWWz", 'z', 3u, [~"", ~"", ~"XXX", ~"YYYzWWWz"]); + t("z", 'z', 5u, [~"",~""]); + t("", 'z', 5u, [~""]); + t("ok", 'z', 5u, [~"ok"]); } - #[test] fn test_splitn_char_3() { fn t(s: &str, c: char, n: uint, u: &[~str]) { - debug!(~"splitn_byte: " + s); + debug!("splitn_byte: %?", s); let mut v = ~[]; for each_splitn_char(s, c, n) |s| { v.push(s.to_owned()) } debug!("split_byte to: %?", v); debug!("comparing vs. %?", u); assert!(vec::all2(v, u, |a,b| a == b)); } - let data = ~"ประเทศไทย中华Việt Nam"; - t(data, 'V', 1u, ~[~"ประเทศไทย中华", ~"iệt Nam"]); - t(data, 'ท', 1u, ~[~"ประเ", ~"ศไทย中华Việt Nam"]); + let data = "ประเทศไทย中华Việt Nam"; + t(data, 'V', 1u, [~"ประเทศไทย中华", ~"iệt Nam"]); + t(data, 'ท', 1u, [~"ประเ", ~"ศไทย中华Việt Nam"]); } #[test] fn test_split_char_no_trailing() { fn t(s: &str, c: char, u: &[~str]) { - debug!(~"split_byte: " + s); + debug!("split_byte: %?", s); let mut v = ~[]; for each_split_char_no_trailing(s, c) |s| { v.push(s.to_owned()) } debug!("split_byte to: %?", v); assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"abc.hello.there", '.', ~[~"abc", ~"hello", ~"there"]); - t(~".hello.there", '.', ~[~"", ~"hello", ~"there"]); - t(~"...hello.there.", '.', ~[~"", ~"", ~"", ~"hello", ~"there"]); + t("abc.hello.there", '.', [~"abc", ~"hello", ~"there"]); + t(".hello.there", '.', [~"", ~"hello", ~"there"]); + t("...hello.there.", '.', [~"", ~"", ~"", ~"hello", ~"there"]); - t(~"...hello.there.", '.', ~[~"", ~"", ~"", ~"hello", ~"there"]); - t(~"", 'z', ~[]); - t(~"z", 'z', ~[~""]); - t(~"ok", 'z', ~[~"ok"]); + t("...hello.there.", '.', [~"", ~"", ~"", ~"hello", ~"there"]); + t("", 'z', []); + t("z", 'z', [~""]); + t("ok", 'z', [~"ok"]); } #[test] fn test_split_char_no_trailing_2() { fn t(s: &str, c: char, u: &[~str]) { - debug!(~"split_byte: " + s); + debug!("split_byte: %?", s); let mut v = ~[]; for each_split_char_no_trailing(s, c) |s| { v.push(s.to_owned()) } debug!("split_byte to: %?", v); assert!(vec::all2(v, u, |a,b| a == b)); } - let data = ~"ประเทศไทย中华Việt Nam"; - t(data, 'V', ~[~"ประเทศไทย中华", ~"iệt Nam"]); - t(data, 'ท', ~[~"ประเ", ~"ศไ", ~"ย中华Việt Nam"]); + let data = "ประเทศไทย中华Việt Nam"; + t(data, 'V', [~"ประเทศไทย中华", ~"iệt Nam"]); + t(data, 'ท', [~"ประเ", ~"ศไ", ~"ย中华Việt Nam"]); } #[test] @@ -2978,20 +2977,20 @@ mod tests { for each_split_str(s, sep) |s| { v.push(s.to_owned()) } assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"--1233345--", ~"12345", ~[~"--1233345--"]); - t(~"abc::hello::there", ~"::", ~[~"abc", ~"hello", ~"there"]); - t(~"::hello::there", ~"::", ~[~"", ~"hello", ~"there"]); - t(~"hello::there::", ~"::", ~[~"hello", ~"there", ~""]); - t(~"::hello::there::", ~"::", ~[~"", ~"hello", ~"there", ~""]); - t(~"ประเทศไทย中华Việt Nam", ~"中华", ~[~"ประเทศไทย", ~"Việt Nam"]); - t(~"zzXXXzzYYYzz", ~"zz", ~[~"", ~"XXX", ~"YYY", ~""]); - t(~"zzXXXzYYYz", ~"XXX", ~[~"zz", ~"zYYYz"]); - t(~".XXX.YYY.", ~".", ~[~"", ~"XXX", ~"YYY", ~""]); - t(~"", ~".", ~[~""]); - t(~"zz", ~"zz", ~[~"",~""]); - t(~"ok", ~"z", ~[~"ok"]); - t(~"zzz", ~"zz", ~[~"",~"z"]); - t(~"zzzzz", ~"zz", ~[~"",~"",~"z"]); + t("--1233345--", "12345", [~"--1233345--"]); + t("abc::hello::there", "::", [~"abc", ~"hello", ~"there"]); + t("::hello::there", "::", [~"", ~"hello", ~"there"]); + t("hello::there::", "::", [~"hello", ~"there", ~""]); + t("::hello::there::", "::", [~"", ~"hello", ~"there", ~""]); + t("ประเทศไทย中华Việt Nam", "中华", [~"ประเทศไทย", ~"Việt Nam"]); + t("zzXXXzzYYYzz", "zz", [~"", ~"XXX", ~"YYY", ~""]); + t("zzXXXzYYYz", "XXX", [~"zz", ~"zYYYz"]); + t(".XXX.YYY.", ".", [~"", ~"XXX", ~"YYY", ~""]); + t("", ".", [~""]); + t("zz", "zz", [~"",~""]); + t("ok", "z", [~"ok"]); + t("zzz", "zz", [~"",~"z"]); + t("zzzzz", "zz", [~"",~"",~"z"]); } @@ -3003,12 +3002,12 @@ mod tests { assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"ประเทศไทย中华Việt Nam", |cc| cc == '华', ~[~"ประเทศไทย中", ~"Việt Nam"]); - t(~"zzXXXzYYYz", char::is_lowercase, ~[~"", ~"", ~"XXX", ~"YYY", ~""]); - t(~"zzXXXzYYYz", char::is_uppercase, ~[~"zz", ~"", ~"", ~"z", ~"", ~"", ~"z"]); - t(~"z", |cc| cc == 'z', ~[~"",~""]); - t(~"", |cc| cc == 'z', ~[~""]); - t(~"ok", |cc| cc == 'z', ~[~"ok"]); + t("ประเทศไทย中华Việt Nam", |cc| cc == '华', [~"ประเทศไทย中", ~"Việt Nam"]); + t("zzXXXzYYYz", char::is_lowercase, [~"", ~"", ~"XXX", ~"YYY", ~""]); + t("zzXXXzYYYz", char::is_uppercase, [~"zz", ~"", ~"", ~"z", ~"", ~"", ~"z"]); + t("z", |cc| cc == 'z', [~"",~""]); + t("", |cc| cc == 'z', [~""]); + t("ok", |cc| cc == 'z', [~"ok"]); } #[test] @@ -3019,18 +3018,18 @@ mod tests { assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"ประเทศไทย中华Việt Nam", |cc| cc == '华', ~[~"ประเทศไทย中", ~"Việt Nam"]); - t(~"zzXXXzYYYz", char::is_lowercase, ~[~"", ~"", ~"XXX", ~"YYY"]); - t(~"zzXXXzYYYz", char::is_uppercase, ~[~"zz", ~"", ~"", ~"z", ~"", ~"", ~"z"]); - t(~"z", |cc| cc == 'z', ~[~""]); - t(~"", |cc| cc == 'z', ~[]); - t(~"ok", |cc| cc == 'z', ~[~"ok"]); + t("ประเทศไทย中华Việt Nam", |cc| cc == '华', [~"ประเทศไทย中", ~"Việt Nam"]); + t("zzXXXzYYYz", char::is_lowercase, [~"", ~"", ~"XXX", ~"YYY"]); + t("zzXXXzYYYz", char::is_uppercase, [~"zz", ~"", ~"", ~"z", ~"", ~"", ~"z"]); + t("z", |cc| cc == 'z', [~""]); + t("", |cc| cc == 'z', []); + t("ok", |cc| cc == 'z', [~"ok"]); } #[test] fn test_lines() { - let lf = ~"\nMary had a little lamb\nLittle lamb\n"; - let crlf = ~"\r\nMary had a little lamb\r\nLittle lamb\r\n"; + let lf = "\nMary had a little lamb\nLittle lamb\n"; + let crlf = "\r\nMary had a little lamb\r\nLittle lamb\r\n"; fn t(s: &str, f: &fn(&str, &fn(&str) -> bool) -> bool, u: &[~str]) { let mut v = ~[]; @@ -3038,30 +3037,30 @@ mod tests { assert!(vec::all2(v, u, |a,b| a == b)); } - t(lf, each_line ,~[~"", ~"Mary had a little lamb", ~"Little lamb"]); - t(lf, each_line_any, ~[~"", ~"Mary had a little lamb", ~"Little lamb"]); - t(crlf, each_line, ~[~"\r", ~"Mary had a little lamb\r", ~"Little lamb\r"]); - t(crlf, each_line_any, ~[~"", ~"Mary had a little lamb", ~"Little lamb"]); - t(~"", each_line, ~[]); - t(~"", each_line_any, ~[]); - t(~"\n", each_line, ~[~""]); - t(~"\n", each_line_any, ~[~""]); - t(~"banana", each_line, ~[~"banana"]); - t(~"banana", each_line_any, ~[~"banana"]); + t(lf, each_line, [~"", ~"Mary had a little lamb", ~"Little lamb"]); + t(lf, each_line_any, [~"", ~"Mary had a little lamb", ~"Little lamb"]); + t(crlf, each_line, [~"\r", ~"Mary had a little lamb\r", ~"Little lamb\r"]); + t(crlf, each_line_any, [~"", ~"Mary had a little lamb", ~"Little lamb"]); + t("", each_line, []); + t("", each_line_any, []); + t("\n", each_line, [~""]); + t("\n", each_line_any, [~""]); + t("banana", each_line, [~"banana"]); + t("banana", each_line_any, [~"banana"]); } #[test] - fn test_words () { + fn test_words() { fn t(s: &str, f: &fn(&str, &fn(&str) -> bool) -> bool, u: &[~str]) { let mut v = ~[]; for f(s) |s| { v.push(s.to_owned()) } assert!(vec::all2(v, u, |a,b| a == b)); } - let data = ~"\nMary had a little lamb\nLittle lamb\n"; + let data = "\nMary had a little lamb\nLittle lamb\n"; - t(data, each_word, ~[~"Mary",~"had",~"a",~"little",~"lamb",~"Little",~"lamb"]); - t(~"ok", each_word, ~[~"ok"]); - t(~"", each_word, ~[]); + t(data, each_word, [~"Mary",~"had",~"a",~"little",~"lamb",~"Little",~"lamb"]); + t("ok", each_word, [~"ok"]); + t("", each_word, []); } #[test] @@ -3071,53 +3070,53 @@ mod tests { for each_split_within(s, i) |s| { v.push(s.to_owned()) } assert!(vec::all2(v, u, |a,b| a == b)); } - t(~"", 0, ~[]); - t(~"", 15, ~[]); - t(~"hello", 15, ~[~"hello"]); - t(~"\nMary had a little lamb\nLittle lamb\n", 15, - ~[~"Mary had a", ~"little lamb", ~"Little lamb"]); + t("", 0, []); + t("", 15, []); + t("hello", 15, [~"hello"]); + t("\nMary had a little lamb\nLittle lamb\n", 15, + [~"Mary had a", ~"little lamb", ~"Little lamb"]); } #[test] fn test_find_str() { // byte positions - assert!(find_str(~"banana", ~"apple pie").is_none()); - assert_eq!(find_str(~"", ~""), Some(0u)); + assert!(find_str("banana", "apple pie").is_none()); + assert_eq!(find_str("", ""), Some(0u)); - let data = ~"ประเทศไทย中华Việt Nam"; - assert_eq!(find_str(data, ~""), Some(0u)); - assert_eq!(find_str(data, ~"ประเ"), Some( 0u)); - assert_eq!(find_str(data, ~"ะเ"), Some( 6u)); - assert_eq!(find_str(data, ~"中华"), Some(27u)); - assert!(find_str(data, ~"ไท华").is_none()); + let data = "ประเทศไทย中华Việt Nam"; + assert_eq!(find_str(data, ""), Some(0u)); + assert_eq!(find_str(data, "ประเ"), Some( 0u)); + assert_eq!(find_str(data, "ะเ"), Some( 6u)); + assert_eq!(find_str(data, "中华"), Some(27u)); + assert!(find_str(data, "ไท华").is_none()); } #[test] fn test_find_str_between() { // byte positions - assert_eq!(find_str_between(~"", ~"", 0u, 0u), Some(0u)); + assert_eq!(find_str_between("", "", 0u, 0u), Some(0u)); - let data = ~"abcabc"; - assert_eq!(find_str_between(data, ~"ab", 0u, 6u), Some(0u)); - assert_eq!(find_str_between(data, ~"ab", 2u, 6u), Some(3u)); - assert!(find_str_between(data, ~"ab", 2u, 4u).is_none()); + let data = "abcabc"; + assert_eq!(find_str_between(data, "ab", 0u, 6u), Some(0u)); + assert_eq!(find_str_between(data, "ab", 2u, 6u), Some(3u)); + assert!(find_str_between(data, "ab", 2u, 4u).is_none()); let mut data = ~"ประเทศไทย中华Việt Nam"; data = data + data; - assert_eq!(find_str_between(data, ~"", 0u, 43u), Some(0u)); - assert_eq!(find_str_between(data, ~"", 6u, 43u), Some(6u)); + assert_eq!(find_str_between(data, "", 0u, 43u), Some(0u)); + assert_eq!(find_str_between(data, "", 6u, 43u), Some(6u)); - assert_eq!(find_str_between(data, ~"ประ", 0u, 43u), Some( 0u)); - assert_eq!(find_str_between(data, ~"ทศไ", 0u, 43u), Some(12u)); - assert_eq!(find_str_between(data, ~"ย中", 0u, 43u), Some(24u)); - assert_eq!(find_str_between(data, ~"iệt", 0u, 43u), Some(34u)); - assert_eq!(find_str_between(data, ~"Nam", 0u, 43u), Some(40u)); + assert_eq!(find_str_between(data, "ประ", 0u, 43u), Some( 0u)); + assert_eq!(find_str_between(data, "ทศไ", 0u, 43u), Some(12u)); + assert_eq!(find_str_between(data, "ย中", 0u, 43u), Some(24u)); + assert_eq!(find_str_between(data, "iệt", 0u, 43u), Some(34u)); + assert_eq!(find_str_between(data, "Nam", 0u, 43u), Some(40u)); - assert_eq!(find_str_between(data, ~"ประ", 43u, 86u), Some(43u)); - assert_eq!(find_str_between(data, ~"ทศไ", 43u, 86u), Some(55u)); - assert_eq!(find_str_between(data, ~"ย中", 43u, 86u), Some(67u)); - assert_eq!(find_str_between(data, ~"iệt", 43u, 86u), Some(77u)); - assert_eq!(find_str_between(data, ~"Nam", 43u, 86u), Some(83u)); + assert_eq!(find_str_between(data, "ประ", 43u, 86u), Some(43u)); + assert_eq!(find_str_between(data, "ทศไ", 43u, 86u), Some(55u)); + assert_eq!(find_str_between(data, "ย中", 43u, 86u), Some(67u)); + assert_eq!(find_str_between(data, "iệt", 43u, 86u), Some(77u)); + assert_eq!(find_str_between(data, "Nam", 43u, 86u), Some(83u)); } #[test] @@ -3135,10 +3134,10 @@ mod tests { fn t(v: &[~str], s: &str) { assert_eq!(concat(v), s.to_str()); } - t(~[~"you", ~"know", ~"I'm", ~"no", ~"good"], ~"youknowI'mnogood"); - let v: ~[~str] = ~[]; - t(v, ~""); - t(~[~"hi"], ~"hi"); + t([~"you", ~"know", ~"I'm", ~"no", ~"good"], "youknowI'mnogood"); + let v: &[~str] = []; + t(v, ""); + t([~"hi"], "hi"); } #[test] @@ -3146,11 +3145,11 @@ mod tests { fn t(v: &[~str], sep: &str, s: &str) { assert_eq!(connect(v, sep), s.to_str()); } - t(~[~"you", ~"know", ~"I'm", ~"no", ~"good"], - ~" ", ~"you know I'm no good"); - let v: ~[~str] = ~[]; - t(v, ~" ", ~""); - t(~[~"hi"], ~" ", ~"hi"); + t([~"you", ~"know", ~"I'm", ~"no", ~"good"], + " ", "you know I'm no good"); + let v: &[~str] = ~[]; + t(v, " ", ""); + t([~"hi"], " ", "hi"); } #[test] @@ -3166,11 +3165,11 @@ mod tests { #[test] fn test_repeat() { - assert_eq!(repeat(~"x", 4), ~"xxxx"); - assert_eq!(repeat(~"hi", 4), ~"hihihihi"); - assert_eq!(repeat(~"ไท华", 3), ~"ไท华ไท华ไท华"); - assert_eq!(repeat(~"", 4), ~""); - assert_eq!(repeat(~"hi", 0), ~""); + assert_eq!(repeat("x", 4), ~"xxxx"); + assert_eq!(repeat("hi", 4), ~"hihihihi"); + assert_eq!(repeat("ไท华", 3), ~"ไท华ไท华ไท华"); + assert_eq!(repeat("", 4), ~""); + assert_eq!(repeat("hi", 0), ~""); } #[test] @@ -3197,38 +3196,38 @@ mod tests { #[test] fn test_starts_with() { - assert!((starts_with(~"", ~""))); - assert!((starts_with(~"abc", ~""))); - assert!((starts_with(~"abc", ~"a"))); - assert!((!starts_with(~"a", ~"abc"))); - assert!((!starts_with(~"", ~"abc"))); + assert!((starts_with("", ""))); + assert!((starts_with("abc", ""))); + assert!((starts_with("abc", "a"))); + assert!((!starts_with("a", "abc"))); + assert!((!starts_with("", "abc"))); } #[test] fn test_ends_with() { - assert!((ends_with(~"", ~""))); - assert!((ends_with(~"abc", ~""))); - assert!((ends_with(~"abc", ~"c"))); - assert!((!ends_with(~"a", ~"abc"))); - assert!((!ends_with(~"", ~"abc"))); + assert!((ends_with("", ""))); + assert!((ends_with("abc", ""))); + assert!((ends_with("abc", "c"))); + assert!((!ends_with("a", "abc"))); + assert!((!ends_with("", "abc"))); } #[test] fn test_is_empty() { - assert!((is_empty(~""))); - assert!((!is_empty(~"a"))); + assert!((is_empty(""))); + assert!((!is_empty("a"))); } #[test] fn test_replace() { - let a = ~"a"; - assert_eq!(replace(~"", a, ~"b"), ~""); - assert_eq!(replace(~"a", a, ~"b"), ~"b"); - assert_eq!(replace(~"ab", a, ~"b"), ~"bb"); - let test = ~"test"; - assert!(replace(~" test test ", test, ~"toast") == + let a = "a"; + assert_eq!(replace("", a, "b"), ~""); + assert_eq!(replace("a", a, "b"), ~"b"); + assert_eq!(replace("ab", a, "b"), ~"bb"); + let test = "test"; + assert!(replace(" test test ", test, "toast") == ~" toast toast "); - assert_eq!(replace(~" test test ", test, ~""), ~" "); + assert_eq!(replace(" test test ", test, ""), ~" "); } #[test] @@ -3338,32 +3337,26 @@ mod tests { #[test] fn test_trim_left_chars() { - assert!(trim_left_chars(" *** foo *** ", ~[]) == - " *** foo *** "); - assert!(trim_left_chars(" *** foo *** ", ~['*', ' ']) == - "foo *** "); - assert_eq!(trim_left_chars(" *** *** ", ~['*', ' ']), ""); - assert!(trim_left_chars("foo *** ", ~['*', ' ']) == - "foo *** "); + assert!(trim_left_chars(" *** foo *** ", []) == " *** foo *** "); + assert!(trim_left_chars(" *** foo *** ", ['*', ' ']) == "foo *** "); + assert_eq!(trim_left_chars(" *** *** ", ['*', ' ']), ""); + assert!(trim_left_chars("foo *** ", ['*', ' ']) == "foo *** "); } #[test] fn test_trim_right_chars() { - assert!(trim_right_chars(" *** foo *** ", ~[]) == - " *** foo *** "); - assert!(trim_right_chars(" *** foo *** ", ~['*', ' ']) == - " *** foo"); - assert_eq!(trim_right_chars(" *** *** ", ~['*', ' ']), ""); - assert!(trim_right_chars(" *** foo", ~['*', ' ']) == - " *** foo"); + assert!(trim_right_chars(" *** foo *** ", []) == " *** foo *** "); + assert!(trim_right_chars(" *** foo *** ", ['*', ' ']) == " *** foo"); + assert_eq!(trim_right_chars(" *** *** ", ['*', ' ']), ""); + assert!(trim_right_chars(" *** foo", ['*', ' ']) == " *** foo"); } #[test] fn test_trim_chars() { - assert_eq!(trim_chars(" *** foo *** ", ~[]), " *** foo *** "); - assert_eq!(trim_chars(" *** foo *** ", ~['*', ' ']), "foo"); - assert_eq!(trim_chars(" *** *** ", ~['*', ' ']), ""); - assert_eq!(trim_chars("foo", ~['*', ' ']), "foo"); + assert_eq!(trim_chars(" *** foo *** ", []), " *** foo *** "); + assert_eq!(trim_chars(" *** foo *** ", ['*', ' ']), "foo"); + assert_eq!(trim_chars(" *** *** ", ['*', ' ']), ""); + assert_eq!(trim_chars("foo", ['*', ' ']), "foo"); } #[test] @@ -3398,11 +3391,11 @@ mod tests { #[test] fn test_is_whitespace() { - assert!((is_whitespace(~""))); - assert!((is_whitespace(~" "))); - assert!((is_whitespace(~"\u2009"))); // Thin space - assert!((is_whitespace(~" \n\t "))); - assert!((!is_whitespace(~" _ "))); + assert!(is_whitespace("")); + assert!(is_whitespace(" ")); + assert!(is_whitespace("\u2009")); // Thin space + assert!(is_whitespace(" \n\t ")); + assert!(!is_whitespace(" _ ")); } #[test] @@ -3543,7 +3536,7 @@ mod tests { #[test] fn test_as_buf() { - let a = ~"Abcdefg"; + let a = "Abcdefg"; let b = as_buf(a, |buf, _l| { assert_eq!(unsafe { *buf }, 65u8); 100 @@ -3553,7 +3546,7 @@ mod tests { #[test] fn test_as_buf_small() { - let a = ~"A"; + let a = "A"; let b = as_buf(a, |buf, _l| { assert_eq!(unsafe { *buf }, 65u8); 100 @@ -3631,32 +3624,32 @@ mod tests { #[test] fn test_contains() { - assert!(contains(~"abcde", ~"bcd")); - assert!(contains(~"abcde", ~"abcd")); - assert!(contains(~"abcde", ~"bcde")); - assert!(contains(~"abcde", ~"")); - assert!(contains(~"", ~"")); - assert!(!contains(~"abcde", ~"def")); - assert!(!contains(~"", ~"a")); + assert!(contains("abcde", "bcd")); + assert!(contains("abcde", "abcd")); + assert!(contains("abcde", "bcde")); + assert!(contains("abcde", "")); + assert!(contains("", "")); + assert!(!contains("abcde", "def")); + assert!(!contains("", "a")); let data = ~"ประเทศไทย中华Việt Nam"; - assert!(contains(data, ~"ประเ")); - assert!(contains(data, ~"ะเ")); - assert!(contains(data, ~"中华")); - assert!(!contains(data, ~"ไท华")); + assert!(contains(data, "ประเ")); + assert!(contains(data, "ะเ")); + assert!(contains(data, "中华")); + assert!(!contains(data, "ไท华")); } #[test] fn test_contains_char() { - assert!(contains_char(~"abc", 'b')); - assert!(contains_char(~"a", 'a')); - assert!(!contains_char(~"abc", 'd')); - assert!(!contains_char(~"", 'a')); + assert!(contains_char("abc", 'b')); + assert!(contains_char("a", 'a')); + assert!(!contains_char("abc", 'd')); + assert!(!contains_char("", 'a')); } #[test] fn test_split_char_each() { - let data = ~"\nMary had a little lamb\nLittle lamb\n"; + let data = "\nMary had a little lamb\nLittle lamb\n"; let mut ii = 0; @@ -3674,7 +3667,7 @@ mod tests { #[test] fn test_splitn_char_each() { - let data = ~"\nMary had a little lamb\nLittle lamb\n"; + let data = "\nMary had a little lamb\nLittle lamb\n"; let mut ii = 0; @@ -3691,7 +3684,7 @@ mod tests { #[test] fn test_words_each() { - let data = ~"\nMary had a little lamb\nLittle lamb\n"; + let data = "\nMary had a little lamb\nLittle lamb\n"; let mut ii = 0; @@ -3706,12 +3699,12 @@ mod tests { ii += 1; } - each_word(~"", |_x| fail!()); // should not fail + each_word("", |_x| fail!()); // should not fail } #[test] fn test_lines_each () { - let lf = ~"\nMary had a little lamb\nLittle lamb\n"; + let lf = "\nMary had a little lamb\nLittle lamb\n"; let mut ii = 0; @@ -3728,26 +3721,26 @@ mod tests { #[test] fn test_map() { - assert_eq!(~"", map(~"", |c| unsafe {libc::toupper(c as c_char)} as char)); - assert_eq!(~"YMCA", map(~"ymca", |c| unsafe {libc::toupper(c as c_char)} as char)); + assert_eq!(~"", map("", |c| unsafe {libc::toupper(c as c_char)} as char)); + assert_eq!(~"YMCA", map("ymca", |c| unsafe {libc::toupper(c as c_char)} as char)); } #[test] fn test_all() { - assert_eq!(true, all(~"", char::is_uppercase)); - assert_eq!(false, all(~"ymca", char::is_uppercase)); - assert_eq!(true, all(~"YMCA", char::is_uppercase)); - assert_eq!(false, all(~"yMCA", char::is_uppercase)); - assert_eq!(false, all(~"YMCy", char::is_uppercase)); + assert_eq!(true, all("", char::is_uppercase)); + assert_eq!(false, all("ymca", char::is_uppercase)); + assert_eq!(true, all("YMCA", char::is_uppercase)); + assert_eq!(false, all("yMCA", char::is_uppercase)); + assert_eq!(false, all("YMCy", char::is_uppercase)); } #[test] fn test_any() { - assert_eq!(false, any(~"", char::is_uppercase)); - assert_eq!(false, any(~"ymca", char::is_uppercase)); - assert_eq!(true, any(~"YMCA", char::is_uppercase)); - assert_eq!(true, any(~"yMCA", char::is_uppercase)); - assert_eq!(true, any(~"Ymcy", char::is_uppercase)); + assert_eq!(false, any("", char::is_uppercase)); + assert_eq!(false, any("ymca", char::is_uppercase)); + assert_eq!(true, any("YMCA", char::is_uppercase)); + assert_eq!(true, any("yMCA", char::is_uppercase)); + assert_eq!(true, any("Ymcy", char::is_uppercase)); } #[test] @@ -3761,41 +3754,41 @@ mod tests { #[test] fn test_utf16() { let pairs = - ~[(~"𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n", + [(~"𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n", ~[0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16, - 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16, - 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16, - 0xd800_u16, 0xdf30_u16, 0x000a_u16]), + 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16, + 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16, + 0xd800_u16, 0xdf30_u16, 0x000a_u16]), (~"𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n", ~[0xd801_u16, 0xdc12_u16, 0xd801_u16, - 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16, - 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16, - 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16, - 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16, - 0x000a_u16]), + 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16, + 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16, + 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16, + 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16, + 0x000a_u16]), (~"𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n", ~[0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16, - 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16, - 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16, - 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16, - 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16, - 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16, - 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]), + 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16, + 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16, + 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16, + 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16, + 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16, + 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]), (~"𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n", ~[0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16, - 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16, - 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16, - 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16, - 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16, - 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16, - 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16, - 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16, - 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16, - 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16, - 0x000a_u16 ]) ]; + 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16, + 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16, + 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16, + 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16, + 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16, + 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16, + 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16, + 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16, + 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16, + 0x000a_u16 ]) ]; for pairs.each |p| { let (s, u) = copy *p; @@ -3972,35 +3965,35 @@ mod tests { #[test] fn test_escape_unicode() { - assert_eq!(escape_unicode(~"abc"), ~"\\x61\\x62\\x63"); - assert_eq!(escape_unicode(~"a c"), ~"\\x61\\x20\\x63"); - assert_eq!(escape_unicode(~"\r\n\t"), ~"\\x0d\\x0a\\x09"); - assert_eq!(escape_unicode(~"'\"\\"), ~"\\x27\\x22\\x5c"); - assert!(escape_unicode(~"\x00\x01\xfe\xff") == + assert_eq!(escape_unicode("abc"), ~"\\x61\\x62\\x63"); + assert_eq!(escape_unicode("a c"), ~"\\x61\\x20\\x63"); + assert_eq!(escape_unicode("\r\n\t"), ~"\\x0d\\x0a\\x09"); + assert_eq!(escape_unicode("'\"\\"), ~"\\x27\\x22\\x5c"); + assert!(escape_unicode("\x00\x01\xfe\xff") == ~"\\x00\\x01\\xfe\\xff"); - assert_eq!(escape_unicode(~"\u0100\uffff"), ~"\\u0100\\uffff"); - assert!(escape_unicode(~"\U00010000\U0010ffff") == + assert_eq!(escape_unicode("\u0100\uffff"), ~"\\u0100\\uffff"); + assert!(escape_unicode("\U00010000\U0010ffff") == ~"\\U00010000\\U0010ffff"); - assert_eq!(escape_unicode(~"ab\ufb00"), ~"\\x61\\x62\\ufb00"); - assert_eq!(escape_unicode(~"\U0001d4ea\r"), ~"\\U0001d4ea\\x0d"); + assert_eq!(escape_unicode("ab\ufb00"), ~"\\x61\\x62\\ufb00"); + assert_eq!(escape_unicode("\U0001d4ea\r"), ~"\\U0001d4ea\\x0d"); } #[test] fn test_escape_default() { - assert_eq!(escape_default(~"abc"), ~"abc"); - assert_eq!(escape_default(~"a c"), ~"a c"); - assert_eq!(escape_default(~"\r\n\t"), ~"\\r\\n\\t"); - assert_eq!(escape_default(~"'\"\\"), ~"\\'\\\"\\\\"); - assert_eq!(escape_default(~"\u0100\uffff"), ~"\\u0100\\uffff"); - assert!(escape_default(~"\U00010000\U0010ffff") == + assert_eq!(escape_default("abc"), ~"abc"); + assert_eq!(escape_default("a c"), ~"a c"); + assert_eq!(escape_default("\r\n\t"), ~"\\r\\n\\t"); + assert_eq!(escape_default("'\"\\"), ~"\\'\\\"\\\\"); + assert_eq!(escape_default("\u0100\uffff"), ~"\\u0100\\uffff"); + assert!(escape_default("\U00010000\U0010ffff") == ~"\\U00010000\\U0010ffff"); - assert_eq!(escape_default(~"ab\ufb00"), ~"ab\\ufb00"); - assert_eq!(escape_default(~"\U0001d4ea\r"), ~"\\U0001d4ea\\r"); + assert_eq!(escape_default("ab\ufb00"), ~"ab\\ufb00"); + assert_eq!(escape_default("\U0001d4ea\r"), ~"\\U0001d4ea\\r"); } #[test] fn test_to_managed() { - assert_eq!((~"abc").to_managed(), @"abc"); + assert_eq!("abc".to_managed(), @"abc"); assert_eq!(slice("abcdef", 1, 5).to_managed(), @"bcde"); } diff --git a/src/libstd/str/ascii.rs b/src/libstd/str/ascii.rs index 4e239c4c82c7d..e48fef01df941 100644 --- a/src/libstd/str/ascii.rs +++ b/src/libstd/str/ascii.rs @@ -228,8 +228,8 @@ mod tests { assert_eq!('`'.to_ascii().to_upper().to_char(), '`'); assert_eq!('{'.to_ascii().to_upper().to_char(), '{'); - assert!(str::all(~"banana", |c| c.is_ascii())); - assert!(! str::all(~"ประเทศไทย中华Việt Nam", |c| c.is_ascii())); + assert!(str::all("banana", |c| c.is_ascii())); + assert!(! str::all("ประเทศไทย中华Việt Nam", |c| c.is_ascii())); } #[test] diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 65f8dab25a5aa..103489988a3e8 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -2962,8 +2962,8 @@ mod tests { #[test] fn test_is_empty() { - assert!(is_empty::(~[])); - assert!(!is_empty(~[0])); + assert!(is_empty::([])); + assert!(!is_empty([0])); } #[test] @@ -3445,7 +3445,7 @@ mod tests { #[test] fn test_each_empty() { - for each::(~[]) |_v| { + for each::([]) |_v| { fail!(); // should never be executed } } @@ -3453,7 +3453,7 @@ mod tests { #[test] fn test_each_nonempty() { let mut i = 0; - for each(~[1, 2, 3]) |v| { + for each([1, 2, 3]) |v| { i += *v; } assert_eq!(i, 6); @@ -3462,7 +3462,7 @@ mod tests { #[test] fn test_eachi() { let mut i = 0; - for eachi(~[1, 2, 3]) |j, v| { + for eachi([1, 2, 3]) |j, v| { if i == 0 { assert!(*v == 1); } assert_eq!(j + 1u, *v as uint); i += *v; @@ -3481,7 +3481,7 @@ mod tests { #[test] fn test_each_reverse_nonempty() { let mut i = 0; - for each_reverse(~[1, 2, 3]) |v| { + for each_reverse([1, 2, 3]) |v| { if i == 0 { assert!(*v == 3); } i += *v } @@ -3491,7 +3491,7 @@ mod tests { #[test] fn test_eachi_reverse() { let mut i = 0; - for eachi_reverse(~[0, 1, 2]) |j, v| { + for eachi_reverse([0, 1, 2]) |j, v| { if i == 0 { assert!(*v == 2); } assert_eq!(j, *v as uint); i += *v; @@ -3512,48 +3512,48 @@ mod tests { let mut results: ~[~[int]]; results = ~[]; - for each_permutation(~[]) |v| { results.push(to_owned(v)); } + for each_permutation([]) |v| { results.push(to_owned(v)); } assert_eq!(results, ~[~[]]); results = ~[]; - for each_permutation(~[7]) |v| { results.push(to_owned(v)); } + for each_permutation([7]) |v| { results.push(to_owned(v)); } assert_eq!(results, ~[~[7]]); results = ~[]; - for each_permutation(~[1,1]) |v| { results.push(to_owned(v)); } + for each_permutation([1,1]) |v| { results.push(to_owned(v)); } assert_eq!(results, ~[~[1,1],~[1,1]]); results = ~[]; - for each_permutation(~[5,2,0]) |v| { results.push(to_owned(v)); } + for each_permutation([5,2,0]) |v| { results.push(to_owned(v)); } assert!(results == ~[~[5,2,0],~[5,0,2],~[2,5,0],~[2,0,5],~[0,5,2],~[0,2,5]]); } #[test] fn test_any_and_all() { - assert!(any(~[1u, 2u, 3u], is_three)); - assert!(!any(~[0u, 1u, 2u], is_three)); - assert!(any(~[1u, 2u, 3u, 4u, 5u], is_three)); - assert!(!any(~[1u, 2u, 4u, 5u, 6u], is_three)); + assert!(any([1u, 2u, 3u], is_three)); + assert!(!any([0u, 1u, 2u], is_three)); + assert!(any([1u, 2u, 3u, 4u, 5u], is_three)); + assert!(!any([1u, 2u, 4u, 5u, 6u], is_three)); - assert!(all(~[3u, 3u, 3u], is_three)); - assert!(!all(~[3u, 3u, 2u], is_three)); - assert!(all(~[3u, 3u, 3u, 3u, 3u], is_three)); - assert!(!all(~[3u, 3u, 0u, 1u, 2u], is_three)); + assert!(all([3u, 3u, 3u], is_three)); + assert!(!all([3u, 3u, 2u], is_three)); + assert!(all([3u, 3u, 3u, 3u, 3u], is_three)); + assert!(!all([3u, 3u, 0u, 1u, 2u], is_three)); } #[test] fn test_any2_and_all2() { - assert!(any2(~[2u, 4u, 6u], ~[2u, 4u, 6u], is_equal)); - assert!(any2(~[1u, 2u, 3u], ~[4u, 5u, 3u], is_equal)); - assert!(!any2(~[1u, 2u, 3u], ~[4u, 5u, 6u], is_equal)); - assert!(any2(~[2u, 4u, 6u], ~[2u, 4u], is_equal)); + assert!(any2([2u, 4u, 6u], [2u, 4u, 6u], is_equal)); + assert!(any2([1u, 2u, 3u], [4u, 5u, 3u], is_equal)); + assert!(!any2([1u, 2u, 3u], [4u, 5u, 6u], is_equal)); + assert!(any2([2u, 4u, 6u], [2u, 4u], is_equal)); - assert!(all2(~[2u, 4u, 6u], ~[2u, 4u, 6u], is_equal)); - assert!(!all2(~[1u, 2u, 3u], ~[4u, 5u, 3u], is_equal)); - assert!(!all2(~[1u, 2u, 3u], ~[4u, 5u, 6u], is_equal)); - assert!(!all2(~[2u, 4u, 6u], ~[2u, 4u], is_equal)); + assert!(all2([2u, 4u, 6u], [2u, 4u, 6u], is_equal)); + assert!(!all2([1u, 2u, 3u], [4u, 5u, 3u], is_equal)); + assert!(!all2([1u, 2u, 3u], [4u, 5u, 6u], is_equal)); + assert!(!all2([2u, 4u, 6u], [2u, 4u], is_equal)); } #[test] @@ -3576,7 +3576,7 @@ mod tests { #[test] fn test_position_elem() { - assert!(position_elem(~[], &1).is_none()); + assert!(position_elem([], &1).is_none()); let v1 = ~[1, 2, 3, 3, 2, 5]; assert_eq!(position_elem(v1, &1), Some(0u)); @@ -3590,7 +3590,7 @@ mod tests { fn less_than_three(i: &int) -> bool { *i < 3 } fn is_eighteen(i: &int) -> bool { *i == 18 } - assert!(position(~[], less_than_three).is_none()); + assert!(position([], less_than_three).is_none()); let v1 = ~[5, 4, 3, 2, 1]; assert_eq!(position(v1, less_than_three), Some(3u)); @@ -3599,7 +3599,7 @@ mod tests { #[test] fn test_position_between() { - assert!(position_between(~[], 0u, 0u, f).is_none()); + assert!(position_between([], 0u, 0u, f).is_none()); fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; @@ -3627,7 +3627,7 @@ mod tests { #[test] fn test_find() { - assert!(find(~[], f).is_none()); + assert!(find([], f).is_none()); fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } @@ -3639,7 +3639,7 @@ mod tests { #[test] fn test_find_between() { - assert!(find_between(~[], 0u, 0u, f).is_none()); + assert!(find_between([], 0u, 0u, f).is_none()); fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; @@ -3667,7 +3667,7 @@ mod tests { #[test] fn test_rposition() { - assert!(find(~[], f).is_none()); + assert!(find([], f).is_none()); fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } @@ -3679,7 +3679,7 @@ mod tests { #[test] fn test_rposition_between() { - assert!(rposition_between(~[], 0u, 0u, f).is_none()); + assert!(rposition_between([], 0u, 0u, f).is_none()); fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; @@ -3707,7 +3707,7 @@ mod tests { #[test] fn test_rfind() { - assert!(rfind(~[], f).is_none()); + assert!(rfind([], f).is_none()); fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } @@ -3719,7 +3719,7 @@ mod tests { #[test] fn test_rfind_between() { - assert!(rfind_between(~[], 0u, 0u, f).is_none()); + assert!(rfind_between([], 0u, 0u, f).is_none()); fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; @@ -3798,14 +3798,14 @@ mod tests { reverse(v); assert_eq!(v[0], 20); assert_eq!(v[1], 10); - let v2 = reversed::(~[10, 20]); + let v2 = reversed::([10, 20]); assert_eq!(v2[0], 20); assert_eq!(v2[1], 10); v[0] = 30; assert_eq!(v2[0], 20); // Make sure they work with 0-length vectors too. - let v4 = reversed::(~[]); + let v4 = reversed::([]); assert_eq!(v4, ~[]); let mut v3: ~[int] = ~[]; reverse::(v3); @@ -3813,7 +3813,7 @@ mod tests { #[test] fn reversed_mut() { - let v2 = reversed::(~[10, 20]); + let v2 = reversed::([10, 20]); assert_eq!(v2[0], 20); assert_eq!(v2[1], 10); } @@ -3822,22 +3822,22 @@ mod tests { fn test_split() { fn f(x: &int) -> bool { *x == 3 } - assert_eq!(split(~[], f), ~[]); - assert_eq!(split(~[1, 2], f), ~[~[1, 2]]); - assert_eq!(split(~[3, 1, 2], f), ~[~[], ~[1, 2]]); - assert_eq!(split(~[1, 2, 3], f), ~[~[1, 2], ~[]]); - assert_eq!(split(~[1, 2, 3, 4, 3, 5], f), ~[~[1, 2], ~[4], ~[5]]); + assert_eq!(split([], f), ~[]); + assert_eq!(split([1, 2], f), ~[~[1, 2]]); + assert_eq!(split([3, 1, 2], f), ~[~[], ~[1, 2]]); + assert_eq!(split([1, 2, 3], f), ~[~[1, 2], ~[]]); + assert_eq!(split([1, 2, 3, 4, 3, 5], f), ~[~[1, 2], ~[4], ~[5]]); } #[test] fn test_splitn() { fn f(x: &int) -> bool { *x == 3 } - assert_eq!(splitn(~[], 1u, f), ~[]); - assert_eq!(splitn(~[1, 2], 1u, f), ~[~[1, 2]]); - assert_eq!(splitn(~[3, 1, 2], 1u, f), ~[~[], ~[1, 2]]); - assert_eq!(splitn(~[1, 2, 3], 1u, f), ~[~[1, 2], ~[]]); - assert!(splitn(~[1, 2, 3, 4, 3, 5], 1u, f) == + assert_eq!(splitn([], 1u, f), ~[]); + assert_eq!(splitn([1, 2], 1u, f), ~[~[1, 2]]); + assert_eq!(splitn([3, 1, 2], 1u, f), ~[~[], ~[1, 2]]); + assert_eq!(splitn([1, 2, 3], 1u, f), ~[~[1, 2], ~[]]); + assert!(splitn([1, 2, 3, 4, 3, 5], 1u, f) == ~[~[1, 2], ~[4, 3, 5]]); } @@ -3845,10 +3845,10 @@ mod tests { fn test_rsplit() { fn f(x: &int) -> bool { *x == 3 } - assert_eq!(rsplit(~[], f), ~[]); - assert_eq!(rsplit(~[1, 2], f), ~[~[1, 2]]); - assert_eq!(rsplit(~[1, 2, 3], f), ~[~[1, 2], ~[]]); - assert!(rsplit(~[1, 2, 3, 4, 3, 5], f) == + assert_eq!(rsplit([], f), ~[]); + assert_eq!(rsplit([1, 2], f), ~[~[1, 2]]); + assert_eq!(rsplit([1, 2, 3], f), ~[~[1, 2], ~[]]); + assert!(rsplit([1, 2, 3, 4, 3, 5], f) == ~[~[1, 2], ~[4], ~[5]]); } @@ -3856,53 +3856,46 @@ mod tests { fn test_rsplitn() { fn f(x: &int) -> bool { *x == 3 } - assert_eq!(rsplitn(~[], 1u, f), ~[]); - assert_eq!(rsplitn(~[1, 2], 1u, f), ~[~[1, 2]]); - assert_eq!(rsplitn(~[1, 2, 3], 1u, f), ~[~[1, 2], ~[]]); - assert!(rsplitn(~[1, 2, 3, 4, 3, 5], 1u, f) == - ~[~[1, 2, 3, 4], ~[5]]); + assert_eq!(rsplitn([], 1u, f), ~[]); + assert_eq!(rsplitn([1, 2], 1u, f), ~[~[1, 2]]); + assert_eq!(rsplitn([1, 2, 3], 1u, f), ~[~[1, 2], ~[]]); + assert_eq!(rsplitn([1, 2, 3, 4, 3, 5], 1u, f), ~[~[1, 2, 3, 4], ~[5]]); } #[test] fn test_partition() { // FIXME (#4355 maybe): using v.partition here crashes assert_eq!(partition(~[], |x: &int| *x < 3), (~[], ~[])); - assert!(partition(~[1, 2, 3], |x: &int| *x < 4) == - (~[1, 2, 3], ~[])); - assert!(partition(~[1, 2, 3], |x: &int| *x < 2) == - (~[1], ~[2, 3])); - assert!(partition(~[1, 2, 3], |x: &int| *x < 0) == - (~[], ~[1, 2, 3])); + assert_eq!(partition(~[1, 2, 3], |x: &int| *x < 4), (~[1, 2, 3], ~[])); + assert_eq!(partition(~[1, 2, 3], |x: &int| *x < 2), (~[1], ~[2, 3])); + assert_eq!(partition(~[1, 2, 3], |x: &int| *x < 0), (~[], ~[1, 2, 3])); } #[test] fn test_partitioned() { - assert_eq!((~[]).partitioned(|x: &int| *x < 3), (~[], ~[])) - assert!((~[1, 2, 3]).partitioned(|x: &int| *x < 4) == - (~[1, 2, 3], ~[])); - assert!((~[1, 2, 3]).partitioned(|x: &int| *x < 2) == - (~[1], ~[2, 3])); - assert!((~[1, 2, 3]).partitioned(|x: &int| *x < 0) == - (~[], ~[1, 2, 3])); + assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[])) + assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[])); + assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3])); + assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3])); } #[test] fn test_concat() { - assert_eq!(concat(~[~[1], ~[2,3]]), ~[1, 2, 3]); + assert_eq!(concat([~[1], ~[2,3]]), ~[1, 2, 3]); } #[test] fn test_connect() { - assert_eq!(connect(~[], &0), ~[]); - assert_eq!(connect(~[~[1], ~[2, 3]], &0), ~[1, 0, 2, 3]); - assert_eq!(connect(~[~[1], ~[2], ~[3]], &0), ~[1, 0, 2, 0, 3]); + assert_eq!(connect([], &0), ~[]); + assert_eq!(connect([~[1], ~[2, 3]], &0), ~[1, 0, 2, 3]); + assert_eq!(connect([~[1], ~[2], ~[3]], &0), ~[1, 0, 2, 0, 3]); } #[test] fn test_windowed () { fn t(n: uint, expected: &[&[int]]) { let mut i = 0; - for windowed(n, ~[1,2,3,4,5,6]) |v| { + for windowed(n, [1,2,3,4,5,6]) |v| { assert_eq!(v, expected[i]); i += 1; } @@ -3920,7 +3913,7 @@ mod tests { #[should_fail] #[ignore(cfg(windows))] fn test_windowed_() { - for windowed (0u, ~[1u,2u,3u,4u,5u,6u]) |_v| {} + for windowed (0u, [1u,2u,3u,4u,5u,6u]) |_v| {} } #[test] From 609a9e69e1c1def4d570cfb3c31640200ef738c9 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 09:39:00 -0700 Subject: [PATCH 208/248] cleanup warnings from libextra --- src/libextra/base64.rs | 18 +-- src/libextra/bitv.rs | 17 +-- src/libextra/dlist.rs | 42 +++--- src/libextra/fileinput.rs | 15 +- src/libextra/flate.rs | 55 +++---- src/libextra/getopts.rs | 255 ++++++++++++++++----------------- src/libextra/json.rs | 248 ++++++++++++++++---------------- src/libextra/list.rs | 26 ++-- src/libextra/md4.rs | 14 +- src/libextra/net_ip.rs | 4 +- src/libextra/net_tcp.rs | 2 +- src/libextra/net_url.rs | 14 +- src/libextra/num/bigint.rs | 18 +-- src/libextra/priority_queue.rs | 1 - src/libextra/sha1.rs | 2 +- src/libextra/sort.rs | 2 +- src/libextra/std.rc | 1 - src/libextra/test.rs | 4 +- src/libextra/time.rs | 188 ++++++++++++------------ src/libextra/treemap.rs | 8 +- 20 files changed, 460 insertions(+), 474 deletions(-) diff --git a/src/libextra/base64.rs b/src/libextra/base64.rs index e623740ca81e3..41584710a4171 100644 --- a/src/libextra/base64.rs +++ b/src/libextra/base64.rs @@ -12,10 +12,6 @@ use core::prelude::*; -use core::old_iter; -use core::str; -use core::vec; - pub trait ToBase64 { fn to_base64(&self) -> ~str; } @@ -242,12 +238,12 @@ mod tests { #[test] fn test_from_base64() { - assert_eq!((~"").from_base64(), str::to_bytes(~"")); - assert!((~"Zg==").from_base64() == str::to_bytes(~"f")); - assert_eq!((~"Zm8=").from_base64(), str::to_bytes(~"fo")); - assert_eq!((~"Zm9v").from_base64(), str::to_bytes(~"foo")); - assert!((~"Zm9vYg==").from_base64() == str::to_bytes(~"foob")); - assert_eq!((~"Zm9vYmE=").from_base64(), str::to_bytes(~"fooba")) - assert_eq!((~"Zm9vYmFy").from_base64(), str::to_bytes(~"foobar")); + assert_eq!((~"").from_base64(), str::to_bytes("")); + assert!((~"Zg==").from_base64() == str::to_bytes("f")); + assert_eq!((~"Zm8=").from_base64(), str::to_bytes("fo")); + assert_eq!((~"Zm9v").from_base64(), str::to_bytes("foo")); + assert!((~"Zm9vYg==").from_base64() == str::to_bytes("foob")); + assert_eq!((~"Zm9vYmE=").from_base64(), str::to_bytes("fooba")) + assert_eq!((~"Zm9vYmFy").from_base64(), str::to_bytes("foobar")); } } diff --git a/src/libextra/bitv.rs b/src/libextra/bitv.rs index c12ebf8fb46ea..1262e90518db3 100644 --- a/src/libextra/bitv.rs +++ b/src/libextra/bitv.rs @@ -10,8 +10,6 @@ use core::prelude::*; -use core::vec::from_elem; - struct SmallBitv { /// only the lowest nbits of this value are used. the rest is undefined. bits: uint @@ -257,7 +255,7 @@ pub impl Bitv { let nelems = nbits/uint::bits + if nbits % uint::bits == 0 {0} else {1}; let elem = if init {!0} else {0}; - let s = from_elem(nelems, elem); + let s = vec::from_elem(nelems, elem); Big(~BigBitv::new(s)) }; Bitv {rep: rep, nbits: nbits} @@ -502,7 +500,7 @@ impl Clone for Bitv { Bitv{nbits: self.nbits, rep: Small(~SmallBitv{bits: b.bits})} } Big(ref b) => { - let mut st = from_elem(self.nbits / uint::bits + 1, 0); + let mut st = vec::from_elem(self.nbits / uint::bits + 1, 0); let len = st.len(); for uint::range(0, len) |i| { st[i] = b.storage[i]; }; Bitv{nbits: self.nbits, rep: Big(~BigBitv{storage: st})} @@ -872,17 +870,14 @@ mod tests { #[test] fn test_0_elements() { - let mut act; - let exp; - act = Bitv::new(0u, false); - exp = vec::from_elem::(0u, 0u); + let act = Bitv::new(0u, false); + let exp = vec::from_elem::(0u, 0u); assert!(act.eq_vec(exp)); } #[test] fn test_1_element() { - let mut act; - act = Bitv::new(1u, false); + let mut act = Bitv::new(1u, false); assert!(act.eq_vec(~[0u])); act = Bitv::new(1u, true); assert!(act.eq_vec(~[1u])); @@ -1488,7 +1483,7 @@ mod tests { #[bench] fn bench_bitv_big_union(b: &mut BenchHarness) { let mut b1 = Bitv::new(bench_bits, false); - let mut b2 = Bitv::new(bench_bits, false); + let b2 = Bitv::new(bench_bits, false); do b.iter { b1.union(&b2); } diff --git a/src/libextra/dlist.rs b/src/libextra/dlist.rs index 75249b9f467ad..d3da13dde987a 100644 --- a/src/libextra/dlist.rs +++ b/src/libextra/dlist.rs @@ -540,13 +540,13 @@ mod tests { #[test] fn test_dlist_concat() { - let a = from_vec(~[1,2]); - let b = from_vec(~[3,4]); - let c = from_vec(~[5,6]); - let d = from_vec(~[7,8]); - let ab = from_vec(~[a,b]); - let cd = from_vec(~[c,d]); - let abcd = concat(concat(from_vec(~[ab,cd]))); + let a = from_vec([1,2]); + let b = from_vec([3,4]); + let c = from_vec([5,6]); + let d = from_vec([7,8]); + let ab = from_vec([a,b]); + let cd = from_vec([c,d]); + let abcd = concat(concat(from_vec([ab,cd]))); abcd.assert_consistent(); assert_eq!(abcd.len(), 8); abcd.assert_consistent(); assert_eq!(abcd.pop().get(), 1); abcd.assert_consistent(); assert_eq!(abcd.pop().get(), 2); @@ -560,8 +560,8 @@ mod tests { } #[test] fn test_dlist_append() { - let a = from_vec(~[1,2,3]); - let b = from_vec(~[4,5,6]); + let a = from_vec([1,2,3]); + let b = from_vec([4,5,6]); a.append(b); assert_eq!(a.len(), 6); assert_eq!(b.len(), 0); @@ -576,7 +576,7 @@ mod tests { } #[test] fn test_dlist_append_empty() { - let a = from_vec(~[1,2,3]); + let a = from_vec([1,2,3]); let b = DList::(); a.append(b); assert_eq!(a.len(), 3); @@ -590,7 +590,7 @@ mod tests { #[test] fn test_dlist_append_to_empty() { let a = DList::(); - let b = from_vec(~[4,5,6]); + let b = from_vec([4,5,6]); a.append(b); assert_eq!(a.len(), 3); assert_eq!(b.len(), 0); @@ -626,8 +626,8 @@ mod tests { } #[test] fn test_dlist_prepend() { - let a = from_vec(~[1,2,3]); - let b = from_vec(~[4,5,6]); + let a = from_vec([1,2,3]); + let b = from_vec([4,5,6]); b.prepend(a); assert_eq!(a.len(), 0); assert_eq!(b.len(), 6); @@ -642,7 +642,7 @@ mod tests { } #[test] fn test_dlist_reverse() { - let a = from_vec(~[5,4,3,2,1]); + let a = from_vec([5,4,3,2,1]); a.reverse(); assert_eq!(a.len(), 5); a.assert_consistent(); assert_eq!(a.pop().get(), 1); @@ -661,7 +661,7 @@ mod tests { } #[test] fn test_dlist_each_node() { - let a = from_vec(~[1,2,4,5]); + let a = from_vec([1,2,4,5]); for a.each_node |nobe| { if nobe.data > 3 { a.insert_before(3, nobe); @@ -678,7 +678,7 @@ mod tests { } #[test] fn test_dlist_clear() { - let a = from_vec(~[5,4,3,2,1]); + let a = from_vec([5,4,3,2,1]); a.clear(); assert_eq!(a.len(), 0); a.assert_consistent(); @@ -686,20 +686,20 @@ mod tests { #[test] fn test_dlist_is_empty() { let empty = DList::(); - let full1 = from_vec(~[1,2,3]); + let full1 = from_vec([1,2,3]); assert!(empty.is_empty()); assert!(!full1.is_empty()); } #[test] fn test_dlist_head_tail() { - let l = from_vec(~[1,2,3]); + let l = from_vec([1,2,3]); assert_eq!(l.head(), 1); assert_eq!(l.tail(), 3); assert_eq!(l.len(), 3); } #[test] fn test_dlist_pop() { - let l = from_vec(~[1,2,3]); + let l = from_vec([1,2,3]); assert_eq!(l.pop().get(), 1); assert_eq!(l.tail(), 3); assert_eq!(l.head(), 2); @@ -712,7 +712,7 @@ mod tests { } #[test] fn test_dlist_pop_tail() { - let l = from_vec(~[1,2,3]); + let l = from_vec([1,2,3]); assert_eq!(l.pop_tail().get(), 3); assert_eq!(l.tail(), 2); assert_eq!(l.head(), 1); @@ -758,7 +758,7 @@ mod tests { } #[test] fn test_dlist_break_early() { - let l = from_vec(~[1,2,3,4,5]); + let l = from_vec([1,2,3,4,5]); let mut x = 0; for l.each |i| { x += 1; diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index ec2c73251ba12..42dde4ab890c8 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -96,8 +96,6 @@ total line count). use core::prelude::*; -use core::io::ReaderUtil; - /** A summary of the internal state of a `FileInput` object. `line_num` and `line_num_file` represent the number of lines read in total and in @@ -407,7 +405,6 @@ pub fn input_vec_state(files: ~[Option], mod test { use core::prelude::*; - use core::io::WriterUtil; use super::{FileInput, pathify, input_vec, input_vec_state}; fn make_file(path : &Path, contents: &[~str]) { @@ -441,7 +438,7 @@ mod test { // 3 files containing 0\n, 1\n, and 2\n respectively for filenames.eachi |i, &filename| { - make_file(filename.get_ref(), ~[fmt!("%u", i)]); + make_file(filename.get_ref(), [fmt!("%u", i)]); } let fi = FileInput::from_vec(copy filenames); @@ -471,7 +468,7 @@ mod test { // 3 files containing 1\n, 2\n, and 3\n respectively for filenames.eachi |i, &filename| { - make_file(filename.get_ref(), ~[fmt!("%u", i)]); + make_file(filename.get_ref(), [fmt!("%u", i)]); } let fi = FileInput::from_vec(filenames); @@ -533,9 +530,9 @@ mod test { 3, |i| fmt!("tmp/lib-fileinput-test-empty-files-%u.tmp", i)),true); - make_file(filenames[0].get_ref(), ~[~"1", ~"2"]); - make_file(filenames[1].get_ref(), ~[]); - make_file(filenames[2].get_ref(), ~[~"3", ~"4"]); + make_file(filenames[0].get_ref(), [~"1", ~"2"]); + make_file(filenames[1].get_ref(), []); + make_file(filenames[2].get_ref(), [~"3", ~"4"]); let mut count = 0; for input_vec_state(copy filenames) |line, state| { @@ -580,7 +577,7 @@ mod test { make_file(&filename.get(), contents); } - let mut in = FileInput::from_vec(filenames); + let in = FileInput::from_vec(filenames); // read once from 0 assert_eq!(in.read_line(), ~"0 1"); diff --git a/src/libextra/flate.rs b/src/libextra/flate.rs index 1f57383140ba2..d184e67ab29f8 100644 --- a/src/libextra/flate.rs +++ b/src/libextra/flate.rs @@ -16,12 +16,8 @@ Simple compression use core::prelude::*; -use core::libc::{c_void, size_t, c_int}; use core::libc; -use core::vec; - -#[cfg(test)] use core::rand; -#[cfg(test)] use core::rand::RngUtil; +use core::libc::{c_void, size_t, c_int}; pub mod rustrt { use core::libc::{c_int, c_void, size_t}; @@ -83,27 +79,34 @@ pub fn inflate_bytes(bytes: &const [u8]) -> ~[u8] { } } -#[test] -#[allow(non_implicitly_copyable_typarams)] -fn test_flate_round_trip() { - let mut r = rand::rng(); - let mut words = ~[]; - for 20.times { - let range = r.gen_uint_range(1, 10); - words.push(r.gen_bytes(range)); - } - for 20.times { - let mut in = ~[]; - for 2000.times { - in.push_all(r.choose(words)); +#[cfg(test)] +mod tests { + use super::*; + use core::rand; + use core::rand::RngUtil; + + #[test] + #[allow(non_implicitly_copyable_typarams)] + fn test_flate_round_trip() { + let mut r = rand::rng(); + let mut words = ~[]; + for 20.times { + let range = r.gen_uint_range(1, 10); + words.push(r.gen_bytes(range)); + } + for 20.times { + let mut in = ~[]; + for 2000.times { + in.push_all(r.choose(words)); + } + debug!("de/inflate of %u bytes of random word-sequences", + in.len()); + let cmp = deflate_bytes(in); + let out = inflate_bytes(cmp); + debug!("%u bytes deflated to %u (%.1f%% size)", + in.len(), cmp.len(), + 100.0 * ((cmp.len() as float) / (in.len() as float))); + assert_eq!(in, out); } - debug!("de/inflate of %u bytes of random word-sequences", - in.len()); - let cmp = deflate_bytes(in); - let out = inflate_bytes(cmp); - debug!("%u bytes deflated to %u (%.1f%% size)", - in.len(), cmp.len(), - 100.0 * ((cmp.len() as float) / (in.len() as float))); - assert_eq!(in, out); } } diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index f4779c24a4ab1..539d18cb0cd5b 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -681,12 +681,12 @@ mod tests { #[test] fn test_reqopt_long() { let args = ~[~"--test=20"]; - let opts = ~[reqopt(~"test")]; + let opts = ~[reqopt("test")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"test"))); - assert_eq!(opt_str(m, ~"test"), ~"20"); + assert!((opt_present(m, "test"))); + assert_eq!(opt_str(m, "test"), ~"20"); } _ => { fail!("test_reqopt_long failed"); } } @@ -695,7 +695,7 @@ mod tests { #[test] fn test_reqopt_long_missing() { let args = ~[~"blah"]; - let opts = ~[reqopt(~"test")]; + let opts = ~[reqopt("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionMissing_), @@ -706,7 +706,7 @@ mod tests { #[test] fn test_reqopt_long_no_arg() { let args = ~[~"--test"]; - let opts = ~[reqopt(~"test")]; + let opts = ~[reqopt("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, ArgumentMissing_), @@ -717,7 +717,7 @@ mod tests { #[test] fn test_reqopt_long_multi() { let args = ~[~"--test=20", ~"--test=30"]; - let opts = ~[reqopt(~"test")]; + let opts = ~[reqopt("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionDuplicated_), @@ -728,12 +728,12 @@ mod tests { #[test] fn test_reqopt_short() { let args = ~[~"-t", ~"20"]; - let opts = ~[reqopt(~"t")]; + let opts = ~[reqopt("t")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"t"))); - assert_eq!(opt_str(m, ~"t"), ~"20"); + assert!((opt_present(m, "t"))); + assert_eq!(opt_str(m, "t"), ~"20"); } _ => fail!() } @@ -742,7 +742,7 @@ mod tests { #[test] fn test_reqopt_short_missing() { let args = ~[~"blah"]; - let opts = ~[reqopt(~"t")]; + let opts = ~[reqopt("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionMissing_), @@ -753,7 +753,7 @@ mod tests { #[test] fn test_reqopt_short_no_arg() { let args = ~[~"-t"]; - let opts = ~[reqopt(~"t")]; + let opts = ~[reqopt("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, ArgumentMissing_), @@ -764,7 +764,7 @@ mod tests { #[test] fn test_reqopt_short_multi() { let args = ~[~"-t", ~"20", ~"-t", ~"30"]; - let opts = ~[reqopt(~"t")]; + let opts = ~[reqopt("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionDuplicated_), @@ -777,12 +777,12 @@ mod tests { #[test] fn test_optopt_long() { let args = ~[~"--test=20"]; - let opts = ~[optopt(~"test")]; + let opts = ~[optopt("test")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"test"))); - assert_eq!(opt_str(m, ~"test"), ~"20"); + assert!((opt_present(m, "test"))); + assert_eq!(opt_str(m, "test"), ~"20"); } _ => fail!() } @@ -791,10 +791,10 @@ mod tests { #[test] fn test_optopt_long_missing() { let args = ~[~"blah"]; - let opts = ~[optopt(~"test")]; + let opts = ~[optopt("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, ~"test")), + Ok(ref m) => assert!(!opt_present(m, "test")), _ => fail!() } } @@ -802,7 +802,7 @@ mod tests { #[test] fn test_optopt_long_no_arg() { let args = ~[~"--test"]; - let opts = ~[optopt(~"test")]; + let opts = ~[optopt("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, ArgumentMissing_), @@ -813,7 +813,7 @@ mod tests { #[test] fn test_optopt_long_multi() { let args = ~[~"--test=20", ~"--test=30"]; - let opts = ~[optopt(~"test")]; + let opts = ~[optopt("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionDuplicated_), @@ -824,12 +824,12 @@ mod tests { #[test] fn test_optopt_short() { let args = ~[~"-t", ~"20"]; - let opts = ~[optopt(~"t")]; + let opts = ~[optopt("t")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"t"))); - assert_eq!(opt_str(m, ~"t"), ~"20"); + assert!((opt_present(m, "t"))); + assert_eq!(opt_str(m, "t"), ~"20"); } _ => fail!() } @@ -838,10 +838,10 @@ mod tests { #[test] fn test_optopt_short_missing() { let args = ~[~"blah"]; - let opts = ~[optopt(~"t")]; + let opts = ~[optopt("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, ~"t")), + Ok(ref m) => assert!(!opt_present(m, "t")), _ => fail!() } } @@ -849,7 +849,7 @@ mod tests { #[test] fn test_optopt_short_no_arg() { let args = ~[~"-t"]; - let opts = ~[optopt(~"t")]; + let opts = ~[optopt("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, ArgumentMissing_), @@ -860,7 +860,7 @@ mod tests { #[test] fn test_optopt_short_multi() { let args = ~[~"-t", ~"20", ~"-t", ~"30"]; - let opts = ~[optopt(~"t")]; + let opts = ~[optopt("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionDuplicated_), @@ -873,10 +873,10 @@ mod tests { #[test] fn test_optflag_long() { let args = ~[~"--test"]; - let opts = ~[optflag(~"test")]; + let opts = ~[optflag("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(opt_present(m, ~"test")), + Ok(ref m) => assert!(opt_present(m, "test")), _ => fail!() } } @@ -884,10 +884,10 @@ mod tests { #[test] fn test_optflag_long_missing() { let args = ~[~"blah"]; - let opts = ~[optflag(~"test")]; + let opts = ~[optflag("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, ~"test")), + Ok(ref m) => assert!(!opt_present(m, "test")), _ => fail!() } } @@ -895,7 +895,7 @@ mod tests { #[test] fn test_optflag_long_arg() { let args = ~[~"--test=20"]; - let opts = ~[optflag(~"test")]; + let opts = ~[optflag("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => { @@ -909,7 +909,7 @@ mod tests { #[test] fn test_optflag_long_multi() { let args = ~[~"--test", ~"--test"]; - let opts = ~[optflag(~"test")]; + let opts = ~[optflag("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionDuplicated_), @@ -920,10 +920,10 @@ mod tests { #[test] fn test_optflag_short() { let args = ~[~"-t"]; - let opts = ~[optflag(~"t")]; + let opts = ~[optflag("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(opt_present(m, ~"t")), + Ok(ref m) => assert!(opt_present(m, "t")), _ => fail!() } } @@ -931,10 +931,10 @@ mod tests { #[test] fn test_optflag_short_missing() { let args = ~[~"blah"]; - let opts = ~[optflag(~"t")]; + let opts = ~[optflag("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, ~"t")), + Ok(ref m) => assert!(!opt_present(m, "t")), _ => fail!() } } @@ -942,7 +942,7 @@ mod tests { #[test] fn test_optflag_short_arg() { let args = ~[~"-t", ~"20"]; - let opts = ~[optflag(~"t")]; + let opts = ~[optflag("t")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { @@ -957,7 +957,7 @@ mod tests { #[test] fn test_optflag_short_multi() { let args = ~[~"-t", ~"-t"]; - let opts = ~[optflag(~"t")]; + let opts = ~[optflag("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, OptionDuplicated_), @@ -969,11 +969,11 @@ mod tests { #[test] fn test_optflagmulti_short1() { let args = ~[~"-v"]; - let opts = ~[optflagmulti(~"v")]; + let opts = ~[optflagmulti("v")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, ~"v"), 1); + assert_eq!(opt_count(m, "v"), 1); } _ => fail!() } @@ -982,11 +982,11 @@ mod tests { #[test] fn test_optflagmulti_short2a() { let args = ~[~"-v", ~"-v"]; - let opts = ~[optflagmulti(~"v")]; + let opts = ~[optflagmulti("v")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, ~"v"), 2); + assert_eq!(opt_count(m, "v"), 2); } _ => fail!() } @@ -995,11 +995,11 @@ mod tests { #[test] fn test_optflagmulti_short2b() { let args = ~[~"-vv"]; - let opts = ~[optflagmulti(~"v")]; + let opts = ~[optflagmulti("v")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, ~"v"), 2); + assert_eq!(opt_count(m, "v"), 2); } _ => fail!() } @@ -1008,11 +1008,11 @@ mod tests { #[test] fn test_optflagmulti_long1() { let args = ~[~"--verbose"]; - let opts = ~[optflagmulti(~"verbose")]; + let opts = ~[optflagmulti("verbose")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, ~"verbose"), 1); + assert_eq!(opt_count(m, "verbose"), 1); } _ => fail!() } @@ -1021,11 +1021,11 @@ mod tests { #[test] fn test_optflagmulti_long2() { let args = ~[~"--verbose", ~"--verbose"]; - let opts = ~[optflagmulti(~"verbose")]; + let opts = ~[optflagmulti("verbose")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert_eq!(opt_count(m, ~"verbose"), 2); + assert_eq!(opt_count(m, "verbose"), 2); } _ => fail!() } @@ -1035,12 +1035,12 @@ mod tests { #[test] fn test_optmulti_long() { let args = ~[~"--test=20"]; - let opts = ~[optmulti(~"test")]; + let opts = ~[optmulti("test")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"test"))); - assert_eq!(opt_str(m, ~"test"), ~"20"); + assert!((opt_present(m, "test"))); + assert_eq!(opt_str(m, "test"), ~"20"); } _ => fail!() } @@ -1049,10 +1049,10 @@ mod tests { #[test] fn test_optmulti_long_missing() { let args = ~[~"blah"]; - let opts = ~[optmulti(~"test")]; + let opts = ~[optmulti("test")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, ~"test")), + Ok(ref m) => assert!(!opt_present(m, "test")), _ => fail!() } } @@ -1060,7 +1060,7 @@ mod tests { #[test] fn test_optmulti_long_no_arg() { let args = ~[~"--test"]; - let opts = ~[optmulti(~"test")]; + let opts = ~[optmulti("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, ArgumentMissing_), @@ -1071,13 +1071,13 @@ mod tests { #[test] fn test_optmulti_long_multi() { let args = ~[~"--test=20", ~"--test=30"]; - let opts = ~[optmulti(~"test")]; + let opts = ~[optmulti("test")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!(opt_present(m, ~"test")); - assert_eq!(opt_str(m, ~"test"), ~"20"); - let pair = opt_strs(m, ~"test"); + assert!(opt_present(m, "test")); + assert_eq!(opt_str(m, "test"), ~"20"); + let pair = opt_strs(m, "test"); assert!(pair[0] == ~"20"); assert!(pair[1] == ~"30"); } @@ -1088,12 +1088,12 @@ mod tests { #[test] fn test_optmulti_short() { let args = ~[~"-t", ~"20"]; - let opts = ~[optmulti(~"t")]; + let opts = ~[optmulti("t")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"t"))); - assert_eq!(opt_str(m, ~"t"), ~"20"); + assert!((opt_present(m, "t"))); + assert_eq!(opt_str(m, "t"), ~"20"); } _ => fail!() } @@ -1102,10 +1102,10 @@ mod tests { #[test] fn test_optmulti_short_missing() { let args = ~[~"blah"]; - let opts = ~[optmulti(~"t")]; + let opts = ~[optmulti("t")]; let rs = getopts(args, opts); match rs { - Ok(ref m) => assert!(!opt_present(m, ~"t")), + Ok(ref m) => assert!(!opt_present(m, "t")), _ => fail!() } } @@ -1113,7 +1113,7 @@ mod tests { #[test] fn test_optmulti_short_no_arg() { let args = ~[~"-t"]; - let opts = ~[optmulti(~"t")]; + let opts = ~[optmulti("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, ArgumentMissing_), @@ -1124,13 +1124,13 @@ mod tests { #[test] fn test_optmulti_short_multi() { let args = ~[~"-t", ~"20", ~"-t", ~"30"]; - let opts = ~[optmulti(~"t")]; + let opts = ~[optmulti("t")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { - assert!((opt_present(m, ~"t"))); - assert_eq!(opt_str(m, ~"t"), ~"20"); - let pair = opt_strs(m, ~"t"); + assert!((opt_present(m, "t"))); + assert_eq!(opt_str(m, "t"), ~"20"); + let pair = opt_strs(m, "t"); assert!(pair[0] == ~"20"); assert!(pair[1] == ~"30"); } @@ -1141,7 +1141,7 @@ mod tests { #[test] fn test_unrecognized_option_long() { let args = ~[~"--untest"]; - let opts = ~[optmulti(~"t")]; + let opts = ~[optmulti("t")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, UnrecognizedOption_), @@ -1152,7 +1152,7 @@ mod tests { #[test] fn test_unrecognized_option_short() { let args = ~[~"-t"]; - let opts = ~[optmulti(~"test")]; + let opts = ~[optmulti("test")]; let rs = getopts(args, opts); match rs { Err(copy f) => check_fail_type(f, UnrecognizedOption_), @@ -1167,26 +1167,26 @@ mod tests { ~"--flag", ~"--long=30", ~"-f", ~"-m", ~"40", ~"-m", ~"50", ~"-n", ~"-A B", ~"-n", ~"-60 70"]; let opts = - ~[optopt(~"s"), optflag(~"flag"), reqopt(~"long"), - optflag(~"f"), optmulti(~"m"), optmulti(~"n"), - optopt(~"notpresent")]; + ~[optopt("s"), optflag("flag"), reqopt("long"), + optflag("f"), optmulti("m"), optmulti("n"), + optopt("notpresent")]; let rs = getopts(args, opts); match rs { Ok(ref m) => { assert!(m.free[0] == ~"prog"); assert!(m.free[1] == ~"free1"); - assert_eq!(opt_str(m, ~"s"), ~"20"); + assert_eq!(opt_str(m, "s"), ~"20"); assert!(m.free[2] == ~"free2"); - assert!((opt_present(m, ~"flag"))); - assert_eq!(opt_str(m, ~"long"), ~"30"); - assert!((opt_present(m, ~"f"))); - let pair = opt_strs(m, ~"m"); + assert!((opt_present(m, "flag"))); + assert_eq!(opt_str(m, "long"), ~"30"); + assert!((opt_present(m, "f"))); + let pair = opt_strs(m, "m"); assert!(pair[0] == ~"40"); assert!(pair[1] == ~"50"); - let pair = opt_strs(m, ~"n"); + let pair = opt_strs(m, "n"); assert!(pair[0] == ~"-A B"); assert!(pair[1] == ~"-60 70"); - assert!((!opt_present(m, ~"notpresent"))); + assert!((!opt_present(m, "notpresent"))); } _ => fail!() } @@ -1195,43 +1195,43 @@ mod tests { #[test] fn test_multi() { let args = ~[~"-e", ~"foo", ~"--encrypt", ~"foo"]; - let opts = ~[optopt(~"e"), optopt(~"encrypt"), optopt(~"f")]; + let opts = ~[optopt("e"), optopt("encrypt"), optopt("f")]; let matches = &match getopts(args, opts) { result::Ok(m) => m, result::Err(_) => fail!() }; - assert!(opts_present(matches, ~[~"e"])); - assert!(opts_present(matches, ~[~"encrypt"])); - assert!(opts_present(matches, ~[~"encrypt", ~"e"])); - assert!(opts_present(matches, ~[~"e", ~"encrypt"])); - assert!(!opts_present(matches, ~[~"f"])); - assert!(!opts_present(matches, ~[~"thing"])); - assert!(!opts_present(matches, ~[])); + assert!(opts_present(matches, [~"e"])); + assert!(opts_present(matches, [~"encrypt"])); + assert!(opts_present(matches, [~"encrypt", ~"e"])); + assert!(opts_present(matches, [~"e", ~"encrypt"])); + assert!(!opts_present(matches, [~"f"])); + assert!(!opts_present(matches, [~"thing"])); + assert!(!opts_present(matches, [])); - assert_eq!(opts_str(matches, ~[~"e"]), ~"foo"); - assert_eq!(opts_str(matches, ~[~"encrypt"]), ~"foo"); - assert_eq!(opts_str(matches, ~[~"e", ~"encrypt"]), ~"foo"); - assert_eq!(opts_str(matches, ~[~"encrypt", ~"e"]), ~"foo"); + assert_eq!(opts_str(matches, [~"e"]), ~"foo"); + assert_eq!(opts_str(matches, [~"encrypt"]), ~"foo"); + assert_eq!(opts_str(matches, [~"e", ~"encrypt"]), ~"foo"); + assert_eq!(opts_str(matches, [~"encrypt", ~"e"]), ~"foo"); } #[test] fn test_nospace() { let args = ~[~"-Lfoo", ~"-M."]; - let opts = ~[optmulti(~"L"), optmulti(~"M")]; + let opts = ~[optmulti("L"), optmulti("M")]; let matches = &match getopts(args, opts) { result::Ok(m) => m, result::Err(_) => fail!() }; - assert!(opts_present(matches, ~[~"L"])); - assert_eq!(opts_str(matches, ~[~"L"]), ~"foo"); - assert!(opts_present(matches, ~[~"M"])); - assert_eq!(opts_str(matches, ~[~"M"]), ~"."); + assert!(opts_present(matches, [~"L"])); + assert_eq!(opts_str(matches, [~"L"]), ~"foo"); + assert!(opts_present(matches, [~"M"])); + assert_eq!(opts_str(matches, [~"M"]), ~"."); } #[test] fn test_groups_reqopt() { - let opt = groups::reqopt(~"b", ~"banana", ~"some bananas", ~"VAL"); + let opt = groups::reqopt("b", "banana", "some bananas", "VAL"); assert!(opt == OptGroup { short_name: ~"b", long_name: ~"banana", hint: ~"VAL", @@ -1242,7 +1242,7 @@ mod tests { #[test] fn test_groups_optopt() { - let opt = groups::optopt(~"a", ~"apple", ~"some apples", ~"VAL"); + let opt = groups::optopt("a", "apple", "some apples", "VAL"); assert!(opt == OptGroup { short_name: ~"a", long_name: ~"apple", hint: ~"VAL", @@ -1253,7 +1253,7 @@ mod tests { #[test] fn test_groups_optflag() { - let opt = groups::optflag(~"k", ~"kiwi", ~"some kiwis"); + let opt = groups::optflag("k", "kiwi", "some kiwis"); assert!(opt == OptGroup { short_name: ~"k", long_name: ~"kiwi", hint: ~"", @@ -1264,8 +1264,7 @@ mod tests { #[test] fn test_groups_optflagopt() { - let opt = groups::optflagopt(~"p", ~"pineapple", - ~"some pineapples", ~"VAL"); + let opt = groups::optflagopt("p", "pineapple", "some pineapples", "VAL"); assert!(opt == OptGroup { short_name: ~"p", long_name: ~"pineapple", hint: ~"VAL", @@ -1276,8 +1275,7 @@ mod tests { #[test] fn test_groups_optmulti() { - let opt = groups::optmulti(~"l", ~"lime", - ~"some limes", ~"VAL"); + let opt = groups::optmulti("l", "lime", "some limes", "VAL"); assert!(opt == OptGroup { short_name: ~"l", long_name: ~"lime", hint: ~"VAL", @@ -1288,9 +1286,8 @@ mod tests { #[test] fn test_groups_long_to_short() { - let short = ~[reqopt(~"b"), reqopt(~"banana")]; - let verbose = groups::reqopt(~"b", ~"banana", - ~"some bananas", ~"VAL"); + let short = ~[reqopt("b"), reqopt("banana")]; + let verbose = groups::reqopt("b", "banana", "some bananas", "VAL"); assert_eq!(groups::long_to_short(&verbose), short); } @@ -1298,19 +1295,19 @@ mod tests { #[test] fn test_groups_getopts() { let short = ~[ - reqopt(~"b"), reqopt(~"banana"), - optopt(~"a"), optopt(~"apple"), - optflag(~"k"), optflagopt(~"kiwi"), - optflagopt(~"p"), - optmulti(~"l") + reqopt("b"), reqopt("banana"), + optopt("a"), optopt("apple"), + optflag("k"), optflagopt("kiwi"), + optflagopt("p"), + optmulti("l") ]; let verbose = ~[ - groups::reqopt(~"b", ~"banana", ~"Desc", ~"VAL"), - groups::optopt(~"a", ~"apple", ~"Desc", ~"VAL"), - groups::optflag(~"k", ~"kiwi", ~"Desc"), - groups::optflagopt(~"p", ~"", ~"Desc", ~"VAL"), - groups::optmulti(~"l", ~"", ~"Desc", ~"VAL"), + groups::reqopt("b", "banana", "Desc", "VAL"), + groups::optopt("a", "apple", "Desc", "VAL"), + groups::optflag("k", "kiwi", "Desc"), + groups::optflagopt("p", "", "Desc", "VAL"), + groups::optmulti("l", "", "Desc", "VAL"), ]; let sample_args = ~[~"-k", ~"15", ~"--apple", ~"1", ~"k", @@ -1324,12 +1321,12 @@ mod tests { #[test] fn test_groups_usage() { let optgroups = ~[ - groups::reqopt(~"b", ~"banana", ~"Desc", ~"VAL"), - groups::optopt(~"a", ~"012345678901234567890123456789", - ~"Desc", ~"VAL"), - groups::optflag(~"k", ~"kiwi", ~"Desc"), - groups::optflagopt(~"p", ~"", ~"Desc", ~"VAL"), - groups::optmulti(~"l", ~"", ~"Desc", ~"VAL"), + groups::reqopt("b", "banana", "Desc", "VAL"), + groups::optopt("a", "012345678901234567890123456789", + "Desc", "VAL"), + groups::optflag("k", "kiwi", "Desc"), + groups::optflagopt("p", "", "Desc", "VAL"), + groups::optmulti("l", "", "Desc", "VAL"), ]; let expected = @@ -1345,7 +1342,7 @@ Options: "; - let generated_usage = groups::usage(~"Usage: fruits", optgroups); + let generated_usage = groups::usage("Usage: fruits", optgroups); debug!("expected: <<%s>>", expected); debug!("generated: <<%s>>", generated_usage); @@ -1358,10 +1355,10 @@ Options: // lines wrap after 78: or rather descriptions wrap after 54 let optgroups = ~[ - groups::optflag(~"k", ~"kiwi", - ~"This is a long description which won't be wrapped..+.."), // 54 - groups::optflag(~"a", ~"apple", - ~"This is a long description which _will_ be wrapped..+.."), // 55 + groups::optflag("k", "kiwi", + "This is a long description which won't be wrapped..+.."), // 54 + groups::optflag("a", "apple", + "This is a long description which _will_ be wrapped..+.."), // 55 ]; let expected = @@ -1374,7 +1371,7 @@ Options: "; - let usage = groups::usage(~"Usage: fruits", optgroups); + let usage = groups::usage("Usage: fruits", optgroups); debug!("expected: <<%s>>", expected); debug!("generated: <<%s>>", usage); diff --git a/src/libextra/json.rs b/src/libextra/json.rs index 6656c896e74c3..5ef0500d53ad5 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -1444,15 +1444,15 @@ mod tests { #[test] fn test_write_object() { - assert_eq!(to_str(&mk_object(~[])), ~"{}"); - assert_eq!(to_pretty_str(&mk_object(~[])), ~"{}"); + assert_eq!(to_str(&mk_object([])), ~"{}"); + assert_eq!(to_pretty_str(&mk_object([])), ~"{}"); assert_eq!( - to_str(&mk_object(~[(~"a", Boolean(true))])), + to_str(&mk_object([(~"a", Boolean(true))])), ~"{\"a\":true}" ); assert_eq!( - to_pretty_str(&mk_object(~[(~"a", Boolean(true))])), + to_pretty_str(&mk_object([(~"a", Boolean(true))])), ~"\ {\n \ \"a\": true\n\ @@ -1460,10 +1460,10 @@ mod tests { ); assert_eq!( - to_str(&mk_object(~[ + to_str(&mk_object([ (~"b", List(~[ - mk_object(~[(~"c", String(~"\x0c\r"))]), - mk_object(~[(~"d", String(~""))]) + mk_object([(~"c", String(~"\x0c\r"))]), + mk_object([(~"d", String(~""))]) ])) ])), ~"{\ @@ -1474,10 +1474,10 @@ mod tests { }" ); assert_eq!( - to_pretty_str(&mk_object(~[ + to_pretty_str(&mk_object([ (~"b", List(~[ - mk_object(~[(~"c", String(~"\x0c\r"))]), - mk_object(~[(~"d", String(~""))]) + mk_object([(~"c", String(~"\x0c\r"))]), + mk_object([(~"d", String(~""))]) ])) ])), ~"\ @@ -1493,11 +1493,11 @@ mod tests { }" ); - let a = mk_object(~[ + let a = mk_object([ (~"a", Boolean(true)), (~"b", List(~[ - mk_object(~[(~"c", String(~"\x0c\r"))]), - mk_object(~[(~"d", String(~""))]) + mk_object([(~"c", String(~"\x0c\r"))]), + mk_object([(~"d", String(~""))]) ])) ]); @@ -1582,299 +1582,299 @@ mod tests { #[test] fn test_trailing_characters() { - assert_eq!(from_str(~"nulla"), + assert_eq!(from_str("nulla"), Err(Error {line: 1u, col: 5u, msg: @~"trailing characters"})); - assert_eq!(from_str(~"truea"), + assert_eq!(from_str("truea"), Err(Error {line: 1u, col: 5u, msg: @~"trailing characters"})); - assert_eq!(from_str(~"falsea"), + assert_eq!(from_str("falsea"), Err(Error {line: 1u, col: 6u, msg: @~"trailing characters"})); - assert_eq!(from_str(~"1a"), + assert_eq!(from_str("1a"), Err(Error {line: 1u, col: 2u, msg: @~"trailing characters"})); - assert_eq!(from_str(~"[]a"), + assert_eq!(from_str("[]a"), Err(Error {line: 1u, col: 3u, msg: @~"trailing characters"})); - assert_eq!(from_str(~"{}a"), + assert_eq!(from_str("{}a"), Err(Error {line: 1u, col: 3u, msg: @~"trailing characters"})); } #[test] fn test_read_identifiers() { - assert_eq!(from_str(~"n"), + assert_eq!(from_str("n"), Err(Error {line: 1u, col: 2u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"nul"), + assert_eq!(from_str("nul"), Err(Error {line: 1u, col: 4u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"t"), + assert_eq!(from_str("t"), Err(Error {line: 1u, col: 2u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"truz"), + assert_eq!(from_str("truz"), Err(Error {line: 1u, col: 4u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"f"), + assert_eq!(from_str("f"), Err(Error {line: 1u, col: 2u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"faz"), + assert_eq!(from_str("faz"), Err(Error {line: 1u, col: 3u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"null"), Ok(Null)); - assert_eq!(from_str(~"true"), Ok(Boolean(true))); - assert_eq!(from_str(~"false"), Ok(Boolean(false))); - assert_eq!(from_str(~" null "), Ok(Null)); - assert_eq!(from_str(~" true "), Ok(Boolean(true))); - assert_eq!(from_str(~" false "), Ok(Boolean(false))); + assert_eq!(from_str("null"), Ok(Null)); + assert_eq!(from_str("true"), Ok(Boolean(true))); + assert_eq!(from_str("false"), Ok(Boolean(false))); + assert_eq!(from_str(" null "), Ok(Null)); + assert_eq!(from_str(" true "), Ok(Boolean(true))); + assert_eq!(from_str(" false "), Ok(Boolean(false))); } #[test] fn test_decode_identifiers() { - let mut decoder = Decoder(from_str(~"null").unwrap()); + let mut decoder = Decoder(from_str("null").unwrap()); let v: () = Decodable::decode(&mut decoder); assert_eq!(v, ()); - let mut decoder = Decoder(from_str(~"true").unwrap()); + let mut decoder = Decoder(from_str("true").unwrap()); let v: bool = Decodable::decode(&mut decoder); assert_eq!(v, true); - let mut decoder = Decoder(from_str(~"false").unwrap()); + let mut decoder = Decoder(from_str("false").unwrap()); let v: bool = Decodable::decode(&mut decoder); assert_eq!(v, false); } #[test] fn test_read_number() { - assert_eq!(from_str(~"+"), + assert_eq!(from_str("+"), Err(Error {line: 1u, col: 1u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"."), + assert_eq!(from_str("."), Err(Error {line: 1u, col: 1u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"-"), + assert_eq!(from_str("-"), Err(Error {line: 1u, col: 2u, msg: @~"invalid number"})); - assert_eq!(from_str(~"00"), + assert_eq!(from_str("00"), Err(Error {line: 1u, col: 2u, msg: @~"invalid number"})); - assert_eq!(from_str(~"1."), + assert_eq!(from_str("1."), Err(Error {line: 1u, col: 3u, msg: @~"invalid number"})); - assert_eq!(from_str(~"1e"), + assert_eq!(from_str("1e"), Err(Error {line: 1u, col: 3u, msg: @~"invalid number"})); - assert_eq!(from_str(~"1e+"), + assert_eq!(from_str("1e+"), Err(Error {line: 1u, col: 4u, msg: @~"invalid number"})); - assert_eq!(from_str(~"3"), Ok(Number(3f))); - assert_eq!(from_str(~"3.1"), Ok(Number(3.1f))); - assert_eq!(from_str(~"-1.2"), Ok(Number(-1.2f))); - assert_eq!(from_str(~"0.4"), Ok(Number(0.4f))); - assert_eq!(from_str(~"0.4e5"), Ok(Number(0.4e5f))); - assert_eq!(from_str(~"0.4e+15"), Ok(Number(0.4e15f))); - assert_eq!(from_str(~"0.4e-01"), Ok(Number(0.4e-01f))); - assert_eq!(from_str(~" 3 "), Ok(Number(3f))); + assert_eq!(from_str("3"), Ok(Number(3f))); + assert_eq!(from_str("3.1"), Ok(Number(3.1f))); + assert_eq!(from_str("-1.2"), Ok(Number(-1.2f))); + assert_eq!(from_str("0.4"), Ok(Number(0.4f))); + assert_eq!(from_str("0.4e5"), Ok(Number(0.4e5f))); + assert_eq!(from_str("0.4e+15"), Ok(Number(0.4e15f))); + assert_eq!(from_str("0.4e-01"), Ok(Number(0.4e-01f))); + assert_eq!(from_str(" 3 "), Ok(Number(3f))); } #[test] fn test_decode_numbers() { - let mut decoder = Decoder(from_str(~"3").unwrap()); + let mut decoder = Decoder(from_str("3").unwrap()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 3f); - let mut decoder = Decoder(from_str(~"3.1").unwrap()); + let mut decoder = Decoder(from_str("3.1").unwrap()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 3.1f); - let mut decoder = Decoder(from_str(~"-1.2").unwrap()); + let mut decoder = Decoder(from_str("-1.2").unwrap()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, -1.2f); - let mut decoder = Decoder(from_str(~"0.4").unwrap()); + let mut decoder = Decoder(from_str("0.4").unwrap()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4f); - let mut decoder = Decoder(from_str(~"0.4e5").unwrap()); + let mut decoder = Decoder(from_str("0.4e5").unwrap()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4e5f); - let mut decoder = Decoder(from_str(~"0.4e15").unwrap()); + let mut decoder = Decoder(from_str("0.4e15").unwrap()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4e15f); - let mut decoder = Decoder(from_str(~"0.4e-01").unwrap()); + let mut decoder = Decoder(from_str("0.4e-01").unwrap()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4e-01f); } #[test] fn test_read_str() { - assert_eq!(from_str(~"\""), + assert_eq!(from_str("\""), Err(Error {line: 1u, col: 2u, msg: @~"EOF while parsing string" })); - assert_eq!(from_str(~"\"lol"), + assert_eq!(from_str("\"lol"), Err(Error {line: 1u, col: 5u, msg: @~"EOF while parsing string" })); - assert_eq!(from_str(~"\"\""), Ok(String(~""))); - assert_eq!(from_str(~"\"foo\""), Ok(String(~"foo"))); - assert_eq!(from_str(~"\"\\\"\""), Ok(String(~"\""))); - assert_eq!(from_str(~"\"\\b\""), Ok(String(~"\x08"))); - assert_eq!(from_str(~"\"\\n\""), Ok(String(~"\n"))); - assert_eq!(from_str(~"\"\\r\""), Ok(String(~"\r"))); - assert_eq!(from_str(~"\"\\t\""), Ok(String(~"\t"))); - assert_eq!(from_str(~" \"foo\" "), Ok(String(~"foo"))); - assert_eq!(from_str(~"\"\\u12ab\""), Ok(String(~"\u12ab"))); - assert_eq!(from_str(~"\"\\uAB12\""), Ok(String(~"\uAB12"))); + assert_eq!(from_str("\"\""), Ok(String(~""))); + assert_eq!(from_str("\"foo\""), Ok(String(~"foo"))); + assert_eq!(from_str("\"\\\"\""), Ok(String(~"\""))); + assert_eq!(from_str("\"\\b\""), Ok(String(~"\x08"))); + assert_eq!(from_str("\"\\n\""), Ok(String(~"\n"))); + assert_eq!(from_str("\"\\r\""), Ok(String(~"\r"))); + assert_eq!(from_str("\"\\t\""), Ok(String(~"\t"))); + assert_eq!(from_str(" \"foo\" "), Ok(String(~"foo"))); + assert_eq!(from_str("\"\\u12ab\""), Ok(String(~"\u12ab"))); + assert_eq!(from_str("\"\\uAB12\""), Ok(String(~"\uAB12"))); } #[test] fn test_decode_str() { - let mut decoder = Decoder(from_str(~"\"\"").unwrap()); + let mut decoder = Decoder(from_str("\"\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~""); - let mut decoder = Decoder(from_str(~"\"foo\"").unwrap()); + let mut decoder = Decoder(from_str("\"foo\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"foo"); - let mut decoder = Decoder(from_str(~"\"\\\"\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\\"\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\""); - let mut decoder = Decoder(from_str(~"\"\\b\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\b\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\x08"); - let mut decoder = Decoder(from_str(~"\"\\n\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\n\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\n"); - let mut decoder = Decoder(from_str(~"\"\\r\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\r\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\r"); - let mut decoder = Decoder(from_str(~"\"\\t\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\t\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\t"); - let mut decoder = Decoder(from_str(~"\"\\u12ab\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\u12ab\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\u12ab"); - let mut decoder = Decoder(from_str(~"\"\\uAB12\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\uAB12\"").unwrap()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\uAB12"); } #[test] fn test_read_list() { - assert_eq!(from_str(~"["), + assert_eq!(from_str("["), Err(Error {line: 1u, col: 2u, msg: @~"EOF while parsing value"})); - assert_eq!(from_str(~"[1"), + assert_eq!(from_str("[1"), Err(Error {line: 1u, col: 3u, msg: @~"EOF while parsing list"})); - assert_eq!(from_str(~"[1,"), + assert_eq!(from_str("[1,"), Err(Error {line: 1u, col: 4u, msg: @~"EOF while parsing value"})); - assert_eq!(from_str(~"[1,]"), + assert_eq!(from_str("[1,]"), Err(Error {line: 1u, col: 4u, msg: @~"invalid syntax"})); - assert_eq!(from_str(~"[6 7]"), + assert_eq!(from_str("[6 7]"), Err(Error {line: 1u, col: 4u, msg: @~"expected `,` or `]`"})); - assert_eq!(from_str(~"[]"), Ok(List(~[]))); - assert_eq!(from_str(~"[ ]"), Ok(List(~[]))); - assert_eq!(from_str(~"[true]"), Ok(List(~[Boolean(true)]))); - assert_eq!(from_str(~"[ false ]"), Ok(List(~[Boolean(false)]))); - assert_eq!(from_str(~"[null]"), Ok(List(~[Null]))); - assert_eq!(from_str(~"[3, 1]"), + assert_eq!(from_str("[]"), Ok(List(~[]))); + assert_eq!(from_str("[ ]"), Ok(List(~[]))); + assert_eq!(from_str("[true]"), Ok(List(~[Boolean(true)]))); + assert_eq!(from_str("[ false ]"), Ok(List(~[Boolean(false)]))); + assert_eq!(from_str("[null]"), Ok(List(~[Null]))); + assert_eq!(from_str("[3, 1]"), Ok(List(~[Number(3f), Number(1f)]))); - assert_eq!(from_str(~"\n[3, 2]\n"), + assert_eq!(from_str("\n[3, 2]\n"), Ok(List(~[Number(3f), Number(2f)]))); - assert_eq!(from_str(~"[2, [4, 1]]"), + assert_eq!(from_str("[2, [4, 1]]"), Ok(List(~[Number(2f), List(~[Number(4f), Number(1f)])]))); } #[test] fn test_decode_list() { - let mut decoder = Decoder(from_str(~"[]").unwrap()); + let mut decoder = Decoder(from_str("[]").unwrap()); let v: ~[()] = Decodable::decode(&mut decoder); assert_eq!(v, ~[]); - let mut decoder = Decoder(from_str(~"[null]").unwrap()); + let mut decoder = Decoder(from_str("[null]").unwrap()); let v: ~[()] = Decodable::decode(&mut decoder); assert_eq!(v, ~[()]); - let mut decoder = Decoder(from_str(~"[true]").unwrap()); + let mut decoder = Decoder(from_str("[true]").unwrap()); let v: ~[bool] = Decodable::decode(&mut decoder); assert_eq!(v, ~[true]); - let mut decoder = Decoder(from_str(~"[true]").unwrap()); + let mut decoder = Decoder(from_str("[true]").unwrap()); let v: ~[bool] = Decodable::decode(&mut decoder); assert_eq!(v, ~[true]); - let mut decoder = Decoder(from_str(~"[3, 1]").unwrap()); + let mut decoder = Decoder(from_str("[3, 1]").unwrap()); let v: ~[int] = Decodable::decode(&mut decoder); assert_eq!(v, ~[3, 1]); - let mut decoder = Decoder(from_str(~"[[3], [1, 2]]").unwrap()); + let mut decoder = Decoder(from_str("[[3], [1, 2]]").unwrap()); let v: ~[~[uint]] = Decodable::decode(&mut decoder); assert_eq!(v, ~[~[3], ~[1, 2]]); } #[test] fn test_read_object() { - assert_eq!(from_str(~"{"), + assert_eq!(from_str("{"), Err(Error { line: 1u, col: 2u, msg: @~"EOF while parsing object"})); - assert_eq!(from_str(~"{ "), + assert_eq!(from_str("{ "), Err(Error { line: 1u, col: 3u, msg: @~"EOF while parsing object"})); - assert_eq!(from_str(~"{1"), + assert_eq!(from_str("{1"), Err(Error { line: 1u, col: 2u, msg: @~"key must be a string"})); - assert_eq!(from_str(~"{ \"a\""), + assert_eq!(from_str("{ \"a\""), Err(Error { line: 1u, col: 6u, msg: @~"EOF while parsing object"})); - assert_eq!(from_str(~"{\"a\""), + assert_eq!(from_str("{\"a\""), Err(Error { line: 1u, col: 5u, msg: @~"EOF while parsing object"})); - assert_eq!(from_str(~"{\"a\" "), + assert_eq!(from_str("{\"a\" "), Err(Error { line: 1u, col: 6u, msg: @~"EOF while parsing object"})); - assert_eq!(from_str(~"{\"a\" 1"), + assert_eq!(from_str("{\"a\" 1"), Err(Error {line: 1u, col: 6u, msg: @~"expected `:`"})); - assert_eq!(from_str(~"{\"a\":"), + assert_eq!(from_str("{\"a\":"), Err(Error {line: 1u, col: 6u, msg: @~"EOF while parsing value"})); - assert_eq!(from_str(~"{\"a\":1"), + assert_eq!(from_str("{\"a\":1"), Err(Error { line: 1u, col: 7u, msg: @~"EOF while parsing object"})); - assert_eq!(from_str(~"{\"a\":1 1"), + assert_eq!(from_str("{\"a\":1 1"), Err(Error {line: 1u, col: 8u, msg: @~"expected `,` or `}`"})); - assert_eq!(from_str(~"{\"a\":1,"), + assert_eq!(from_str("{\"a\":1,"), Err(Error { line: 1u, col: 8u, msg: @~"EOF while parsing object"})); - assert_eq!(result::unwrap(from_str(~"{}")), mk_object(~[])); - assert_eq!(result::unwrap(from_str(~"{\"a\": 3}")), - mk_object(~[(~"a", Number(3.0f))])); + assert_eq!(result::unwrap(from_str("{}")), mk_object([])); + assert_eq!(result::unwrap(from_str("{\"a\": 3}")), + mk_object([(~"a", Number(3.0f))])); assert_eq!(result::unwrap(from_str( - ~"{ \"a\": null, \"b\" : true }")), - mk_object(~[ + "{ \"a\": null, \"b\" : true }")), + mk_object([ (~"a", Null), (~"b", Boolean(true))])); assert_eq!(result::unwrap( - from_str(~"\n{ \"a\": null, \"b\" : true }\n")), - mk_object(~[ + from_str("\n{ \"a\": null, \"b\" : true }\n")), + mk_object([ (~"a", Null), (~"b", Boolean(true))])); assert_eq!(result::unwrap(from_str( - ~"{\"a\" : 1.0 ,\"b\": [ true ]}")), - mk_object(~[ + "{\"a\" : 1.0 ,\"b\": [ true ]}")), + mk_object([ (~"a", Number(1.0)), (~"b", List(~[Boolean(true)])) ])); @@ -1887,13 +1887,13 @@ mod tests { ~"{ \"c\": {\"d\": null} } " + ~"]" + ~"}")), - mk_object(~[ + mk_object([ (~"a", Number(1.0f)), (~"b", List(~[ Boolean(true), String(~"foo\nbar"), - mk_object(~[ - (~"c", mk_object(~[(~"d", Null)])) + mk_object([ + (~"c", mk_object([(~"d", Null)])) ]) ])) ])); @@ -1920,23 +1920,23 @@ mod tests { #[test] fn test_decode_option() { - let mut decoder = Decoder(from_str(~"null").unwrap()); + let mut decoder = Decoder(from_str("null").unwrap()); let value: Option<~str> = Decodable::decode(&mut decoder); assert_eq!(value, None); - let mut decoder = Decoder(from_str(~"\"jodhpurs\"").unwrap()); + let mut decoder = Decoder(from_str("\"jodhpurs\"").unwrap()); let value: Option<~str> = Decodable::decode(&mut decoder); assert_eq!(value, Some(~"jodhpurs")); } #[test] fn test_decode_enum() { - let mut decoder = Decoder(from_str(~"\"Dog\"").unwrap()); + let mut decoder = Decoder(from_str("\"Dog\"").unwrap()); let value: Animal = Decodable::decode(&mut decoder); assert_eq!(value, Dog); let mut decoder = - Decoder(from_str(~"[\"Frog\",\"Henry\",349]").unwrap()); + Decoder(from_str("[\"Frog\",\"Henry\",349]").unwrap()); let value: Animal = Decodable::decode(&mut decoder); assert_eq!(value, Frog(~"Henry", 349)); } @@ -1953,7 +1953,7 @@ mod tests { #[test] fn test_multiline_errors() { - assert_eq!(from_str(~"{\n \"foo\":\n \"bar\""), + assert_eq!(from_str("{\n \"foo\":\n \"bar\""), Err(Error { line: 3u, col: 8u, diff --git a/src/libextra/list.rs b/src/libextra/list.rs index 919a4426cead9..0cde57d5ad762 100644 --- a/src/libextra/list.rs +++ b/src/libextra/list.rs @@ -184,9 +184,9 @@ mod tests { #[test] fn test_is_empty() { - let empty : @list::List = from_vec(~[]); - let full1 = from_vec(~[1]); - let full2 = from_vec(~['r', 'u']); + let empty : @list::List = from_vec([]); + let full1 = from_vec([1]); + let full2 = from_vec(['r', 'u']); assert!(is_empty(empty)); assert!(!is_empty(full1)); @@ -195,7 +195,7 @@ mod tests { #[test] fn test_from_vec() { - let l = from_vec(~[0, 1, 2]); + let l = from_vec([0, 1, 2]); assert_eq!(head(l), 0); @@ -208,14 +208,14 @@ mod tests { #[test] fn test_from_vec_empty() { - let empty : @list::List = from_vec(~[]); + let empty : @list::List = from_vec([]); assert_eq!(empty, @list::Nil::); } #[test] fn test_foldl() { fn add(a: &uint, b: &int) -> uint { return *a + (*b as uint); } - let l = from_vec(~[0, 1, 2, 3, 4]); + let l = from_vec([0, 1, 2, 3, 4]); let empty = @list::Nil::; assert_eq!(list::foldl(0u, l, add), 10u); assert_eq!(list::foldl(0u, empty, add), 0u); @@ -226,21 +226,21 @@ mod tests { fn sub(a: &int, b: &int) -> int { *a - *b } - let l = from_vec(~[1, 2, 3, 4]); + let l = from_vec([1, 2, 3, 4]); assert_eq!(list::foldl(0, l, sub), -10); } #[test] fn test_find_success() { fn match_(i: &int) -> bool { return *i == 2; } - let l = from_vec(~[0, 1, 2]); + let l = from_vec([0, 1, 2]); assert_eq!(list::find(l, match_), option::Some(2)); } #[test] fn test_find_fail() { fn match_(_i: &int) -> bool { return false; } - let l = from_vec(~[0, 1, 2]); + let l = from_vec([0, 1, 2]); let empty = @list::Nil::; assert_eq!(list::find(l, match_), option::None::); assert_eq!(list::find(empty, match_), option::None::); @@ -248,7 +248,7 @@ mod tests { #[test] fn test_has() { - let l = from_vec(~[5, 8, 6]); + let l = from_vec([5, 8, 6]); let empty = @list::Nil::; assert!((list::has(l, 5))); assert!((!list::has(l, 7))); @@ -258,7 +258,7 @@ mod tests { #[test] fn test_len() { - let l = from_vec(~[0, 1, 2]); + let l = from_vec([0, 1, 2]); let empty = @list::Nil::; assert_eq!(list::len(l), 3u); assert_eq!(list::len(empty), 0u); @@ -266,7 +266,7 @@ mod tests { #[test] fn test_append() { - assert!(from_vec(~[1,2,3,4]) - == list::append(list::from_vec(~[1,2]), list::from_vec(~[3,4]))); + assert!(from_vec([1,2,3,4]) + == list::append(list::from_vec([1,2]), list::from_vec([3,4]))); } } diff --git a/src/libextra/md4.rs b/src/libextra/md4.rs index f99de89588bf2..449774e4cbc16 100644 --- a/src/libextra/md4.rs +++ b/src/libextra/md4.rs @@ -127,17 +127,17 @@ pub fn md4_text(msg: &str) -> ~str { md4_str(str::to_bytes(msg)) } #[test] fn test_md4() { - assert_eq!(md4_text(~""), ~"31d6cfe0d16ae931b73c59d7e0c089c0"); - assert_eq!(md4_text(~"a"), ~"bde52cb31de33e46245e05fbdbd6fb24"); - assert_eq!(md4_text(~"abc"), ~"a448017aaf21d8525fc10ae87aa6729d"); - assert!(md4_text(~"message digest") == + assert_eq!(md4_text(""), ~"31d6cfe0d16ae931b73c59d7e0c089c0"); + assert_eq!(md4_text("a"), ~"bde52cb31de33e46245e05fbdbd6fb24"); + assert_eq!(md4_text("abc"), ~"a448017aaf21d8525fc10ae87aa6729d"); + assert!(md4_text("message digest") == ~"d9130a8164549fe818874806e1c7014b"); - assert!(md4_text(~"abcdefghijklmnopqrstuvwxyz") == + assert!(md4_text("abcdefghijklmnopqrstuvwxyz") == ~"d79e1c308aa5bbcdeea8ed63df412da9"); assert!(md4_text( - ~"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\ + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\ 0123456789") == ~"043f8582f241db351ce627e153e7f0e4"); - assert!(md4_text(~"1234567890123456789012345678901234567890123456789\ + assert!(md4_text("1234567890123456789012345678901234567890123456789\ 0123456789012345678901234567890") == ~"e33b4ddc9c38f2199c3e7b164fcc0536"); } diff --git a/src/libextra/net_ip.rs b/src/libextra/net_ip.rs index e98c1f26d4c1f..70a8c3fb0cb8a 100644 --- a/src/libextra/net_ip.rs +++ b/src/libextra/net_ip.rs @@ -393,7 +393,7 @@ mod test { } #[test] fn test_ip_ipv4_bad_parse() { - match v4::try_parse_addr(~"b4df00d") { + match v4::try_parse_addr("b4df00d") { result::Err(ref err_info) => { debug!("got error as expected %?", err_info); assert!(true); @@ -406,7 +406,7 @@ mod test { #[test] #[ignore(target_os="win32")] fn test_ip_ipv6_bad_parse() { - match v6::try_parse_addr(~"::,~2234k;") { + match v6::try_parse_addr("::,~2234k;") { result::Err(ref err_info) => { debug!("got error as expected %?", err_info); assert!(true); diff --git a/src/libextra/net_tcp.rs b/src/libextra/net_tcp.rs index 894488e47e123..ae1707c9922b8 100644 --- a/src/libextra/net_tcp.rs +++ b/src/libextra/net_tcp.rs @@ -1630,7 +1630,7 @@ mod test { assert_eq!(net::ip::get_port(&sock.get_peer_addr()), 8887); // Fulfill the protocol the test server expects - let resp_bytes = str::to_bytes(~"ping"); + let resp_bytes = str::to_bytes("ping"); tcp_write_single(&sock, resp_bytes); debug!("message sent"); sock.read(0u); diff --git a/src/libextra/net_url.rs b/src/libextra/net_url.rs index f6d4d75c49858..3b7c808c596ea 100644 --- a/src/libextra/net_url.rs +++ b/src/libextra/net_url.rs @@ -716,11 +716,11 @@ impl IterBytes for Url { #[test] fn test_split_char_first() { - let (u,v) = split_char_first(~"hello, sweet world", ','); + let (u,v) = split_char_first("hello, sweet world", ','); assert_eq!(u, ~"hello"); assert_eq!(v, ~" sweet world"); - let (u,v) = split_char_first(~"hello sweet world", ','); + let (u,v) = split_char_first("hello sweet world", ','); assert_eq!(u, ~"hello sweet world"); assert_eq!(v, ~""); } @@ -774,9 +774,9 @@ fn test_get_authority() { "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000:00").is_err()); // these parse as empty, because they don't start with '//' - let (_, h, _, _) = get_authority(~"user:pass@rust-lang").unwrap(); + let (_, h, _, _) = get_authority("user:pass@rust-lang").unwrap(); assert_eq!(h, ~""); - let (_, h, _, _) = get_authority(~"rust-lang.org").unwrap(); + let (_, h, _, _) = get_authority("rust-lang.org").unwrap(); assert_eq!(h, ~""); } @@ -788,12 +788,12 @@ fn test_get_path() { let (p, r) = get_path("test@email.com#fragment", false).unwrap(); assert_eq!(p, ~"test@email.com"); assert_eq!(r, ~"#fragment"); - let (p, r) = get_path(~"/gen/:addr=?q=v", false).unwrap(); + let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap(); assert_eq!(p, ~"/gen/:addr="); assert_eq!(r, ~"?q=v"); //failure cases - assert!(get_path(~"something?q", true).is_err()); + assert!(get_path("something?q", true).is_err()); } #[cfg(test)] @@ -1058,7 +1058,7 @@ mod tests { // FIXME #4449: Commented out because this causes an ICE, but only // on FreeBSD /* - assert_eq!(decode_form_urlencoded(~[]).len(), 0); + assert_eq!(decode_form_urlencoded([]).len(), 0); let s = str::to_bytes("a=1&foo+bar=abc&foo+bar=12+%3D+34"); let form = decode_form_urlencoded(s); diff --git a/src/libextra/num/bigint.rs b/src/libextra/num/bigint.rs index 776172262b742..7ff8c25d95ff0 100644 --- a/src/libextra/num/bigint.rs +++ b/src/libextra/num/bigint.rs @@ -1156,12 +1156,12 @@ mod biguint_tests { fn check(slice: &[BigDigit], data: &[BigDigit]) { assert!(data == BigUint::from_slice(slice).data); } - check(~[1], ~[1]); - check(~[0, 0, 0], ~[]); - check(~[1, 2, 0, 0], ~[1, 2]); - check(~[0, 0, 1, 2], ~[0, 0, 1, 2]); - check(~[0, 0, 1, 2, 0, 0], ~[0, 0, 1, 2]); - check(~[-1], ~[-1]); + check([1], [1]); + check([0, 0, 0], []); + check([1, 2, 0, 0], [1, 2]); + check([0, 0, 1, 2], [0, 0, 1, 2]); + check([0, 0, 1, 2, 0, 0], [0, 0, 1, 2]); + check([-1], [-1]); } #[test] @@ -1579,9 +1579,9 @@ mod biguint_tests { } } - assert_eq!(FromStrRadix::from_str_radix::(~"Z", 10), None); - assert_eq!(FromStrRadix::from_str_radix::(~"_", 2), None); - assert_eq!(FromStrRadix::from_str_radix::(~"-1", 10), None); + assert_eq!(FromStrRadix::from_str_radix::("Z", 10), None); + assert_eq!(FromStrRadix::from_str_radix::("_", 2), None); + assert_eq!(FromStrRadix::from_str_radix::("-1", 10), None); } #[test] diff --git a/src/libextra/priority_queue.rs b/src/libextra/priority_queue.rs index a4fc30cedcdaa..4b84e2aa8c931 100644 --- a/src/libextra/priority_queue.rs +++ b/src/libextra/priority_queue.rs @@ -14,7 +14,6 @@ use core::prelude::*; use core::old_iter::BaseIter; use core::unstable::intrinsics::{move_val_init, init}; -use core::unstable::intrinsics::uninit; use core::util::{replace, swap}; pub struct PriorityQueue { diff --git a/src/libextra/sha1.rs b/src/libextra/sha1.rs index 8910442849e37..7b38c031774d1 100644 --- a/src/libextra/sha1.rs +++ b/src/libextra/sha1.rs @@ -295,7 +295,7 @@ mod tests { let mut i = 0; let mut rs = ~""; while i < 100000 { - str::push_str(&mut rs, ~"aaaaaaaaaa"); + rs.push_str("aaaaaaaaaa"); i += 1; } return rs; diff --git a/src/libextra/sort.rs b/src/libextra/sort.rs index 388f321d9ea87..c56a02e03800a 100644 --- a/src/libextra/sort.rs +++ b/src/libextra/sort.rs @@ -895,7 +895,7 @@ mod tests { #[test] fn test_merge_sort_mutable() { pub fn le(a: &int, b: &int) -> bool { *a <= *b } - let mut v1 = ~[3, 2, 1]; + let v1 = ~[3, 2, 1]; let v2 = merge_sort(v1, le); assert_eq!(v2, ~[1, 2, 3]); } diff --git a/src/libextra/std.rc b/src/libextra/std.rc index 2a18f021e7897..a23a547634242 100644 --- a/src/libextra/std.rc +++ b/src/libextra/std.rc @@ -27,7 +27,6 @@ not required in or otherwise suitable for the core library. #[crate_type = "lib"]; #[deny(non_camel_case_types)]; -#[allow(unnecessary_allocation)]; #[no_core]; #[no_std]; diff --git a/src/libextra/test.rs b/src/libextra/test.rs index 3245ad5d3346f..ba2ee3c352ef5 100644 --- a/src/libextra/test.rs +++ b/src/libextra/test.rs @@ -394,8 +394,8 @@ fn should_sort_failures_before_printing_them() { print_failures(st); }; - let apos = str::find_str(s, ~"a").get(); - let bpos = str::find_str(s, ~"b").get(); + let apos = str::find_str(s, "a").get(); + let bpos = str::find_str(s, "b").get(); assert!(apos < bpos); } diff --git a/src/libextra/time.rs b/src/libextra/time.rs index 624d7d4256a8a..8a0d50ed52c71 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -899,7 +899,7 @@ mod tests { } fn test_at_utc() { - os::setenv(~"TZ", ~"America/Los_Angeles"); + os::setenv("TZ", "America/Los_Angeles"); tzset(); let time = ::time::Timespec::new(1234567890, 54321); @@ -920,7 +920,7 @@ mod tests { } fn test_at() { - os::setenv(~"TZ", ~"America/Los_Angeles"); + os::setenv("TZ", "America/Los_Angeles"); tzset(); let time = ::time::Timespec::new(1234567890, 54321); @@ -948,7 +948,7 @@ mod tests { } fn test_to_timespec() { - os::setenv(~"TZ", ~"America/Los_Angeles"); + os::setenv("TZ", "America/Los_Angeles"); tzset(); let time = ::time::Timespec::new(1234567890, 54321); @@ -959,7 +959,7 @@ mod tests { } fn test_conversions() { - os::setenv(~"TZ", ~"America/Los_Angeles"); + os::setenv("TZ", "America/Los_Angeles"); tzset(); let time = ::time::Timespec::new(1234567890, 54321); @@ -975,10 +975,10 @@ mod tests { } fn test_strptime() { - os::setenv(~"TZ", ~"America/Los_Angeles"); + os::setenv("TZ", "America/Los_Angeles"); tzset(); - match strptime(~"", ~"") { + match strptime("", "") { Ok(ref tm) => { assert!(tm.tm_sec == 0_i32); assert!(tm.tm_min == 0_i32); @@ -995,12 +995,12 @@ mod tests { Err(_) => () } - let format = ~"%a %b %e %T %Y"; - assert_eq!(strptime(~"", format), Err(~"Invalid time")); - assert!(strptime(~"Fri Feb 13 15:31:30", format) + let format = "%a %b %e %T %Y"; + assert_eq!(strptime("", format), Err(~"Invalid time")); + assert!(strptime("Fri Feb 13 15:31:30", format) == Err(~"Invalid time")); - match strptime(~"Fri Feb 13 15:31:30 2009", format) { + match strptime("Fri Feb 13 15:31:30 2009", format) { Err(copy e) => fail!(e), Ok(ref tm) => { assert!(tm.tm_sec == 30_i32); @@ -1034,7 +1034,7 @@ mod tests { ~"Friday", ~"Saturday" ].each |day| { - assert!(test(*day, ~"%A")); + assert!(test(*day, "%A")); } for [ @@ -1046,7 +1046,7 @@ mod tests { ~"Fri", ~"Sat" ].each |day| { - assert!(test(*day, ~"%a")); + assert!(test(*day, "%a")); } for [ @@ -1063,7 +1063,7 @@ mod tests { ~"November", ~"December" ].each |day| { - assert!(test(*day, ~"%B")); + assert!(test(*day, "%B")); } for [ @@ -1080,60 +1080,60 @@ mod tests { ~"Nov", ~"Dec" ].each |day| { - assert!(test(*day, ~"%b")); + assert!(test(*day, "%b")); } - assert!(test(~"19", ~"%C")); - assert!(test(~"Fri Feb 13 23:31:30 2009", ~"%c")); - assert!(test(~"02/13/09", ~"%D")); - assert!(test(~"03", ~"%d")); - assert!(test(~"13", ~"%d")); - assert!(test(~" 3", ~"%e")); - assert!(test(~"13", ~"%e")); - assert!(test(~"2009-02-13", ~"%F")); - assert!(test(~"03", ~"%H")); - assert!(test(~"13", ~"%H")); - assert!(test(~"03", ~"%I")); // FIXME (#2350): flesh out - assert!(test(~"11", ~"%I")); // FIXME (#2350): flesh out - assert!(test(~"044", ~"%j")); - assert!(test(~" 3", ~"%k")); - assert!(test(~"13", ~"%k")); - assert!(test(~" 1", ~"%l")); - assert!(test(~"11", ~"%l")); - assert!(test(~"03", ~"%M")); - assert!(test(~"13", ~"%M")); - assert!(test(~"\n", ~"%n")); - assert!(test(~"am", ~"%P")); - assert!(test(~"pm", ~"%P")); - assert!(test(~"AM", ~"%p")); - assert!(test(~"PM", ~"%p")); - assert!(test(~"23:31", ~"%R")); - assert!(test(~"11:31:30 AM", ~"%r")); - assert!(test(~"11:31:30 PM", ~"%r")); - assert!(test(~"03", ~"%S")); - assert!(test(~"13", ~"%S")); - assert!(test(~"15:31:30", ~"%T")); - assert!(test(~"\t", ~"%t")); - assert!(test(~"1", ~"%u")); - assert!(test(~"7", ~"%u")); - assert!(test(~"13-Feb-2009", ~"%v")); - assert!(test(~"0", ~"%w")); - assert!(test(~"6", ~"%w")); - assert!(test(~"2009", ~"%Y")); - assert!(test(~"09", ~"%y")); - assert!(result::unwrap(strptime(~"UTC", ~"%Z")).tm_zone == + assert!(test("19", "%C")); + assert!(test("Fri Feb 13 23:31:30 2009", "%c")); + assert!(test("02/13/09", "%D")); + assert!(test("03", "%d")); + assert!(test("13", "%d")); + assert!(test(" 3", "%e")); + assert!(test("13", "%e")); + assert!(test("2009-02-13", "%F")); + assert!(test("03", "%H")); + assert!(test("13", "%H")); + assert!(test("03", "%I")); // FIXME (#2350): flesh out + assert!(test("11", "%I")); // FIXME (#2350): flesh out + assert!(test("044", "%j")); + assert!(test(" 3", "%k")); + assert!(test("13", "%k")); + assert!(test(" 1", "%l")); + assert!(test("11", "%l")); + assert!(test("03", "%M")); + assert!(test("13", "%M")); + assert!(test("\n", "%n")); + assert!(test("am", "%P")); + assert!(test("pm", "%P")); + assert!(test("AM", "%p")); + assert!(test("PM", "%p")); + assert!(test("23:31", "%R")); + assert!(test("11:31:30 AM", "%r")); + assert!(test("11:31:30 PM", "%r")); + assert!(test("03", "%S")); + assert!(test("13", "%S")); + assert!(test("15:31:30", "%T")); + assert!(test("\t", "%t")); + assert!(test("1", "%u")); + assert!(test("7", "%u")); + assert!(test("13-Feb-2009", "%v")); + assert!(test("0", "%w")); + assert!(test("6", "%w")); + assert!(test("2009", "%Y")); + assert!(test("09", "%y")); + assert!(result::unwrap(strptime("UTC", "%Z")).tm_zone == ~"UTC"); - assert!(result::unwrap(strptime(~"PST", ~"%Z")).tm_zone == + assert!(result::unwrap(strptime("PST", "%Z")).tm_zone == ~""); - assert!(result::unwrap(strptime(~"-0000", ~"%z")).tm_gmtoff == + assert!(result::unwrap(strptime("-0000", "%z")).tm_gmtoff == 0); - assert!(result::unwrap(strptime(~"-0800", ~"%z")).tm_gmtoff == + assert!(result::unwrap(strptime("-0800", "%z")).tm_gmtoff == 0); - assert!(test(~"%", ~"%%")); + assert!(test("%", "%%")); } fn test_ctime() { - os::setenv(~"TZ", ~"America/Los_Angeles"); + os::setenv("TZ", "America/Los_Angeles"); tzset(); let time = ::time::Timespec::new(1234567890, 54321); @@ -1147,60 +1147,60 @@ mod tests { } fn test_strftime() { - os::setenv(~"TZ", ~"America/Los_Angeles"); + os::setenv("TZ", "America/Los_Angeles"); tzset(); let time = ::time::Timespec::new(1234567890, 54321); let utc = at_utc(time); let local = at(time); - assert_eq!(local.strftime(~""), ~""); - assert_eq!(local.strftime(~"%A"), ~"Friday"); - assert_eq!(local.strftime(~"%a"), ~"Fri"); - assert_eq!(local.strftime(~"%B"), ~"February"); - assert_eq!(local.strftime(~"%b"), ~"Feb"); - assert_eq!(local.strftime(~"%C"), ~"20"); - assert_eq!(local.strftime(~"%c"), ~"Fri Feb 13 15:31:30 2009"); - assert_eq!(local.strftime(~"%D"), ~"02/13/09"); - assert_eq!(local.strftime(~"%d"), ~"13"); - assert_eq!(local.strftime(~"%e"), ~"13"); - assert_eq!(local.strftime(~"%F"), ~"2009-02-13"); + assert_eq!(local.strftime(""), ~""); + assert_eq!(local.strftime("%A"), ~"Friday"); + assert_eq!(local.strftime("%a"), ~"Fri"); + assert_eq!(local.strftime("%B"), ~"February"); + assert_eq!(local.strftime("%b"), ~"Feb"); + assert_eq!(local.strftime("%C"), ~"20"); + assert_eq!(local.strftime("%c"), ~"Fri Feb 13 15:31:30 2009"); + assert_eq!(local.strftime("%D"), ~"02/13/09"); + assert_eq!(local.strftime("%d"), ~"13"); + assert_eq!(local.strftime("%e"), ~"13"); + assert_eq!(local.strftime("%F"), ~"2009-02-13"); // assert!(local.strftime("%G") == "2009"); // assert!(local.strftime("%g") == "09"); - assert_eq!(local.strftime(~"%H"), ~"15"); - assert_eq!(local.strftime(~"%I"), ~"03"); - assert_eq!(local.strftime(~"%j"), ~"044"); - assert_eq!(local.strftime(~"%k"), ~"15"); - assert_eq!(local.strftime(~"%l"), ~" 3"); - assert_eq!(local.strftime(~"%M"), ~"31"); - assert_eq!(local.strftime(~"%m"), ~"02"); - assert_eq!(local.strftime(~"%n"), ~"\n"); - assert_eq!(local.strftime(~"%P"), ~"pm"); - assert_eq!(local.strftime(~"%p"), ~"PM"); - assert_eq!(local.strftime(~"%R"), ~"15:31"); - assert_eq!(local.strftime(~"%r"), ~"03:31:30 PM"); - assert_eq!(local.strftime(~"%S"), ~"30"); - assert_eq!(local.strftime(~"%s"), ~"1234567890"); - assert_eq!(local.strftime(~"%T"), ~"15:31:30"); - assert_eq!(local.strftime(~"%t"), ~"\t"); + assert_eq!(local.strftime("%H"), ~"15"); + assert_eq!(local.strftime("%I"), ~"03"); + assert_eq!(local.strftime("%j"), ~"044"); + assert_eq!(local.strftime("%k"), ~"15"); + assert_eq!(local.strftime("%l"), ~" 3"); + assert_eq!(local.strftime("%M"), ~"31"); + assert_eq!(local.strftime("%m"), ~"02"); + assert_eq!(local.strftime("%n"), ~"\n"); + assert_eq!(local.strftime("%P"), ~"pm"); + assert_eq!(local.strftime("%p"), ~"PM"); + assert_eq!(local.strftime("%R"), ~"15:31"); + assert_eq!(local.strftime("%r"), ~"03:31:30 PM"); + assert_eq!(local.strftime("%S"), ~"30"); + assert_eq!(local.strftime("%s"), ~"1234567890"); + assert_eq!(local.strftime("%T"), ~"15:31:30"); + assert_eq!(local.strftime("%t"), ~"\t"); // assert!(local.strftime("%U") == "06"); - assert_eq!(local.strftime(~"%u"), ~"5"); + assert_eq!(local.strftime("%u"), ~"5"); // assert!(local.strftime("%V") == "07"); - assert_eq!(local.strftime(~"%v"), ~"13-Feb-2009"); + assert_eq!(local.strftime("%v"), ~"13-Feb-2009"); // assert!(local.strftime("%W") == "06"); - assert_eq!(local.strftime(~"%w"), ~"5"); + assert_eq!(local.strftime("%w"), ~"5"); // handle "%X" // handle "%x" - assert_eq!(local.strftime(~"%Y"), ~"2009"); - assert_eq!(local.strftime(~"%y"), ~"09"); + assert_eq!(local.strftime("%Y"), ~"2009"); + assert_eq!(local.strftime("%y"), ~"09"); // FIXME (#2350): We should probably standardize on the timezone // abbreviation. - let zone = local.strftime(~"%Z"); + let zone = local.strftime("%Z"); assert!(zone == ~"PST" || zone == ~"Pacific Standard Time"); - assert_eq!(local.strftime(~"%z"), ~"-0800"); - assert_eq!(local.strftime(~"%%"), ~"%"); + assert_eq!(local.strftime("%z"), ~"-0800"); + assert_eq!(local.strftime("%%"), ~"%"); // FIXME (#2350): We should probably standardize on the timezone // abbreviation. diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index 973d1faa9a6e5..5551431b551fc 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -759,10 +759,10 @@ mod test_treemap { fn u8_map() { let mut m = TreeMap::new(); - let k1 = str::to_bytes(~"foo"); - let k2 = str::to_bytes(~"bar"); - let v1 = str::to_bytes(~"baz"); - let v2 = str::to_bytes(~"foobar"); + let k1 = str::to_bytes("foo"); + let k2 = str::to_bytes("bar"); + let v1 = str::to_bytes("baz"); + let v2 = str::to_bytes("foobar"); m.insert(copy k1, copy v1); m.insert(copy k2, copy v2); From a4df35f2bcb9a399b2d4a1aa3c1def7682f9cb62 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 09:39:24 -0700 Subject: [PATCH 209/248] cleanup warnings from libsyntax --- src/libsyntax/ast.rs | 3 +-- src/libsyntax/ext/pipes/ast_builder.rs | 2 -- src/libsyntax/parse/parser.rs | 6 +++--- 3 files changed, 4 insertions(+), 7 deletions(-) diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 9ab6f13bb4bcf..a71f0ef20647f 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -17,9 +17,8 @@ use abi::AbiSet; use opt_vec::OptVec; use parse::token::get_ident_interner; -use core::cast; use core::hashmap::HashMap; -use core::option::{Option}; +use core::option::Option; use core::to_bytes::IterBytes; use core::to_bytes; use core::to_str::ToStr; diff --git a/src/libsyntax/ext/pipes/ast_builder.rs b/src/libsyntax/ext/pipes/ast_builder.rs index 545b5338ab107..da59059a0cc41 100644 --- a/src/libsyntax/ext/pipes/ast_builder.rs +++ b/src/libsyntax/ext/pipes/ast_builder.rs @@ -15,11 +15,9 @@ use core::prelude::*; -use abi::AbiSet; use ast::ident; use ast; use codemap::span; -// use ext::quote::rt::*; // Transitional reexports so qquote can find the paths it is looking for mod syntax { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 0a2d0ed924edf..b8993520ae4cc 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -2752,7 +2752,7 @@ pub impl Parser { match *self.token { token::SEMI => { if !vec::is_empty(attributes_box) { - self.span_err(*self.last_span,~"expected item after attributes"); + self.span_err(*self.last_span, "expected item after attributes"); attributes_box = ~[]; } self.bump(); // empty @@ -2823,7 +2823,7 @@ pub impl Parser { } if !vec::is_empty(attributes_box) { - self.span_err(*self.last_span,~"expected item after attributes"); + self.span_err(*self.last_span, "expected item after attributes"); } let hi = self.span.hi; @@ -3742,7 +3742,7 @@ pub impl Parser { } = self.parse_foreign_items(first_item_attrs, true); if (! attrs_remaining.is_empty()) { self.span_err(*self.last_span, - ~"expected item after attributes"); + "expected item after attributes"); } assert!(*self.token == token::RBRACE); ast::foreign_mod { From 9635b3083726c3070a52825b3f101ffe362110f2 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 09:39:10 -0700 Subject: [PATCH 210/248] cleanup warnings from librustc --- src/librustc/back/rpath.rs | 12 ++++++------ src/librustc/driver/driver.rs | 8 ++++---- src/librustc/middle/lint.rs | 1 - src/librustc/middle/resolve.rs | 6 +++--- src/librustc/middle/trans/meth.rs | 2 +- src/librustc/middle/trans/reflect.rs | 2 +- src/librustc/util/enum_set.rs | 2 -- 7 files changed, 15 insertions(+), 18 deletions(-) diff --git a/src/librustc/back/rpath.rs b/src/librustc/back/rpath.rs index 026b2944a624f..24be917aedc9f 100644 --- a/src/librustc/back/rpath.rs +++ b/src/librustc/back/rpath.rs @@ -211,8 +211,8 @@ mod test { #[test] fn test_rpaths_to_flags() { - let flags = rpaths_to_flags(~[Path("path1"), - Path("path2")]); + let flags = rpaths_to_flags([Path("path1"), + Path("path2")]); assert_eq!(flags, ~[~"-Wl,-rpath,path1", ~"-Wl,-rpath,path2"]); } @@ -243,10 +243,10 @@ mod test { #[test] fn test_minimize2() { - let res = minimize_rpaths(~[Path("1a"), Path("2"), Path("2"), - Path("1a"), Path("4a"),Path("1a"), - Path("2"), Path("3"), Path("4a"), - Path("3")]); + let res = minimize_rpaths([Path("1a"), Path("2"), Path("2"), + Path("1a"), Path("4a"),Path("1a"), + Path("2"), Path("3"), Path("4a"), + Path("3")]); assert_eq!(res, ~[Path("1a"), Path("2"), Path("4a"), Path("3")]); } diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index 4298cb5b15b31..a7cc90f473d4b 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -30,7 +30,7 @@ use core::io; use core::os; use core::str; use core::vec; -use extra::getopts::groups::{optopt, optmulti, optflag, optflagopt, getopts}; +use extra::getopts::groups::{optopt, optmulti, optflag, optflagopt}; use extra::getopts::{opt_present}; use extra::getopts; use syntax::ast; @@ -942,7 +942,7 @@ mod test { @~"rustc", matches, diagnostic::emit); let sess = build_session(sessopts, diagnostic::emit); let cfg = build_configuration(sess, @~"whatever", &str_input(~"")); - assert!((attr::contains_name(cfg, ~"test"))); + assert!((attr::contains_name(cfg, "test"))); } // When the user supplies --test and --cfg test, don't implicitly add @@ -950,7 +950,7 @@ mod test { #[test] fn test_switch_implies_cfg_test_unless_cfg_test() { let matches = - &match getopts(~[~"--test", ~"--cfg=test"], optgroups()) { + &match getopts([~"--test", ~"--cfg=test"], optgroups()) { Ok(copy m) => m, Err(copy f) => { fail!("test_switch_implies_cfg_test_unless_cfg_test: %s", getopts::fail_str(f)); @@ -960,7 +960,7 @@ mod test { @~"rustc", matches, diagnostic::emit); let sess = build_session(sessopts, diagnostic::emit); let cfg = build_configuration(sess, @~"whatever", &str_input(~"")); - let test_items = attr::find_meta_items_by_name(cfg, ~"test"); + let test_items = attr::find_meta_items_by_name(cfg, "test"); assert_eq!(test_items.len(), 1u); } } diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 2b2f2df577b2e..d156457ca8865 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -10,7 +10,6 @@ use core::prelude::*; -use driver::session::Session; use driver::session; use middle::ty; use middle::pat_util; diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 6a6746ab20bd9..cda0dfd12a35e 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -535,7 +535,7 @@ pub impl NameBindings { parent_link: ParentLink, def_id: Option, kind: ModuleKind, - sp: span) { + _sp: span) { match self.type_def { None => { let module = @mut Module(parent_link, def_id, kind); @@ -2586,8 +2586,8 @@ pub impl Resolver { (ImportSearch, ImplModuleKind) => { self.session.span_err( span, - ~"cannot import from a trait \ - or type implementation"); + "cannot import from a trait \ + or type implementation"); return Failed; } (_, _) => search_module = module_def, diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index baa0dfc79e9fc..381c257f6511c 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -873,7 +873,7 @@ pub fn trans_trait_cast(bcx: block, val: @ast::expr, id: ast::node_id, dest: expr::Dest, - store: ty::TraitStore) + _store: ty::TraitStore) -> block { let mut bcx = bcx; let _icx = bcx.insn_ctxt("impl::trans_cast"); diff --git a/src/librustc/middle/trans/reflect.rs b/src/librustc/middle/trans/reflect.rs index 0e82de86bc6dd..4d9d9f53e4c16 100644 --- a/src/librustc/middle/trans/reflect.rs +++ b/src/librustc/middle/trans/reflect.rs @@ -145,7 +145,7 @@ pub impl Reflector { } fn leaf(&mut self, name: ~str) { - self.visit(name, ~[]); + self.visit(name, []); } // Entrypoint diff --git a/src/librustc/util/enum_set.rs b/src/librustc/util/enum_set.rs index d31d943db0701..6534a7ba9b088 100644 --- a/src/librustc/util/enum_set.rs +++ b/src/librustc/util/enum_set.rs @@ -10,8 +10,6 @@ use core::prelude::*; -use core; - #[deriving(Eq, IterBytes)] pub struct EnumSet { // We must maintain the invariant that no bits are set From 50f6198ee28516b81253e0c519616954a2d79606 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 09:39:31 -0700 Subject: [PATCH 211/248] cleanup warnings from librusti --- src/librusti/rusti.rc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librusti/rusti.rc b/src/librusti/rusti.rc index d99e6f5085d46..2097d0b690743 100644 --- a/src/librusti/rusti.rc +++ b/src/librusti/rusti.rc @@ -80,7 +80,7 @@ fn record(mut repl: Repl, blk: &ast::blk, intr: @token::ident_interner) -> Repl let new_view_items = do with_pp(intr) |pp, writer| { for blk.node.view_items.each |view_item| { pprust::print_view_item(pp, *view_item); - writer.write_line(~""); + writer.write_line(""); } }; @@ -94,7 +94,7 @@ fn record(mut repl: Repl, blk: &ast::blk, intr: @token::ident_interner) -> Repl match stmt.node { ast::stmt_decl(*) | ast::stmt_mac(*) => { pprust::print_stmt(pp, *stmt); - writer.write_line(~""); + writer.write_line(""); } ast::stmt_expr(expr, _) | ast::stmt_semi(expr, _) => { match expr.node { @@ -415,7 +415,7 @@ pub fn main() { Some(line) => { if line.is_empty() { if istty { - io::println(~"()"); + io::println("()"); } loop; } From d7e43aa779f3a82614766af41adb5828d9282b5a Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 09:39:38 -0700 Subject: [PATCH 212/248] cleanup warnings from librustdoc --- src/librustdoc/config.rs | 28 +++---- src/librustdoc/desc_to_brief_pass.rs | 4 +- src/librustdoc/extract.rs | 2 - src/librustdoc/markdown_index_pass.rs | 16 ++-- src/librustdoc/markdown_pass.rs | 110 +++++++++++++------------- src/librustdoc/sectionalize_pass.rs | 8 +- 6 files changed, 81 insertions(+), 87 deletions(-) diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 39c72686a4d97..7366aca4c4f6f 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -278,26 +278,26 @@ mod test { #[test] fn should_error_with_no_crates() { - let config = parse_config(~[~"rustdoc"]); + let config = parse_config([~"rustdoc"]); assert!(config.get_err() == ~"no crates specified"); } #[test] fn should_error_with_multiple_crates() { let config = - parse_config(~[~"rustdoc", ~"crate1.rc", ~"crate2.rc"]); + parse_config([~"rustdoc", ~"crate1.rc", ~"crate2.rc"]); assert!(config.get_err() == ~"multiple crates specified"); } #[test] fn should_set_output_dir_to_cwd_if_not_provided() { - let config = parse_config(~[~"rustdoc", ~"crate.rc"]); + let config = parse_config([~"rustdoc", ~"crate.rc"]); assert!(config.get().output_dir == Path(".")); } #[test] fn should_set_output_dir_if_provided() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--output-dir", ~"snuggles" ]); assert!(config.get().output_dir == Path("snuggles")); @@ -305,13 +305,13 @@ mod test { #[test] fn should_set_output_format_to_pandoc_html_if_not_provided() { - let config = parse_config(~[~"rustdoc", ~"crate.rc"]); + let config = parse_config([~"rustdoc", ~"crate.rc"]); assert!(config.get().output_format == PandocHtml); } #[test] fn should_set_output_format_to_markdown_if_requested() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--output-format", ~"markdown" ]); assert!(config.get().output_format == Markdown); @@ -319,7 +319,7 @@ mod test { #[test] fn should_set_output_format_to_pandoc_html_if_requested() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--output-format", ~"html" ]); assert!(config.get().output_format == PandocHtml); @@ -327,7 +327,7 @@ mod test { #[test] fn should_error_on_bogus_format() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--output-format", ~"bogus" ]); assert!(config.get_err() == ~"unknown output format 'bogus'"); @@ -335,13 +335,13 @@ mod test { #[test] fn should_set_output_style_to_doc_per_mod_by_default() { - let config = parse_config(~[~"rustdoc", ~"crate.rc"]); + let config = parse_config([~"rustdoc", ~"crate.rc"]); assert!(config.get().output_style == DocPerMod); } #[test] fn should_set_output_style_to_one_doc_if_requested() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--output-style", ~"doc-per-crate" ]); assert!(config.get().output_style == DocPerCrate); @@ -349,7 +349,7 @@ mod test { #[test] fn should_set_output_style_to_doc_per_mod_if_requested() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--output-style", ~"doc-per-mod" ]); assert!(config.get().output_style == DocPerMod); @@ -357,7 +357,7 @@ mod test { #[test] fn should_error_on_bogus_output_style() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--output-style", ~"bogus" ]); assert!(config.get_err() == ~"unknown output style 'bogus'"); @@ -365,7 +365,7 @@ mod test { #[test] fn should_set_pandoc_command_if_requested() { - let config = parse_config(~[ + let config = parse_config([ ~"rustdoc", ~"crate.rc", ~"--pandoc-cmd", ~"panda-bear-doc" ]); assert!(config.get().pandoc_cmd == Some(~"panda-bear-doc")); @@ -373,7 +373,7 @@ mod test { #[test] fn should_set_pandoc_command_when_using_pandoc() { - let config = parse_config(~[~"rustdoc", ~"crate.rc"]); + let config = parse_config([~"rustdoc", ~"crate.rc"]); assert!(config.get().pandoc_cmd == Some(~"pandoc")); } } diff --git a/src/librustdoc/desc_to_brief_pass.rs b/src/librustdoc/desc_to_brief_pass.rs index d74be0580f49a..130cbb784ee37 100644 --- a/src/librustdoc/desc_to_brief_pass.rs +++ b/src/librustdoc/desc_to_brief_pass.rs @@ -220,13 +220,13 @@ mod test { #[test] fn test_paragraphs_1() { - let paras = paragraphs(~"1\n\n2"); + let paras = paragraphs("1\n\n2"); assert_eq!(paras, ~[~"1", ~"2"]); } #[test] fn test_paragraphs_2() { - let paras = paragraphs(~"\n\n1\n1\n\n2\n\n"); + let paras = paragraphs("\n\n1\n1\n\n2\n\n"); assert_eq!(paras, ~[~"1\n1", ~"2"]); } diff --git a/src/librustdoc/extract.rs b/src/librustdoc/extract.rs index 2ebdd82165a40..3ef907d819d68 100644 --- a/src/librustdoc/extract.rs +++ b/src/librustdoc/extract.rs @@ -16,9 +16,7 @@ use astsrv; use doc::ItemUtils; use doc; -use core::local_data::local_data_get; use syntax::ast; -use syntax; use syntax::parse::token::{ident_interner}; use syntax::parse::token; diff --git a/src/librustdoc/markdown_index_pass.rs b/src/librustdoc/markdown_index_pass.rs index f2467d7ad2257..8ff0aa2314647 100644 --- a/src/librustdoc/markdown_index_pass.rs +++ b/src/librustdoc/markdown_index_pass.rs @@ -193,21 +193,21 @@ mod test { #[test] fn should_remove_punctuation_from_headers() { - assert!(pandoc_header_id(~"impl foo of bar") == + assert!(pandoc_header_id("impl foo of bar") == ~"impl-foo-of-bara"); - assert!(pandoc_header_id(~"impl of num::num for int") + assert!(pandoc_header_id("impl of num::num for int") == ~"impl-of-numnum-for-int"); - assert!(pandoc_header_id(~"impl of num::num for int/&") + assert!(pandoc_header_id("impl of num::num for int/&") == ~"impl-of-numnum-for-int"); - assert!(pandoc_header_id(~"impl of num::num for ^int") + assert!(pandoc_header_id("impl of num::num for ^int") == ~"impl-of-numnum-for-int"); - assert!(pandoc_header_id(~"impl for & condvar") + assert!(pandoc_header_id("impl for & condvar") == ~"impl-for-condvar"); - assert!(pandoc_header_id(~"impl of Select for (Left, Right)") + assert!(pandoc_header_id("impl of Select for (Left, Right)") == ~"impl-of-selectt-u-for-left-right"); - assert!(pandoc_header_id(~"impl of Condition<'self, T, U>") + assert!(pandoc_header_id("impl of Condition<'self, T, U>") == ~"impl-of-conditionself-t-u"); - assert!(pandoc_header_id(~"impl of Condition") + assert!(pandoc_header_id("impl of Condition") == ~"impl-of-conditiont-copy-clone"); } diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index e0fb88ff703c7..c6f5dbefb6add 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -587,13 +587,13 @@ mod test { #[test] fn write_markdown_should_write_mod_headers() { let markdown = render(~"mod moo { }"); - assert!(str::contains(markdown, ~"# Module `moo`")); + assert!(str::contains(markdown, "# Module `moo`")); } #[test] fn should_leave_blank_line_after_header() { let markdown = render(~"mod morp { }"); - assert!(str::contains(markdown, ~"Module `morp`\n\n")); + assert!(str::contains(markdown, "Module `morp`\n\n")); } #[test] @@ -613,10 +613,10 @@ mod test { fn d() { }" ); - let idx_a = str::find_str(markdown, ~"# Module `a`").get(); - let idx_b = str::find_str(markdown, ~"## Function `b`").get(); - let idx_c = str::find_str(markdown, ~"# Module `c`").get(); - let idx_d = str::find_str(markdown, ~"## Function `d`").get(); + let idx_a = str::find_str(markdown, "# Module `a`").get(); + let idx_b = str::find_str(markdown, "## Function `b`").get(); + let idx_c = str::find_str(markdown, "# Module `c`").get(); + let idx_d = str::find_str(markdown, "## Function `d`").get(); assert!(idx_b < idx_d); assert!(idx_d < idx_a); @@ -649,7 +649,7 @@ mod test { let (page, markdown) = po.recv(); match page { doc::CratePage(_) => { - assert!(str::contains(markdown, ~"% Crate core")); + assert!(str::contains(markdown, "% Crate core")); } doc::ItemPage(_) => { assert!(str::contains(markdown, ~"% Module a")); @@ -661,7 +661,7 @@ mod test { #[test] fn should_write_full_path_to_mod() { let markdown = render(~"mod a { mod b { mod c { } } }"); - assert!(str::contains(markdown, ~"# Module `a::b::c`")); + assert!(str::contains(markdown, "# Module `a::b::c`")); } #[test] @@ -672,13 +672,13 @@ mod test { Body\"]\ mod a { }"); - assert!(str::contains(markdown, ~"#### Header\n\nBody\n\n")); + assert!(str::contains(markdown, "#### Header\n\nBody\n\n")); } #[test] fn should_write_crate_description() { let markdown = render(~"#[doc = \"this is the crate\"];"); - assert!(str::contains(markdown, ~"this is the crate")); + assert!(str::contains(markdown, "this is the crate")); } @@ -687,21 +687,21 @@ mod test { let markdown = render(~"mod a { } mod b { }"); assert!(str::contains( markdown, - ~"\n\n* [Module `a`](#module-a)\n\ - * [Module `b`](#module-b)\n\n" + "\n\n* [Module `a`](#module-a)\n\ + * [Module `b`](#module-b)\n\n" )); } #[test] fn should_write_index_brief() { let markdown = render(~"#[doc = \"test\"] mod a { }"); - assert!(str::contains(markdown, ~"(#module-a) - test\n")); + assert!(str::contains(markdown, "(#module-a) - test\n")); } #[test] fn should_not_write_index_if_no_entries() { let markdown = render(~""); - assert!(!str::contains(markdown, ~"\n\n\n")); + assert!(!str::contains(markdown, "\n\n\n")); } #[test] @@ -709,7 +709,7 @@ mod test { let markdown = render(~"extern { fn a(); }"); assert!(str::contains( markdown, - ~"\n\n* [Function `a`](#function-a)\n\n" + "\n\n* [Function `a`](#function-a)\n\n" )); } @@ -717,32 +717,32 @@ mod test { fn should_write_foreign_fns() { let markdown = render( ~"extern { #[doc = \"test\"] fn a(); }"); - assert!(str::contains(markdown, ~"test")); + assert!(str::contains(markdown, "test")); } #[test] fn should_write_foreign_fn_headers() { let markdown = render( ~"extern { #[doc = \"test\"] fn a(); }"); - assert!(str::contains(markdown, ~"## Function `a`")); + assert!(str::contains(markdown, "## Function `a`")); } #[test] fn write_markdown_should_write_function_header() { let markdown = render(~"fn func() { }"); - assert!(str::contains(markdown, ~"## Function `func`")); + assert!(str::contains(markdown, "## Function `func`")); } #[test] fn should_write_the_function_signature() { let markdown = render(~"#[doc = \"f\"] fn a() { }"); - assert!(str::contains(markdown, ~"\n fn a()\n")); + assert!(str::contains(markdown, "\n fn a()\n")); } #[test] fn should_insert_blank_line_after_fn_signature() { let markdown = render(~"#[doc = \"f\"] fn a() { }"); - assert!(str::contains(markdown, ~"fn a()\n\n")); + assert!(str::contains(markdown, "fn a()\n\n")); } #[test] @@ -763,19 +763,19 @@ mod test { ] }; let markdown = write_markdown_str(doc); - assert!(str::contains(markdown, ~" line 1\n line 2")); + assert!(str::contains(markdown, " line 1\n line 2")); } #[test] fn should_leave_blank_line_between_fn_header_and_sig() { let markdown = render(~"fn a() { }"); - assert!(str::contains(markdown, ~"Function `a`\n\n fn a()")); + assert!(str::contains(markdown, "Function `a`\n\n fn a()")); } #[test] fn should_write_const_header() { let markdown = render(~"static a: bool = true;"); - assert!(str::contains(markdown, ~"## Const `a`\n\n")); + assert!(str::contains(markdown, "## Const `a`\n\n")); } #[test] @@ -783,20 +783,19 @@ mod test { let markdown = render( ~"#[doc = \"b\"]\ static a: bool = true;"); - assert!(str::contains(markdown, ~"\n\nb\n\n")); + assert!(str::contains(markdown, "\n\nb\n\n")); } #[test] fn should_write_enum_header() { let markdown = render(~"enum a { b }"); - assert!(str::contains(markdown, ~"## Enum `a`\n\n")); + assert!(str::contains(markdown, "## Enum `a`\n\n")); } #[test] fn should_write_enum_description() { - let markdown = render( - ~"#[doc = \"b\"] enum a { b }"); - assert!(str::contains(markdown, ~"\n\nb\n\n")); + let markdown = render(~"#[doc = \"b\"] enum a { b }"); + assert!(str::contains(markdown, "\n\nb\n\n")); } #[test] @@ -807,9 +806,9 @@ mod test { #[doc = \"test\"] c }"); assert!(str::contains( markdown, - ~"\n\n#### Variants\n\ - \n* `b` - test\ - \n* `c` - test\n\n")); + "\n\n#### Variants\n\ + \n* `b` - test\ + \n* `c` - test\n\n")); } #[test] @@ -817,9 +816,9 @@ mod test { let markdown = render(~"enum a { b, c }"); assert!(str::contains( markdown, - ~"\n\n#### Variants\n\ - \n* `b`\ - \n* `c`\n\n")); + "\n\n#### Variants\n\ + \n* `b`\ + \n* `c`\n\n")); } #[test] @@ -827,100 +826,97 @@ mod test { let markdown = render(~"enum a { b(int), #[doc = \"a\"] c(int) }"); assert!(str::contains( markdown, - ~"\n\n#### Variants\n\ - \n* `b(int)`\ - \n* `c(int)` - a\n\n")); + "\n\n#### Variants\n\ + \n* `b(int)`\ + \n* `c(int)` - a\n\n")); } #[test] fn should_write_trait_header() { let markdown = render(~"trait i { fn a(); }"); - assert!(str::contains(markdown, ~"## Trait `i`")); + assert!(str::contains(markdown, "## Trait `i`")); } #[test] fn should_write_trait_desc() { - let markdown = render( - ~"#[doc = \"desc\"] trait i { fn a(); }"); - assert!(str::contains(markdown, ~"desc")); + let markdown = render(~"#[doc = \"desc\"] trait i { fn a(); }"); + assert!(str::contains(markdown, "desc")); } #[test] fn should_write_trait_method_header() { - let markdown = render( - ~"trait i { fn a(); }"); - assert!(str::contains(markdown, ~"### Method `a`")); + let markdown = render(~"trait i { fn a(); }"); + assert!(str::contains(markdown, "### Method `a`")); } #[test] fn should_write_trait_method_signature() { - let markdown = render( - ~"trait i { fn a(&self); }"); - assert!(str::contains(markdown, ~"\n fn a(&self)")); + let markdown = render(~"trait i { fn a(&self); }"); + assert!(str::contains(markdown, "\n fn a(&self)")); } #[test] fn should_write_impl_header() { let markdown = render(~"impl int { fn a() { } }"); - assert!(str::contains(markdown, ~"## Implementation for `int`")); + assert!(str::contains(markdown, "## Implementation for `int`")); } #[test] fn should_write_impl_header_with_bounds() { let markdown = render(~"impl int { }"); - assert!(str::contains(markdown, ~"## Implementation for `int` where ``")); + assert!(str::contains(markdown, "## Implementation for `int` where ``")); } #[test] fn should_write_impl_header_with_trait() { let markdown = render(~"impl j for int { fn a() { } }"); assert!(str::contains(markdown, - ~"## Implementation of `j` for `int`")); + "## Implementation of `j` for `int`")); } #[test] fn should_write_impl_desc() { let markdown = render( ~"#[doc = \"desc\"] impl int { fn a() { } }"); - assert!(str::contains(markdown, ~"desc")); + assert!(str::contains(markdown, "desc")); } #[test] fn should_write_impl_method_header() { let markdown = render( ~"impl int { fn a() { } }"); - assert!(str::contains(markdown, ~"### Method `a`")); + assert!(str::contains(markdown, "### Method `a`")); } #[test] fn should_write_impl_method_signature() { let markdown = render( ~"impl int { fn a(&mut self) { } }"); - assert!(str::contains(markdown, ~"\n fn a(&mut self)")); + assert!(str::contains(markdown, "\n fn a(&mut self)")); } #[test] fn should_write_type_header() { let markdown = render(~"type t = int;"); - assert!(str::contains(markdown, ~"## Type `t`")); + assert!(str::contains(markdown, "## Type `t`")); } #[test] fn should_write_type_desc() { let markdown = render( ~"#[doc = \"desc\"] type t = int;"); - assert!(str::contains(markdown, ~"\n\ndesc\n\n")); + assert!(str::contains(markdown, "\n\ndesc\n\n")); } #[test] fn should_write_type_signature() { let markdown = render(~"type t = int;"); - assert!(str::contains(markdown, ~"\n\n type t = int\n\n")); + assert!(str::contains(markdown, "\n\n type t = int\n\n")); } #[test] fn should_put_struct_header() { let markdown = render(~"struct S { field: () }"); - assert!(str::contains(markdown, ~"## Struct `S`\n\n")); + assert!(str::contains(markdown, "## Struct `S`\n\n")); } } diff --git a/src/librustdoc/sectionalize_pass.rs b/src/librustdoc/sectionalize_pass.rs index 4220a2bef78dd..1ffdd396da9d5 100644 --- a/src/librustdoc/sectionalize_pass.rs +++ b/src/librustdoc/sectionalize_pass.rs @@ -188,7 +188,7 @@ mod test { }"); assert!(str::contains( doc.cratemod().mods()[0].item.sections[0].header, - ~"Header")); + "Header")); } #[test] @@ -201,7 +201,7 @@ mod test { }"); assert!(str::contains( doc.cratemod().mods()[0].item.sections[0].body, - ~"Body")); + "Body")); } #[test] @@ -226,10 +226,10 @@ mod test { }"); assert!(!str::contains( doc.cratemod().mods()[0].desc().get(), - ~"Header")); + "Header")); assert!(!str::contains( doc.cratemod().mods()[0].desc().get(), - ~"Body")); + "Body")); } #[test] From 88a12193365ae1a73d4840409cc7ef111b028eff Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 09:39:48 -0700 Subject: [PATCH 213/248] cleanup warnings from compiletest --- src/compiletest/compiletest.rc | 72 +++++++++++++++++----------------- src/compiletest/header.rs | 7 ++-- src/compiletest/runtest.rs | 28 ++++++------- 3 files changed, 53 insertions(+), 54 deletions(-) diff --git a/src/compiletest/compiletest.rc b/src/compiletest/compiletest.rc index f9ad0d5f925fb..8147f8abb93da 100644 --- a/src/compiletest/compiletest.rc +++ b/src/compiletest/compiletest.rc @@ -50,20 +50,20 @@ pub fn main() { pub fn parse_config(args: ~[~str]) -> config { let opts = - ~[getopts::reqopt(~"compile-lib-path"), - getopts::reqopt(~"run-lib-path"), - getopts::reqopt(~"rustc-path"), getopts::reqopt(~"src-base"), - getopts::reqopt(~"build-base"), getopts::reqopt(~"aux-base"), - getopts::reqopt(~"stage-id"), - getopts::reqopt(~"mode"), getopts::optflag(~"ignored"), - getopts::optopt(~"runtool"), getopts::optopt(~"rustcflags"), - getopts::optflag(~"verbose"), - getopts::optopt(~"logfile"), - getopts::optflag(~"jit"), - getopts::optflag(~"newrt"), - getopts::optopt(~"target"), - getopts::optopt(~"adb-path"), - getopts::optopt(~"adb-test-dir") + ~[getopts::reqopt("compile-lib-path"), + getopts::reqopt("run-lib-path"), + getopts::reqopt("rustc-path"), getopts::reqopt("src-base"), + getopts::reqopt("build-base"), getopts::reqopt("aux-base"), + getopts::reqopt("stage-id"), + getopts::reqopt("mode"), getopts::optflag("ignored"), + getopts::optopt("runtool"), getopts::optopt("rustcflags"), + getopts::optflag("verbose"), + getopts::optopt("logfile"), + getopts::optflag("jit"), + getopts::optflag("newrt"), + getopts::optopt("target"), + getopts::optopt("adb-path"), + getopts::optopt("adb-test-dir") ]; assert!(!args.is_empty()); @@ -74,43 +74,43 @@ pub fn parse_config(args: ~[~str]) -> config { Err(f) => fail!(getopts::fail_str(f)) }; - fn opt_path(m: &getopts::Matches, nm: ~str) -> Path { + fn opt_path(m: &getopts::Matches, nm: &str) -> Path { Path(getopts::opt_str(m, nm)) } config { - compile_lib_path: getopts::opt_str(matches, ~"compile-lib-path"), - run_lib_path: getopts::opt_str(matches, ~"run-lib-path"), - rustc_path: opt_path(matches, ~"rustc-path"), - src_base: opt_path(matches, ~"src-base"), - build_base: opt_path(matches, ~"build-base"), - aux_base: opt_path(matches, ~"aux-base"), - stage_id: getopts::opt_str(matches, ~"stage-id"), - mode: str_mode(getopts::opt_str(matches, ~"mode")), - run_ignored: getopts::opt_present(matches, ~"ignored"), + compile_lib_path: getopts::opt_str(matches, "compile-lib-path"), + run_lib_path: getopts::opt_str(matches, "run-lib-path"), + rustc_path: opt_path(matches, "rustc-path"), + src_base: opt_path(matches, "src-base"), + build_base: opt_path(matches, "build-base"), + aux_base: opt_path(matches, "aux-base"), + stage_id: getopts::opt_str(matches, "stage-id"), + mode: str_mode(getopts::opt_str(matches, "mode")), + run_ignored: getopts::opt_present(matches, "ignored"), filter: if vec::len(matches.free) > 0u { option::Some(copy matches.free[0]) } else { option::None }, - logfile: getopts::opt_maybe_str(matches, ~"logfile").map(|s| Path(*s)), - runtool: getopts::opt_maybe_str(matches, ~"runtool"), - rustcflags: getopts::opt_maybe_str(matches, ~"rustcflags"), - jit: getopts::opt_present(matches, ~"jit"), - newrt: getopts::opt_present(matches, ~"newrt"), - target: opt_str2(getopts::opt_maybe_str(matches, ~"target")).to_str(), - adb_path: opt_str2(getopts::opt_maybe_str(matches, ~"adb-path")).to_str(), + logfile: getopts::opt_maybe_str(matches, "logfile").map(|s| Path(*s)), + runtool: getopts::opt_maybe_str(matches, "runtool"), + rustcflags: getopts::opt_maybe_str(matches, "rustcflags"), + jit: getopts::opt_present(matches, "jit"), + newrt: getopts::opt_present(matches, "newrt"), + target: opt_str2(getopts::opt_maybe_str(matches, "target")).to_str(), + adb_path: opt_str2(getopts::opt_maybe_str(matches, "adb-path")).to_str(), adb_test_dir: - opt_str2(getopts::opt_maybe_str(matches, ~"adb-test-dir")).to_str(), + opt_str2(getopts::opt_maybe_str(matches, "adb-test-dir")).to_str(), adb_device_status: - if (opt_str2(getopts::opt_maybe_str(matches, ~"target")) == + if (opt_str2(getopts::opt_maybe_str(matches, "target")) == ~"arm-linux-androideabi") { - if (opt_str2(getopts::opt_maybe_str(matches, ~"adb-test-dir")) != + if (opt_str2(getopts::opt_maybe_str(matches, "adb-test-dir")) != ~"(none)" && - opt_str2(getopts::opt_maybe_str(matches, ~"adb-test-dir")) != + opt_str2(getopts::opt_maybe_str(matches, "adb-test-dir")) != ~"") { true } else { false } } else { false }, - verbose: getopts::opt_present(matches, ~"verbose") + verbose: getopts::opt_present(matches, "verbose") } } diff --git a/src/compiletest/header.rs b/src/compiletest/header.rs index b3205a4861072..cc4320248cdff 100644 --- a/src/compiletest/header.rs +++ b/src/compiletest/header.rs @@ -87,10 +87,10 @@ pub fn load_props(testfile: &Path) -> TestProps { pub fn is_test_ignored(config: &config, testfile: &Path) -> bool { for iter_header(testfile) |ln| { - if parse_name_directive(ln, ~"xfail-test") { return true; } + if parse_name_directive(ln, "xfail-test") { return true; } if parse_name_directive(ln, xfail_target()) { return true; } if config.mode == common::mode_pretty && - parse_name_directive(ln, ~"xfail-pretty") { return true; } + parse_name_directive(ln, "xfail-pretty") { return true; } }; return false; @@ -107,8 +107,7 @@ fn iter_header(testfile: &Path, it: &fn(~str) -> bool) -> bool { // Assume that any directives will be found before the first // module or function. This doesn't seem to be an optimization // with a warm page cache. Maybe with a cold one. - if str::starts_with(ln, ~"fn") - || str::starts_with(ln, ~"mod") { + if str::starts_with(ln, "fn") || str::starts_with(ln, "mod") { return false; } else { if !(it(ln)) { return false; } } } diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index da81df0e404d5..c1586a1b350fa 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -25,7 +25,7 @@ use util::logv; pub fn run(config: config, testfile: ~str) { if config.verbose { // We're going to be dumping a lot of info. Start on a new line. - io::stdout().write_str(~"\n\n"); + io::stdout().write_str("\n\n"); } let testfile = Path(testfile); debug!("running %s", testfile.to_str()); @@ -231,7 +231,7 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) { // do not optimize debuginfo tests let mut config = match config.rustcflags { Some(ref flags) => config { - rustcflags: Some(str::replace(*flags, ~"-O", ~"")), + rustcflags: Some(str::replace(*flags, "-O", "")), .. copy *config }, None => copy *config @@ -249,19 +249,19 @@ fn run_debuginfo_test(config: &config, props: &TestProps, testfile: &Path) { // write debugger script let script_str = str::append(cmds, "\nquit\n"); debug!("script_str = %s", script_str); - dump_output_file(config, testfile, script_str, ~"debugger.script"); + dump_output_file(config, testfile, script_str, "debugger.script"); // run debugger script with gdb #[cfg(windows)] fn debugger() -> ~str { ~"gdb.exe" } #[cfg(unix)] fn debugger() -> ~str { ~"gdb" } - let debugger_script = make_out_name(config, testfile, ~"debugger.script"); + let debugger_script = make_out_name(config, testfile, "debugger.script"); let debugger_opts = ~[~"-quiet", ~"-batch", ~"-nx", ~"-command=" + debugger_script.to_str(), make_exe_name(config, testfile).to_str()]; let ProcArgs = ProcArgs {prog: debugger(), args: debugger_opts}; - ProcRes = compose_and_run(config, testfile, ProcArgs, ~[], ~"", None); + ProcRes = compose_and_run(config, testfile, ProcArgs, ~[], "", None); if ProcRes.status != 0 { fatal(~"gdb failed to execute"); } @@ -368,7 +368,7 @@ fn check_expected_errors(expected_errors: ~[errors::ExpectedError], } // ignore this msg which gets printed at the end - if str::contains(line, ~"aborting due to") { + if str::contains(line, "aborting due to") { was_expected = true; } @@ -643,7 +643,7 @@ fn program_output(config: &config, testfile: &Path, lib_path: &str, prog: ~str, #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] fn make_cmdline(_libpath: &str, prog: &str, args: &[~str]) -> ~str { - fmt!("%s %s", prog, str::connect(args, ~" ")) + fmt!("%s %s", prog, str::connect(args, " ")) } #[cfg(target_os = "win32")] @@ -668,7 +668,7 @@ fn dump_output_file(config: &config, testfile: &Path, out: &str, extension: &str) { let outfile = make_out_name(config, testfile, extension); let writer = - io::file_writer(&outfile, ~[io::Create, io::Truncate]).get(); + io::file_writer(&outfile, [io::Create, io::Truncate]).get(); writer.write_str(out); } @@ -692,8 +692,8 @@ fn output_base_name(config: &config, testfile: &Path) -> Path { fn maybe_dump_to_stdout(config: &config, out: &str, err: &str) { if config.verbose { - let sep1 = fmt!("------%s------------------------------", ~"stdout"); - let sep2 = fmt!("------%s------------------------------", ~"stderr"); + let sep1 = fmt!("------%s------------------------------", "stdout"); + let sep2 = fmt!("------%s------------------------------", "stderr"); let sep3 = ~"------------------------------------------"; io::stdout().write_line(sep1); io::stdout().write_line(out); @@ -781,10 +781,10 @@ fn _arm_exec_compiled_test(config: &config, props: &TestProps, newargs_err.push(newcmd_err); let procsrv::Result{ out: out_out, err: _out_err, status: out_status } = - procsrv::run(~"", config.adb_path, newargs_out, ~[(~"",~"")], + procsrv::run("", config.adb_path, newargs_out, ~[(~"",~"")], Some(~"")); let procsrv::Result{ out: err_out, err: _err_err, status: _err_status } = - procsrv::run(~"", config.adb_path, newargs_err, ~[(~"",~"")], + procsrv::run("", config.adb_path, newargs_err, ~[(~"",~"")], Some(~"")); dump_output(config, testfile, out_out, err_out); @@ -818,8 +818,8 @@ fn _arm_push_aux_shared_library(config: &config, testfile: &Path) { if (file.filetype() == Some(~".so")) { - let copy_result = procsrv::run(~"", config.adb_path, - ~[~"push", file.to_str(), copy config.adb_test_dir], + let copy_result = procsrv::run("", config.adb_path, + [~"push", file.to_str(), copy config.adb_test_dir], ~[(~"",~"")], Some(~"")); if config.verbose { From 21c3cf02f056e66d492a5a324e047ae1fec0c7d8 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 17:44:22 -0700 Subject: [PATCH 214/248] cleanup warnings from librustpkg --- src/librustpkg/tests.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/librustpkg/tests.rs b/src/librustpkg/tests.rs index 55bc302d9a17e..1bd1a6bfd77ce 100644 --- a/src/librustpkg/tests.rs +++ b/src/librustpkg/tests.rs @@ -12,7 +12,6 @@ use context::Ctx; use core::hashmap::HashMap; -use core::path::Path; use core::prelude::*; use std::tempfile::mkdtemp; use util::{PkgId, default_version}; From cc4fabcb4361d0daada096f5e6ac19eb6ed21d33 Mon Sep 17 00:00:00 2001 From: Erick Tryzelaar Date: Thu, 23 May 2013 17:58:30 -0700 Subject: [PATCH 215/248] Fix some std/extra language in the tutorial --- doc/tutorial.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/doc/tutorial.md b/doc/tutorial.md index ad9431ef60ca9..91a41cb9b85ae 100644 --- a/doc/tutorial.md +++ b/doc/tutorial.md @@ -1480,7 +1480,6 @@ This code creates a closure that adds a given string to its argument, returns it from a function, and then calls it: ~~~~ -# extern mod std; fn mk_appender(suffix: ~str) -> @fn(~str) -> ~str { // The compiler knows that we intend this closure to be of type @fn return |s| s + suffix; @@ -2292,7 +2291,7 @@ let nonsense = mycircle.radius() * mycircle.area(); ## Deriving implementations for traits -A small number of traits in `std` and `std` can have implementations +A small number of traits in `std` and `extra` can have implementations that can be automatically derived. These instances are specified by placing the `deriving` attribute on a data type declaration. For example, the following will mean that `Circle` has an implementation @@ -2541,9 +2540,9 @@ as well as an inscrutable string of alphanumerics. These are both part of Rust's library versioning scheme. The alphanumerics are a hash representing the crate metadata. -## The std library +## The standard library -The Rust std library provides runtime features required by the language, +The Rust standard library provides runtime features required by the language, including the task scheduler and memory allocators, as well as library support for Rust built-in types, platform abstractions, and other commonly used features. @@ -2559,7 +2558,7 @@ I/O abstractions ([`io`]), [containers] like [`hashmap`], common traits ([`kinds`], [`ops`], [`cmp`], [`num`], [`to_str`], [`clone`]), and complete bindings to the C standard library ([`libc`]). -### Core injection and the Rust prelude +### Standard Library injection and the Rust prelude `std` is imported at the topmost level of every crate by default, as if the first line of each crate was @@ -2571,7 +2570,7 @@ with the `std::` path prefix, as in `use std::vec`, `use std::task::spawn`, etc. Additionally, `std` contains a `prelude` module that reexports many of the -most common std modules, types and traits. The contents of the prelude are +most common standard modules, types and traits. The contents of the prelude are imported into every *module* by default. Implicitly, all modules behave as if they contained the following prologue: From 5ba5865e856818c236066aa65592691f1c21b7ac Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Thu, 23 May 2013 20:52:17 -0400 Subject: [PATCH 216/248] swap_ptr: rm equality check This isn't needed semantically, and it's the wrong case to optimize for. --- src/libstd/ptr.rs | 1 + src/libstd/util.rs | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libstd/ptr.rs b/src/libstd/ptr.rs index f6cc00ccc8681..1a822ca62cbad 100644 --- a/src/libstd/ptr.rs +++ b/src/libstd/ptr.rs @@ -103,6 +103,7 @@ pub unsafe fn copy_memory(dst: *mut T, src: *const T, count: uint) { let n = count * sys::size_of::(); memmove32(dst as *mut u8, src as *u8, n as u32); } + #[inline(always)] #[cfg(target_word_size = "64")] pub unsafe fn copy_memory(dst: *mut T, src: *const T, count: uint) { diff --git a/src/libstd/util.rs b/src/libstd/util.rs index e2b91594d123c..53de853ad469c 100644 --- a/src/libstd/util.rs +++ b/src/libstd/util.rs @@ -61,8 +61,6 @@ pub fn swap(x: &mut T, y: &mut T) { */ #[inline] pub unsafe fn swap_ptr(x: *mut T, y: *mut T) { - if x == y { return } - // Give ourselves some scratch space to work with let mut tmp: T = intrinsics::uninit(); let t = ptr::to_mut_unsafe_ptr(&mut tmp); @@ -72,7 +70,7 @@ pub unsafe fn swap_ptr(x: *mut T, y: *mut T) { ptr::copy_memory(x, y, 1); ptr::copy_memory(y, t, 1); - // y and t now point to the same thing, but we need to completely forget t + // y and t now point to the same thing, but we need to completely forget `tmp` // because it's no longer relevant. cast::forget(tmp); } From 7d2f836065b51d6f7fa50ccc17b07ff907ba2d46 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Thu, 23 May 2013 22:15:31 -0400 Subject: [PATCH 217/248] add memcpy intrinsic to mirror memmove --- src/librustc/middle/trans/foreign.rs | 20 +++++++++++++++++ src/librustc/middle/trans/type_use.rs | 2 +- src/librustc/middle/typeck/check/mod.rs | 30 +++++++++++++++++++++++++ src/libstd/unstable/intrinsics.rs | 7 ++++++ 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index 460d7407e5069..58c77f037ded3 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -845,6 +845,26 @@ pub fn trans_intrinsic(ccx: @CrateContext, T_ptr(T_nil())); Store(bcx, morestack_addr, fcx.llretptr.get()); } + ~"memcpy32" => { + let dst_ptr = get_param(decl, first_real_arg); + let src_ptr = get_param(decl, first_real_arg + 1); + let size = get_param(decl, first_real_arg + 2); + let align = C_i32(1); + let volatile = C_i1(false); + let llfn = *bcx.ccx().intrinsics.get( + &~"llvm.memcpy.p0i8.p0i8.i32"); + Call(bcx, llfn, [dst_ptr, src_ptr, size, align, volatile]); + } + ~"memcpy64" => { + let dst_ptr = get_param(decl, first_real_arg); + let src_ptr = get_param(decl, first_real_arg + 1); + let size = get_param(decl, first_real_arg + 2); + let align = C_i32(1); + let volatile = C_i1(false); + let llfn = *bcx.ccx().intrinsics.get( + &~"llvm.memcpy.p0i8.p0i8.i64"); + Call(bcx, llfn, [dst_ptr, src_ptr, size, align, volatile]); + } ~"memmove32" => { let dst_ptr = get_param(decl, first_real_arg); let src_ptr = get_param(decl, first_real_arg + 1); diff --git a/src/librustc/middle/trans/type_use.rs b/src/librustc/middle/trans/type_use.rs index 365b75b8dd43d..d4c34a3ace53b 100644 --- a/src/librustc/middle/trans/type_use.rs +++ b/src/librustc/middle/trans/type_use.rs @@ -135,7 +135,7 @@ pub fn type_uses_for(ccx: @CrateContext, fn_id: def_id, n_tps: uint) ~"visit_tydesc" | ~"forget" | ~"frame_address" | ~"morestack_addr" => 0, - ~"memmove32" | ~"memmove64" => 0, + ~"memcpy32" | ~"memcpy64" | ~"memmove32" | ~"memmove64" => 0, ~"sqrtf32" | ~"sqrtf64" | ~"powif32" | ~"powif64" | ~"sinf32" | ~"sinf64" | ~"cosf32" | ~"cosf64" | diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 6131280f90038..c8b372a37cea7 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -3537,6 +3537,36 @@ pub fn check_intrinsic_type(ccx: @mut CrateCtxt, it: @ast::foreign_item) { ~"morestack_addr" => { (0u, ~[], ty::mk_nil_ptr(ccx.tcx)) } + ~"memcpy32" => { + (0, + ~[ + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_mutbl + }), + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_imm + }), + ty::mk_u32() + ], + ty::mk_nil()) + } + ~"memcpy64" => { + (0, + ~[ + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_mutbl + }), + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_imm + }), + ty::mk_u64() + ], + ty::mk_nil()) + } ~"memmove32" => { (0, ~[ diff --git a/src/libstd/unstable/intrinsics.rs b/src/libstd/unstable/intrinsics.rs index d476822819eb9..033d9fb9954d9 100644 --- a/src/libstd/unstable/intrinsics.rs +++ b/src/libstd/unstable/intrinsics.rs @@ -128,6 +128,13 @@ pub extern "rust-intrinsic" { /// Get the address of the `__morestack` stack growth function. pub fn morestack_addr() -> *(); + /// Equivalent to the `llvm.memcpy.p0i8.0i8.i32` intrinsic. + #[cfg(not(stage0))] + pub fn memcpy32(dst: *mut u8, src: *u8, size: u32); + /// Equivalent to the `llvm.memcpy.p0i8.0i8.i64` intrinsic. + #[cfg(not(stage0))] + pub fn memcpy64(dst: *mut u8, src: *u8, size: u64); + /// Equivalent to the `llvm.memmove.p0i8.0i8.i32` intrinsic. pub fn memmove32(dst: *mut u8, src: *u8, size: u32); /// Equivalent to the `llvm.memmove.p0i8.0i8.i64` intrinsic. From a7f450ab2284ace796ce01f99919f058735c491c Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Thu, 23 May 2013 22:32:33 -0400 Subject: [PATCH 218/248] indentation fix --- src/librustc/middle/typeck/check/mod.rs | 290 ++++++++++++------------ 1 file changed, 145 insertions(+), 145 deletions(-) diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index c8b372a37cea7..6ae03ee45062d 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -3451,152 +3451,152 @@ pub fn check_intrinsic_type(ccx: @mut CrateCtxt, it: @ast::foreign_item) { let tcx = ccx.tcx; let (n_tps, inputs, output) = match *ccx.tcx.sess.str_of(it.ident) { - ~"size_of" | - ~"pref_align_of" | ~"min_align_of" => (1u, ~[], ty::mk_uint()), - ~"init" => (1u, ~[], param(ccx, 0u)), - ~"uninit" => (1u, ~[], param(ccx, 0u)), - ~"forget" => (1u, ~[ param(ccx, 0) ], ty::mk_nil()), - ~"transmute" => (2, ~[ param(ccx, 0) ], param(ccx, 1)), - ~"move_val" | ~"move_val_init" => { - (1u, + ~"size_of" | + ~"pref_align_of" | ~"min_align_of" => (1u, ~[], ty::mk_uint()), + ~"init" => (1u, ~[], param(ccx, 0u)), + ~"uninit" => (1u, ~[], param(ccx, 0u)), + ~"forget" => (1u, ~[ param(ccx, 0) ], ty::mk_nil()), + ~"transmute" => (2, ~[ param(ccx, 0) ], param(ccx, 1)), + ~"move_val" | ~"move_val_init" => { + (1u, + ~[ + ty::mk_mut_rptr(tcx, ty::re_bound(ty::br_anon(0)), param(ccx, 0)), + param(ccx, 0u) + ], + ty::mk_nil()) + } + ~"needs_drop" => (1u, ~[], ty::mk_bool()), + + ~"atomic_cxchg" | ~"atomic_cxchg_acq"| ~"atomic_cxchg_rel" => { + (0, ~[ - ty::mk_mut_rptr(tcx, ty::re_bound(ty::br_anon(0)), param(ccx, 0)), - param(ccx, 0u) - ], - ty::mk_nil()) - } - ~"needs_drop" => (1u, ~[], ty::mk_bool()), - - ~"atomic_cxchg" | ~"atomic_cxchg_acq"| ~"atomic_cxchg_rel" => { - (0, - ~[ - ty::mk_mut_rptr(tcx, - ty::re_bound(ty::br_anon(0)), - ty::mk_int()), - ty::mk_int(), - ty::mk_int() - ], - ty::mk_int()) - } - ~"atomic_load" | ~"atomic_load_acq" => { - (0, - ~[ - ty::mk_imm_rptr(tcx, ty::re_bound(ty::br_anon(0)), ty::mk_int()) - ], - ty::mk_int()) - } - ~"atomic_store" | ~"atomic_store_rel" => { - (0, - ~[ - ty::mk_mut_rptr(tcx, ty::re_bound(ty::br_anon(0)), ty::mk_int()), - ty::mk_int() - ], - ty::mk_nil()) - } - ~"atomic_xchg" | ~"atomic_xadd" | ~"atomic_xsub" | - ~"atomic_xchg_acq" | ~"atomic_xadd_acq" | ~"atomic_xsub_acq" | - ~"atomic_xchg_rel" | ~"atomic_xadd_rel" | ~"atomic_xsub_rel" => { - (0, - ~[ - ty::mk_mut_rptr(tcx, ty::re_bound(ty::br_anon(0)), ty::mk_int()), - ty::mk_int() - ], - ty::mk_int()) - } - - ~"get_tydesc" => { - // FIXME (#3730): return *intrinsic::tydesc, not *() - (1u, ~[], ty::mk_nil_ptr(ccx.tcx)) - } - ~"visit_tydesc" => { - let tydesc_name = special_idents::tydesc; - assert!(tcx.intrinsic_defs.contains_key(&tydesc_name)); - let (_, tydesc_ty) = tcx.intrinsic_defs.get_copy(&tydesc_name); - let (_, visitor_object_ty) = ty::visitor_object_ty(tcx); - let td_ptr = ty::mk_ptr(ccx.tcx, ty::mt { - ty: tydesc_ty, - mutbl: ast::m_imm - }); - (0, ~[ td_ptr, visitor_object_ty ], ty::mk_nil()) - } - ~"frame_address" => { - let fty = ty::mk_closure(ccx.tcx, ty::ClosureTy { - purity: ast::impure_fn, - sigil: ast::BorrowedSigil, - onceness: ast::Once, - region: ty::re_bound(ty::br_anon(0)), - bounds: ty::EmptyBuiltinBounds(), - sig: ty::FnSig { - bound_lifetime_names: opt_vec::Empty, - inputs: ~[ty::mk_imm_ptr(ccx.tcx, ty::mk_mach_uint(ast::ty_u8))], - output: ty::mk_nil() - } - }); - (0u, ~[fty], ty::mk_nil()) - } - ~"morestack_addr" => { - (0u, ~[], ty::mk_nil_ptr(ccx.tcx)) - } - ~"memcpy32" => { - (0, - ~[ - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_mutbl - }), - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_imm - }), - ty::mk_u32() - ], - ty::mk_nil()) - } - ~"memcpy64" => { - (0, - ~[ - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_mutbl - }), - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_imm - }), - ty::mk_u64() - ], - ty::mk_nil()) - } - ~"memmove32" => { - (0, - ~[ - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_mutbl - }), - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_imm - }), - ty::mk_u32() - ], - ty::mk_nil()) - } - ~"memmove64" => { - (0, - ~[ - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_mutbl - }), - ty::mk_ptr(tcx, ty::mt { - ty: ty::mk_u8(), - mutbl: ast::m_imm - }), - ty::mk_u64() - ], - ty::mk_nil()) - } + ty::mk_mut_rptr(tcx, + ty::re_bound(ty::br_anon(0)), + ty::mk_int()), + ty::mk_int(), + ty::mk_int() + ], + ty::mk_int()) + } + ~"atomic_load" | ~"atomic_load_acq" => { + (0, + ~[ + ty::mk_imm_rptr(tcx, ty::re_bound(ty::br_anon(0)), ty::mk_int()) + ], + ty::mk_int()) + } + ~"atomic_store" | ~"atomic_store_rel" => { + (0, + ~[ + ty::mk_mut_rptr(tcx, ty::re_bound(ty::br_anon(0)), ty::mk_int()), + ty::mk_int() + ], + ty::mk_nil()) + } + ~"atomic_xchg" | ~"atomic_xadd" | ~"atomic_xsub" | + ~"atomic_xchg_acq" | ~"atomic_xadd_acq" | ~"atomic_xsub_acq" | + ~"atomic_xchg_rel" | ~"atomic_xadd_rel" | ~"atomic_xsub_rel" => { + (0, + ~[ + ty::mk_mut_rptr(tcx, ty::re_bound(ty::br_anon(0)), ty::mk_int()), + ty::mk_int() + ], + ty::mk_int()) + } + + ~"get_tydesc" => { + // FIXME (#3730): return *intrinsic::tydesc, not *() + (1u, ~[], ty::mk_nil_ptr(ccx.tcx)) + } + ~"visit_tydesc" => { + let tydesc_name = special_idents::tydesc; + assert!(tcx.intrinsic_defs.contains_key(&tydesc_name)); + let (_, tydesc_ty) = tcx.intrinsic_defs.get_copy(&tydesc_name); + let (_, visitor_object_ty) = ty::visitor_object_ty(tcx); + let td_ptr = ty::mk_ptr(ccx.tcx, ty::mt { + ty: tydesc_ty, + mutbl: ast::m_imm + }); + (0, ~[ td_ptr, visitor_object_ty ], ty::mk_nil()) + } + ~"frame_address" => { + let fty = ty::mk_closure(ccx.tcx, ty::ClosureTy { + purity: ast::impure_fn, + sigil: ast::BorrowedSigil, + onceness: ast::Once, + region: ty::re_bound(ty::br_anon(0)), + bounds: ty::EmptyBuiltinBounds(), + sig: ty::FnSig { + bound_lifetime_names: opt_vec::Empty, + inputs: ~[ty::mk_imm_ptr(ccx.tcx, ty::mk_mach_uint(ast::ty_u8))], + output: ty::mk_nil() + } + }); + (0u, ~[fty], ty::mk_nil()) + } + ~"morestack_addr" => { + (0u, ~[], ty::mk_nil_ptr(ccx.tcx)) + } + ~"memcpy32" => { + (0, + ~[ + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_mutbl + }), + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_imm + }), + ty::mk_u32() + ], + ty::mk_nil()) + } + ~"memcpy64" => { + (0, + ~[ + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_mutbl + }), + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_imm + }), + ty::mk_u64() + ], + ty::mk_nil()) + } + ~"memmove32" => { + (0, + ~[ + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_mutbl + }), + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_imm + }), + ty::mk_u32() + ], + ty::mk_nil()) + } + ~"memmove64" => { + (0, + ~[ + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_mutbl + }), + ty::mk_ptr(tcx, ty::mt { + ty: ty::mk_u8(), + mutbl: ast::m_imm + }), + ty::mk_u64() + ], + ty::mk_nil()) + } ~"sqrtf32" => (0, ~[ ty::mk_f32() ], ty::mk_f32()), ~"sqrtf64" => (0, ~[ ty::mk_f64() ], ty::mk_f64()), ~"powif32" => { From abb2823c35f24d526d05f6757288e272d65fd42e Mon Sep 17 00:00:00 2001 From: Jyun-Yan You Date: Thu, 23 May 2013 01:49:43 +0800 Subject: [PATCH 219/248] make arm register definition consistent with rt --- src/libstd/cleanup.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/cleanup.rs b/src/libstd/cleanup.rs index 5796be7b1e4ce..d1460b7a3c96b 100644 --- a/src/libstd/cleanup.rs +++ b/src/libstd/cleanup.rs @@ -39,11 +39,11 @@ struct AllocHeader { priv opaque: () } struct MemoryRegion { priv opaque: () } #[cfg(target_arch="x86")] -#[cfg(target_arch="arm")] struct Registers { data: [u32, ..16] } +#[cfg(target_arch="arm")] #[cfg(target_arch="mips")] struct Registers { data: [u32, ..32] From 7bff0281c72d64ec5129871354a55d6a2070dd51 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Thu, 23 May 2013 22:54:46 -0400 Subject: [PATCH 220/248] optimize util::swap, &mut pointers never alias --- src/libstd/ptr.rs | 22 ++++++++++++++++++++++ src/libstd/unstable/intrinsics.rs | 1 - src/libstd/util.rs | 15 +++++++++++++-- 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/libstd/ptr.rs b/src/libstd/ptr.rs index 1a822ca62cbad..d1c0ffe795311 100644 --- a/src/libstd/ptr.rs +++ b/src/libstd/ptr.rs @@ -112,6 +112,28 @@ pub unsafe fn copy_memory(dst: *mut T, src: *const T, count: uint) { memmove64(dst as *mut u8, src as *u8, n as u64); } +#[inline(always)] +#[cfg(target_word_size = "32")] +pub unsafe fn copy_nonoverlapping_memory(dst: *mut T, src: *const T, count: uint) { + #[cfg(stage0)] + use memcpy32 = unstable::intrinsics::memmove32; + #[cfg(not(stage0))] + use unstable::intrinsics::memcpy32; + let n = count * sys::size_of::(); + memcpy32(dst as *mut u8, src as *u8, n as u32); +} + +#[inline(always)] +#[cfg(target_word_size = "64")] +pub unsafe fn copy_nonoverlapping_memory(dst: *mut T, src: *const T, count: uint) { + #[cfg(stage0)] + use memcpy64 = unstable::intrinsics::memmove64; + #[cfg(not(stage0))] + use unstable::intrinsics::memcpy64; + let n = count * sys::size_of::(); + memcpy64(dst as *mut u8, src as *u8, n as u64); +} + #[inline(always)] pub unsafe fn set_memory(dst: *mut T, c: int, count: uint) { let n = count * sys::size_of::(); diff --git a/src/libstd/unstable/intrinsics.rs b/src/libstd/unstable/intrinsics.rs index 033d9fb9954d9..521708621fc89 100644 --- a/src/libstd/unstable/intrinsics.rs +++ b/src/libstd/unstable/intrinsics.rs @@ -31,7 +31,6 @@ A quick refresher on memory ordering: with atomic types and is equivalent to Java's `volatile`. */ - #[abi = "rust-intrinsic"] pub extern "rust-intrinsic" { diff --git a/src/libstd/util.rs b/src/libstd/util.rs index 53de853ad469c..400a13896be8c 100644 --- a/src/libstd/util.rs +++ b/src/libstd/util.rs @@ -51,7 +51,18 @@ pub fn with( #[inline(always)] pub fn swap(x: &mut T, y: &mut T) { unsafe { - swap_ptr(ptr::to_mut_unsafe_ptr(x), ptr::to_mut_unsafe_ptr(y)); + // Give ourselves some scratch space to work with + let mut tmp: T = intrinsics::uninit(); + let t: *mut T = &mut tmp; + + // Perform the swap, `&mut` pointers never alias + ptr::copy_nonoverlapping_memory(t, x, 1); + ptr::copy_nonoverlapping_memory(x, y, 1); + ptr::copy_nonoverlapping_memory(y, t, 1); + + // y and t now point to the same thing, but we need to completely forget `tmp` + // because it's no longer relevant. + cast::forget(tmp); } } @@ -63,7 +74,7 @@ pub fn swap(x: &mut T, y: &mut T) { pub unsafe fn swap_ptr(x: *mut T, y: *mut T) { // Give ourselves some scratch space to work with let mut tmp: T = intrinsics::uninit(); - let t = ptr::to_mut_unsafe_ptr(&mut tmp); + let t: *mut T = &mut tmp; // Perform the swap ptr::copy_memory(t, x, 1); From 248a66938181e67855ac6f330ff626a509611a9b Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Thu, 23 May 2013 20:27:25 -0700 Subject: [PATCH 221/248] docs: Don't mention obsolete move operator, as per #5700 --- doc/rust.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/rust.md b/doc/rust.md index 1d5a685a6a2cb..719750ea7ca06 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -2435,10 +2435,11 @@ match x { } ~~~~ -Patterns that bind variables default to binding to a copy of the matched value. This can be made -explicit using the ```copy``` keyword, changed to bind to a borrowed pointer by using the ```ref``` -keyword, or to a mutable borrowed pointer using ```ref mut```, or the value can be moved into -the new binding using ```move```. +Patterns that bind variables default to binding to a copy or move of the matched value +(depending on the matched value's type). +This can be made explicit using the ```copy``` keyword, +changed to bind to a borrowed pointer by using the ```ref``` keyword, +or to a mutable borrowed pointer using ```ref mut```. A pattern that's just an identifier, like `Nil` in the previous answer, From 0629ef16e8d93e7e461b025e829b350b5daeed6a Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Fri, 24 May 2013 01:16:15 -0400 Subject: [PATCH 222/248] use deriving for DeepClone --- src/libstd/cell.rs | 15 +-------------- src/libstd/option.rs | 11 +---------- 2 files changed, 2 insertions(+), 24 deletions(-) diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs index b707e3bbb9efa..d1fa9e697bf62 100644 --- a/src/libstd/cell.rs +++ b/src/libstd/cell.rs @@ -21,24 +21,11 @@ Similar to a mutable option type, but friendlier. */ #[mutable] -#[deriving(Clone)] +#[deriving(Clone, DeepClone, Eq)] pub struct Cell { priv value: Option } -impl DeepClone for Cell { - fn deep_clone(&self) -> Cell { - Cell{value: self.value.deep_clone()} - } -} - -impl cmp::Eq for Cell { - fn eq(&self, other: &Cell) -> bool { - (self.value) == (other.value) - } - fn ne(&self, other: &Cell) -> bool { !self.eq(other) } -} - /// Creates a new full cell with the given value. pub fn Cell(value: T) -> Cell { Cell { value: Some(value) } diff --git a/src/libstd/option.rs b/src/libstd/option.rs index bc1ffcdc81ae4..be6ec8c85186c 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -54,21 +54,12 @@ use clone::DeepClone; #[cfg(test)] use str; /// The option type -#[deriving(Clone, Eq)] +#[deriving(Clone, DeepClone, Eq)] pub enum Option { None, Some(T), } -impl DeepClone for Option { - fn deep_clone(&self) -> Option { - match *self { - Some(ref x) => Some(x.deep_clone()), - None => None - } - } -} - impl Ord for Option { fn lt(&self, other: &Option) -> bool { match (self, other) { From e69e80938bd000611ec17c3c23606e060f9b660a Mon Sep 17 00:00:00 2001 From: Tom Lee Date: Thu, 23 May 2013 23:49:20 -0700 Subject: [PATCH 223/248] Define _RUST_STAGEN when building rustrt. This lets us use #ifdefs to determine which stage of the build we happen to be in, which is useful in the event we need to make changes to rustrt that are incompatible with the code generated by stage0. This should help pave the way to completing #6575, which will likely require changes to type signatures for spawn_fn & glue_fn in rustrt. --- configure | 14 +++++--- mk/rt.mk | 100 +++++++++++++++++++++++++++------------------------ mk/target.mk | 4 +-- 3 files changed, 64 insertions(+), 54 deletions(-) diff --git a/configure b/configure index 0b8189416bb0b..4fb0ed01bdf6e 100755 --- a/configure +++ b/configure @@ -665,12 +665,16 @@ make_dir rt for t in $CFG_TARGET_TRIPLES do make_dir rt/$t - for i in \ - isaac linenoise sync test \ - arch/i386 arch/x86_64 arch/arm arch/mips \ - libuv libuv/src/ares libuv/src/eio libuv/src/ev + for s in 0 1 2 3 do - make_dir rt/$t/$i + make_dir rt/$t/stage$s + for i in \ + isaac linenoise sync test \ + arch/i386 arch/x86_64 arch/arm arch/mips \ + libuv libuv/src/ares libuv/src/eio libuv/src/ev + do + make_dir rt/$t/stage$s/$i + done done done diff --git a/mk/rt.mk b/mk/rt.mk index 2087945afb529..d8d74d0d0e3fa 100644 --- a/mk/rt.mk +++ b/mk/rt.mk @@ -41,14 +41,19 @@ ifneq ($(strip $(findstring snap,$(MAKECMDGOALS))),) SNAP_DEFINES=-DRUST_SNAPSHOT endif - define DEF_RUNTIME_TARGETS ###################################################################### # Runtime (C++) library variables ###################################################################### -RUNTIME_CXXS_$(1) := \ +# $(1) is the target triple +# $(2) is the stage number + +RUNTIME_CFLAGS_$(1)_$(2) = -D_RUST_STAGE$(2) +RUNTIME_CXXFLAGS_$(1)_$(2) = -D_RUST_STAGE$(2) + +RUNTIME_CXXS_$(1)_$(2) := \ rt/sync/timer.cpp \ rt/sync/lock_and_signal.cpp \ rt/sync/rust_thread.cpp \ @@ -83,70 +88,70 @@ RUNTIME_CXXS_$(1) := \ rt/rust_android_dummy.cpp \ rt/rust_test_helpers.cpp -RUNTIME_CS_$(1) := rt/linenoise/linenoise.c rt/linenoise/utf8.c +RUNTIME_CS_$(1)_$(2) := rt/linenoise/linenoise.c rt/linenoise/utf8.c -RUNTIME_S_$(1) := rt/arch/$$(HOST_$(1))/_context.S \ - rt/arch/$$(HOST_$(1))/ccall.S \ - rt/arch/$$(HOST_$(1))/record_sp.S +RUNTIME_S_$(1)_$(2) := rt/arch/$$(HOST_$(1))/_context.S \ + rt/arch/$$(HOST_$(1))/ccall.S \ + rt/arch/$$(HOST_$(1))/record_sp.S ifeq ($$(CFG_WINDOWSY_$(1)), 1) - LIBUV_OSTYPE_$(1) := win - LIBUV_LIB_$(1) := rt/$(1)/libuv/libuv.a + LIBUV_OSTYPE_$(1)_$(2) := win + LIBUV_LIB_$(1)_$(2) := rt/$(1)/stage$(2)/libuv/libuv.a else ifeq ($(OSTYPE_$(1)), apple-darwin) - LIBUV_OSTYPE_$(1) := mac - LIBUV_LIB_$(1) := rt/$(1)/libuv/libuv.a + LIBUV_OSTYPE_$(1)_$(2) := mac + LIBUV_LIB_$(1)_$(2) := rt/$(1)/stage$(2)/libuv/libuv.a else ifeq ($(OSTYPE_$(1)), unknown-freebsd) - LIBUV_OSTYPE_$(1) := unix/freebsd - LIBUV_LIB_$(1) := rt/$(1)/libuv/libuv.a + LIBUV_OSTYPE_$(1)_$(2) := unix/freebsd + LIBUV_LIB_$(1)_$(2) := rt/$(1)/stage$(2)/libuv/libuv.a else ifeq ($(OSTYPE_$(1)), linux-androideabi) - LIBUV_OSTYPE_$(1) := unix/android - LIBUV_LIB_$(1) := rt/$(1)/libuv/libuv.a + LIBUV_OSTYPE_$(1)_$(2) := unix/android + LIBUV_LIB_$(1)_$(2) := rt/$(1)/stage$(2)/libuv/libuv.a else - LIBUV_OSTYPE_$(1) := unix/linux - LIBUV_LIB_$(1) := rt/$(1)/libuv/libuv.a + LIBUV_OSTYPE_$(1)_$(2) := unix/linux + LIBUV_LIB_$(1)_$(2) := rt/$(1)/stage$(2)/libuv/libuv.a endif -RUNTIME_DEF_$(1) := rt/rustrt$(CFG_DEF_SUFFIX_$(1)) -RUNTIME_INCS_$(1) := -I $$(S)src/rt -I $$(S)src/rt/isaac -I $$(S)src/rt/uthash \ +RUNTIME_DEF_$(1)_$(2) := rt/rustrt$(CFG_DEF_SUFFIX_$(1)) +RUNTIME_INCS_$(1)_$(2) := -I $$(S)src/rt -I $$(S)src/rt/isaac -I $$(S)src/rt/uthash \ -I $$(S)src/rt/arch/$$(HOST_$(1)) \ -I $$(S)src/rt/linenoise \ -I $$(S)src/libuv/include -RUNTIME_OBJS_$(1) := $$(RUNTIME_CXXS_$(1):rt/%.cpp=rt/$(1)/%.o) \ - $$(RUNTIME_CS_$(1):rt/%.c=rt/$(1)/%.o) \ - $$(RUNTIME_S_$(1):rt/%.S=rt/$(1)/%.o) -ALL_OBJ_FILES += $$(RUNTIME_OBJS_$(1)) +RUNTIME_OBJS_$(1)_$(2) := $$(RUNTIME_CXXS_$(1)_$(2):rt/%.cpp=rt/$(1)/stage$(2)/%.o) \ + $$(RUNTIME_CS_$(1)_$(2):rt/%.c=rt/$(1)/stage$(2)/%.o) \ + $$(RUNTIME_S_$(1)_$(2):rt/%.S=rt/$(1)/stage$(2)/%.o) +ALL_OBJ_FILES += $$(RUNTIME_OBJS_$(1)_$(2)) -MORESTACK_OBJ_$(1) := rt/$(1)/arch/$$(HOST_$(1))/morestack.o -ALL_OBJ_FILES += $$(MORESTACK_OBJS_$(1)) +MORESTACK_OBJ_$(1)_$(2) := rt/$(1)/stage$(2)/arch/$$(HOST_$(1))/morestack.o +ALL_OBJ_FILES += $$(MORESTACK_OBJS_$(1)_$(2)) -RUNTIME_LIBS_$(1) := $$(LIBUV_LIB_$(1)) +RUNTIME_LIBS_$(1)_$(2) := $$(LIBUV_LIB_$(1)_$(2)) -rt/$(1)/%.o: rt/%.cpp $$(MKFILE_DEPS) +rt/$(1)/stage$(2)/%.o: rt/%.cpp $$(MKFILE_DEPS) @$$(call E, compile: $$@) - $$(Q)$$(call CFG_COMPILE_CXX_$(1), $$@, $$(RUNTIME_INCS_$(1)) \ - $$(SNAP_DEFINES)) $$< + $$(Q)$$(call CFG_COMPILE_CXX_$(1), $$@, $$(RUNTIME_INCS_$(1)_$(2)) \ + $$(SNAP_DEFINES) $$(RUNTIME_CXXFLAGS_$(1)_$(2))) $$< -rt/$(1)/%.o: rt/%.c $$(MKFILE_DEPS) +rt/$(1)/stage$(2)/%.o: rt/%.c $$(MKFILE_DEPS) @$$(call E, compile: $$@) - $$(Q)$$(call CFG_COMPILE_C_$(1), $$@, $$(RUNTIME_INCS_$(1)) \ - $$(SNAP_DEFINES)) $$< + $$(Q)$$(call CFG_COMPILE_C_$(1), $$@, $$(RUNTIME_INCS_$(1)_$(2)) \ + $$(SNAP_DEFINES) $$(RUNTIME_CFLAGS_$(1)_$(2))) $$< -rt/$(1)/%.o: rt/%.S $$(MKFILE_DEPS) \ +rt/$(1)/stage$(2)/%.o: rt/%.S $$(MKFILE_DEPS) \ $$(LLVM_CONFIG_$$(CFG_BUILD_TRIPLE)) @$$(call E, compile: $$@) $$(Q)$$(call CFG_ASSEMBLE_$(1),$$@,$$<) -rt/$(1)/arch/$$(HOST_$(1))/libmorestack.a: $$(MORESTACK_OBJ_$(1)) +rt/$(1)/stage$(2)/arch/$$(HOST_$(1))/libmorestack.a: $$(MORESTACK_OBJ_$(1)_$(2)) @$$(call E, link: $$@) $$(Q)$(AR_$(1)) rcs $$@ $$< -rt/$(1)/$(CFG_RUNTIME_$(1)): $$(RUNTIME_OBJS_$(1)) $$(MKFILE_DEPS) \ - $$(RUNTIME_DEF_$(1)) \ - $$(RUNTIME_LIBS_$(1)) +rt/$(1)/stage$(2)/$(CFG_RUNTIME_$(1)): $$(RUNTIME_OBJS_$(1)_$(2)) $$(MKFILE_DEPS) \ + $$(RUNTIME_DEF_$(1)_$(2)) \ + $$(RUNTIME_LIBS_$(1)_$(2)) @$$(call E, link: $$@) - $$(Q)$$(call CFG_LINK_CXX_$(1),$$@, $$(RUNTIME_OBJS_$(1)) \ - $$(CFG_GCCISH_POST_LIB_FLAGS_$(1)) $$(RUNTIME_LIBS_$(1)) \ - $$(CFG_LIBUV_LINK_FLAGS_$(1)),$$(RUNTIME_DEF_$(1)),$$(CFG_RUNTIME_$(1))) + $$(Q)$$(call CFG_LINK_CXX_$(1),$$@, $$(RUNTIME_OBJS_$(1)_$(2)) \ + $$(CFG_GCCISH_POST_LIB_FLAGS_$(1)) $$(RUNTIME_LIBS_$(1)_$(2)) \ + $$(CFG_LIBUV_LINK_FLAGS_$(1)),$$(RUNTIME_DEF_$(1)_$(2)),$$(CFG_RUNTIME_$(1))) # FIXME: For some reason libuv's makefiles can't figure out the # correct definition of CC on the mingw I'm using, so we are @@ -165,13 +170,13 @@ endif # XXX: Shouldn't need platform-specific conditions here ifdef CFG_WINDOWSY_$(1) -$$(LIBUV_LIB_$(1)): $$(LIBUV_DEPS) +$$(LIBUV_LIB_$(1)_$(2)): $$(LIBUV_DEPS) $$(Q)$$(MAKE) -C $$(S)src/libuv/ \ - builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/libuv" \ + builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/stage$(2)/libuv" \ OS=mingw \ V=$$(VERBOSE) else ifeq ($(OSTYPE_$(1)), linux-androideabi) -$$(LIBUV_LIB_$(1)): $$(LIBUV_DEPS) +$$(LIBUV_LIB_$(1)_$(2)): $$(LIBUV_DEPS) $$(Q)$$(MAKE) -C $$(S)src/libuv/ \ CFLAGS="$$(CFG_GCCISH_CFLAGS) $$(LIBUV_FLAGS_$$(HOST_$(1))) $$(SNAP_DEFINES)" \ LDFLAGS="$$(CFG_GCCISH_LINK_FLAGS) $$(LIBUV_FLAGS_$$(HOST_$(1)))" \ @@ -179,18 +184,18 @@ $$(LIBUV_LIB_$(1)): $$(LIBUV_DEPS) CXX="$$(CXX_$(1))" \ AR="$$(AR_$(1))" \ BUILDTYPE=Release \ - builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/libuv" \ + builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/stage$(2)/libuv" \ host=android OS=linux \ V=$$(VERBOSE) else -$$(LIBUV_LIB_$(1)): $$(LIBUV_DEPS) +$$(LIBUV_LIB_$(1)_$(2)): $$(LIBUV_DEPS) $$(Q)$$(MAKE) -C $$(S)src/libuv/ \ CFLAGS="$$(CFG_GCCISH_CFLAGS) $$(LIBUV_FLAGS_$$(HOST_$(1))) $$(SNAP_DEFINES)" \ LDFLAGS="$$(CFG_GCCISH_LINK_FLAGS) $$(LIBUV_FLAGS_$$(HOST_$(1)))" \ CC="$$(CC_$(1))" \ CXX="$$(CXX_$(1))" \ AR="$$(AR_$(1))" \ - builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/libuv" \ + builddir_name="$$(CFG_BUILD_DIR)/rt/$(1)/stage$(2)/libuv" \ V=$$(VERBOSE) endif @@ -229,5 +234,6 @@ endif endef # Instantiate template for all stages -$(foreach target,$(CFG_TARGET_TRIPLES), \ - $(eval $(call DEF_RUNTIME_TARGETS,$(target)))) +$(foreach stage,$(STAGES), \ + $(foreach target,$(CFG_TARGET_TRIPLES), \ + $(eval $(call DEF_RUNTIME_TARGETS,$(target),$(stage))))) diff --git a/mk/target.mk b/mk/target.mk index 9b4153d7ed50d..2aeed841e3534 100644 --- a/mk/target.mk +++ b/mk/target.mk @@ -18,13 +18,13 @@ define TARGET_STAGE_N $$(TLIB$(1)_T_$(2)_H_$(3))/libmorestack.a: \ - rt/$(2)/arch/$$(HOST_$(2))/libmorestack.a \ + rt/$(2)/stage$(1)/arch/$$(HOST_$(2))/libmorestack.a \ | $$(TLIB$(1)_T_$(2)_H_$(3))/ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ $$(TLIB$(1)_T_$(2)_H_$(3))/$(CFG_RUNTIME_$(2)): \ - rt/$(2)/$(CFG_RUNTIME_$(2)) \ + rt/$(2)/stage$(1)/$(CFG_RUNTIME_$(2)) \ | $$(TLIB$(1)_T_$(2)_H_$(3))/ @$$(call E, cp: $$@) $$(Q)cp $$< $$@ From 1009c21ad7b1db366a5c600946652cc490598ec1 Mon Sep 17 00:00:00 2001 From: Lenny222 Date: Fri, 24 May 2013 21:32:30 +0200 Subject: [PATCH 224/248] show options for -W help and -W --- src/librustc/driver/driver.rs | 2 +- src/librustc/rustc.rc | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index a7cc90f473d4b..75731cf4dc62d 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -811,7 +811,7 @@ pub fn optgroups() -> ~[getopts::groups::OptGroup] { for detail)", "FEATURE"), optopt("", "android-cross-path", "The path to the Android NDK", "PATH"), - optmulti("W", "warn", + optflagopt("W", "warn", "Set lint warnings", "OPT"), optmulti("A", "allow", "Set lint allowed", "OPT"), diff --git a/src/librustc/rustc.rc b/src/librustc/rustc.rc index 2b392efaa859c..056b4a9a49ef9 100644 --- a/src/librustc/rustc.rc +++ b/src/librustc/rustc.rc @@ -228,9 +228,14 @@ pub fn run_compiler(args: &~[~str], demitter: diagnostic::Emitter) { return; } + // Display the available lint options if "-W help" or only "-W" is given. let lint_flags = vec::append(getopts::opt_strs(matches, "W"), getopts::opt_strs(matches, "warn")); - if lint_flags.contains(&~"help") { + + let show_lint_options = lint_flags.contains(&~"help") || + (opt_present(matches, "W") && lint_flags.is_empty()); + + if show_lint_options { describe_warnings(); return; } From ec8fb884e94975ed6d82a4cc0ea0a064a4b7155f Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sun, 12 May 2013 21:14:40 -0400 Subject: [PATCH 225/248] Remove usage of the #[merge] hack with int modules --- src/libstd/core.rc | 46 +- src/libstd/num/i16.rs | 32 ++ src/libstd/num/i32.rs | 32 ++ src/libstd/num/i64.rs | 32 ++ src/libstd/num/i8.rs | 32 ++ src/libstd/num/int-template/i16.rs | 41 -- src/libstd/num/int-template/i32.rs | 41 -- src/libstd/num/int-template/i64.rs | 41 -- src/libstd/num/int-template/i8.rs | 41 -- src/libstd/num/int-template/int.rs | 104 ---- src/libstd/num/int.rs | 89 ++++ .../num/{int-template.rs => int_macros.rs} | 490 +++++++++--------- src/libstd/num/u16.rs | 14 + src/libstd/num/u32.rs | 14 + src/libstd/num/u64.rs | 14 + src/libstd/num/u8.rs | 14 + src/libstd/num/uint-template/u16.rs | 43 -- src/libstd/num/uint-template/u32.rs | 43 -- src/libstd/num/uint-template/u64.rs | 43 -- src/libstd/num/uint-template/u8.rs | 43 -- src/libstd/num/uint-template/uint.rs | 256 --------- src/libstd/num/uint.rs | 195 +++++++ .../num/{uint-template.rs => uint_macros.rs} | 390 +++++++------- 23 files changed, 941 insertions(+), 1149 deletions(-) create mode 100644 src/libstd/num/i16.rs create mode 100644 src/libstd/num/i32.rs create mode 100644 src/libstd/num/i64.rs create mode 100644 src/libstd/num/i8.rs delete mode 100644 src/libstd/num/int-template/i16.rs delete mode 100644 src/libstd/num/int-template/i32.rs delete mode 100644 src/libstd/num/int-template/i64.rs delete mode 100644 src/libstd/num/int-template/i8.rs delete mode 100644 src/libstd/num/int-template/int.rs create mode 100644 src/libstd/num/int.rs rename src/libstd/num/{int-template.rs => int_macros.rs} (56%) create mode 100644 src/libstd/num/u16.rs create mode 100644 src/libstd/num/u32.rs create mode 100644 src/libstd/num/u64.rs create mode 100644 src/libstd/num/u8.rs delete mode 100644 src/libstd/num/uint-template/u16.rs delete mode 100644 src/libstd/num/uint-template/u32.rs delete mode 100644 src/libstd/num/uint-template/u64.rs delete mode 100644 src/libstd/num/uint-template/u8.rs delete mode 100644 src/libstd/num/uint-template/uint.rs create mode 100644 src/libstd/num/uint.rs rename src/libstd/num/{uint-template.rs => uint_macros.rs} (50%) diff --git a/src/libstd/core.rc b/src/libstd/core.rc index 0b9e09cfa8db4..3d5f0fb849356 100644 --- a/src/libstd/core.rc +++ b/src/libstd/core.rc @@ -88,34 +88,24 @@ pub mod prelude; /* Primitive types */ -#[path = "num/int-template.rs"] #[merge = "num/int-template/int.rs"] -pub mod int; -#[path = "num/int-template.rs"] #[merge = "num/int-template/i8.rs"] -pub mod i8; -#[path = "num/int-template.rs"] #[merge = "num/int-template/i16.rs"] -pub mod i16; -#[path = "num/int-template.rs"] #[merge = "num/int-template/i32.rs"] -pub mod i32; -#[path = "num/int-template.rs"] #[merge = "num/int-template/i64.rs"] -pub mod i64; -#[path = "num/uint-template.rs"] #[merge = "num/uint-template/uint.rs"] -pub mod uint; - -#[path = "num/uint-template.rs"] #[merge = "num/uint-template/u8.rs"] -pub mod u8; -#[path = "num/uint-template.rs"] #[merge = "num/uint-template/u16.rs"] -pub mod u16; -#[path = "num/uint-template.rs"] #[merge = "num/uint-template/u32.rs"] -pub mod u32; -#[path = "num/uint-template.rs"] #[merge = "num/uint-template/u64.rs"] -pub mod u64; - -#[path = "num/float.rs"] -pub mod float; -#[path = "num/f32.rs"] -pub mod f32; -#[path = "num/f64.rs"] -pub mod f64; +#[path = "num/int_macros.rs"] mod int_macros; +#[path = "num/uint_macros.rs"] mod uint_macros; + +#[path = "num/int.rs"] pub mod int; +#[path = "num/i8.rs"] pub mod i8; +#[path = "num/i16.rs"] pub mod i16; +#[path = "num/i32.rs"] pub mod i32; +#[path = "num/i64.rs"] pub mod i64; + +#[path = "num/uint.rs"] pub mod uint; +#[path = "num/u8.rs"] pub mod u8; +#[path = "num/u16.rs"] pub mod u16; +#[path = "num/u32.rs"] pub mod u32; +#[path = "num/u64.rs"] pub mod u64; + +#[path = "num/float.rs"] pub mod float; +#[path = "num/f32.rs"] pub mod f32; +#[path = "num/f64.rs"] pub mod f64; pub mod nil; pub mod bool; diff --git a/src/libstd/num/i16.rs b/src/libstd/num/i16.rs new file mode 100644 index 0000000000000..9977247b249b5 --- /dev/null +++ b/src/libstd/num/i16.rs @@ -0,0 +1,32 @@ +// Copyright 2012 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. + +//! Operations and constants for `i16` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i16, 16) + +impl BitCount for i16 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i16 { unsafe { intrinsics::ctpop16(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } } +} diff --git a/src/libstd/num/i32.rs b/src/libstd/num/i32.rs new file mode 100644 index 0000000000000..0115f306e4e0e --- /dev/null +++ b/src/libstd/num/i32.rs @@ -0,0 +1,32 @@ +// Copyright 2012 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. + +//! Operations and constants for `i32` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i32, 32) + +impl BitCount for i32 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i32 { unsafe { intrinsics::ctpop32(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i32 { unsafe { intrinsics::ctlz32(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i32 { unsafe { intrinsics::cttz32(*self) } } +} diff --git a/src/libstd/num/i64.rs b/src/libstd/num/i64.rs new file mode 100644 index 0000000000000..4e280f01f2720 --- /dev/null +++ b/src/libstd/num/i64.rs @@ -0,0 +1,32 @@ +// Copyright 2012 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. + +//! Operations and constants for `i64` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i64, 64) + +impl BitCount for i64 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i64 { unsafe { intrinsics::ctpop64(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i64 { unsafe { intrinsics::ctlz64(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i64 { unsafe { intrinsics::cttz64(*self) } } +} diff --git a/src/libstd/num/i8.rs b/src/libstd/num/i8.rs new file mode 100644 index 0000000000000..939965b969185 --- /dev/null +++ b/src/libstd/num/i8.rs @@ -0,0 +1,32 @@ +// Copyright 2012 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. + +//! Operations and constants for `i8` + +use num::BitCount; +use unstable::intrinsics; + +pub use self::generated::*; + +int_module!(i8, 8) + +impl BitCount for i8 { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> i8 { unsafe { intrinsics::ctpop8(*self) } } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> i8 { unsafe { intrinsics::ctlz8(*self) } } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> i8 { unsafe { intrinsics::cttz8(*self) } } +} diff --git a/src/libstd/num/int-template/i16.rs b/src/libstd/num/int-template/i16.rs deleted file mode 100644 index 282633785553b..0000000000000 --- a/src/libstd/num/int-template/i16.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `i16` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i16; - pub static bits: uint = ::u16::bits; - - impl Primitive for i16 { - #[inline(always)] - fn bits() -> uint { 16 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i16 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i16 { unsafe { intrinsics::ctpop16(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i16 { unsafe { intrinsics::ctlz16(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i16 { unsafe { intrinsics::cttz16(*self) } } - } -} diff --git a/src/libstd/num/int-template/i32.rs b/src/libstd/num/int-template/i32.rs deleted file mode 100644 index 959cf8f7d77ca..0000000000000 --- a/src/libstd/num/int-template/i32.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `i32` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i32; - pub static bits: uint = ::u32::bits; - - impl Primitive for i32 { - #[inline(always)] - fn bits() -> uint { 32 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i32 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i32 { unsafe { intrinsics::ctpop32(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i32 { unsafe { intrinsics::ctlz32(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i32 { unsafe { intrinsics::cttz32(*self) } } - } -} diff --git a/src/libstd/num/int-template/i64.rs b/src/libstd/num/int-template/i64.rs deleted file mode 100644 index 3b51c70be12e5..0000000000000 --- a/src/libstd/num/int-template/i64.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `i64` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i64; - pub static bits: uint = ::u64::bits; - - impl Primitive for i64 { - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i64 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i64 { unsafe { intrinsics::ctpop64(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i64 { unsafe { intrinsics::ctlz64(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i64 { unsafe { intrinsics::cttz64(*self) } } - } -} diff --git a/src/libstd/num/int-template/i8.rs b/src/libstd/num/int-template/i8.rs deleted file mode 100644 index 896fb4dbf50f8..0000000000000 --- a/src/libstd/num/int-template/i8.rs +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `i8` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = i8; - pub static bits: uint = ::u8::bits; - - impl Primitive for i8 { - #[inline(always)] - fn bits() -> uint { 8 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for i8 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> i8 { unsafe { intrinsics::ctpop8(*self) } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> i8 { unsafe { intrinsics::ctlz8(*self) } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> i8 { unsafe { intrinsics::cttz8(*self) } } - } -} diff --git a/src/libstd/num/int-template/int.rs b/src/libstd/num/int-template/int.rs deleted file mode 100644 index 64f6f2d2a9a9b..0000000000000 --- a/src/libstd/num/int-template/int.rs +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `int` - -pub use self::inst::pow; - -mod inst { - use num::{Primitive, BitCount}; - - pub type T = int; - pub static bits: uint = ::uint::bits; - - impl Primitive for int { - #[cfg(target_word_size = "32")] - #[inline(always)] - fn bits() -> uint { 32 } - - #[cfg(target_word_size = "64")] - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - #[cfg(target_word_size = "32")] - #[inline(always)] - impl BitCount for int { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> int { (*self as i32).population_count() as int } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } - } - - #[cfg(target_word_size = "64")] - #[inline(always)] - impl BitCount for int { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> int { (*self as i64).population_count() as int } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int } - } - - /// Returns `base` raised to the power of `exponent` - pub fn pow(base: int, exponent: uint) -> int { - if exponent == 0u { - //Not mathemtically true if ~[base == 0] - return 1; - } - if base == 0 { return 0; } - let mut my_pow = exponent; - let mut acc = 1; - let mut multiplier = base; - while(my_pow > 0u) { - if my_pow % 2u == 1u { - acc *= multiplier; - } - my_pow /= 2u; - multiplier *= multiplier; - } - return acc; - } - - #[test] - fn test_pow() { - assert_eq!(pow(0, 0u), 1); - assert_eq!(pow(0, 1u), 0); - assert_eq!(pow(0, 2u), 0); - assert_eq!(pow(-1, 0u), 1); - assert_eq!(pow(1, 0u), 1); - assert_eq!(pow(-3, 2u), 9); - assert_eq!(pow(-3, 3u), -27); - assert_eq!(pow(4, 9u), 262144); - } - - #[test] - fn test_overflows() { - assert!((::int::max_value > 0)); - assert!((::int::min_value <= 0)); - assert_eq!(::int::min_value + ::int::max_value + 1, 0); - } -} diff --git a/src/libstd/num/int.rs b/src/libstd/num/int.rs new file mode 100644 index 0000000000000..96ef7e9e3412c --- /dev/null +++ b/src/libstd/num/int.rs @@ -0,0 +1,89 @@ +// Copyright 2012 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. + +//! Operations and constants for `int` + +use num::BitCount; + +pub use self::generated::*; + +#[cfg(target_word_size = "32")] pub static bits: uint = 32; +#[cfg(target_word_size = "64")] pub static bits: uint = 64; + +int_module!(int, super::bits) + +#[cfg(target_word_size = "32")] +impl BitCount for int { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> int { (*self as i32).population_count() as int } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> int { (*self as i32).leading_zeros() as int } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> int { (*self as i32).trailing_zeros() as int } +} + +#[cfg(target_word_size = "64")] +impl BitCount for int { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> int { (*self as i64).population_count() as int } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> int { (*self as i64).leading_zeros() as int } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> int { (*self as i64).trailing_zeros() as int } +} + +/// Returns `base` raised to the power of `exponent` +pub fn pow(base: int, exponent: uint) -> int { + if exponent == 0u { + //Not mathemtically true if ~[base == 0] + return 1; + } + if base == 0 { return 0; } + let mut my_pow = exponent; + let mut acc = 1; + let mut multiplier = base; + while(my_pow > 0u) { + if my_pow % 2u == 1u { + acc *= multiplier; + } + my_pow /= 2u; + multiplier *= multiplier; + } + return acc; +} + +#[test] +fn test_pow() { + assert!((pow(0, 0u) == 1)); + assert!((pow(0, 1u) == 0)); + assert!((pow(0, 2u) == 0)); + assert!((pow(-1, 0u) == 1)); + assert!((pow(1, 0u) == 1)); + assert!((pow(-3, 2u) == 9)); + assert!((pow(-3, 3u) == -27)); + assert!((pow(4, 9u) == 262144)); +} + +#[test] +fn test_overflows() { + assert!((::int::max_value > 0)); + assert!((::int::min_value <= 0)); + assert!((::int::min_value + ::int::max_value + 1 == 0)); +} diff --git a/src/libstd/num/int-template.rs b/src/libstd/num/int_macros.rs similarity index 56% rename from src/libstd/num/int-template.rs rename to src/libstd/num/int_macros.rs index 068f553ea6b57..6fde30fdb50c5 100644 --- a/src/libstd/num/int-template.rs +++ b/src/libstd/num/int_macros.rs @@ -8,7 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use T = self::inst::T; +// FIXME(#4375): this shouldn't have to be a nested module named 'generated' + +#[macro_escape]; + +macro_rules! int_module (($T:ty, $bits:expr) => (mod generated { use num::{ToStrRadix, FromStrRadix}; use num::{Zero, One, strconv}; @@ -16,20 +20,20 @@ use prelude::*; pub use cmp::{min, max}; -pub static bits : uint = inst::bits; -pub static bytes : uint = (inst::bits / 8); +pub static bits : uint = $bits; +pub static bytes : uint = ($bits / 8); -pub static min_value: T = (-1 as T) << (bits - 1); -pub static max_value: T = min_value - 1 as T; +pub static min_value: $T = (-1 as $T) << (bits - 1); +pub static max_value: $T = min_value - 1 as $T; #[inline(always)] -pub fn add(x: T, y: T) -> T { x + y } +pub fn add(x: $T, y: $T) -> $T { x + y } #[inline(always)] -pub fn sub(x: T, y: T) -> T { x - y } +pub fn sub(x: $T, y: $T) -> $T { x - y } #[inline(always)] -pub fn mul(x: T, y: T) -> T { x * y } +pub fn mul(x: $T, y: $T) -> $T { x * y } #[inline(always)] -pub fn div(x: T, y: T) -> T { x / y } +pub fn div(x: $T, y: $T) -> $T { x / y } /// /// Returns the remainder of y / x. @@ -52,20 +56,20 @@ pub fn div(x: T, y: T) -> T { x / y } /// /// #[inline(always)] -pub fn rem(x: T, y: T) -> T { x % y } +pub fn rem(x: $T, y: $T) -> $T { x % y } #[inline(always)] -pub fn lt(x: T, y: T) -> bool { x < y } +pub fn lt(x: $T, y: $T) -> bool { x < y } #[inline(always)] -pub fn le(x: T, y: T) -> bool { x <= y } +pub fn le(x: $T, y: $T) -> bool { x <= y } #[inline(always)] -pub fn eq(x: T, y: T) -> bool { x == y } +pub fn eq(x: $T, y: $T) -> bool { x == y } #[inline(always)] -pub fn ne(x: T, y: T) -> bool { x != y } +pub fn ne(x: $T, y: $T) -> bool { x != y } #[inline(always)] -pub fn ge(x: T, y: T) -> bool { x >= y } +pub fn ge(x: $T, y: $T) -> bool { x >= y } #[inline(always)] -pub fn gt(x: T, y: T) -> bool { x > y } +pub fn gt(x: $T, y: $T) -> bool { x > y } /// /// Iterate over the range [`lo`..`hi`) @@ -85,11 +89,10 @@ pub fn gt(x: T, y: T) -> bool { x > y } /// ~~~ /// #[inline(always)] -/// Iterate over the range [`start`,`start`+`step`..`stop`) -pub fn _range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) -> bool { +pub fn range_step(start: $T, stop: $T, step: $T, it: &fn($T) -> bool) -> bool { let mut i = start; if step == 0 { - fail!("range_step called with step == 0"); + fail!(~"range_step called with step == 0"); } else if step > 0 { // ascending while i < stop { if !it(i) { return false; } @@ -108,109 +111,101 @@ pub fn _range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) -> bool { return true; } -pub fn range_step(start: T, stop: T, step: T, it: &fn(T) -> bool) -> bool { - _range_step(start, stop, step, it) -} - #[inline(always)] /// Iterate over the range [`lo`..`hi`) -pub fn range(lo: T, hi: T, it: &fn(T) -> bool) -> bool { - range_step(lo, hi, 1 as T, it) +pub fn range(lo: $T, hi: $T, it: &fn($T) -> bool) -> bool { + range_step(lo, hi, 1 as $T, it) } #[inline(always)] /// Iterate over the range [`hi`..`lo`) -pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) -> bool { - range_step(hi, lo, -1 as T, it) +pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool { + range_step(hi, lo, -1 as $T, it) } /// Computes the bitwise complement #[inline(always)] -pub fn compl(i: T) -> T { - -1 as T ^ i +pub fn compl(i: $T) -> $T { + -1 as $T ^ i } /// Computes the absolute value #[inline(always)] -pub fn abs(i: T) -> T { i.abs() } +pub fn abs(i: $T) -> $T { i.abs() } -impl Num for T {} +impl Num for $T {} #[cfg(not(test))] -impl Ord for T { +impl Ord for $T { #[inline(always)] - fn lt(&self, other: &T) -> bool { return (*self) < (*other); } + fn lt(&self, other: &$T) -> bool { return (*self) < (*other); } #[inline(always)] - fn le(&self, other: &T) -> bool { return (*self) <= (*other); } + fn le(&self, other: &$T) -> bool { return (*self) <= (*other); } #[inline(always)] - fn ge(&self, other: &T) -> bool { return (*self) >= (*other); } + fn ge(&self, other: &$T) -> bool { return (*self) >= (*other); } #[inline(always)] - fn gt(&self, other: &T) -> bool { return (*self) > (*other); } + fn gt(&self, other: &$T) -> bool { return (*self) > (*other); } } #[cfg(not(test))] -impl Eq for T { +impl Eq for $T { #[inline(always)] - fn eq(&self, other: &T) -> bool { return (*self) == (*other); } + fn eq(&self, other: &$T) -> bool { return (*self) == (*other); } #[inline(always)] - fn ne(&self, other: &T) -> bool { return (*self) != (*other); } + fn ne(&self, other: &$T) -> bool { return (*self) != (*other); } } -impl Orderable for T { +impl Orderable for $T { #[inline(always)] - fn min(&self, other: &T) -> T { + fn min(&self, other: &$T) -> $T { if *self < *other { *self } else { *other } } #[inline(always)] - fn max(&self, other: &T) -> T { + fn max(&self, other: &$T) -> $T { if *self > *other { *self } else { *other } } - /// Returns the number constrained within the range `mn <= self <= mx`. #[inline(always)] - fn clamp(&self, mn: &T, mx: &T) -> T { - cond!( - (*self > *mx) { *mx } - (*self < *mn) { *mn } - _ { *self } - ) + fn clamp(&self, mn: &$T, mx: &$T) -> $T { + if *self > *mx { *mx } else + if *self < *mn { *mn } else { *self } } } -impl Zero for T { +impl Zero for $T { #[inline(always)] - fn zero() -> T { 0 } + fn zero() -> $T { 0 } #[inline(always)] fn is_zero(&self) -> bool { *self == 0 } } -impl One for T { +impl One for $T { #[inline(always)] - fn one() -> T { 1 } + fn one() -> $T { 1 } } #[cfg(not(test))] -impl Add for T { +impl Add<$T,$T> for $T { #[inline(always)] - fn add(&self, other: &T) -> T { *self + *other } + fn add(&self, other: &$T) -> $T { *self + *other } } #[cfg(not(test))] -impl Sub for T { +impl Sub<$T,$T> for $T { #[inline(always)] - fn sub(&self, other: &T) -> T { *self - *other } + fn sub(&self, other: &$T) -> $T { *self - *other } } #[cfg(not(test))] -impl Mul for T { +impl Mul<$T,$T> for $T { #[inline(always)] - fn mul(&self, other: &T) -> T { *self * *other } + fn mul(&self, other: &$T) -> $T { *self * *other } } #[cfg(not(test))] -impl Div for T { +impl Div<$T,$T> for $T { /// /// Integer division, truncated towards 0. As this behaviour reflects the underlying /// machine implementation it is more efficient than `Integer::div_floor`. @@ -230,11 +225,11 @@ impl Div for T { /// ~~~ /// #[inline(always)] - fn div(&self, other: &T) -> T { *self / *other } + fn div(&self, other: &$T) -> $T { *self / *other } } #[cfg(not(test))] -impl Rem for T { +impl Rem<$T,$T> for $T { /// /// Returns the integer remainder after division, satisfying: /// @@ -257,19 +252,19 @@ impl Rem for T { /// ~~~ /// #[inline(always)] - fn rem(&self, other: &T) -> T { *self % *other } + fn rem(&self, other: &$T) -> $T { *self % *other } } #[cfg(not(test))] -impl Neg for T { +impl Neg<$T> for $T { #[inline(always)] - fn neg(&self) -> T { -*self } + fn neg(&self) -> $T { -*self } } -impl Signed for T { +impl Signed for $T { /// Computes the absolute value #[inline(always)] - fn abs(&self) -> T { + fn abs(&self) -> $T { if self.is_negative() { -*self } else { *self } } @@ -278,7 +273,7 @@ impl Signed for T { /// equal to `other`, otherwise the difference between`self` and `other` is returned. /// #[inline(always)] - fn abs_sub(&self, other: &T) -> T { + fn abs_sub(&self, other: &$T) -> $T { if *self <= *other { 0 } else { *self - *other } } @@ -290,7 +285,7 @@ impl Signed for T { /// - `-1` if the number is negative /// #[inline(always)] - fn signum(&self) -> T { + fn signum(&self) -> $T { match *self { n if n > 0 => 1, 0 => 0, @@ -307,7 +302,7 @@ impl Signed for T { fn is_negative(&self) -> bool { *self < 0 } } -impl Integer for T { +impl Integer for $T { /// /// Floored integer division /// @@ -326,7 +321,7 @@ impl Integer for T { /// ~~~ /// #[inline(always)] - fn div_floor(&self, other: &T) -> T { + fn div_floor(&self, other: &$T) -> $T { // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) match self.div_rem(other) { @@ -358,7 +353,7 @@ impl Integer for T { /// ~~~ /// #[inline(always)] - fn mod_floor(&self, other: &T) -> T { + fn mod_floor(&self, other: &$T) -> $T { // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) match *self % *other { @@ -370,7 +365,7 @@ impl Integer for T { /// Calculates `div_floor` and `mod_floor` simultaneously #[inline(always)] - fn div_mod_floor(&self, other: &T) -> (T,T) { + fn div_mod_floor(&self, other: &$T) -> ($T,$T) { // Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_, // December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf) match self.div_rem(other) { @@ -382,7 +377,7 @@ impl Integer for T { /// Calculates `div` (`\`) and `rem` (`%`) simultaneously #[inline(always)] - fn div_rem(&self, other: &T) -> (T,T) { + fn div_rem(&self, other: &$T) -> ($T,$T) { (*self / *other, *self % *other) } @@ -392,7 +387,7 @@ impl Integer for T { /// The result is always positive /// #[inline(always)] - fn gcd(&self, other: &T) -> T { + fn gcd(&self, other: &$T) -> $T { // Use Euclid's algorithm let mut m = *self, n = *other; while m != 0 { @@ -407,13 +402,13 @@ impl Integer for T { /// Calculates the Lowest Common Multiple (LCM) of the number and `other` /// #[inline(always)] - fn lcm(&self, other: &T) -> T { + fn lcm(&self, other: &$T) -> $T { ((*self * *other) / self.gcd(other)).abs() // should not have to recaluculate abs } /// Returns `true` if the number can be divided by `other` without leaving a remainder #[inline(always)] - fn is_multiple_of(&self, other: &T) -> bool { *self % *other == 0 } + fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } /// Returns `true` if the number is divisible by `2` #[inline(always)] @@ -424,87 +419,95 @@ impl Integer for T { fn is_odd(&self) -> bool { !self.is_even() } } -impl Bitwise for T {} +impl Bitwise for $T {} #[cfg(not(test))] -impl BitOr for T { +impl BitOr<$T,$T> for $T { #[inline(always)] - fn bitor(&self, other: &T) -> T { *self | *other } + fn bitor(&self, other: &$T) -> $T { *self | *other } } #[cfg(not(test))] -impl BitAnd for T { +impl BitAnd<$T,$T> for $T { #[inline(always)] - fn bitand(&self, other: &T) -> T { *self & *other } + fn bitand(&self, other: &$T) -> $T { *self & *other } } #[cfg(not(test))] -impl BitXor for T { +impl BitXor<$T,$T> for $T { #[inline(always)] - fn bitxor(&self, other: &T) -> T { *self ^ *other } + fn bitxor(&self, other: &$T) -> $T { *self ^ *other } } #[cfg(not(test))] -impl Shl for T { +impl Shl<$T,$T> for $T { #[inline(always)] - fn shl(&self, other: &T) -> T { *self << *other } + fn shl(&self, other: &$T) -> $T { *self << *other } } #[cfg(not(test))] -impl Shr for T { +impl Shr<$T,$T> for $T { #[inline(always)] - fn shr(&self, other: &T) -> T { *self >> *other } + fn shr(&self, other: &$T) -> $T { *self >> *other } } #[cfg(not(test))] -impl Not for T { +impl Not<$T> for $T { #[inline(always)] - fn not(&self) -> T { !*self } + fn not(&self) -> $T { !*self } } -impl Bounded for T { +impl Bounded for $T { #[inline(always)] - fn min_value() -> T { min_value } + fn min_value() -> $T { min_value } #[inline(always)] - fn max_value() -> T { max_value } + fn max_value() -> $T { max_value } } -impl Int for T {} +impl Int for $T {} + +impl Primitive for $T { + #[inline(always)] + fn bits() -> uint { bits } + + #[inline(always)] + fn bytes() -> uint { bits / 8 } +} // String conversion functions and impl str -> num /// Parse a string as a number in base 10. #[inline(always)] -pub fn from_str(s: &str) -> Option { +pub fn from_str(s: &str) -> Option<$T> { strconv::from_str_common(s, 10u, true, false, false, strconv::ExpNone, false, false) } /// Parse a string as a number in the given base. #[inline(always)] -pub fn from_str_radix(s: &str, radix: uint) -> Option { +pub fn from_str_radix(s: &str, radix: uint) -> Option<$T> { strconv::from_str_common(s, radix, true, false, false, strconv::ExpNone, false, false) } /// Parse a byte slice as a number in the given base. #[inline(always)] -pub fn parse_bytes(buf: &[u8], radix: uint) -> Option { +pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> { strconv::from_str_bytes_common(buf, radix, true, false, false, strconv::ExpNone, false, false) } -impl FromStr for T { +impl FromStr for $T { #[inline(always)] - fn from_str(s: &str) -> Option { + fn from_str(s: &str) -> Option<$T> { from_str(s) } } -impl FromStrRadix for T { +impl FromStrRadix for $T { #[inline(always)] - fn from_str_radix(s: &str, radix: uint) -> Option { + fn from_str_radix(s: &str, radix: uint) -> Option<$T> { from_str_radix(s, radix) } } @@ -513,7 +516,7 @@ impl FromStrRadix for T { /// Convert to a string as a byte slice in a given base. #[inline(always)] -pub fn to_str_bytes(n: T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { +pub fn to_str_bytes(n: $T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, strconv::SignNeg, strconv::DigAll); f(buf) @@ -521,7 +524,7 @@ pub fn to_str_bytes(n: T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { /// Convert to a string in base 10. #[inline(always)] -pub fn to_str(num: T) -> ~str { +pub fn to_str(num: $T) -> ~str { let (buf, _) = strconv::to_str_common(&num, 10u, false, strconv::SignNeg, strconv::DigAll); buf @@ -529,20 +532,20 @@ pub fn to_str(num: T) -> ~str { /// Convert to a string in a given base. #[inline(always)] -pub fn to_str_radix(num: T, radix: uint) -> ~str { +pub fn to_str_radix(num: $T, radix: uint) -> ~str { let (buf, _) = strconv::to_str_common(&num, radix, false, strconv::SignNeg, strconv::DigAll); buf } -impl ToStr for T { +impl ToStr for $T { #[inline(always)] fn to_str(&self) -> ~str { to_str(*self) } } -impl ToStrRadix for T { +impl ToStrRadix for $T { #[inline(always)] fn to_str_radix(&self, radix: uint) -> ~str { to_str_radix(*self, radix) @@ -552,62 +555,61 @@ impl ToStrRadix for T { #[cfg(test)] mod tests { use super::*; - use super::inst::T; use prelude::*; #[test] fn test_num() { - num::test_num(10 as T, 2 as T); + num::test_num(10 as $T, 2 as $T); } #[test] fn test_orderable() { - assert_eq!((1 as T).min(&(2 as T)), 1 as T); - assert_eq!((2 as T).min(&(1 as T)), 1 as T); - assert_eq!((1 as T).max(&(2 as T)), 2 as T); - assert_eq!((2 as T).max(&(1 as T)), 2 as T); - assert_eq!((1 as T).clamp(&(2 as T), &(4 as T)), 2 as T); - assert_eq!((8 as T).clamp(&(2 as T), &(4 as T)), 4 as T); - assert_eq!((3 as T).clamp(&(2 as T), &(4 as T)), 3 as T); + assert_eq!((1 as $T).min(&(2 as $T)), 1 as $T); + assert_eq!((2 as $T).min(&(1 as $T)), 1 as $T); + assert_eq!((1 as $T).max(&(2 as $T)), 2 as $T); + assert_eq!((2 as $T).max(&(1 as $T)), 2 as $T); + assert_eq!((1 as $T).clamp(&(2 as $T), &(4 as $T)), 2 as $T); + assert_eq!((8 as $T).clamp(&(2 as $T), &(4 as $T)), 4 as $T); + assert_eq!((3 as $T).clamp(&(2 as $T), &(4 as $T)), 3 as $T); } #[test] pub fn test_abs() { - assert_eq!((1 as T).abs(), 1 as T); - assert_eq!((0 as T).abs(), 0 as T); - assert_eq!((-1 as T).abs(), 1 as T); + assert_eq!((1 as $T).abs(), 1 as $T); + assert_eq!((0 as $T).abs(), 0 as $T); + assert_eq!((-1 as $T).abs(), 1 as $T); } #[test] fn test_abs_sub() { - assert_eq!((-1 as T).abs_sub(&(1 as T)), 0 as T); - assert_eq!((1 as T).abs_sub(&(1 as T)), 0 as T); - assert_eq!((1 as T).abs_sub(&(0 as T)), 1 as T); - assert_eq!((1 as T).abs_sub(&(-1 as T)), 2 as T); + assert_eq!((-1 as $T).abs_sub(&(1 as $T)), 0 as $T); + assert_eq!((1 as $T).abs_sub(&(1 as $T)), 0 as $T); + assert_eq!((1 as $T).abs_sub(&(0 as $T)), 1 as $T); + assert_eq!((1 as $T).abs_sub(&(-1 as $T)), 2 as $T); } #[test] fn test_signum() { - assert_eq!((1 as T).signum(), 1 as T); - assert_eq!((0 as T).signum(), 0 as T); - assert_eq!((-0 as T).signum(), 0 as T); - assert_eq!((-1 as T).signum(), -1 as T); + assert_eq!((1 as $T).signum(), 1 as $T); + assert_eq!((0 as $T).signum(), 0 as $T); + assert_eq!((-0 as $T).signum(), 0 as $T); + assert_eq!((-1 as $T).signum(), -1 as $T); } #[test] fn test_is_positive() { - assert!((1 as T).is_positive()); - assert!(!(0 as T).is_positive()); - assert!(!(-0 as T).is_positive()); - assert!(!(-1 as T).is_positive()); + assert!((1 as $T).is_positive()); + assert!(!(0 as $T).is_positive()); + assert!(!(-0 as $T).is_positive()); + assert!(!(-1 as $T).is_positive()); } #[test] fn test_is_negative() { - assert!(!(1 as T).is_negative()); - assert!(!(0 as T).is_negative()); - assert!(!(-0 as T).is_negative()); - assert!((-1 as T).is_negative()); + assert!(!(1 as $T).is_negative()); + assert!(!(0 as $T).is_negative()); + assert!(!(-0 as $T).is_negative()); + assert!((-1 as $T).is_negative()); } /// @@ -618,13 +620,13 @@ mod tests { /// - `qr`: quotient and remainder /// #[cfg(test)] - fn test_division_rule((n,d): (T,T), (q,r): (T,T)) { + fn test_division_rule((n,d): ($T,$T), (q,r): ($T,$T)) { assert_eq!(d * q + r, n); } #[test] fn test_div_rem() { - fn test_nd_dr(nd: (T,T), qr: (T,T)) { + fn test_nd_dr(nd: ($T,$T), qr: ($T,$T)) { let (n,d) = nd; let separate_div_rem = (n / d, n % d); let combined_div_rem = n.div_rem(&d); @@ -649,7 +651,7 @@ mod tests { #[test] fn test_div_mod_floor() { - fn test_nd_dm(nd: (T,T), dm: (T,T)) { + fn test_nd_dm(nd: ($T,$T), dm: ($T,$T)) { let (n,d) = nd; let separate_div_mod_floor = (n.div_floor(&d), n.mod_floor(&d)); let combined_div_mod_floor = n.div_mod_floor(&d); @@ -674,135 +676,135 @@ mod tests { #[test] fn test_gcd() { - assert_eq!((10 as T).gcd(&2), 2 as T); - assert_eq!((10 as T).gcd(&3), 1 as T); - assert_eq!((0 as T).gcd(&3), 3 as T); - assert_eq!((3 as T).gcd(&3), 3 as T); - assert_eq!((56 as T).gcd(&42), 14 as T); - assert_eq!((3 as T).gcd(&-3), 3 as T); - assert_eq!((-6 as T).gcd(&3), 3 as T); - assert_eq!((-4 as T).gcd(&-2), 2 as T); + assert_eq!((10 as $T).gcd(&2), 2 as $T); + assert_eq!((10 as $T).gcd(&3), 1 as $T); + assert_eq!((0 as $T).gcd(&3), 3 as $T); + assert_eq!((3 as $T).gcd(&3), 3 as $T); + assert_eq!((56 as $T).gcd(&42), 14 as $T); + assert_eq!((3 as $T).gcd(&-3), 3 as $T); + assert_eq!((-6 as $T).gcd(&3), 3 as $T); + assert_eq!((-4 as $T).gcd(&-2), 2 as $T); } #[test] fn test_lcm() { - assert_eq!((1 as T).lcm(&0), 0 as T); - assert_eq!((0 as T).lcm(&1), 0 as T); - assert_eq!((1 as T).lcm(&1), 1 as T); - assert_eq!((-1 as T).lcm(&1), 1 as T); - assert_eq!((1 as T).lcm(&-1), 1 as T); - assert_eq!((-1 as T).lcm(&-1), 1 as T); - assert_eq!((8 as T).lcm(&9), 72 as T); - assert_eq!((11 as T).lcm(&5), 55 as T); + assert_eq!((1 as $T).lcm(&0), 0 as $T); + assert_eq!((0 as $T).lcm(&1), 0 as $T); + assert_eq!((1 as $T).lcm(&1), 1 as $T); + assert_eq!((-1 as $T).lcm(&1), 1 as $T); + assert_eq!((1 as $T).lcm(&-1), 1 as $T); + assert_eq!((-1 as $T).lcm(&-1), 1 as $T); + assert_eq!((8 as $T).lcm(&9), 72 as $T); + assert_eq!((11 as $T).lcm(&5), 55 as $T); } #[test] fn test_bitwise() { - assert_eq!(0b1110 as T, (0b1100 as T).bitor(&(0b1010 as T))); - assert_eq!(0b1000 as T, (0b1100 as T).bitand(&(0b1010 as T))); - assert_eq!(0b0110 as T, (0b1100 as T).bitxor(&(0b1010 as T))); - assert_eq!(0b1110 as T, (0b0111 as T).shl(&(1 as T))); - assert_eq!(0b0111 as T, (0b1110 as T).shr(&(1 as T))); - assert_eq!(-(0b11 as T) - (1 as T), (0b11 as T).not()); + assert_eq!(0b1110 as $T, (0b1100 as $T).bitor(&(0b1010 as $T))); + assert_eq!(0b1000 as $T, (0b1100 as $T).bitand(&(0b1010 as $T))); + assert_eq!(0b0110 as $T, (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert_eq!(0b1110 as $T, (0b0111 as $T).shl(&(1 as $T))); + assert_eq!(0b0111 as $T, (0b1110 as $T).shr(&(1 as $T))); + assert_eq!(-(0b11 as $T) - (1 as $T), (0b11 as $T).not()); } #[test] fn test_multiple_of() { - assert!((6 as T).is_multiple_of(&(6 as T))); - assert!((6 as T).is_multiple_of(&(3 as T))); - assert!((6 as T).is_multiple_of(&(1 as T))); - assert!((-8 as T).is_multiple_of(&(4 as T))); - assert!((8 as T).is_multiple_of(&(-1 as T))); - assert!((-8 as T).is_multiple_of(&(-2 as T))); + assert!((6 as $T).is_multiple_of(&(6 as $T))); + assert!((6 as $T).is_multiple_of(&(3 as $T))); + assert!((6 as $T).is_multiple_of(&(1 as $T))); + assert!((-8 as $T).is_multiple_of(&(4 as $T))); + assert!((8 as $T).is_multiple_of(&(-1 as $T))); + assert!((-8 as $T).is_multiple_of(&(-2 as $T))); } #[test] fn test_even() { - assert_eq!((-4 as T).is_even(), true); - assert_eq!((-3 as T).is_even(), false); - assert_eq!((-2 as T).is_even(), true); - assert_eq!((-1 as T).is_even(), false); - assert_eq!((0 as T).is_even(), true); - assert_eq!((1 as T).is_even(), false); - assert_eq!((2 as T).is_even(), true); - assert_eq!((3 as T).is_even(), false); - assert_eq!((4 as T).is_even(), true); + assert_eq!((-4 as $T).is_even(), true); + assert_eq!((-3 as $T).is_even(), false); + assert_eq!((-2 as $T).is_even(), true); + assert_eq!((-1 as $T).is_even(), false); + assert_eq!((0 as $T).is_even(), true); + assert_eq!((1 as $T).is_even(), false); + assert_eq!((2 as $T).is_even(), true); + assert_eq!((3 as $T).is_even(), false); + assert_eq!((4 as $T).is_even(), true); } #[test] fn test_odd() { - assert_eq!((-4 as T).is_odd(), false); - assert_eq!((-3 as T).is_odd(), true); - assert_eq!((-2 as T).is_odd(), false); - assert_eq!((-1 as T).is_odd(), true); - assert_eq!((0 as T).is_odd(), false); - assert_eq!((1 as T).is_odd(), true); - assert_eq!((2 as T).is_odd(), false); - assert_eq!((3 as T).is_odd(), true); - assert_eq!((4 as T).is_odd(), false); + assert_eq!((-4 as $T).is_odd(), false); + assert_eq!((-3 as $T).is_odd(), true); + assert_eq!((-2 as $T).is_odd(), false); + assert_eq!((-1 as $T).is_odd(), true); + assert_eq!((0 as $T).is_odd(), false); + assert_eq!((1 as $T).is_odd(), true); + assert_eq!((2 as $T).is_odd(), false); + assert_eq!((3 as $T).is_odd(), true); + assert_eq!((4 as $T).is_odd(), false); } #[test] fn test_bitcount() { - assert_eq!((0b010101 as T).population_count(), 3); + assert_eq!((0b010101 as $T).population_count(), 3); } #[test] fn test_primitive() { - assert_eq!(Primitive::bits::(), sys::size_of::() * 8); - assert_eq!(Primitive::bytes::(), sys::size_of::()); + assert_eq!(Primitive::bits::<$T>(), sys::size_of::<$T>() * 8); + assert_eq!(Primitive::bytes::<$T>(), sys::size_of::<$T>()); } #[test] fn test_from_str() { - assert_eq!(from_str("0"), Some(0 as T)); - assert_eq!(from_str("3"), Some(3 as T)); - assert_eq!(from_str("10"), Some(10 as T)); - assert_eq!(i32::from_str("123456789"), Some(123456789 as i32)); - assert_eq!(from_str("00100"), Some(100 as T)); + assert_eq!(from_str(~"0"), Some(0 as $T)); + assert_eq!(from_str(~"3"), Some(3 as $T)); + assert_eq!(from_str(~"10"), Some(10 as $T)); + assert_eq!(i32::from_str(~"123456789"), Some(123456789 as i32)); + assert_eq!(from_str(~"00100"), Some(100 as $T)); - assert_eq!(from_str("-1"), Some(-1 as T)); - assert_eq!(from_str("-3"), Some(-3 as T)); - assert_eq!(from_str("-10"), Some(-10 as T)); - assert_eq!(i32::from_str("-123456789"), Some(-123456789 as i32)); - assert_eq!(from_str("-00100"), Some(-100 as T)); + assert_eq!(from_str(~"-1"), Some(-1 as $T)); + assert_eq!(from_str(~"-3"), Some(-3 as $T)); + assert_eq!(from_str(~"-10"), Some(-10 as $T)); + assert_eq!(i32::from_str(~"-123456789"), Some(-123456789 as i32)); + assert_eq!(from_str(~"-00100"), Some(-100 as $T)); - assert!(from_str(" ").is_none()); - assert!(from_str("x").is_none()); + assert!(from_str(~" ").is_none()); + assert!(from_str(~"x").is_none()); } #[test] fn test_parse_bytes() { use str::to_bytes; - assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123 as T)); - assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9 as T)); - assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83 as T)); - assert_eq!(i32::parse_bytes(to_bytes("123"), 16u), Some(291 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("ffff"), 16u), Some(65535 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("FFFF"), 16u), Some(65535 as i32)); - assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35 as T)); - assert_eq!(parse_bytes(to_bytes("Z"), 36u), Some(35 as T)); - - assert_eq!(parse_bytes(to_bytes("-123"), 10u), Some(-123 as T)); - assert_eq!(parse_bytes(to_bytes("-1001"), 2u), Some(-9 as T)); - assert_eq!(parse_bytes(to_bytes("-123"), 8u), Some(-83 as T)); - assert_eq!(i32::parse_bytes(to_bytes("-123"), 16u), Some(-291 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("-ffff"), 16u), Some(-65535 as i32)); - assert_eq!(i32::parse_bytes(to_bytes("-FFFF"), 16u), Some(-65535 as i32)); - assert_eq!(parse_bytes(to_bytes("-z"), 36u), Some(-35 as T)); - assert_eq!(parse_bytes(to_bytes("-Z"), 36u), Some(-35 as T)); - - assert!(parse_bytes(to_bytes("Z"), 35u).is_none()); - assert!(parse_bytes(to_bytes("-9"), 2u).is_none()); + assert_eq!(parse_bytes(to_bytes(~"123"), 10u), Some(123 as $T)); + assert_eq!(parse_bytes(to_bytes(~"1001"), 2u), Some(9 as $T)); + assert_eq!(parse_bytes(to_bytes(~"123"), 8u), Some(83 as $T)); + assert_eq!(i32::parse_bytes(to_bytes(~"123"), 16u), Some(291 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"ffff"), 16u), Some(65535 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"FFFF"), 16u), Some(65535 as i32)); + assert_eq!(parse_bytes(to_bytes(~"z"), 36u), Some(35 as $T)); + assert_eq!(parse_bytes(to_bytes(~"Z"), 36u), Some(35 as $T)); + + assert_eq!(parse_bytes(to_bytes(~"-123"), 10u), Some(-123 as $T)); + assert_eq!(parse_bytes(to_bytes(~"-1001"), 2u), Some(-9 as $T)); + assert_eq!(parse_bytes(to_bytes(~"-123"), 8u), Some(-83 as $T)); + assert_eq!(i32::parse_bytes(to_bytes(~"-123"), 16u), Some(-291 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"-ffff"), 16u), Some(-65535 as i32)); + assert_eq!(i32::parse_bytes(to_bytes(~"-FFFF"), 16u), Some(-65535 as i32)); + assert_eq!(parse_bytes(to_bytes(~"-z"), 36u), Some(-35 as $T)); + assert_eq!(parse_bytes(to_bytes(~"-Z"), 36u), Some(-35 as $T)); + + assert!(parse_bytes(to_bytes(~"Z"), 35u).is_none()); + assert!(parse_bytes(to_bytes(~"-9"), 2u).is_none()); } #[test] fn test_to_str() { - assert_eq!(to_str_radix(0 as T, 10u), ~"0"); - assert_eq!(to_str_radix(1 as T, 10u), ~"1"); - assert_eq!(to_str_radix(-1 as T, 10u), ~"-1"); - assert_eq!(to_str_radix(127 as T, 16u), ~"7f"); - assert_eq!(to_str_radix(100 as T, 10u), ~"100"); + assert_eq!(to_str_radix(0 as $T, 10u), ~"0"); + assert_eq!(to_str_radix(1 as $T, 10u), ~"1"); + assert_eq!(to_str_radix(-1 as $T, 10u), ~"-1"); + assert_eq!(to_str_radix(127 as $T, 16u), ~"7f"); + assert_eq!(to_str_radix(100 as $T, 10u), ~"100"); } @@ -836,36 +838,36 @@ mod tests { #[test] fn test_int_from_str_overflow() { let mut i8_val: i8 = 127_i8; - assert_eq!(i8::from_str("127"), Some(i8_val)); - assert!(i8::from_str("128").is_none()); + assert_eq!(i8::from_str(~"127"), Some(i8_val)); + assert!(i8::from_str(~"128").is_none()); i8_val += 1 as i8; - assert_eq!(i8::from_str("-128"), Some(i8_val)); - assert!(i8::from_str("-129").is_none()); + assert_eq!(i8::from_str(~"-128"), Some(i8_val)); + assert!(i8::from_str(~"-129").is_none()); let mut i16_val: i16 = 32_767_i16; - assert_eq!(i16::from_str("32767"), Some(i16_val)); - assert!(i16::from_str("32768").is_none()); + assert_eq!(i16::from_str(~"32767"), Some(i16_val)); + assert!(i16::from_str(~"32768").is_none()); i16_val += 1 as i16; - assert_eq!(i16::from_str("-32768"), Some(i16_val)); - assert!(i16::from_str("-32769").is_none()); + assert_eq!(i16::from_str(~"-32768"), Some(i16_val)); + assert!(i16::from_str(~"-32769").is_none()); let mut i32_val: i32 = 2_147_483_647_i32; - assert_eq!(i32::from_str("2147483647"), Some(i32_val)); - assert!(i32::from_str("2147483648").is_none()); + assert_eq!(i32::from_str(~"2147483647"), Some(i32_val)); + assert!(i32::from_str(~"2147483648").is_none()); i32_val += 1 as i32; - assert_eq!(i32::from_str("-2147483648"), Some(i32_val)); - assert!(i32::from_str("-2147483649").is_none()); + assert_eq!(i32::from_str(~"-2147483648"), Some(i32_val)); + assert!(i32::from_str(~"-2147483649").is_none()); let mut i64_val: i64 = 9_223_372_036_854_775_807_i64; - assert_eq!(i64::from_str("9223372036854775807"), Some(i64_val)); - assert!(i64::from_str("9223372036854775808").is_none()); + assert_eq!(i64::from_str(~"9223372036854775807"), Some(i64_val)); + assert!(i64::from_str(~"9223372036854775808").is_none()); i64_val += 1 as i64; - assert_eq!(i64::from_str("-9223372036854775808"), Some(i64_val)); - assert!(i64::from_str("-9223372036854775809").is_none()); + assert_eq!(i64::from_str(~"-9223372036854775808"), Some(i64_val)); + assert!(i64::from_str(~"-9223372036854775809").is_none()); } #[test] @@ -907,16 +909,16 @@ mod tests { // None of the `fail`s should execute. for range(10,0) |_i| { - fail!("unreachable"); + fail!(~"unreachable"); } for range_rev(0,10) |_i| { - fail!("unreachable"); + fail!(~"unreachable"); } for range_step(10,0,1) |_i| { - fail!("unreachable"); + fail!(~"unreachable"); } for range_step(0,10,-1) |_i| { - fail!("unreachable"); + fail!(~"unreachable"); } } @@ -927,3 +929,5 @@ mod tests { for range_step(0,10,0) |_i| {} } } + +})) diff --git a/src/libstd/num/u16.rs b/src/libstd/num/u16.rs new file mode 100644 index 0000000000000..3a4c2420f9ed5 --- /dev/null +++ b/src/libstd/num/u16.rs @@ -0,0 +1,14 @@ +// Copyright 2012 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. + +//! Operations and constants for `u16` + +pub use self::generated::*; +uint_module!(u16, i16, 16) diff --git a/src/libstd/num/u32.rs b/src/libstd/num/u32.rs new file mode 100644 index 0000000000000..f87fa7fcd426b --- /dev/null +++ b/src/libstd/num/u32.rs @@ -0,0 +1,14 @@ +// Copyright 2012 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. + +//! Operations and constants for `u32` + +pub use self::generated::*; +uint_module!(u32, i32, 32) diff --git a/src/libstd/num/u64.rs b/src/libstd/num/u64.rs new file mode 100644 index 0000000000000..792db1555695a --- /dev/null +++ b/src/libstd/num/u64.rs @@ -0,0 +1,14 @@ +// Copyright 2012 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. + +//! Operations and constants for `u64` + +pub use self::generated::*; +uint_module!(u64, i64, 64) diff --git a/src/libstd/num/u8.rs b/src/libstd/num/u8.rs new file mode 100644 index 0000000000000..e21e80f840678 --- /dev/null +++ b/src/libstd/num/u8.rs @@ -0,0 +1,14 @@ +// Copyright 2012 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. + +//! Operations and constants for `u8` + +pub use self::generated::*; +uint_module!(u8, i8, 8) diff --git a/src/libstd/num/uint-template/u16.rs b/src/libstd/num/uint-template/u16.rs deleted file mode 100644 index cc262f6b4dee7..0000000000000 --- a/src/libstd/num/uint-template/u16.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `u16` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u16; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i16; - pub static bits: uint = 16; - - impl Primitive for u16 { - #[inline(always)] - fn bits() -> uint { 16 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u16 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u16 { unsafe { intrinsics::ctpop16(*self as i16) as u16 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u16 { unsafe { intrinsics::ctlz16(*self as i16) as u16 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u16 { unsafe { intrinsics::cttz16(*self as i16) as u16 } } - } -} diff --git a/src/libstd/num/uint-template/u32.rs b/src/libstd/num/uint-template/u32.rs deleted file mode 100644 index 7d7c8e3be302e..0000000000000 --- a/src/libstd/num/uint-template/u32.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `u32` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u32; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i32; - pub static bits: uint = 32; - - impl Primitive for u32 { - #[inline(always)] - fn bits() -> uint { 32 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u32 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u32 { unsafe { intrinsics::ctpop32(*self as i32) as u32 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlp` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u32 { unsafe { intrinsics::ctlz32(*self as i32) as u32 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttp` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u32 { unsafe { intrinsics::cttz32(*self as i32) as u32 } } - } -} diff --git a/src/libstd/num/uint-template/u64.rs b/src/libstd/num/uint-template/u64.rs deleted file mode 100644 index 756c29950c35b..0000000000000 --- a/src/libstd/num/uint-template/u64.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `u64` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u64; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i64; - pub static bits: uint = 64; - - impl Primitive for u64 { - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u64 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u64 { unsafe { intrinsics::ctpop64(*self as i64) as u64 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u64 { unsafe { intrinsics::ctlz64(*self as i64) as u64 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u64 { unsafe { intrinsics::cttz64(*self as i64) as u64 } } - } -} diff --git a/src/libstd/num/uint-template/u8.rs b/src/libstd/num/uint-template/u8.rs deleted file mode 100644 index 5ac860c0359c5..0000000000000 --- a/src/libstd/num/uint-template/u8.rs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `u8` - -mod inst { - use num::{Primitive, BitCount}; - use unstable::intrinsics; - - pub type T = u8; - #[allow(non_camel_case_types)] - pub type T_SIGNED = i8; - pub static bits: uint = 8; - - impl Primitive for u8 { - #[inline(always)] - fn bits() -> uint { 8 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - impl BitCount for u8 { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> u8 { unsafe { intrinsics::ctpop8(*self as i8) as u8 } } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> u8 { unsafe { intrinsics::ctlz8(*self as i8) as u8 } } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> u8 { unsafe { intrinsics::cttz8(*self as i8) as u8 } } - } -} diff --git a/src/libstd/num/uint-template/uint.rs b/src/libstd/num/uint-template/uint.rs deleted file mode 100644 index 763c305f22149..0000000000000 --- a/src/libstd/num/uint-template/uint.rs +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright 2012 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. - -//! Operations and constants for `uint` - -pub use self::inst::{ - div_ceil, div_round, div_floor, iterate, - next_power_of_two -}; - -pub mod inst { - use iter; - use num::{Primitive, BitCount}; - use sys; - - pub type T = uint; - #[allow(non_camel_case_types)] - pub type T_SIGNED = int; - - #[cfg(target_arch = "x86")] - #[cfg(target_arch = "arm")] - #[cfg(target_arch = "mips")] - pub static bits: uint = 32; - - #[cfg(target_arch = "x86_64")] - pub static bits: uint = 64; - - impl Primitive for uint { - #[cfg(target_word_size = "32")] - #[inline(always)] - fn bits() -> uint { 32 } - - #[cfg(target_word_size = "64")] - #[inline(always)] - fn bits() -> uint { 64 } - - #[inline(always)] - fn bytes() -> uint { Primitive::bits::() / 8 } - } - - #[cfg(target_word_size = "32")] - #[inline(always)] - impl BitCount for uint { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> uint { (*self as i32).population_count() as uint } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> uint { (*self as i32).leading_zeros() as uint } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> uint { (*self as i32).trailing_zeros() as uint } - } - - #[cfg(target_word_size = "64")] - #[inline(always)] - impl BitCount for uint { - /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. - #[inline(always)] - fn population_count(&self) -> uint { (*self as i64).population_count() as uint } - - /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. - #[inline(always)] - fn leading_zeros(&self) -> uint { (*self as i64).leading_zeros() as uint } - - /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. - #[inline(always)] - fn trailing_zeros(&self) -> uint { (*self as i64).trailing_zeros() as uint } - } - - /// - /// Divide two numbers, return the result, rounded up. - /// - /// # Arguments - /// - /// * x - an integer - /// * y - an integer distinct from 0u - /// - /// # Return value - /// - /// The smallest integer `q` such that `x/y <= q`. - /// - pub fn div_ceil(x: uint, y: uint) -> uint { - let div = x / y; - if x % y == 0u { div } - else { div + 1u } - } - - /// - /// Divide two numbers, return the result, rounded to the closest integer. - /// - /// # Arguments - /// - /// * x - an integer - /// * y - an integer distinct from 0u - /// - /// # Return value - /// - /// The integer `q` closest to `x/y`. - /// - pub fn div_round(x: uint, y: uint) -> uint { - let div = x / y; - if x % y * 2u < y { div } - else { div + 1u } - } - - /// - /// Divide two numbers, return the result, rounded down. - /// - /// Note: This is the same function as `div`. - /// - /// # Arguments - /// - /// * x - an integer - /// * y - an integer distinct from 0u - /// - /// # Return value - /// - /// The smallest integer `q` such that `x/y <= q`. This - /// is either `x/y` or `x/y + 1`. - /// - pub fn div_floor(x: uint, y: uint) -> uint { return x / y; } - - /// - /// Iterate over the range [`lo`..`hi`), or stop when requested - /// - /// # Arguments - /// - /// * lo - The integer at which to start the loop (included) - /// * hi - The integer at which to stop the loop (excluded) - /// * it - A block to execute with each consecutive integer of the range. - /// Return `true` to continue, `false` to stop. - /// - /// # Return value - /// - /// `true` If execution proceeded correctly, `false` if it was interrupted, - /// that is if `it` returned `false` at any point. - /// - pub fn iterate(lo: uint, hi: uint, it: &fn(uint) -> bool) -> bool { - let mut i = lo; - while i < hi { - if (!it(i)) { return false; } - i += 1u; - } - return true; - } - - impl iter::Times for uint { - #[inline(always)] - /// - /// A convenience form for basic iteration. Given a uint `x`, - /// `for x.times { ... }` executes the given block x times. - /// - /// Equivalent to `for uint::range(0, x) |_| { ... }`. - /// - /// Not defined on all integer types to permit unambiguous - /// use with integer literals of inferred integer-type as - /// the self-value (eg. `for 100.times { ... }`). - /// - fn times(&self, it: &fn() -> bool) -> bool { - let mut i = *self; - while i > 0 { - if !it() { return false; } - i -= 1; - } - return true; - } - } - - /// Returns the smallest power of 2 greater than or equal to `n` - #[inline(always)] - pub fn next_power_of_two(n: uint) -> uint { - let halfbits: uint = sys::size_of::() * 4u; - let mut tmp: uint = n - 1u; - let mut shift: uint = 1u; - while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; } - return tmp + 1u; - } - - #[test] - fn test_next_power_of_two() { - assert_eq!(next_power_of_two(0u), 0u); - assert_eq!(next_power_of_two(1u), 1u); - assert_eq!(next_power_of_two(2u), 2u); - assert_eq!(next_power_of_two(3u), 4u); - assert_eq!(next_power_of_two(4u), 4u); - assert_eq!(next_power_of_two(5u), 8u); - assert_eq!(next_power_of_two(6u), 8u); - assert_eq!(next_power_of_two(7u), 8u); - assert_eq!(next_power_of_two(8u), 8u); - assert_eq!(next_power_of_two(9u), 16u); - assert_eq!(next_power_of_two(10u), 16u); - assert_eq!(next_power_of_two(11u), 16u); - assert_eq!(next_power_of_two(12u), 16u); - assert_eq!(next_power_of_two(13u), 16u); - assert_eq!(next_power_of_two(14u), 16u); - assert_eq!(next_power_of_two(15u), 16u); - assert_eq!(next_power_of_two(16u), 16u); - assert_eq!(next_power_of_two(17u), 32u); - assert_eq!(next_power_of_two(18u), 32u); - assert_eq!(next_power_of_two(19u), 32u); - assert_eq!(next_power_of_two(20u), 32u); - assert_eq!(next_power_of_two(21u), 32u); - assert_eq!(next_power_of_two(22u), 32u); - assert_eq!(next_power_of_two(23u), 32u); - assert_eq!(next_power_of_two(24u), 32u); - assert_eq!(next_power_of_two(25u), 32u); - assert_eq!(next_power_of_two(26u), 32u); - assert_eq!(next_power_of_two(27u), 32u); - assert_eq!(next_power_of_two(28u), 32u); - assert_eq!(next_power_of_two(29u), 32u); - assert_eq!(next_power_of_two(30u), 32u); - assert_eq!(next_power_of_two(31u), 32u); - assert_eq!(next_power_of_two(32u), 32u); - assert_eq!(next_power_of_two(33u), 64u); - assert_eq!(next_power_of_two(34u), 64u); - assert_eq!(next_power_of_two(35u), 64u); - assert_eq!(next_power_of_two(36u), 64u); - assert_eq!(next_power_of_two(37u), 64u); - assert_eq!(next_power_of_two(38u), 64u); - assert_eq!(next_power_of_two(39u), 64u); - } - - #[test] - fn test_overflows() { - use uint; - assert!((uint::max_value > 0u)); - assert!((uint::min_value <= 0u)); - assert_eq!(uint::min_value + uint::max_value + 1u, 0u); - } - - #[test] - fn test_div() { - assert_eq!(div_floor(3u, 4u), 0u); - assert_eq!(div_ceil(3u, 4u), 1u); - assert_eq!(div_round(3u, 4u), 1u); - } - - #[test] - pub fn test_times() { - use iter::Times; - let ten = 10 as uint; - let mut accum = 0; - for ten.times { accum += 1; } - assert_eq!(accum, 10); - } -} diff --git a/src/libstd/num/uint.rs b/src/libstd/num/uint.rs new file mode 100644 index 0000000000000..bcb97ff5a07f6 --- /dev/null +++ b/src/libstd/num/uint.rs @@ -0,0 +1,195 @@ +// Copyright 2012 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. + +//! Operations and constants for `uint` + +use iter; +use sys; + +pub use self::generated::*; + +uint_module!(uint, int, ::int::bits) + +/// +/// Divide two numbers, return the result, rounded up. +/// +/// # Arguments +/// +/// * x - an integer +/// * y - an integer distinct from 0u +/// +/// # Return value +/// +/// The smallest integer `q` such that `x/y <= q`. +/// +pub fn div_ceil(x: uint, y: uint) -> uint { + let div = x / y; + if x % y == 0u { div } + else { div + 1u } +} + +/// +/// Divide two numbers, return the result, rounded to the closest integer. +/// +/// # Arguments +/// +/// * x - an integer +/// * y - an integer distinct from 0u +/// +/// # Return value +/// +/// The integer `q` closest to `x/y`. +/// +pub fn div_round(x: uint, y: uint) -> uint { + let div = x / y; + if x % y * 2u < y { div } + else { div + 1u } +} + +/// +/// Divide two numbers, return the result, rounded down. +/// +/// Note: This is the same function as `div`. +/// +/// # Arguments +/// +/// * x - an integer +/// * y - an integer distinct from 0u +/// +/// # Return value +/// +/// The smallest integer `q` such that `x/y <= q`. This +/// is either `x/y` or `x/y + 1`. +/// +pub fn div_floor(x: uint, y: uint) -> uint { return x / y; } + +/// +/// Iterate over the range [`lo`..`hi`), or stop when requested +/// +/// # Arguments +/// +/// * lo - The integer at which to start the loop (included) +/// * hi - The integer at which to stop the loop (excluded) +/// * it - A block to execute with each consecutive integer of the range. +/// Return `true` to continue, `false` to stop. +/// +/// # Return value +/// +/// `true` If execution proceeded correctly, `false` if it was interrupted, +/// that is if `it` returned `false` at any point. +/// +pub fn iterate(lo: uint, hi: uint, it: &fn(uint) -> bool) -> bool { + let mut i = lo; + while i < hi { + if (!it(i)) { return false; } + i += 1u; + } + return true; +} + +impl iter::Times for uint { + #[inline(always)] + /// + /// A convenience form for basic iteration. Given a uint `x`, + /// `for x.times { ... }` executes the given block x times. + /// + /// Equivalent to `for uint::range(0, x) |_| { ... }`. + /// + /// Not defined on all integer types to permit unambiguous + /// use with integer literals of inferred integer-type as + /// the self-value (eg. `for 100.times { ... }`). + /// + fn times(&self, it: &fn() -> bool) -> bool { + let mut i = *self; + while i > 0 { + if !it() { return false; } + i -= 1; + } + return true; + } +} + +/// Returns the smallest power of 2 greater than or equal to `n` +#[inline(always)] +pub fn next_power_of_two(n: uint) -> uint { + let halfbits: uint = sys::size_of::() * 4u; + let mut tmp: uint = n - 1u; + let mut shift: uint = 1u; + while shift <= halfbits { tmp |= tmp >> shift; shift <<= 1u; } + return tmp + 1u; +} + +#[test] +fn test_next_power_of_two() { + assert!((next_power_of_two(0u) == 0u)); + assert!((next_power_of_two(1u) == 1u)); + assert!((next_power_of_two(2u) == 2u)); + assert!((next_power_of_two(3u) == 4u)); + assert!((next_power_of_two(4u) == 4u)); + assert!((next_power_of_two(5u) == 8u)); + assert!((next_power_of_two(6u) == 8u)); + assert!((next_power_of_two(7u) == 8u)); + assert!((next_power_of_two(8u) == 8u)); + assert!((next_power_of_two(9u) == 16u)); + assert!((next_power_of_two(10u) == 16u)); + assert!((next_power_of_two(11u) == 16u)); + assert!((next_power_of_two(12u) == 16u)); + assert!((next_power_of_two(13u) == 16u)); + assert!((next_power_of_two(14u) == 16u)); + assert!((next_power_of_two(15u) == 16u)); + assert!((next_power_of_two(16u) == 16u)); + assert!((next_power_of_two(17u) == 32u)); + assert!((next_power_of_two(18u) == 32u)); + assert!((next_power_of_two(19u) == 32u)); + assert!((next_power_of_two(20u) == 32u)); + assert!((next_power_of_two(21u) == 32u)); + assert!((next_power_of_two(22u) == 32u)); + assert!((next_power_of_two(23u) == 32u)); + assert!((next_power_of_two(24u) == 32u)); + assert!((next_power_of_two(25u) == 32u)); + assert!((next_power_of_two(26u) == 32u)); + assert!((next_power_of_two(27u) == 32u)); + assert!((next_power_of_two(28u) == 32u)); + assert!((next_power_of_two(29u) == 32u)); + assert!((next_power_of_two(30u) == 32u)); + assert!((next_power_of_two(31u) == 32u)); + assert!((next_power_of_two(32u) == 32u)); + assert!((next_power_of_two(33u) == 64u)); + assert!((next_power_of_two(34u) == 64u)); + assert!((next_power_of_two(35u) == 64u)); + assert!((next_power_of_two(36u) == 64u)); + assert!((next_power_of_two(37u) == 64u)); + assert!((next_power_of_two(38u) == 64u)); + assert!((next_power_of_two(39u) == 64u)); +} + +#[test] +fn test_overflows() { + use uint; + assert!((uint::max_value > 0u)); + assert!((uint::min_value <= 0u)); + assert!((uint::min_value + uint::max_value + 1u == 0u)); +} + +#[test] +fn test_div() { + assert!((div_floor(3u, 4u) == 0u)); + assert!((div_ceil(3u, 4u) == 1u)); + assert!((div_round(3u, 4u) == 1u)); +} + +#[test] +pub fn test_times() { + use iter::Times; + let ten = 10 as uint; + let mut accum = 0; + for ten.times { accum += 1; } + assert!((accum == 10)); +} diff --git a/src/libstd/num/uint-template.rs b/src/libstd/num/uint_macros.rs similarity index 50% rename from src/libstd/num/uint-template.rs rename to src/libstd/num/uint_macros.rs index 9784fe24206c3..3448314c43692 100644 --- a/src/libstd/num/uint-template.rs +++ b/src/libstd/num/uint_macros.rs @@ -8,53 +8,54 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use T = self::inst::T; -use T_SIGNED = self::inst::T_SIGNED; +// FIXME(#4375): this shouldn't have to be a nested module named 'generated' +#[macro_escape]; + +macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (mod generated { + +use num::BitCount; use num::{ToStrRadix, FromStrRadix}; use num::{Zero, One, strconv}; use prelude::*; pub use cmp::{min, max}; -pub static bits : uint = inst::bits; -pub static bytes : uint = (inst::bits / 8); +pub static bits : uint = $bits; +pub static bytes : uint = ($bits / 8); -pub static min_value: T = 0 as T; -pub static max_value: T = 0 as T - 1 as T; +pub static min_value: $T = 0 as $T; +pub static max_value: $T = 0 as $T - 1 as $T; #[inline(always)] -pub fn add(x: T, y: T) -> T { x + y } +pub fn add(x: $T, y: $T) -> $T { x + y } #[inline(always)] -pub fn sub(x: T, y: T) -> T { x - y } +pub fn sub(x: $T, y: $T) -> $T { x - y } #[inline(always)] -pub fn mul(x: T, y: T) -> T { x * y } +pub fn mul(x: $T, y: $T) -> $T { x * y } #[inline(always)] -pub fn div(x: T, y: T) -> T { x / y } +pub fn div(x: $T, y: $T) -> $T { x / y } #[inline(always)] -pub fn rem(x: T, y: T) -> T { x % y } +pub fn rem(x: $T, y: $T) -> $T { x % y } #[inline(always)] -pub fn lt(x: T, y: T) -> bool { x < y } +pub fn lt(x: $T, y: $T) -> bool { x < y } #[inline(always)] -pub fn le(x: T, y: T) -> bool { x <= y } +pub fn le(x: $T, y: $T) -> bool { x <= y } #[inline(always)] -pub fn eq(x: T, y: T) -> bool { x == y } +pub fn eq(x: $T, y: $T) -> bool { x == y } #[inline(always)] -pub fn ne(x: T, y: T) -> bool { x != y } +pub fn ne(x: $T, y: $T) -> bool { x != y } #[inline(always)] -pub fn ge(x: T, y: T) -> bool { x >= y } +pub fn ge(x: $T, y: $T) -> bool { x >= y } #[inline(always)] -pub fn gt(x: T, y: T) -> bool { x > y } +pub fn gt(x: $T, y: $T) -> bool { x > y } #[inline(always)] /// /// Iterate over the range [`start`,`start`+`step`..`stop`) /// -pub fn _range_step(start: T, - stop: T, - step: T_SIGNED, - it: &fn(T) -> bool) -> bool { +pub fn range_step(start: $T, stop: $T, step: $T_SIGNED, it: &fn($T) -> bool) -> bool { let mut i = start; if step == 0 { fail!("range_step called with step == 0"); @@ -63,78 +64,74 @@ pub fn _range_step(start: T, while i < stop { if !it(i) { return false; } // avoiding overflow. break if i + step > max_value - if i > max_value - (step as T) { return true; } - i += step as T; + if i > max_value - (step as $T) { return true; } + i += step as $T; } } else { while i > stop { if !it(i) { return false; } // avoiding underflow. break if i + step < min_value - if i < min_value + ((-step) as T) { return true; } - i -= -step as T; + if i < min_value + ((-step) as $T) { return true; } + i -= -step as $T; } } return true; } -pub fn range_step(start: T, stop: T, step: T_SIGNED, it: &fn(T) -> bool) -> bool { - _range_step(start, stop, step, it) -} - #[inline(always)] /// Iterate over the range [`lo`..`hi`) -pub fn range(lo: T, hi: T, it: &fn(T) -> bool) -> bool { - range_step(lo, hi, 1 as T_SIGNED, it) +pub fn range(lo: $T, hi: $T, it: &fn($T) -> bool) -> bool { + range_step(lo, hi, 1 as $T_SIGNED, it) } #[inline(always)] /// Iterate over the range [`hi`..`lo`) -pub fn range_rev(hi: T, lo: T, it: &fn(T) -> bool) -> bool { - range_step(hi, lo, -1 as T_SIGNED, it) +pub fn range_rev(hi: $T, lo: $T, it: &fn($T) -> bool) -> bool { + range_step(hi, lo, -1 as $T_SIGNED, it) } /// Computes the bitwise complement #[inline(always)] -pub fn compl(i: T) -> T { +pub fn compl(i: $T) -> $T { max_value ^ i } -impl Num for T {} +impl Num for $T {} #[cfg(not(test))] -impl Ord for T { +impl Ord for $T { #[inline(always)] - fn lt(&self, other: &T) -> bool { (*self) < (*other) } + fn lt(&self, other: &$T) -> bool { (*self) < (*other) } #[inline(always)] - fn le(&self, other: &T) -> bool { (*self) <= (*other) } + fn le(&self, other: &$T) -> bool { (*self) <= (*other) } #[inline(always)] - fn ge(&self, other: &T) -> bool { (*self) >= (*other) } + fn ge(&self, other: &$T) -> bool { (*self) >= (*other) } #[inline(always)] - fn gt(&self, other: &T) -> bool { (*self) > (*other) } + fn gt(&self, other: &$T) -> bool { (*self) > (*other) } } #[cfg(not(test))] -impl Eq for T { +impl Eq for $T { #[inline(always)] - fn eq(&self, other: &T) -> bool { return (*self) == (*other); } + fn eq(&self, other: &$T) -> bool { return (*self) == (*other); } #[inline(always)] - fn ne(&self, other: &T) -> bool { return (*self) != (*other); } + fn ne(&self, other: &$T) -> bool { return (*self) != (*other); } } -impl Orderable for T { +impl Orderable for $T { #[inline(always)] - fn min(&self, other: &T) -> T { + fn min(&self, other: &$T) -> $T { if *self < *other { *self } else { *other } } #[inline(always)] - fn max(&self, other: &T) -> T { + fn max(&self, other: &$T) -> $T { if *self > *other { *self } else { *other } } /// Returns the number constrained within the range `mn <= self <= mx`. #[inline(always)] - fn clamp(&self, mn: &T, mx: &T) -> T { + fn clamp(&self, mn: &$T, mx: &$T) -> $T { cond!( (*self > *mx) { *mx } (*self < *mn) { *mn } @@ -143,81 +140,81 @@ impl Orderable for T { } } -impl Zero for T { +impl Zero for $T { #[inline(always)] - fn zero() -> T { 0 } + fn zero() -> $T { 0 } #[inline(always)] fn is_zero(&self) -> bool { *self == 0 } } -impl One for T { +impl One for $T { #[inline(always)] - fn one() -> T { 1 } + fn one() -> $T { 1 } } #[cfg(not(test))] -impl Add for T { +impl Add<$T,$T> for $T { #[inline(always)] - fn add(&self, other: &T) -> T { *self + *other } + fn add(&self, other: &$T) -> $T { *self + *other } } #[cfg(not(test))] -impl Sub for T { +impl Sub<$T,$T> for $T { #[inline(always)] - fn sub(&self, other: &T) -> T { *self - *other } + fn sub(&self, other: &$T) -> $T { *self - *other } } #[cfg(not(test))] -impl Mul for T { +impl Mul<$T,$T> for $T { #[inline(always)] - fn mul(&self, other: &T) -> T { *self * *other } + fn mul(&self, other: &$T) -> $T { *self * *other } } #[cfg(not(test))] -impl Div for T { +impl Div<$T,$T> for $T { #[inline(always)] - fn div(&self, other: &T) -> T { *self / *other } + fn div(&self, other: &$T) -> $T { *self / *other } } #[cfg(not(test))] -impl Rem for T { +impl Rem<$T,$T> for $T { #[inline(always)] - fn rem(&self, other: &T) -> T { *self % *other } + fn rem(&self, other: &$T) -> $T { *self % *other } } #[cfg(not(test))] -impl Neg for T { +impl Neg<$T> for $T { #[inline(always)] - fn neg(&self) -> T { -*self } + fn neg(&self) -> $T { -*self } } -impl Unsigned for T {} +impl Unsigned for $T {} -impl Integer for T { +impl Integer for $T { /// Calculates `div` (`\`) and `rem` (`%`) simultaneously #[inline(always)] - fn div_rem(&self, other: &T) -> (T,T) { + fn div_rem(&self, other: &$T) -> ($T,$T) { (*self / *other, *self % *other) } /// Unsigned integer division. Returns the same result as `div` (`/`). #[inline(always)] - fn div_floor(&self, other: &T) -> T { *self / *other } + fn div_floor(&self, other: &$T) -> $T { *self / *other } /// Unsigned integer modulo operation. Returns the same result as `rem` (`%`). #[inline(always)] - fn mod_floor(&self, other: &T) -> T { *self / *other } + fn mod_floor(&self, other: &$T) -> $T { *self / *other } /// Calculates `div_floor` and `modulo_floor` simultaneously #[inline(always)] - fn div_mod_floor(&self, other: &T) -> (T,T) { + fn div_mod_floor(&self, other: &$T) -> ($T,$T) { (*self / *other, *self % *other) } /// Calculates the Greatest Common Divisor (GCD) of the number and `other` #[inline(always)] - fn gcd(&self, other: &T) -> T { + fn gcd(&self, other: &$T) -> $T { // Use Euclid's algorithm let mut m = *self, n = *other; while m != 0 { @@ -230,13 +227,13 @@ impl Integer for T { /// Calculates the Lowest Common Multiple (LCM) of the number and `other` #[inline(always)] - fn lcm(&self, other: &T) -> T { + fn lcm(&self, other: &$T) -> $T { (*self * *other) / self.gcd(other) } /// Returns `true` if the number can be divided by `other` without leaving a remainder #[inline(always)] - fn is_multiple_of(&self, other: &T) -> bool { *self % *other == 0 } + fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 } /// Returns `true` if the number is divisible by `2` #[inline(always)] @@ -247,87 +244,87 @@ impl Integer for T { fn is_odd(&self) -> bool { !self.is_even() } } -impl Bitwise for T {} +impl Bitwise for $T {} #[cfg(not(test))] -impl BitOr for T { +impl BitOr<$T,$T> for $T { #[inline(always)] - fn bitor(&self, other: &T) -> T { *self | *other } + fn bitor(&self, other: &$T) -> $T { *self | *other } } #[cfg(not(test))] -impl BitAnd for T { +impl BitAnd<$T,$T> for $T { #[inline(always)] - fn bitand(&self, other: &T) -> T { *self & *other } + fn bitand(&self, other: &$T) -> $T { *self & *other } } #[cfg(not(test))] -impl BitXor for T { +impl BitXor<$T,$T> for $T { #[inline(always)] - fn bitxor(&self, other: &T) -> T { *self ^ *other } + fn bitxor(&self, other: &$T) -> $T { *self ^ *other } } #[cfg(not(test))] -impl Shl for T { +impl Shl<$T,$T> for $T { #[inline(always)] - fn shl(&self, other: &T) -> T { *self << *other } + fn shl(&self, other: &$T) -> $T { *self << *other } } #[cfg(not(test))] -impl Shr for T { +impl Shr<$T,$T> for $T { #[inline(always)] - fn shr(&self, other: &T) -> T { *self >> *other } + fn shr(&self, other: &$T) -> $T { *self >> *other } } #[cfg(not(test))] -impl Not for T { +impl Not<$T> for $T { #[inline(always)] - fn not(&self) -> T { !*self } + fn not(&self) -> $T { !*self } } -impl Bounded for T { +impl Bounded for $T { #[inline(always)] - fn min_value() -> T { min_value } + fn min_value() -> $T { min_value } #[inline(always)] - fn max_value() -> T { max_value } + fn max_value() -> $T { max_value } } -impl Int for T {} +impl Int for $T {} // String conversion functions and impl str -> num /// Parse a string as a number in base 10. #[inline(always)] -pub fn from_str(s: &str) -> Option { +pub fn from_str(s: &str) -> Option<$T> { strconv::from_str_common(s, 10u, false, false, false, strconv::ExpNone, false, false) } /// Parse a string as a number in the given base. #[inline(always)] -pub fn from_str_radix(s: &str, radix: uint) -> Option { +pub fn from_str_radix(s: &str, radix: uint) -> Option<$T> { strconv::from_str_common(s, radix, false, false, false, strconv::ExpNone, false, false) } /// Parse a byte slice as a number in the given base. #[inline(always)] -pub fn parse_bytes(buf: &[u8], radix: uint) -> Option { +pub fn parse_bytes(buf: &[u8], radix: uint) -> Option<$T> { strconv::from_str_bytes_common(buf, radix, false, false, false, strconv::ExpNone, false, false) } -impl FromStr for T { +impl FromStr for $T { #[inline(always)] - fn from_str(s: &str) -> Option { + fn from_str(s: &str) -> Option<$T> { from_str(s) } } -impl FromStrRadix for T { +impl FromStrRadix for $T { #[inline(always)] - fn from_str_radix(s: &str, radix: uint) -> Option { + fn from_str_radix(s: &str, radix: uint) -> Option<$T> { from_str_radix(s, radix) } } @@ -336,7 +333,7 @@ impl FromStrRadix for T { /// Convert to a string as a byte slice in a given base. #[inline(always)] -pub fn to_str_bytes(n: T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { +pub fn to_str_bytes(n: $T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { let (buf, _) = strconv::to_str_bytes_common(&n, radix, false, strconv::SignNeg, strconv::DigAll); f(buf) @@ -344,7 +341,7 @@ pub fn to_str_bytes(n: T, radix: uint, f: &fn(v: &[u8]) -> U) -> U { /// Convert to a string in base 10. #[inline(always)] -pub fn to_str(num: T) -> ~str { +pub fn to_str(num: $T) -> ~str { let (buf, _) = strconv::to_str_common(&num, 10u, false, strconv::SignNeg, strconv::DigAll); buf @@ -352,149 +349,176 @@ pub fn to_str(num: T) -> ~str { /// Convert to a string in a given base. #[inline(always)] -pub fn to_str_radix(num: T, radix: uint) -> ~str { +pub fn to_str_radix(num: $T, radix: uint) -> ~str { let (buf, _) = strconv::to_str_common(&num, radix, false, strconv::SignNeg, strconv::DigAll); buf } -impl ToStr for T { +impl ToStr for $T { #[inline(always)] fn to_str(&self) -> ~str { to_str(*self) } } -impl ToStrRadix for T { +impl ToStrRadix for $T { #[inline(always)] fn to_str_radix(&self, radix: uint) -> ~str { to_str_radix(*self, radix) } } +impl Primitive for $T { + #[inline(always)] + fn bits() -> uint { bits } + + #[inline(always)] + fn bytes() -> uint { bits / 8 } +} + +impl BitCount for $T { + /// Counts the number of bits set. Wraps LLVM's `ctpop` intrinsic. + #[inline(always)] + fn population_count(&self) -> $T { + (*self as $T_SIGNED).population_count() as $T + } + + /// Counts the number of leading zeros. Wraps LLVM's `ctlz` intrinsic. + #[inline(always)] + fn leading_zeros(&self) -> $T { + (*self as $T_SIGNED).leading_zeros() as $T + } + + /// Counts the number of trailing zeros. Wraps LLVM's `cttz` intrinsic. + #[inline(always)] + fn trailing_zeros(&self) -> $T { + (*self as $T_SIGNED).trailing_zeros() as $T + } +} + #[cfg(test)] mod tests { use super::*; - use super::inst::T; use prelude::*; #[test] fn test_num() { - num::test_num(10 as T, 2 as T); + num::test_num(10 as $T, 2 as $T); } #[test] fn test_orderable() { - assert_eq!((1 as T).min(&(2 as T)), 1 as T); - assert_eq!((2 as T).min(&(1 as T)), 1 as T); - assert_eq!((1 as T).max(&(2 as T)), 2 as T); - assert_eq!((2 as T).max(&(1 as T)), 2 as T); - assert_eq!((1 as T).clamp(&(2 as T), &(4 as T)), 2 as T); - assert_eq!((8 as T).clamp(&(2 as T), &(4 as T)), 4 as T); - assert_eq!((3 as T).clamp(&(2 as T), &(4 as T)), 3 as T); + assert_eq!((1 as $T).min(&(2 as $T)), 1 as $T); + assert_eq!((2 as $T).min(&(1 as $T)), 1 as $T); + assert_eq!((1 as $T).max(&(2 as $T)), 2 as $T); + assert_eq!((2 as $T).max(&(1 as $T)), 2 as $T); + assert_eq!((1 as $T).clamp(&(2 as $T), &(4 as $T)), 2 as $T); + assert_eq!((8 as $T).clamp(&(2 as $T), &(4 as $T)), 4 as $T); + assert_eq!((3 as $T).clamp(&(2 as $T), &(4 as $T)), 3 as $T); } #[test] fn test_gcd() { - assert_eq!((10 as T).gcd(&2), 2 as T); - assert_eq!((10 as T).gcd(&3), 1 as T); - assert_eq!((0 as T).gcd(&3), 3 as T); - assert_eq!((3 as T).gcd(&3), 3 as T); - assert_eq!((56 as T).gcd(&42), 14 as T); + assert_eq!((10 as $T).gcd(&2), 2 as $T); + assert_eq!((10 as $T).gcd(&3), 1 as $T); + assert_eq!((0 as $T).gcd(&3), 3 as $T); + assert_eq!((3 as $T).gcd(&3), 3 as $T); + assert_eq!((56 as $T).gcd(&42), 14 as $T); } #[test] fn test_lcm() { - assert_eq!((1 as T).lcm(&0), 0 as T); - assert_eq!((0 as T).lcm(&1), 0 as T); - assert_eq!((1 as T).lcm(&1), 1 as T); - assert_eq!((8 as T).lcm(&9), 72 as T); - assert_eq!((11 as T).lcm(&5), 55 as T); - assert_eq!((99 as T).lcm(&17), 1683 as T); + assert_eq!((1 as $T).lcm(&0), 0 as $T); + assert_eq!((0 as $T).lcm(&1), 0 as $T); + assert_eq!((1 as $T).lcm(&1), 1 as $T); + assert_eq!((8 as $T).lcm(&9), 72 as $T); + assert_eq!((11 as $T).lcm(&5), 55 as $T); + assert_eq!((99 as $T).lcm(&17), 1683 as $T); } #[test] fn test_multiple_of() { - assert!((6 as T).is_multiple_of(&(6 as T))); - assert!((6 as T).is_multiple_of(&(3 as T))); - assert!((6 as T).is_multiple_of(&(1 as T))); + assert!((6 as $T).is_multiple_of(&(6 as $T))); + assert!((6 as $T).is_multiple_of(&(3 as $T))); + assert!((6 as $T).is_multiple_of(&(1 as $T))); } #[test] fn test_even() { - assert_eq!((0 as T).is_even(), true); - assert_eq!((1 as T).is_even(), false); - assert_eq!((2 as T).is_even(), true); - assert_eq!((3 as T).is_even(), false); - assert_eq!((4 as T).is_even(), true); + assert_eq!((0 as $T).is_even(), true); + assert_eq!((1 as $T).is_even(), false); + assert_eq!((2 as $T).is_even(), true); + assert_eq!((3 as $T).is_even(), false); + assert_eq!((4 as $T).is_even(), true); } #[test] fn test_odd() { - assert_eq!((0 as T).is_odd(), false); - assert_eq!((1 as T).is_odd(), true); - assert_eq!((2 as T).is_odd(), false); - assert_eq!((3 as T).is_odd(), true); - assert_eq!((4 as T).is_odd(), false); + assert_eq!((0 as $T).is_odd(), false); + assert_eq!((1 as $T).is_odd(), true); + assert_eq!((2 as $T).is_odd(), false); + assert_eq!((3 as $T).is_odd(), true); + assert_eq!((4 as $T).is_odd(), false); } #[test] fn test_bitwise() { - assert_eq!(0b1110 as T, (0b1100 as T).bitor(&(0b1010 as T))); - assert_eq!(0b1000 as T, (0b1100 as T).bitand(&(0b1010 as T))); - assert_eq!(0b0110 as T, (0b1100 as T).bitxor(&(0b1010 as T))); - assert_eq!(0b1110 as T, (0b0111 as T).shl(&(1 as T))); - assert_eq!(0b0111 as T, (0b1110 as T).shr(&(1 as T))); - assert_eq!(max_value - (0b1011 as T), (0b1011 as T).not()); + assert_eq!(0b1110 as $T, (0b1100 as $T).bitor(&(0b1010 as $T))); + assert_eq!(0b1000 as $T, (0b1100 as $T).bitand(&(0b1010 as $T))); + assert_eq!(0b0110 as $T, (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert_eq!(0b1110 as $T, (0b0111 as $T).shl(&(1 as $T))); + assert_eq!(0b0111 as $T, (0b1110 as $T).shr(&(1 as $T))); + assert_eq!(max_value - (0b1011 as $T), (0b1011 as $T).not()); } #[test] fn test_bitcount() { - assert_eq!((0b010101 as T).population_count(), 3); + assert_eq!((0b010101 as $T).population_count(), 3); } #[test] fn test_primitive() { - assert_eq!(Primitive::bits::(), sys::size_of::() * 8); - assert_eq!(Primitive::bytes::(), sys::size_of::()); + assert_eq!(Primitive::bits::<$T>(), sys::size_of::<$T>() * 8); + assert_eq!(Primitive::bytes::<$T>(), sys::size_of::<$T>()); } #[test] pub fn test_to_str() { - assert_eq!(to_str_radix(0 as T, 10u), ~"0"); - assert_eq!(to_str_radix(1 as T, 10u), ~"1"); - assert_eq!(to_str_radix(2 as T, 10u), ~"2"); - assert_eq!(to_str_radix(11 as T, 10u), ~"11"); - assert_eq!(to_str_radix(11 as T, 16u), ~"b"); - assert_eq!(to_str_radix(255 as T, 16u), ~"ff"); - assert_eq!(to_str_radix(0xff as T, 10u), ~"255"); + assert_eq!(to_str_radix(0 as $T, 10u), ~"0"); + assert_eq!(to_str_radix(1 as $T, 10u), ~"1"); + assert_eq!(to_str_radix(2 as $T, 10u), ~"2"); + assert_eq!(to_str_radix(11 as $T, 10u), ~"11"); + assert_eq!(to_str_radix(11 as $T, 16u), ~"b"); + assert_eq!(to_str_radix(255 as $T, 16u), ~"ff"); + assert_eq!(to_str_radix(0xff as $T, 10u), ~"255"); } #[test] pub fn test_from_str() { - assert_eq!(from_str("0"), Some(0u as T)); - assert_eq!(from_str("3"), Some(3u as T)); - assert_eq!(from_str("10"), Some(10u as T)); - assert_eq!(u32::from_str("123456789"), Some(123456789 as u32)); - assert_eq!(from_str("00100"), Some(100u as T)); + assert_eq!(from_str(~"0"), Some(0u as $T)); + assert_eq!(from_str(~"3"), Some(3u as $T)); + assert_eq!(from_str(~"10"), Some(10u as $T)); + assert_eq!(u32::from_str(~"123456789"), Some(123456789 as u32)); + assert_eq!(from_str(~"00100"), Some(100u as $T)); - assert!(from_str("").is_none()); - assert!(from_str(" ").is_none()); - assert!(from_str("x").is_none()); + assert!(from_str(~"").is_none()); + assert!(from_str(~" ").is_none()); + assert!(from_str(~"x").is_none()); } #[test] pub fn test_parse_bytes() { use str::to_bytes; - assert_eq!(parse_bytes(to_bytes("123"), 10u), Some(123u as T)); - assert_eq!(parse_bytes(to_bytes("1001"), 2u), Some(9u as T)); - assert_eq!(parse_bytes(to_bytes("123"), 8u), Some(83u as T)); - assert_eq!(u16::parse_bytes(to_bytes("123"), 16u), Some(291u as u16)); - assert_eq!(u16::parse_bytes(to_bytes("ffff"), 16u), Some(65535u as u16)); - assert_eq!(parse_bytes(to_bytes("z"), 36u), Some(35u as T)); + assert_eq!(parse_bytes(to_bytes(~"123"), 10u), Some(123u as $T)); + assert_eq!(parse_bytes(to_bytes(~"1001"), 2u), Some(9u as $T)); + assert_eq!(parse_bytes(to_bytes(~"123"), 8u), Some(83u as $T)); + assert_eq!(u16::parse_bytes(to_bytes(~"123"), 16u), Some(291u as u16)); + assert_eq!(u16::parse_bytes(to_bytes(~"ffff"), 16u), Some(65535u as u16)); + assert_eq!(parse_bytes(to_bytes(~"z"), 36u), Some(35u as $T)); - assert!(parse_bytes(to_bytes("Z"), 10u).is_none()); - assert!(parse_bytes(to_bytes("_"), 2u).is_none()); + assert!(parse_bytes(to_bytes(~"Z"), 10u).is_none()); + assert!(parse_bytes(to_bytes(~"_"), 2u).is_none()); } #[test] @@ -527,36 +551,36 @@ mod tests { #[test] fn test_uint_from_str_overflow() { let mut u8_val: u8 = 255_u8; - assert_eq!(u8::from_str("255"), Some(u8_val)); - assert!(u8::from_str("256").is_none()); + assert_eq!(u8::from_str(~"255"), Some(u8_val)); + assert!(u8::from_str(~"256").is_none()); u8_val += 1 as u8; - assert_eq!(u8::from_str("0"), Some(u8_val)); - assert!(u8::from_str("-1").is_none()); + assert_eq!(u8::from_str(~"0"), Some(u8_val)); + assert!(u8::from_str(~"-1").is_none()); let mut u16_val: u16 = 65_535_u16; - assert_eq!(u16::from_str("65535"), Some(u16_val)); - assert!(u16::from_str("65536").is_none()); + assert_eq!(u16::from_str(~"65535"), Some(u16_val)); + assert!(u16::from_str(~"65536").is_none()); u16_val += 1 as u16; - assert_eq!(u16::from_str("0"), Some(u16_val)); - assert!(u16::from_str("-1").is_none()); + assert_eq!(u16::from_str(~"0"), Some(u16_val)); + assert!(u16::from_str(~"-1").is_none()); let mut u32_val: u32 = 4_294_967_295_u32; - assert_eq!(u32::from_str("4294967295"), Some(u32_val)); - assert!(u32::from_str("4294967296").is_none()); + assert_eq!(u32::from_str(~"4294967295"), Some(u32_val)); + assert!(u32::from_str(~"4294967296").is_none()); u32_val += 1 as u32; - assert_eq!(u32::from_str("0"), Some(u32_val)); - assert!(u32::from_str("-1").is_none()); + assert_eq!(u32::from_str(~"0"), Some(u32_val)); + assert!(u32::from_str(~"-1").is_none()); let mut u64_val: u64 = 18_446_744_073_709_551_615_u64; - assert_eq!(u64::from_str("18446744073709551615"), Some(u64_val)); - assert!(u64::from_str("18446744073709551616").is_none()); + assert_eq!(u64::from_str(~"18446744073709551615"), Some(u64_val)); + assert!(u64::from_str(~"18446744073709551616").is_none()); u64_val += 1 as u64; - assert_eq!(u64::from_str("0"), Some(u64_val)); - assert!(u64::from_str("-1").is_none()); + assert_eq!(u64::from_str(~"0"), Some(u64_val)); + assert!(u64::from_str(~"-1").is_none()); } #[test] @@ -639,3 +663,5 @@ mod tests { for range_step(0,-10,0) |_i| {} } } + +})) From 03ae629259b0a721c3695ba85f22048f44cc43b0 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 20 May 2013 14:14:26 -0500 Subject: [PATCH 226/248] Remove the #[merge] hack from the parser --- src/libsyntax/parse/parser.rs | 35 +------------------- src/test/run-pass/mod-merge-hack-inst.rs | 16 --------- src/test/run-pass/mod-merge-hack-template.rs | 16 --------- src/test/run-pass/mod-merge-hack.rs | 19 ----------- 4 files changed, 1 insertion(+), 85 deletions(-) delete mode 100644 src/test/run-pass/mod-merge-hack-inst.rs delete mode 100644 src/test/run-pass/mod-merge-hack-template.rs delete mode 100644 src/test/run-pass/mod-merge-hack.rs diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index b8993520ae4cc..fe1787fca3cb0 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -3550,8 +3550,7 @@ pub impl Parser { fn parse_item_mod(&self, outer_attrs: ~[ast::attribute]) -> item_info { let id_span = *self.span; let id = self.parse_ident(); - let merge = ::attr::first_attr_value_str_by_name(outer_attrs, "merge"); - let info_ = if *self.token == token::SEMI { + if *self.token == token::SEMI { self.bump(); // This mod is in an external file. Let's go get it! let (m, attrs) = self.eval_src_mod(id, outer_attrs, id_span); @@ -3564,38 +3563,6 @@ pub impl Parser { self.expect(&token::RBRACE); self.pop_mod_path(); (id, item_mod(m), Some(inner)) - }; - - // XXX: Transitionary hack to do the template work inside core - // (int-template, iter-trait). If there's a 'merge' attribute - // on the mod, then we'll go and suck in another file and merge - // its contents - match merge { - Some(path) => { - let prefix = Path( - self.sess.cm.span_to_filename(*self.span)); - let prefix = prefix.dir_path(); - let path = Path(copy *path); - let (new_mod_item, new_attrs) = self.eval_src_mod_from_path( - prefix, path, ~[], id_span); - - let (main_id, main_mod_item, main_attrs) = info_; - let main_attrs = main_attrs.get(); - - let (main_mod, new_mod) = - match (main_mod_item, new_mod_item) { - (item_mod(m), item_mod(n)) => (m, n), - _ => self.bug("parsed mod item should be mod") - }; - let merged_mod = ast::_mod { - view_items: main_mod.view_items + new_mod.view_items, - items: main_mod.items + new_mod.items - }; - - let merged_attrs = main_attrs + new_attrs; - (main_id, item_mod(merged_mod), Some(merged_attrs)) - } - None => info_ } } diff --git a/src/test/run-pass/mod-merge-hack-inst.rs b/src/test/run-pass/mod-merge-hack-inst.rs deleted file mode 100644 index 999c6ac2a71d5..0000000000000 --- a/src/test/run-pass/mod-merge-hack-inst.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2012 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. - -// xfail-test not a test. used by mod-merge-hack.rs - -mod inst { - pub type T = i32; - pub static bits: uint = 32; -} diff --git a/src/test/run-pass/mod-merge-hack-template.rs b/src/test/run-pass/mod-merge-hack-template.rs deleted file mode 100644 index 7f7dd33dc099f..0000000000000 --- a/src/test/run-pass/mod-merge-hack-template.rs +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2012 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. - -// xfail-test not a test. used by mod-merge-hack.rs - -use T = self::inst::T; - -pub static bits: uint = inst::bits; -pub fn min(x: T, y: T) -> T { if x < y { x } else { y } } diff --git a/src/test/run-pass/mod-merge-hack.rs b/src/test/run-pass/mod-merge-hack.rs deleted file mode 100644 index fdef8c5b54102..0000000000000 --- a/src/test/run-pass/mod-merge-hack.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2012 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. - -// xfail-pretty -#[path = "mod-merge-hack-template.rs"] -#[merge = "mod-merge-hack-inst.rs"] -mod myint32; - -pub fn main() { - assert_eq!(myint32::bits, 32); - assert_eq!(myint32::min(10, 20), 10); -} From 264c84b892f531f968b1ab9c9b8e15f2c66cf524 Mon Sep 17 00:00:00 2001 From: "Herman J. Radtke III" Date: Fri, 24 May 2013 13:37:39 -0700 Subject: [PATCH 227/248] Make rust {test, run} exit with appropriate code. Scripts need to know if the tests pass or the program ran correctly. --- src/librust/rust.rc | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/src/librust/rust.rc b/src/librust/rust.rc index f1d92f1d9576e..6449958e09c0c 100644 --- a/src/librust/rust.rc +++ b/src/librust/rust.rc @@ -32,16 +32,17 @@ extern mod rustc; use core::prelude::*; use core::run; +use core::libc::exit; enum ValidUsage { - Valid, Invalid + Valid(int), Invalid } impl ValidUsage { fn is_valid(&self) -> bool { match *self { - Valid => true, - Invalid => false + Valid(_) => true, + Invalid => false } } } @@ -144,7 +145,7 @@ fn cmd_help(args: &[~str]) -> ValidUsage { UsgStr(msg) => io::println(fmt!("%s\n", msg)), UsgCall(f) => f(), } - Valid + Valid(0) }, None => Invalid } @@ -162,8 +163,8 @@ fn cmd_test(args: &[~str]) -> ValidUsage { let test_exec = Path(filename).filestem().unwrap() + "test~"; invoke("rustc", &[~"--test", filename.to_owned(), ~"-o", test_exec.to_owned()], rustc::main); - run::run_program(~"./" + test_exec, []); - Valid + let exit_code = run::run_program(~"./" + test_exec, []); + Valid(exit_code) } _ => Invalid } @@ -175,8 +176,8 @@ fn cmd_run(args: &[~str]) -> ValidUsage { let exec = Path(filename).filestem().unwrap() + "~"; invoke("rustc", &[filename.to_owned(), ~"-o", exec.to_owned()], rustc::main); - run::run_program(~"./"+exec, prog_args); - Valid + let exit_code = run::run_program(~"./"+exec, prog_args); + Valid(exit_code) } _ => Invalid } @@ -194,7 +195,7 @@ fn do_command(command: &Command, args: &[~str]) -> ValidUsage { Call(f) => f(args), CallMain(prog, f) => { invoke(prog, args, f); - Valid + Valid(0) } } } @@ -233,7 +234,10 @@ pub fn main() { if !args.is_empty() { for find_cmd(*args.head()).each |command| { let result = do_command(command, args.tail()); - if result.is_valid() { return; } + match result { + Valid(exit_code) => unsafe { exit(exit_code.to_i32()) }, + _ => loop + } } } From f2125434d86669d3086094397855f80c2bf636ac Mon Sep 17 00:00:00 2001 From: Olivier Saut Date: Fri, 24 May 2013 21:38:12 +0200 Subject: [PATCH 228/248] Remove the get function Rust is now preferring methods over functions and there is no legacy with ARC --- src/libextra/arc.rs | 25 ++++++++-------------- src/test/bench/graph500-bfs.rs | 14 ++++++------ src/test/compile-fail/no-capture-arc.rs | 6 +++--- src/test/compile-fail/no-reuse-move-arc.rs | 6 +++--- 4 files changed, 22 insertions(+), 29 deletions(-) diff --git a/src/libextra/arc.rs b/src/libextra/arc.rs index 648089a552475..820b85f4544d4 100644 --- a/src/libextra/arc.rs +++ b/src/libextra/arc.rs @@ -107,7 +107,7 @@ pub impl<'self> Condvar<'self> { ****************************************************************************/ /// An atomically reference counted wrapper for shared immutable state. -struct ARC { x: UnsafeAtomicRcBox } +pub struct ARC { x: UnsafeAtomicRcBox } /// Create an atomically reference counted wrapper. pub fn ARC(data: T) -> ARC { @@ -118,12 +118,8 @@ pub fn ARC(data: T) -> ARC { * Access the underlying data in an atomically reference counted * wrapper. */ -pub fn get<'a, T:Const + Owned>(rc: &'a ARC) -> &'a T { - rc.get() -} - -impl ARC { - pub fn get<'a>(&'a self) -> &'a T { +pub impl ARC { + fn get<'a>(&'a self) -> &'a T { unsafe { &*self.x.get_immut() } } } @@ -512,17 +508,14 @@ pub impl<'self, T:Const + Owned> RWReadMode<'self, T> { #[cfg(test)] mod tests { use core::prelude::*; - + use core::cell::Cell; use arc::*; use arc; - use core::cell::Cell; - use core::task; - #[test] fn manually_share_arc() { let v = ~[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - let arc_v = arc::ARC(v); + let arc_v = ARC(v); let (p, c) = comm::stream(); @@ -530,16 +523,16 @@ mod tests { let p = comm::PortSet::new(); c.send(p.chan()); - let arc_v = p.recv(); + let arc_v : ARC<~[int]> = p.recv(); - let v = copy *arc::get::<~[int]>(&arc_v); + let v = copy (*arc_v.get()); assert_eq!(v[3], 4); }; let c = p.recv(); - c.send(arc::clone(&arc_v)); + c.send(arc_v.clone()); - assert_eq!((*arc::get(&arc_v))[2], 3); + assert_eq!(arc_v.get()[2], 3); assert_eq!(arc_v.get()[4], 5); info!(arc_v); diff --git a/src/test/bench/graph500-bfs.rs b/src/test/bench/graph500-bfs.rs index 734b5a0006f90..06c8d0c145bf4 100644 --- a/src/test/bench/graph500-bfs.rs +++ b/src/test/bench/graph500-bfs.rs @@ -1,6 +1,6 @@ // xfail-pretty -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -234,7 +234,7 @@ fn pbfs(graph: &arc::ARC, key: node_id) -> bfs_result { black(node_id) }; - let graph_vec = arc::get(graph); // FIXME #3387 requires this temp + let graph_vec = graph.get(); // FIXME #3387 requires this temp let mut colors = do vec::from_fn(graph_vec.len()) |i| { if i as node_id == key { gray(key) @@ -266,13 +266,13 @@ fn pbfs(graph: &arc::ARC, key: node_id) -> bfs_result { let color = arc::ARC(colors); - let color_vec = arc::get(&color); // FIXME #3387 requires this temp + let color_vec = color.get(); // FIXME #3387 requires this temp colors = do par::mapi(*color_vec) { - let colors = arc::clone(&color); - let graph = arc::clone(graph); + let colors = color.clone(); + let graph = graph.clone(); let result: ~fn(x: uint, y: &color) -> color = |i, c| { - let colors = arc::get(&colors); - let graph = arc::get(&graph); + let colors = colors.get(); + let graph = graph.get(); match *c { white => { let i = i as node_id; diff --git a/src/test/compile-fail/no-capture-arc.rs b/src/test/compile-fail/no-capture-arc.rs index 132a5326a8846..2a83e479e873c 100644 --- a/src/test/compile-fail/no-capture-arc.rs +++ b/src/test/compile-fail/no-capture-arc.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -18,11 +18,11 @@ fn main() { let arc_v = arc::ARC(v); do task::spawn() { - let v = *arc::get(&arc_v); + let v = arc_v.get(); assert_eq!(v[3], 4); }; - assert_eq!((*arc::get(&arc_v))[2], 3); + assert_eq!((arc_v.get())[2], 3); info!(arc_v); } diff --git a/src/test/compile-fail/no-reuse-move-arc.rs b/src/test/compile-fail/no-reuse-move-arc.rs index 8bed4e6da47d6..607127f2fee74 100644 --- a/src/test/compile-fail/no-reuse-move-arc.rs +++ b/src/test/compile-fail/no-reuse-move-arc.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -16,11 +16,11 @@ fn main() { let arc_v = arc::ARC(v); do task::spawn() { //~ NOTE `arc_v` moved into closure environment here - let v = *arc::get(&arc_v); + let v = arc_v.get(); assert_eq!(v[3], 4); }; - assert!((*arc::get(&arc_v))[2] == 3); //~ ERROR use of moved value: `arc_v` + assert_eq!((arc_v.get())[2], 3); //~ ERROR use of moved value: `arc_v` info!(arc_v); } From ff28bb7839a039641788436b21130ae2d378609b Mon Sep 17 00:00:00 2001 From: Olivier Saut Date: Fri, 24 May 2013 22:54:58 +0200 Subject: [PATCH 229/248] Remove the clone function for the method --- src/libextra/arc.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/libextra/arc.rs b/src/libextra/arc.rs index 820b85f4544d4..123e727593568 100644 --- a/src/libextra/arc.rs +++ b/src/libextra/arc.rs @@ -123,6 +123,7 @@ pub impl ARC { unsafe { &*self.x.get_immut() } } } + /** * Duplicate an atomically reference counted wrapper. * @@ -130,13 +131,9 @@ pub impl ARC { * object. However, one of the `arc` objects can be sent to another task, * allowing them to share the underlying data. */ -pub fn clone(rc: &ARC) -> ARC { - ARC { x: rc.x.clone() } -} - impl Clone for ARC { fn clone(&self) -> ARC { - clone(self) + ARC { x: self.x.clone() } } } From ac6c15aecea4bb9a328cf8f80e1cbb9f0104d98b Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Fri, 24 May 2013 17:29:54 -0500 Subject: [PATCH 230/248] Actually filter view_items in blocks --- src/librustc/front/config.rs | 4 +++- src/test/run-pass/filter-block-view-items.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 src/test/run-pass/filter-block-view-items.rs diff --git a/src/librustc/front/config.rs b/src/librustc/front/config.rs index be2f5cf0f6138..b295e7524cfbe 100644 --- a/src/librustc/front/config.rs +++ b/src/librustc/front/config.rs @@ -136,8 +136,10 @@ fn fold_block( ) -> ast::blk_ { let filtered_stmts = b.stmts.filter_mapped(|a| filter_stmt(cx, *a)); + let filtered_view_items = + b.view_items.filter_mapped(|a| filter_view_item(cx, *a)); ast::blk_ { - view_items: /*bad*/copy b.view_items, + view_items: vec::map(filtered_view_items, |x| fld.fold_view_item(*x)), stmts: vec::map(filtered_stmts, |x| fld.fold_stmt(*x)), expr: b.expr.map(|x| fld.fold_expr(*x)), id: b.id, diff --git a/src/test/run-pass/filter-block-view-items.rs b/src/test/run-pass/filter-block-view-items.rs new file mode 100644 index 0000000000000..4286183371799 --- /dev/null +++ b/src/test/run-pass/filter-block-view-items.rs @@ -0,0 +1,15 @@ +// 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. + +fn main() { + // Make sure that this view item is filtered out because otherwise it would + // trigger a compilation error + #[cfg(not_present)] use foo = bar; +} From 876ce1026451047ddb8f455ed0c923f78f7dc39d Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 23 May 2013 20:47:13 -0500 Subject: [PATCH 231/248] Update the linenoise library --- src/rt/linenoise/linenoise.c | 228 ++++++++++++++++++++++++++++++++--- src/rt/linenoise/linenoise.h | 2 + 2 files changed, 211 insertions(+), 19 deletions(-) diff --git a/src/rt/linenoise/linenoise.c b/src/rt/linenoise/linenoise.c index 5e3216e4591d7..230711b5b8c8b 100644 --- a/src/rt/linenoise/linenoise.c +++ b/src/rt/linenoise/linenoise.c @@ -150,6 +150,9 @@ enum { SPECIAL_DELETE = -24, SPECIAL_HOME = -25, SPECIAL_END = -26, + SPECIAL_INSERT = -27, + SPECIAL_PAGE_UP = -28, + SPECIAL_PAGE_DOWN = -29 }; static int history_max_len = LINENOISE_DEFAULT_HISTORY_MAX_LEN; @@ -165,6 +168,7 @@ struct current { int pos; /* Cursor position, measured in chars */ int cols; /* Size of the window, in chars */ const char *prompt; + char *capture; /* Allocated capture buffer, or NULL for none. Always null terminated */ #if defined(USE_TERMIOS) int fd; /* Terminal fd */ #elif defined(USE_WINCONSOLE) @@ -187,6 +191,7 @@ void linenoiseHistoryFree(void) { free(history[j]); free(history); history = NULL; + history_len = 0; } } @@ -268,7 +273,10 @@ static void linenoiseAtExit(void) { linenoiseHistoryFree(); } -/* gcc/glibc insists that we care about the return code of write! */ +/* gcc/glibc insists that we care about the return code of write! + * Clarification: This means that a void-cast like "(void) (EXPR)" + * does not work. + */ #define IGNORE_RC(EXPR) if (EXPR) {} /* This is fdprintf() on some systems, but use a different @@ -374,6 +382,70 @@ static int fd_read(struct current *current) #endif } +static int countColorControlChars(const char* prompt, int plen) +{ + /* ANSI color control sequences have the form: + * "\x1b" "[" [0-9;]+ "m" + * We parse them with a simple state machine. + */ + + enum { + search_esc, + expect_bracket, + expect_inner, + expect_trail + } state = search_esc; + int len, found = 0; + char ch; + + /* XXX: Strictly we should be checking utf8 chars rather than + * bytes in case of the extremely unlikely scenario where + * an ANSI sequence is part of a utf8 sequence. + */ + for (; plen ; plen--, prompt++) { + ch = *prompt; + + switch (state) { + case search_esc: + len = 0; + if (ch == '\x1b') { + state = expect_bracket; + len++; + } + break; + case expect_bracket: + if (ch == '[') { + state = expect_inner; + len++; + } else { + state = search_esc; + } + break; + case expect_inner: + if (ch >= '0' && ch <= '9') { + len++; + state = expect_trail; + } else { + state = search_esc; + } + break; + case expect_trail: + if (ch == 'm') { + len++; + found += len; + state = search_esc; + } else if ((ch != ';') && ((ch < '0') || (ch > '9'))) { + state = search_esc; + } + /* 0-9, or semicolon */ + len++; + break; + } + } + + return found; +} + static int getWindowSize(struct current *current) { struct winsize ws; @@ -467,8 +539,14 @@ static int check_special(int fd) c = fd_read_char(fd, 50); if (c == '~') { switch (c2) { + case '2': + return SPECIAL_INSERT; case '3': return SPECIAL_DELETE; + case '5': + return SPECIAL_PAGE_UP; + case '6': + return SPECIAL_PAGE_DOWN; case '7': return SPECIAL_HOME; case '8': @@ -538,7 +616,7 @@ static int outputChars(struct current *current, const char *buf, int len) { COORD pos = { (SHORT)current->x, (SHORT)current->y }; DWORD n; - + WriteConsoleOutputCharacter(current->outh, buf, len, pos, &n); current->x += len; return 0; @@ -593,12 +671,18 @@ static int fd_read(struct current *current) return SPECIAL_UP; case VK_DOWN: return SPECIAL_DOWN; + case VK_INSERT: + return SPECIAL_INSERT; case VK_DELETE: return SPECIAL_DELETE; case VK_HOME: return SPECIAL_HOME; case VK_END: return SPECIAL_END; + case VK_PRIOR: + return SPECIAL_PAGE_UP; + case VK_NEXT: + return SPECIAL_PAGE_DOWN; } } /* Note that control characters are already translated in AsciiChar */ @@ -614,6 +698,14 @@ static int fd_read(struct current *current) return -1; } +static int countColorControlChars(char* prompt, int plen) +{ + /* For windows we assume that there are no embedded ansi color + * control sequences. + */ + return 0; +} + static int getWindowSize(struct current *current) { CONSOLE_SCREEN_BUFFER_INFO info; @@ -676,6 +768,11 @@ static void refreshLine(const char *prompt, struct current *current) plen = strlen(prompt); pchars = utf8_strlen(prompt, plen); + /* Scan the prompt for embedded ansi color control sequences and + * discount them as characters/columns. + */ + pchars -= countColorControlChars(prompt, plen); + /* Account for a line which is too long to fit in the window. * Note that control chars require an extra column */ @@ -692,7 +789,7 @@ static void refreshLine(const char *prompt, struct current *current) } } - /* If too many are need, strip chars off the front of 'buf' + /* If too many are needed, strip chars off the front of 'buf' * until it fits. Note that if the current char is a control character, * we need one extra col. */ @@ -843,16 +940,64 @@ static int insert_char(struct current *current, int pos, int ch) } /** + * Captures up to 'n' characters starting at 'pos' for the cut buffer. + * + * This replaces any existing characters in the cut buffer. + */ +static void capture_chars(struct current *current, int pos, int n) +{ + if (pos >= 0 && (pos + n - 1) < current->chars) { + int p1 = utf8_index(current->buf, pos); + int nbytes = utf8_index(current->buf + p1, n); + + if (nbytes) { + free(current->capture); + /* Include space for the null terminator */ + current->capture = (char *)malloc(nbytes + 1); + memcpy(current->capture, current->buf + p1, nbytes); + current->capture[nbytes] = '\0'; + } + } +} + +/** + * Removes up to 'n' characters at cursor position 'pos'. + * * Returns 0 if no chars were removed or non-zero otherwise. */ static int remove_chars(struct current *current, int pos, int n) { int removed = 0; + + /* First save any chars which will be removed */ + capture_chars(current, pos, n); + while (n-- && remove_char(current, pos)) { removed++; } return removed; } +/** + * Inserts the characters (string) 'chars' at the cursor position 'pos'. + * + * Returns 0 if no chars were inserted or non-zero otherwise. + */ +static int insert_chars(struct current *current, int pos, const char *chars) +{ + int inserted = 0; + + while (*chars) { + int ch; + int n = utf8_tounicode(chars, &ch); + if (insert_char(current, pos, ch) == 0) { + break; + } + inserted++; + pos++; + chars += n; + } + return inserted; +} #ifndef NO_COMPLETION static linenoiseCompletionCallback *completionCallback = NULL; @@ -937,7 +1082,7 @@ void linenoiseAddCompletion(linenoiseCompletions *lc, const char *str) { #endif -static int linenoisePrompt(struct current *current) { +static int linenoiseEdit(struct current *current) { int history_index = 0; /* The latest history entry is always our current buffer, that @@ -998,7 +1143,12 @@ static int linenoisePrompt(struct current *current) { refreshLine(current->prompt, current); } break; - case ctrl('W'): /* ctrl-w */ + case SPECIAL_INSERT: + /* Ignore. Expansion Hook. + * Future possibility: Toggle Insert/Overwrite Modes + */ + break; + case ctrl('W'): /* ctrl-w, delete word at left. save deleted chars */ /* eat any spaces on the left */ { int pos = current->pos; @@ -1118,9 +1268,11 @@ static int linenoisePrompt(struct current *current) { } break; case ctrl('T'): /* ctrl-t */ - if (current->pos > 0 && current->pos < current->chars) { - c = get_char(current, current->pos); - remove_char(current, current->pos); + if (current->pos > 0 && current->pos <= current->chars) { + /* If cursor is at end, transpose the previous two chars */ + int fixer = (current->pos == current->chars); + c = get_char(current, current->pos - fixer); + remove_char(current, current->pos - fixer); insert_char(current, current->pos - 1, c); refreshLine(current->prompt, current); } @@ -1157,26 +1309,34 @@ static int linenoisePrompt(struct current *current) { refreshLine(current->prompt, current); } break; + case SPECIAL_PAGE_UP: + dir = history_len - history_index - 1; /* move to start of history */ + goto history_navigation; + case SPECIAL_PAGE_DOWN: + dir = -history_index; /* move to 0 == end of history, i.e. current */ + goto history_navigation; case ctrl('P'): case SPECIAL_UP: dir = 1; + goto history_navigation; case ctrl('N'): case SPECIAL_DOWN: +history_navigation: if (history_len > 1) { /* Update the current history entry before to * overwrite it with tne next one. */ - free(history[history_len-1-history_index]); - history[history_len-1-history_index] = strdup(current->buf); + free(history[history_len - 1 - history_index]); + history[history_len - 1 - history_index] = strdup(current->buf); /* Show the new entry */ history_index += dir; if (history_index < 0) { history_index = 0; break; } else if (history_index >= history_len) { - history_index = history_len-1; + history_index = history_len - 1; break; } - set_current(current, history[history_len-1-history_index]); + set_current(current, history[history_len - 1 - history_index]); refreshLine(current->prompt, current); } break; @@ -1190,16 +1350,21 @@ static int linenoisePrompt(struct current *current) { current->pos = current->chars; refreshLine(current->prompt, current); break; - case ctrl('U'): /* Ctrl+u, delete to beginning of line. */ + case ctrl('U'): /* Ctrl+u, delete to beginning of line, save deleted chars. */ if (remove_chars(current, 0, current->pos)) { refreshLine(current->prompt, current); } break; - case ctrl('K'): /* Ctrl+k, delete from current to end of line. */ + case ctrl('K'): /* Ctrl+k, delete from current to end of line, save deleted chars. */ if (remove_chars(current, current->pos, current->chars - current->pos)) { refreshLine(current->prompt, current); } break; + case ctrl('Y'): /* Ctrl+y, insert saved chars at current position */ + if (current->capture && insert_chars(current, current->pos, current->capture)) { + refreshLine(current->prompt, current); + } + break; case ctrl('L'): /* Ctrl+L, clear screen */ clearScreen(current); /* Force recalc of window size for serial terminals */ @@ -1219,6 +1384,15 @@ static int linenoisePrompt(struct current *current) { return current->len; } +int linenoiseColumns(void) +{ + struct current current; + enableRawMode (¤t); + getWindowSize (¤t); + disableRawMode (¤t); + return current.cols; +} + char *linenoise(const char *prompt) { int count; @@ -1226,10 +1400,10 @@ char *linenoise(const char *prompt) char buf[LINENOISE_MAX_LINE]; if (enableRawMode(¤t) == -1) { - printf("%s", prompt); + printf("%s", prompt); fflush(stdout); if (fgets(buf, sizeof(buf), stdin) == NULL) { - return NULL; + return NULL; } count = strlen(buf); if (count && buf[count-1] == '\n') { @@ -1245,10 +1419,14 @@ char *linenoise(const char *prompt) current.chars = 0; current.pos = 0; current.prompt = prompt; + current.capture = NULL; + + count = linenoiseEdit(¤t); - count = linenoisePrompt(¤t); disableRawMode(¤t); printf("\n"); + + free(current.capture); if (count == -1) { return NULL; } @@ -1284,6 +1462,10 @@ int linenoiseHistoryAdd(const char *line) { return 1; } +int linenoiseHistoryGetMaxLen(void) { + return history_max_len; +} + int linenoiseHistorySetMaxLen(int len) { char **newHistory; @@ -1293,8 +1475,16 @@ int linenoiseHistorySetMaxLen(int len) { newHistory = (char **)malloc(sizeof(char*)*len); if (newHistory == NULL) return 0; - if (len < tocopy) tocopy = len; - memcpy(newHistory,history+(history_max_len-tocopy), sizeof(char*)*tocopy); + + /* If we can't copy everything, free the elements we'll not use. */ + if (len < tocopy) { + int j; + + for (j = 0; j < tocopy-len; j++) free(history[j]); + tocopy = len; + } + memset(newHistory,0,sizeof(char*)*len); + memcpy(newHistory,history+(history_len-tocopy), sizeof(char*)*tocopy); free(history); history = newHistory; } diff --git a/src/rt/linenoise/linenoise.h b/src/rt/linenoise/linenoise.h index 59f28976d67e5..7ebf244ee80e7 100644 --- a/src/rt/linenoise/linenoise.h +++ b/src/rt/linenoise/linenoise.h @@ -51,9 +51,11 @@ void linenoiseAddCompletion(linenoiseCompletions *, const char *); char *linenoise(const char *prompt); int linenoiseHistoryAdd(const char *line); int linenoiseHistorySetMaxLen(int len); +int linenoiseHistoryGetMaxLen(void); int linenoiseHistorySave(const char *filename); int linenoiseHistoryLoad(const char *filename); void linenoiseHistoryFree(void); char **linenoiseHistory(int *len); +int linenoiseColumns(void); #endif /* __LINENOISE_H */ From af27e17992062b13344af1f15ef1a8516807d83f Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 23 May 2013 20:47:22 -0500 Subject: [PATCH 232/248] Set the USE_UTF8 flag for linenoise to handle utf8-input --- mk/platform.mk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mk/platform.mk b/mk/platform.mk index ba1cbc32f5465..471ad667a2a13 100644 --- a/mk/platform.mk +++ b/mk/platform.mk @@ -29,7 +29,7 @@ $(foreach t,$(CFG_TARGET_TRIPLES),$(info cfg: os for $(t) is $(OSTYPE_$(t)))) # FIXME: no-omit-frame-pointer is just so that task_start_wrapper # has a frame pointer and the stack walker can understand it. Turning off # frame pointers everywhere is overkill -CFG_GCCISH_CFLAGS += -fno-omit-frame-pointer +CFG_GCCISH_CFLAGS += -fno-omit-frame-pointer -DUSE_UTF8 # On Darwin, we need to run dsymutil so the debugging information ends # up in the right place. On other platforms, it automatically gets From bf4d3729e83b9a9e51497b73242fa9b394acbac1 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Sat, 25 May 2013 00:40:12 -0500 Subject: [PATCH 233/248] Fix compilation errors with linenoise --- src/rt/linenoise/linenoise.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/rt/linenoise/linenoise.c b/src/rt/linenoise/linenoise.c index 230711b5b8c8b..0ce4d559bed99 100644 --- a/src/rt/linenoise/linenoise.c +++ b/src/rt/linenoise/linenoise.c @@ -395,7 +395,7 @@ static int countColorControlChars(const char* prompt, int plen) expect_inner, expect_trail } state = search_esc; - int len, found = 0; + int len = 0, found = 0; char ch; /* XXX: Strictly we should be checking utf8 chars rather than @@ -698,7 +698,7 @@ static int fd_read(struct current *current) return -1; } -static int countColorControlChars(char* prompt, int plen) +static int countColorControlChars(const char* prompt, int plen) { /* For windows we assume that there are no embedded ansi color * control sequences. From 523360415cca24ac0cbd198804d797dd05c48559 Mon Sep 17 00:00:00 2001 From: James Miller Date: Sat, 25 May 2013 17:51:26 +1200 Subject: [PATCH 234/248] Add basic atomic types --- src/libstd/unstable/atomics.rs | 343 +++++++++++++++++++++++++++++++++ src/libstd/unstable/mod.rs | 1 + 2 files changed, 344 insertions(+) create mode 100644 src/libstd/unstable/atomics.rs diff --git a/src/libstd/unstable/atomics.rs b/src/libstd/unstable/atomics.rs new file mode 100644 index 0000000000000..09febfebaac02 --- /dev/null +++ b/src/libstd/unstable/atomics.rs @@ -0,0 +1,343 @@ +// Copyright 2012-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. + +/*! + * Atomic types + */ + +use unstable::intrinsics; +use cast; +use option::{Option,Some,None}; + +pub struct AtomicFlag { + priv v:int +} + +pub struct AtomicBool { + priv v:uint +} + +pub struct AtomicInt { + priv v:int +} + +pub struct AtomicUint { + priv v:uint +} + +pub struct AtomicPtr { + priv p:~T +} + +pub enum Ordering { + Release, + Acquire, + SeqCst +} + + +impl AtomicFlag { + + fn new() -> AtomicFlag { + AtomicFlag { v: 0 } + } + + /** + * Clears the atomic flag + */ + #[inline(always)] + fn clear(&mut self, order:Ordering) { + unsafe {atomic_store(&mut self.v, 0, order)} + } + + #[inline(always)] + /** + * Sets the flag if it was previously unset, returns the previous value of the + * flag. + */ + fn test_and_set(&mut self, order:Ordering) -> bool { + unsafe {atomic_compare_and_swap(&mut self.v, 0, 1, order) > 0} + } +} + +impl AtomicBool { + fn new(v:bool) -> AtomicBool { + AtomicBool { v: if v { 1 } else { 0 } } + } + + #[inline(always)] + fn load(&self, order:Ordering) -> bool { + unsafe { atomic_load(&self.v, order) > 0 } + } + + #[inline(always)] + fn store(&mut self, val:bool, order:Ordering) { + let val = if val { 1 } else { 0 }; + + unsafe { atomic_store(&mut self.v, val, order); } + } + + #[inline(always)] + fn swap(&mut self, val:bool, order:Ordering) -> bool { + let val = if val { 1 } else { 0 }; + + unsafe { atomic_swap(&mut self.v, val, order) > 0} + } + + #[inline(always)] + fn compare_and_swap(&mut self, old: bool, new: bool, order:Ordering) -> bool { + let old = if old { 1 } else { 0 }; + let new = if new { 1 } else { 0 }; + + unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) > 0 } + } +} + +impl AtomicInt { + fn new(v:int) -> AtomicInt { + AtomicInt { v:v } + } + + #[inline(always)] + fn load(&self, order:Ordering) -> int { + unsafe { atomic_load(&self.v, order) } + } + + #[inline(always)] + fn store(&mut self, val:int, order:Ordering) { + unsafe { atomic_store(&mut self.v, val, order); } + } + + #[inline(always)] + fn swap(&mut self, val:int, order:Ordering) -> int { + unsafe { atomic_swap(&mut self.v, val, order) } + } + + #[inline(always)] + fn compare_and_swap(&mut self, old: int, new: int, order:Ordering) -> int { + unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) } + } + + #[inline(always)] + fn fetch_add(&mut self, val:int, order:Ordering) -> int { + unsafe { atomic_add(&mut self.v, val, order) } + } + + #[inline(always)] + fn fetch_sub(&mut self, val:int, order:Ordering) -> int { + unsafe { atomic_sub(&mut self.v, val, order) } + } +} + +impl AtomicUint { + fn new(v:uint) -> AtomicUint { + AtomicUint { v:v } + } + + #[inline(always)] + fn load(&self, order:Ordering) -> uint { + unsafe { atomic_load(&self.v, order) } + } + + #[inline(always)] + fn store(&mut self, val:uint, order:Ordering) { + unsafe { atomic_store(&mut self.v, val, order); } + } + + #[inline(always)] + fn swap(&mut self, val:uint, order:Ordering) -> uint { + unsafe { atomic_swap(&mut self.v, val, order) } + } + + #[inline(always)] + fn compare_and_swap(&mut self, old: uint, new: uint, order:Ordering) -> uint { + unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) } + } + + #[inline(always)] + fn fetch_add(&mut self, val:uint, order:Ordering) -> uint { + unsafe { atomic_add(&mut self.v, val, order) } + } + + #[inline(always)] + fn fetch_sub(&mut self, val:uint, order:Ordering) -> uint { + unsafe { atomic_sub(&mut self.v, val, order) } + } +} + +impl AtomicPtr { + fn new(p:~T) -> AtomicPtr { + AtomicPtr { p:p } + } + + /** + * Atomically swaps the stored pointer with the one given. + * + * Returns None if the pointer stored has been taken + */ + #[inline(always)] + fn swap(&mut self, ptr:~T, order:Ordering) -> Option<~T> { + unsafe { + let p = atomic_swap(&mut self.p, ptr, order); + let pv : &uint = cast::transmute(&p); + + if *pv == 0 { + None + } else { + Some(p) + } + } + } + + /** + * Atomically takes the stored pointer out. + * + * Returns None if it was already taken. + */ + #[inline(always)] + fn take(&mut self, order:Ordering) -> Option<~T> { + unsafe { self.swap(cast::transmute(0), order) } + } + + /** + * Atomically stores the given pointer, this will overwrite + * and previous value stored. + */ + #[inline(always)] + fn give(&mut self, ptr:~T, order:Ordering) { + let _ = self.swap(ptr, order); + } + + /** + * Checks to see if the stored pointer has been taken. + */ + fn taken(&self, order:Ordering) -> bool { + unsafe { + let p : ~T = atomic_load(&self.p, order); + + let pv : &uint = cast::transmute(&p); + + cast::forget(p); + *pv == 0 + } + } +} + +#[inline(always)] +pub unsafe fn atomic_store(dst: &mut T, val: T, order:Ordering) { + let dst = cast::transmute(dst); + let val = cast::transmute(val); + + match order { + Release => intrinsics::atomic_store_rel(dst, val), + _ => intrinsics::atomic_store(dst, val) + } +} + +#[inline(always)] +pub unsafe fn atomic_load(dst: &T, order:Ordering) -> T { + let dst = cast::transmute(dst); + + cast::transmute(match order { + Acquire => intrinsics::atomic_load_acq(dst), + _ => intrinsics::atomic_load(dst) + }) +} + +#[inline(always)] +pub unsafe fn atomic_swap(dst: &mut T, val: T, order: Ordering) -> T { + let dst = cast::transmute(dst); + let val = cast::transmute(val); + + cast::transmute(match order { + Acquire => intrinsics::atomic_xchg_acq(dst, val), + Release => intrinsics::atomic_xchg_rel(dst, val), + _ => intrinsics::atomic_xchg(dst, val) + }) +} + +#[inline(always)] +pub unsafe fn atomic_add(dst: &mut T, val: T, order: Ordering) -> T { + let dst = cast::transmute(dst); + let val = cast::transmute(val); + + cast::transmute(match order { + Acquire => intrinsics::atomic_xadd_acq(dst, val), + Release => intrinsics::atomic_xadd_rel(dst, val), + _ => intrinsics::atomic_xadd(dst, val) + }) +} + +#[inline(always)] +pub unsafe fn atomic_sub(dst: &mut T, val: T, order: Ordering) -> T { + let dst = cast::transmute(dst); + let val = cast::transmute(val); + + cast::transmute(match order { + Acquire => intrinsics::atomic_xsub_acq(dst, val), + Release => intrinsics::atomic_xsub_rel(dst, val), + _ => intrinsics::atomic_xsub(dst, val) + }) +} + +#[inline(always)] +pub unsafe fn atomic_compare_and_swap(dst:&mut T, old:T, new:T, order: Ordering) -> T { + let dst = cast::transmute(dst); + let old = cast::transmute(old); + let new = cast::transmute(new); + + cast::transmute(match order { + Acquire => intrinsics::atomic_cxchg_acq(dst, old, new), + Release => intrinsics::atomic_cxchg_rel(dst, old, new), + _ => intrinsics::atomic_cxchg(dst, old, new), + }) +} + +#[cfg(test)] +mod test { + use option::*; + use super::*; + + #[test] + fn flag() { + let mut flg = AtomicFlag::new(); + assert!(!flg.test_and_set(SeqCst)); + assert!(flg.test_and_set(SeqCst)); + + flg.clear(SeqCst); + assert!(!flg.test_and_set(SeqCst)); + } + + #[test] + fn pointer_swap() { + let mut p = AtomicPtr::new(~1); + let a = ~2; + + let b = p.swap(a, SeqCst); + + assert_eq!(b, Some(~1)); + assert_eq!(p.take(SeqCst), Some(~2)); + } + + #[test] + fn pointer_take() { + let mut p = AtomicPtr::new(~1); + + assert_eq!(p.take(SeqCst), Some(~1)); + assert_eq!(p.take(SeqCst), None); + assert!(p.taken(SeqCst)); + + let p2 = ~2; + p.give(p2, SeqCst); + + assert_eq!(p.take(SeqCst), Some(~2)); + } + +} diff --git a/src/libstd/unstable/mod.rs b/src/libstd/unstable/mod.rs index 9681a3f36fcee..afdc22a1c63e9 100644 --- a/src/libstd/unstable/mod.rs +++ b/src/libstd/unstable/mod.rs @@ -25,6 +25,7 @@ pub mod extfmt; #[cfg(not(test))] pub mod lang; pub mod sync; +pub mod atomics; /** From 257192c69e08c174753e1abe7efd53c3a87ed92e Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Sat, 25 May 2013 17:07:18 +1000 Subject: [PATCH 235/248] Ignore the generated docs for libextra --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 7ef656055ecc6..eef182a12233d 100644 --- a/.gitignore +++ b/.gitignore @@ -73,6 +73,7 @@ src/.DS_Store /doc/html /doc/latex /doc/std +/doc/extra /nd/ /llvm/ version.md @@ -81,7 +82,6 @@ keywords.md x86_64-apple-darwin/ x86_64-unknown-linux-gnu/ i686-unknown-linux-gnu/ -doc/core/ tmp.*.rs config.stamp .DS_Store From 6c62d77830d75c5bbc9f546f944c038be2622a8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B6rn=20Steinbrink?= Date: Sat, 25 May 2013 17:45:45 +0200 Subject: [PATCH 236/248] Use an enum for keywords and intern them to improve parser performance Currently, keywords are stored in hashsets that are recreated for every Parser instance, which is quite expensive since macro expansion creates lots of them. Additionally, the parser functions that look for a keyword currently accept a string and have a runtime check to validate that they actually received a keyword. By creating an enum for the keywords and inserting them into the ident interner, we can avoid the creation of the hashsets and get static checks for the keywords. For libstd, this cuts the parse+expansion part from ~2.6s to ~1.6s. --- src/libsyntax/ext/trace_macros.rs | 5 +- src/libsyntax/parse/common.rs | 97 ++------------ src/libsyntax/parse/obsolete.rs | 6 +- src/libsyntax/parse/parser.rs | 216 +++++++++++++++--------------- src/libsyntax/parse/token.rs | 201 ++++++++++++++++++++------- 5 files changed, 280 insertions(+), 245 deletions(-) diff --git a/src/libsyntax/ext/trace_macros.rs b/src/libsyntax/ext/trace_macros.rs index 185d2fac11be8..f899004de5c5f 100644 --- a/src/libsyntax/ext/trace_macros.rs +++ b/src/libsyntax/ext/trace_macros.rs @@ -16,6 +16,7 @@ use ext::base::ExtCtxt; use ext::base; use parse::lexer::{new_tt_reader, reader}; use parse::parser::Parser; +use parse::token::keywords; pub fn expand_trace_macros(cx: @ExtCtxt, sp: span, @@ -36,9 +37,9 @@ pub fn expand_trace_macros(cx: @ExtCtxt, rdr.dup() ); - if rust_parser.is_keyword("true") { + if rust_parser.is_keyword(keywords::True) { cx.set_trace_macros(true); - } else if rust_parser.is_keyword("false") { + } else if rust_parser.is_keyword(keywords::False) { cx.set_trace_macros(false); } else { cx.span_fatal(sp, "trace_macros! only accepts `true` or `false`") diff --git a/src/libsyntax/parse/common.rs b/src/libsyntax/parse/common.rs index 7182b80880ff9..6a868fbf173dd 100644 --- a/src/libsyntax/parse/common.rs +++ b/src/libsyntax/parse/common.rs @@ -14,6 +14,7 @@ use ast; use codemap::{BytePos, spanned}; use parse::lexer::reader; use parse::parser::Parser; +use parse::token::keywords; use parse::token; use opt_vec; @@ -133,54 +134,15 @@ pub impl Parser { return if *self.token == *tok { self.bump(); true } else { false }; } - // Storing keywords as interned idents instead of strings would be nifty. - - // A sanity check that the word we are asking for is a known keyword - // NOTE: this could be done statically.... - fn require_keyword(&self, word: &str) { - if !self.keywords.contains_equiv(&word) { - self.bug(fmt!("unknown keyword: %s", word)); - } - } - - // return true when this token represents the given string, and is not - // followed immediately by :: . - fn token_is_word(&self, word: &str, tok: &token::Token) -> bool { - match *tok { - token::IDENT(sid, false) => { word == *self.id_to_str(sid) } - _ => { false } - } - } - - fn token_is_keyword(&self, word: &str, tok: &token::Token) -> bool { - self.require_keyword(word); - self.token_is_word(word, tok) - } - - fn is_keyword(&self, word: &str) -> bool { - self.token_is_keyword(word, © *self.token) - } - - fn id_is_any_keyword(&self, id: ast::ident) -> bool { - self.keywords.contains(self.id_to_str(id)) - } - - fn is_any_keyword(&self, tok: &token::Token) -> bool { - match *tok { - token::IDENT(sid, false) => { - self.keywords.contains(self.id_to_str(sid)) - } - _ => false - } + fn is_keyword(&self, kw: keywords::Keyword) -> bool { + token::is_keyword(kw, self.token) } - // if the given word is not a keyword, signal an error. // if the next token is the given keyword, eat it and return // true. Otherwise, return false. - fn eat_keyword(&self, word: &str) -> bool { - self.require_keyword(word); + fn eat_keyword(&self, kw: keywords::Keyword) -> bool { let is_kw = match *self.token { - token::IDENT(sid, false) => word == *self.id_to_str(sid), + token::IDENT(sid, false) => kw.to_ident().repr == sid.repr, _ => false }; if is_kw { self.bump() } @@ -190,63 +152,30 @@ pub impl Parser { // if the given word is not a keyword, signal an error. // if the next token is not the given word, signal an error. // otherwise, eat it. - fn expect_keyword(&self, word: &str) { - self.require_keyword(word); - if !self.eat_keyword(word) { + fn expect_keyword(&self, kw: keywords::Keyword) { + if !self.eat_keyword(kw) { self.fatal( fmt!( "expected `%s`, found `%s`", - word, + *self.id_to_str(kw.to_ident()), self.this_token_to_str() ) ); } } - // return true if the given string is a strict keyword - fn is_strict_keyword(&self, word: &str) -> bool { - self.strict_keywords.contains_equiv(&word) - } - - // signal an error if the current token is a strict keyword - fn check_strict_keywords(&self) { - match *self.token { - token::IDENT(_, false) => { - let w = token_to_str(self.reader, © *self.token); - self.check_strict_keywords_(w); - } - _ => () - } - } - // signal an error if the given string is a strict keyword - fn check_strict_keywords_(&self, w: &str) { - if self.is_strict_keyword(w) { + fn check_strict_keywords(&self) { + if token::is_strict_keyword(self.token) { self.span_err(*self.last_span, - fmt!("found `%s` in ident position", w)); + fmt!("found `%s` in ident position", self.this_token_to_str())); } } - // return true if this is a reserved keyword - fn is_reserved_keyword(&self, word: &str) -> bool { - self.reserved_keywords.contains_equiv(&word) - } - // signal an error if the current token is a reserved keyword fn check_reserved_keywords(&self) { - match *self.token { - token::IDENT(_, false) => { - let w = token_to_str(self.reader, © *self.token); - self.check_reserved_keywords_(w); - } - _ => () - } - } - - // signal an error if the given string is a reserved keyword - fn check_reserved_keywords_(&self, w: &str) { - if self.is_reserved_keyword(w) { - self.fatal(fmt!("`%s` is a reserved keyword", w)); + if token::is_reserved_keyword(self.token) { + self.fatal(fmt!("`%s` is a reserved keyword", self.this_token_to_str())); } } diff --git a/src/libsyntax/parse/obsolete.rs b/src/libsyntax/parse/obsolete.rs index 34205e7b9abcb..9a8001386abd8 100644 --- a/src/libsyntax/parse/obsolete.rs +++ b/src/libsyntax/parse/obsolete.rs @@ -23,7 +23,7 @@ use ast::{expr, expr_lit, lit_nil, attribute}; use ast; use codemap::{span, respan}; use parse::parser::Parser; -use parse::token::Token; +use parse::token::{keywords, Token}; use parse::token; use core::to_bytes; @@ -295,9 +295,9 @@ pub impl Parser { } fn try_parse_obsolete_priv_section(&self, attrs: &[attribute]) -> bool { - if self.is_keyword("priv") && self.look_ahead(1) == token::LBRACE { + if self.is_keyword(keywords::Priv) && self.look_ahead(1) == token::LBRACE { self.obsolete(copy *self.span, ObsoletePrivSection); - self.eat_keyword("priv"); + self.eat_keyword(keywords::Priv); self.bump(); while *self.token != token::RBRACE { self.parse_single_struct_field(ast::private, attrs.to_owned()); diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index b8993520ae4cc..d3c39f4b24686 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -86,7 +86,7 @@ use parse::obsolete::{ObsoletePurity, ObsoleteStaticMethod}; use parse::obsolete::{ObsoleteConstItem, ObsoleteFixedLengthVectorType}; use parse::obsolete::{ObsoleteNamedExternModule}; use parse::token::{can_begin_expr, is_ident, is_ident_or_path}; -use parse::token::{is_plain_ident, INTERPOLATED, special_idents, token_to_binop}; +use parse::token::{is_plain_ident, INTERPOLATED, keywords, special_idents, token_to_binop}; use parse::token; use parse::{new_sub_parser_from_file, next_node_id, ParseSess}; use opt_vec; @@ -234,9 +234,6 @@ pub fn Parser(sess: @mut ParseSess, tokens_consumed: @mut 0, restriction: @mut UNRESTRICTED, quote_depth: @mut 0, - keywords: token::keyword_table(), - strict_keywords: token::strict_keyword_table(), - reserved_keywords: token::reserved_keyword_table(), obsolete_set: @mut HashSet::new(), mod_path_stack: @mut ~[], } @@ -260,9 +257,6 @@ pub struct Parser { quote_depth: @mut uint, // not (yet) related to the quasiquoter reader: @reader, interner: @token::ident_interner, - keywords: HashSet<~str>, - strict_keywords: HashSet<~str>, - reserved_keywords: HashSet<~str>, /// The set of seen errors about obsolete syntax. Used to suppress /// extra detail when the same error is seen twice obsolete_set: @mut HashSet, @@ -340,10 +334,10 @@ pub impl Parser { // is this one of the keywords that signals a closure type? fn token_is_closure_keyword(&self, tok: &token::Token) -> bool { - self.token_is_keyword("pure", tok) || - self.token_is_keyword("unsafe", tok) || - self.token_is_keyword("once", tok) || - self.token_is_keyword("fn", tok) + token::is_keyword(keywords::Pure, tok) || + token::is_keyword(keywords::Unsafe, tok) || + token::is_keyword(keywords::Once, tok) || + token::is_keyword(keywords::Fn, tok) } fn token_is_lifetime(&self, tok: &token::Token) -> bool { @@ -380,7 +374,7 @@ pub impl Parser { let opt_abis = self.parse_opt_abis(); let abis = opt_abis.get_or_default(AbiSet::Rust()); let purity = self.parse_unsafety(); - self.expect_keyword("fn"); + self.expect_keyword(keywords::Fn); let (decl, lifetimes) = self.parse_ty_fn_decl(); return ty_bare_fn(@TyBareFn { abis: abis, @@ -416,7 +410,7 @@ pub impl Parser { let purity = self.parse_unsafety(); let onceness = parse_onceness(self); - self.expect_keyword("fn"); + self.expect_keyword(keywords::Fn); let bounds = self.parse_optional_ty_param_bounds(); if self.parse_fn_ty_sigil().is_some() { @@ -436,7 +430,7 @@ pub impl Parser { }); fn parse_onceness(this: &Parser) -> Onceness { - if this.eat_keyword("once") { + if this.eat_keyword(keywords::Once) { Once } else { Many @@ -446,10 +440,10 @@ pub impl Parser { // looks like this should be called parse_unsafety fn parse_unsafety(&self) -> purity { - if self.eat_keyword("pure") { + if self.eat_keyword(keywords::Pure) { self.obsolete(*self.last_span, ObsoletePurity); return impure_fn; - } else if self.eat_keyword("unsafe") { + } else if self.eat_keyword(keywords::Unsafe) { return unsafe_fn; } else { return impure_fn; @@ -704,7 +698,7 @@ pub impl Parser { // BORROWED POINTER self.bump(); self.parse_borrowed_pointee() - } else if self.eat_keyword("extern") { + } else if self.eat_keyword(keywords::Extern) { // EXTERN FUNCTION self.parse_ty_bare_fn() } else if self.token_is_closure_keyword(© *self.token) { @@ -828,7 +822,7 @@ pub impl Parser { let mut is_mutbl = false; let pat = if require_name || self.is_named_argument() { self.parse_arg_mode(); - is_mutbl = self.eat_keyword("mut"); + is_mutbl = self.eat_keyword(keywords::Mut); let pat = self.parse_pat(false); self.expect(&token::COLON); pat @@ -856,7 +850,7 @@ pub impl Parser { // parse an argument in a lambda header e.g. |arg, arg| fn parse_fn_block_arg(&self) -> arg_or_capture_item { self.parse_arg_mode(); - let is_mutbl = self.eat_keyword("mut"); + let is_mutbl = self.eat_keyword(keywords::Mut); let pat = self.parse_pat(false); let t = if self.eat(&token::COLON) { self.parse_ty(false) @@ -907,9 +901,9 @@ pub impl Parser { // matches lit = true | false | token_lit fn parse_lit(&self) -> lit { let lo = self.span.lo; - let lit = if self.eat_keyword("true") { + let lit = if self.eat_keyword(keywords::True) { lit_bool(true) - } else if self.eat_keyword("false") { + } else if self.eat_keyword(keywords::False) { lit_bool(false) } else { // XXX: This is a really bad copy! @@ -1145,15 +1139,15 @@ pub impl Parser { } fn token_is_mutability(&self, tok: &token::Token) -> bool { - self.token_is_keyword("mut", tok) || - self.token_is_keyword("const", tok) + token::is_keyword(keywords::Mut, tok) || + token::is_keyword(keywords::Const, tok) } // parse mutability declaration (mut/const/imm) fn parse_mutability(&self) -> mutability { - if self.eat_keyword("mut") { + if self.eat_keyword(keywords::Mut) { m_mutbl - } else if self.eat_keyword("const") { + } else if self.eat_keyword(keywords::Const) { m_const } else { m_imm @@ -1251,30 +1245,30 @@ pub impl Parser { expr_block(blk)); } else if token::is_bar(&*self.token) { return self.parse_lambda_expr(); - } else if self.eat_keyword("self") { + } else if self.eat_keyword(keywords::Self) { ex = expr_self; hi = self.span.hi; - } else if self.eat_keyword("if") { + } else if self.eat_keyword(keywords::If) { return self.parse_if_expr(); - } else if self.eat_keyword("for") { + } else if self.eat_keyword(keywords::For) { return self.parse_sugary_call_expr(~"for", ForSugar, expr_loop_body); - } else if self.eat_keyword("do") { + } else if self.eat_keyword(keywords::Do) { return self.parse_sugary_call_expr(~"do", DoSugar, expr_do_body); - } else if self.eat_keyword("while") { + } else if self.eat_keyword(keywords::While) { return self.parse_while_expr(); } else if self.token_is_lifetime(&*self.token) { let lifetime = self.get_lifetime(&*self.token); self.bump(); self.expect(&token::COLON); - self.expect_keyword("loop"); + self.expect_keyword(keywords::Loop); return self.parse_loop_expr(Some(lifetime)); - } else if self.eat_keyword("loop") { + } else if self.eat_keyword(keywords::Loop) { return self.parse_loop_expr(None); - } else if self.eat_keyword("match") { + } else if self.eat_keyword(keywords::Match) { return self.parse_match_expr(); - } else if self.eat_keyword("unsafe") { + } else if self.eat_keyword(keywords::Unsafe) { return self.parse_block_expr(lo, unsafe_blk); } else if *self.token == token::LBRACKET { self.bump(); @@ -1314,7 +1308,7 @@ pub impl Parser { } } hi = self.last_span.hi; - } else if self.eat_keyword("__log") { + } else if self.eat_keyword(keywords::__Log) { // LOG expression self.expect(&token::LPAREN); let lvl = self.parse_expr(); @@ -1323,14 +1317,14 @@ pub impl Parser { ex = expr_log(lvl, e); hi = self.span.hi; self.expect(&token::RPAREN); - } else if self.eat_keyword("return") { + } else if self.eat_keyword(keywords::Return) { // RETURN expression if can_begin_expr(&*self.token) { let e = self.parse_expr(); hi = e.span.hi; ex = expr_ret(Some(e)); } else { ex = expr_ret(None); } - } else if self.eat_keyword("break") { + } else if self.eat_keyword(keywords::Break) { // BREAK expression if self.token_is_lifetime(&*self.token) { let lifetime = self.get_lifetime(&*self.token); @@ -1340,14 +1334,14 @@ pub impl Parser { ex = expr_break(None); } hi = self.span.hi; - } else if self.eat_keyword("copy") { + } else if self.eat_keyword(keywords::Copy) { // COPY expression let e = self.parse_expr(); ex = expr_copy(e); hi = e.span.hi; } else if *self.token == token::MOD_SEP || - is_ident(&*self.token) && !self.is_keyword("true") && - !self.is_keyword("false") { + is_ident(&*self.token) && !self.is_keyword(keywords::True) && + !self.is_keyword(keywords::False) { let pth = self.parse_path_with_tps(true); // `!`, as an operator, is prefix, so we know this isn't that @@ -1827,7 +1821,7 @@ pub impl Parser { } } None => { - if as_prec > min_prec && self.eat_keyword("as") { + if as_prec > min_prec && self.eat_keyword(keywords::As) { let rhs = self.parse_ty(true); let _as = self.mk_expr(lhs.span.lo, rhs.span.hi, @@ -1901,7 +1895,7 @@ pub impl Parser { let thn = self.parse_block(); let mut els: Option<@expr> = None; let mut hi = thn.span.hi; - if self.eat_keyword("else") { + if self.eat_keyword(keywords::Else) { let elexpr = self.parse_else_expr(); els = Some(elexpr); hi = elexpr.span.hi; @@ -1968,7 +1962,7 @@ pub impl Parser { } fn parse_else_expr(&self) -> @expr { - if self.eat_keyword("if") { + if self.eat_keyword(keywords::If) { return self.parse_if_expr(); } else { let blk = self.parse_block(); @@ -2082,7 +2076,7 @@ pub impl Parser { fn looking_at_record_literal(&self) -> bool { let lookahead = self.look_ahead(1); *self.token == token::LBRACE && - (self.token_is_keyword("mut", &lookahead) || + (token::is_keyword(keywords::Mut, &lookahead) || (is_plain_ident(&lookahead) && self.look_ahead(2) == token::COLON)) } @@ -2095,7 +2089,7 @@ pub impl Parser { while *self.token != token::RBRACE { let pats = self.parse_pats(); let mut guard = None; - if self.eat_keyword("if") { guard = Some(self.parse_expr()); } + if self.eat_keyword(keywords::If) { guard = Some(self.parse_expr()); } self.expect(&token::FAT_ARROW); let expr = self.parse_expr_res(RESTRICT_STMT_EXPR); @@ -2384,8 +2378,8 @@ pub impl Parser { } ref tok => { if !is_ident_or_path(tok) - || self.is_keyword("true") - || self.is_keyword("false") + || self.is_keyword(keywords::True) + || self.is_keyword(keywords::False) { // Parse an expression pattern or exp .. exp. // @@ -2404,11 +2398,11 @@ pub impl Parser { } else { pat = pat_lit(val); } - } else if self.eat_keyword("ref") { + } else if self.eat_keyword(keywords::Ref) { // parse ref pat let mutbl = self.parse_mutability(); pat = self.parse_pat_ident(refutable, bind_by_ref(mutbl)); - } else if self.eat_keyword("copy") { + } else if self.eat_keyword(keywords::Copy) { // parse copy pat pat = self.parse_pat_ident(refutable, bind_by_copy); } else { @@ -2558,7 +2552,7 @@ pub impl Parser { // parse a "let" stmt fn parse_let(&self) -> @decl { - let is_mutbl = self.eat_keyword("mut"); + let is_mutbl = self.eat_keyword(keywords::Mut); let lo = self.span.lo; let mut locals = ~[self.parse_local(is_mutbl)]; while self.eat(&token::COMMA) { @@ -2572,7 +2566,7 @@ pub impl Parser { pr: visibility, attrs: ~[attribute]) -> @struct_field { let lo = self.span.lo; - if self.eat_keyword("mut") { + if self.eat_keyword(keywords::Mut) { // Do nothing, for backwards compatibility. // XXX: Remove after snapshot. } @@ -2604,13 +2598,13 @@ pub impl Parser { } let lo = self.span.lo; - if self.is_keyword("let") { + if self.is_keyword(keywords::Let) { check_expected_item(self, item_attrs); - self.expect_keyword("let"); + self.expect_keyword(keywords::Let); let decl = self.parse_let(); return @spanned(lo, decl.span.hi, stmt_decl(decl, self.get_id())); } else if is_ident(&*self.token) - && !self.is_any_keyword(© *self.token) + && !token::is_any_keyword(self.token) && self.look_ahead(1) == token::NOT { // parse a macro invocation. Looks like there's serious // overlap here; if this clause doesn't catch it (and it @@ -2690,7 +2684,7 @@ pub impl Parser { maybe_whole!(self, nt_block); let lo = self.span.lo; - if self.eat_keyword("unsafe") { + if self.eat_keyword(keywords::Unsafe) { self.obsolete(copy *self.span, ObsoleteUnsafeBlock); } self.expect(&token::LBRACE); @@ -2705,7 +2699,7 @@ pub impl Parser { maybe_whole!(pair_empty self, nt_block); let lo = self.span.lo; - if self.eat_keyword("unsafe") { + if self.eat_keyword(keywords::Unsafe) { self.obsolete(copy *self.span, ObsoleteUnsafeBlock); } self.expect(&token::LBRACE); @@ -2849,10 +2843,10 @@ pub impl Parser { } fn parse_optional_purity(&self) -> ast::purity { - if self.eat_keyword("pure") { + if self.eat_keyword(keywords::Pure) { self.obsolete(*self.last_span, ObsoletePurity); ast::impure_fn - } else if self.eat_keyword("unsafe") { + } else if self.eat_keyword(keywords::Unsafe) { ast::unsafe_fn } else { ast::impure_fn @@ -2860,7 +2854,7 @@ pub impl Parser { } fn parse_optional_onceness(&self) -> ast::Onceness { - if self.eat_keyword("once") { ast::Once } else { ast::Many } + if self.eat_keyword(keywords::Once) { ast::Once } else { ast::Many } } // matches optbounds = ( ( : ( boundseq )? )? ) @@ -3023,10 +3017,10 @@ pub impl Parser { p: &Parser ) -> ast::explicit_self_ { // We need to make sure it isn't a mode or a type - if p.token_is_keyword("self", &p.look_ahead(1)) || - ((p.token_is_keyword("const", &p.look_ahead(1)) || - p.token_is_keyword("mut", &p.look_ahead(1))) && - p.token_is_keyword("self", &p.look_ahead(2))) { + if token::is_keyword(keywords::Self, &p.look_ahead(1)) || + ((token::is_keyword(keywords::Const, &p.look_ahead(1)) || + token::is_keyword(keywords::Mut, &p.look_ahead(1))) && + token::is_keyword(keywords::Self, &p.look_ahead(2))) { p.bump(); let mutability = p.parse_mutability(); @@ -3047,25 +3041,25 @@ pub impl Parser { // // We already know that the current token is `&`. - if (this.token_is_keyword("self", &this.look_ahead(1))) { + if (token::is_keyword(keywords::Self, &this.look_ahead(1))) { this.bump(); this.expect_self_ident(); sty_region(None, m_imm) } else if (this.token_is_mutability(&this.look_ahead(1)) && - this.token_is_keyword("self", &this.look_ahead(2))) { + token::is_keyword(keywords::Self, &this.look_ahead(2))) { this.bump(); let mutability = this.parse_mutability(); this.expect_self_ident(); sty_region(None, mutability) } else if (this.token_is_lifetime(&this.look_ahead(1)) && - this.token_is_keyword("self", &this.look_ahead(2))) { + token::is_keyword(keywords::Self, &this.look_ahead(2))) { this.bump(); let lifetime = @this.parse_lifetime(); this.expect_self_ident(); sty_region(Some(lifetime), m_imm) } else if (this.token_is_lifetime(&this.look_ahead(1)) && this.token_is_mutability(&this.look_ahead(2)) && - this.token_is_keyword("self", &this.look_ahead(3))) { + token::is_keyword(keywords::Self, &this.look_ahead(3))) { this.bump(); let lifetime = @this.parse_lifetime(); let mutability = this.parse_mutability(); @@ -3274,7 +3268,7 @@ pub impl Parser { let mut ty = self.parse_ty(false); // Parse traits, if necessary. - let opt_trait = if could_be_trait && self.eat_keyword("for") { + let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) { // New-style trait. Reinterpret the type as a trait. let opt_trait_ref = match ty.node { ty_path(path, node_id) => { @@ -3449,11 +3443,11 @@ pub impl Parser { return ~[]; } - if self.eat_keyword("priv") { + if self.eat_keyword(keywords::Priv) { return ~[self.parse_single_struct_field(private, attrs)] } - if self.eat_keyword("pub") { + if self.eat_keyword(keywords::Pub) { return ~[self.parse_single_struct_field(public, attrs)]; } @@ -3466,13 +3460,13 @@ pub impl Parser { // parse visiility: PUB, PRIV, or nothing fn parse_visibility(&self) -> visibility { - if self.eat_keyword("pub") { public } - else if self.eat_keyword("priv") { private } + if self.eat_keyword(keywords::Pub) { public } + else if self.eat_keyword(keywords::Priv) { private } else { inherited } } fn parse_staticness(&self) -> bool { - if self.eat_keyword("static") { + if self.eat_keyword(keywords::Static) { self.obsolete(*self.last_span, ObsoleteStaticMethod); true } else { @@ -3692,10 +3686,10 @@ pub impl Parser { let lo = self.span.lo; // XXX: Obsolete; remove after snap. - if self.eat_keyword("const") { + if self.eat_keyword(keywords::Const) { self.obsolete(*self.last_span, ObsoleteConstItem); } else { - self.expect_keyword("static"); + self.expect_keyword(keywords::Static); } let ident = self.parse_ident(); @@ -3713,14 +3707,14 @@ pub impl Parser { // parse safe/unsafe and fn fn parse_fn_purity(&self) -> purity { - if self.eat_keyword("fn") { impure_fn } - else if self.eat_keyword("pure") { + if self.eat_keyword(keywords::Fn) { impure_fn } + else if self.eat_keyword(keywords::Pure) { self.obsolete(*self.last_span, ObsoletePurity); - self.expect_keyword("fn"); + self.expect_keyword(keywords::Fn); // NB: We parse this as impure for bootstrapping purposes. impure_fn - } else if self.eat_keyword("unsafe") { - self.expect_keyword("fn"); + } else if self.eat_keyword(keywords::Unsafe) { + self.expect_keyword(keywords::Fn); unsafe_fn } else { self.unexpected(); } @@ -3762,9 +3756,9 @@ pub impl Parser { items_allowed: bool) -> item_or_view_item { let mut must_be_named_mod = false; - if self.is_keyword("mod") { + if self.is_keyword(keywords::Mod) { must_be_named_mod = true; - self.expect_keyword("mod"); + self.expect_keyword(keywords::Mod); } else if *self.token != token::LBRACE { self.span_fatal( copy *self.span, @@ -4049,7 +4043,7 @@ pub impl Parser { let visibility = self.parse_visibility(); // must be a view item: - if self.eat_keyword("use") { + if self.eat_keyword(keywords::Use) { // USE ITEM (iovi_view_item) let view_item = self.parse_use(); self.expect(&token::SEMI); @@ -4061,10 +4055,10 @@ pub impl Parser { }); } // either a view item or an item: - if self.eat_keyword("extern") { + if self.eat_keyword(keywords::Extern) { let opt_abis = self.parse_opt_abis(); - if self.eat_keyword("fn") { + if self.eat_keyword(keywords::Fn) { // EXTERN FUNCTION ITEM let abis = opt_abis.get_or_default(AbiSet::C()); let (ident, item_, extra_attrs) = @@ -4080,11 +4074,11 @@ pub impl Parser { } } // the rest are all guaranteed to be items: - if (self.is_keyword("const") || - (self.is_keyword("static") && - !self.token_is_keyword("fn", &self.look_ahead(1)))) { + if (self.is_keyword(keywords::Const) || + (self.is_keyword(keywords::Static) && + !token::is_keyword(keywords::Fn, &self.look_ahead(1)))) { // CONST / STATIC ITEM - if self.is_keyword("const") { + if self.is_keyword(keywords::Const) { self.obsolete(*self.span, ObsoleteConstItem); } self.bump(); @@ -4093,7 +4087,7 @@ pub impl Parser { visibility, maybe_append(attrs, extra_attrs))); } - if self.is_keyword("fn") && + if self.is_keyword(keywords::Fn) && !self.fn_expr_lookahead(self.look_ahead(1u)) { // FUNCTION ITEM self.bump(); @@ -4103,28 +4097,28 @@ pub impl Parser { visibility, maybe_append(attrs, extra_attrs))); } - if self.eat_keyword("pure") { + if self.eat_keyword(keywords::Pure) { // PURE FUNCTION ITEM (obsolete) self.obsolete(*self.last_span, ObsoletePurity); - self.expect_keyword("fn"); + self.expect_keyword(keywords::Fn); let (ident, item_, extra_attrs) = self.parse_item_fn(impure_fn, AbiSet::Rust()); return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs))); } - if self.is_keyword("unsafe") + if self.is_keyword(keywords::Unsafe) && self.look_ahead(1u) != token::LBRACE { // UNSAFE FUNCTION ITEM self.bump(); - self.expect_keyword("fn"); + self.expect_keyword(keywords::Fn); let (ident, item_, extra_attrs) = self.parse_item_fn(unsafe_fn, AbiSet::Rust()); return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs))); } - if self.eat_keyword("mod") { + if self.eat_keyword(keywords::Mod) { // MODULE ITEM let (ident, item_, extra_attrs) = self.parse_item_mod(/*bad*/ copy attrs); @@ -4132,28 +4126,28 @@ pub impl Parser { visibility, maybe_append(attrs, extra_attrs))); } - if self.eat_keyword("type") { + if self.eat_keyword(keywords::Type) { // TYPE ITEM let (ident, item_, extra_attrs) = self.parse_item_type(); return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs))); } - if self.eat_keyword("enum") { + if self.eat_keyword(keywords::Enum) { // ENUM ITEM let (ident, item_, extra_attrs) = self.parse_item_enum(); return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs))); } - if self.eat_keyword("trait") { + if self.eat_keyword(keywords::Trait) { // TRAIT ITEM let (ident, item_, extra_attrs) = self.parse_item_trait(); return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_, visibility, maybe_append(attrs, extra_attrs))); } - if self.eat_keyword("impl") { + if self.eat_keyword(keywords::Impl) { // IMPL ITEM let (ident, item_, extra_attrs) = self.parse_item_impl(visibility); @@ -4161,7 +4155,7 @@ pub impl Parser { visibility, maybe_append(attrs, extra_attrs))); } - if self.eat_keyword("struct") { + if self.eat_keyword(keywords::Struct) { // STRUCT ITEM let (ident, item_, extra_attrs) = self.parse_item_struct(); return iovi_item(self.mk_item(lo, self.last_span.hi, ident, item_, @@ -4182,13 +4176,13 @@ pub impl Parser { let visibility = self.parse_visibility(); - if (self.is_keyword("const") || self.is_keyword("static")) { + if (self.is_keyword(keywords::Const) || self.is_keyword(keywords::Static)) { // FOREIGN CONST ITEM let item = self.parse_item_foreign_const(visibility, attrs); return iovi_foreign_item(item); } - if (self.is_keyword("fn") || self.is_keyword("pure") || - self.is_keyword("unsafe")) { + if (self.is_keyword(keywords::Fn) || self.is_keyword(keywords::Pure) || + self.is_keyword(keywords::Unsafe)) { // FOREIGN FUNCTION ITEM let item = self.parse_item_foreign_fn(attrs); return iovi_foreign_item(item); @@ -4204,7 +4198,7 @@ pub impl Parser { lo : BytePos, visibility : visibility ) -> item_or_view_item { - if macros_allowed && !self.is_any_keyword(© *self.token) + if macros_allowed && !token::is_any_keyword(self.token) && self.look_ahead(1) == token::NOT && (is_plain_ident(&self.look_ahead(2)) || self.look_ahead(2) == token::LPAREN @@ -4379,16 +4373,16 @@ pub impl Parser { fn is_view_item(&self) -> bool { let tok, next_tok; - if !self.is_keyword("pub") && !self.is_keyword("priv") { + if !self.is_keyword(keywords::Pub) && !self.is_keyword(keywords::Priv) { tok = copy *self.token; next_tok = self.look_ahead(1); } else { tok = self.look_ahead(1); next_tok = self.look_ahead(2); }; - self.token_is_keyword("use", &tok) - || (self.token_is_keyword("extern", &tok) && - self.token_is_keyword("mod", &next_tok)) + token::is_keyword(keywords::Use, &tok) + || (token::is_keyword(keywords::Extern, &tok) && + token::is_keyword(keywords::Mod, &next_tok)) } // parse a view item. @@ -4398,10 +4392,10 @@ pub impl Parser { vis: visibility ) -> @view_item { let lo = self.span.lo; - let node = if self.eat_keyword("use") { + let node = if self.eat_keyword(keywords::Use) { self.parse_use() - } else if self.eat_keyword("extern") { - self.expect_keyword("mod"); + } else if self.eat_keyword(keywords::Extern) { + self.expect_keyword(keywords::Mod); let ident = self.parse_ident(); let metadata = self.parse_optional_meta(); view_item_extern_mod(ident, metadata, self.get_id()) diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 1153c361e69fa..56b1ed5d5c7f8 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -17,7 +17,6 @@ use util::interner::StrInterner; use util::interner; use core::cmp::Equiv; -use core::hashmap::HashSet; use core::to_bytes; #[deriving(Encodable, Decodable, Eq)] @@ -452,6 +451,45 @@ fn mk_fresh_ident_interner() -> @ident_interner { "__field__", // 32 "C", // 33 "Self", // 34 + + "as", // 35 + "break", // 36 + "const", // 37 + "copy", // 38 + "do", // 39 + "drop", // 40 + "else", // 41 + "enum", // 42 + "extern", // 43 + "false", // 44 + "fn", // 45 + "for", // 46 + "if", // 47 + "impl", // 48 + "let", // 49 + "__log", // 50 + "loop", // 51 + "match", // 52 + "mod", // 53 + "mut", // 54 + "once", // 55 + "priv", // 56 + "pub", // 57 + "pure", // 58 + "ref", // 59 + "return", // 60 + "static", // 29 -- also a special ident + "self", // 8 -- also a special ident + "struct", // 61 + "super", // 62 + "true", // 63 + "trait", // 64 + "type", // 65 + "unsafe", // 66 + "use", // 67 + "while", // 68 + + "be", // 69 ]; @ident_interner { @@ -495,61 +533,134 @@ pub fn intern(str : &str) -> ast::ident { /** * All the valid words that have meaning in the Rust language. * - * Rust keywords are either 'temporary', 'strict' or 'reserved'. Temporary - * keywords are contextual and may be used as identifiers anywhere. They are - * expected to disappear from the grammar soon. Strict keywords may not + * Rust keywords are either 'strict' or 'reserved'. Strict keywords may not * appear as identifiers at all. Reserved keywords are not used anywhere in * the language and may not appear as identifiers. */ -pub fn keyword_table() -> HashSet<~str> { - let mut keywords = HashSet::new(); - let mut strict = strict_keyword_table(); - let mut reserved = reserved_keyword_table(); +pub mod keywords { + use ast::ident; + + pub enum Keyword { + // Strict keywords + As, + Break, + Const, + Copy, + Do, + Drop, + Else, + Enum, + Extern, + False, + Fn, + For, + If, + Impl, + Let, + __Log, + Loop, + Match, + Mod, + Mut, + Once, + Priv, + Pub, + Pure, + Ref, + Return, + Static, + Self, + Struct, + Super, + True, + Trait, + Type, + Unsafe, + Use, + While, + + // Reserved keywords + Be, + } - do strict.consume |word| { - keywords.insert(word); + pub impl Keyword { + fn to_ident(&self) -> ident { + match *self { + As => ident { repr: 35, ctxt: 0 }, + Break => ident { repr: 36, ctxt: 0 }, + Const => ident { repr: 37, ctxt: 0 }, + Copy => ident { repr: 38, ctxt: 0 }, + Do => ident { repr: 39, ctxt: 0 }, + Drop => ident { repr: 40, ctxt: 0 }, + Else => ident { repr: 41, ctxt: 0 }, + Enum => ident { repr: 42, ctxt: 0 }, + Extern => ident { repr: 43, ctxt: 0 }, + False => ident { repr: 44, ctxt: 0 }, + Fn => ident { repr: 45, ctxt: 0 }, + For => ident { repr: 46, ctxt: 0 }, + If => ident { repr: 47, ctxt: 0 }, + Impl => ident { repr: 48, ctxt: 0 }, + Let => ident { repr: 49, ctxt: 0 }, + __Log => ident { repr: 50, ctxt: 0 }, + Loop => ident { repr: 51, ctxt: 0 }, + Match => ident { repr: 52, ctxt: 0 }, + Mod => ident { repr: 53, ctxt: 0 }, + Mut => ident { repr: 54, ctxt: 0 }, + Once => ident { repr: 55, ctxt: 0 }, + Priv => ident { repr: 56, ctxt: 0 }, + Pub => ident { repr: 57, ctxt: 0 }, + Pure => ident { repr: 58, ctxt: 0 }, + Ref => ident { repr: 59, ctxt: 0 }, + Return => ident { repr: 60, ctxt: 0 }, + Static => ident { repr: 29, ctxt: 0 }, + Self => ident { repr: 8, ctxt: 0 }, + Struct => ident { repr: 61, ctxt: 0 }, + Super => ident { repr: 62, ctxt: 0 }, + True => ident { repr: 63, ctxt: 0 }, + Trait => ident { repr: 64, ctxt: 0 }, + Type => ident { repr: 65, ctxt: 0 }, + Unsafe => ident { repr: 66, ctxt: 0 }, + Use => ident { repr: 67, ctxt: 0 }, + While => ident { repr: 68, ctxt: 0 }, + Be => ident { repr: 69, ctxt: 0 }, + } + } } - do reserved.consume |word| { - keywords.insert(word); +} + +pub fn is_keyword(kw: keywords::Keyword, tok: &Token) -> bool { + match *tok { + token::IDENT(sid, false) => { kw.to_ident().repr == sid.repr } + _ => { false } } +} - keywords +pub fn is_any_keyword(tok: &Token) -> bool { + match *tok { + token::IDENT(sid, false) => match sid.repr { + 8 | 29 | 35 .. 69 => true, + _ => false, + }, + _ => false + } } -/// Full keywords. May not appear anywhere else. -pub fn strict_keyword_table() -> HashSet<~str> { - let mut words = HashSet::new(); - let keys = ~[ - ~"as", - ~"break", - ~"const", ~"copy", - ~"do", ~"drop", - ~"else", ~"enum", ~"extern", - ~"false", ~"fn", ~"for", - ~"if", ~"impl", - ~"let", ~"__log", ~"loop", - ~"match", ~"mod", ~"mut", - ~"once", - ~"priv", ~"pub", ~"pure", - ~"ref", ~"return", - ~"static", ~"self", ~"struct", ~"super", - ~"true", ~"trait", ~"type", - ~"unsafe", ~"use", - ~"while" - ]; - do vec::consume(keys) |_, w| { - words.insert(w); +pub fn is_strict_keyword(tok: &Token) -> bool { + match *tok { + token::IDENT(sid, false) => match sid.repr { + 8 | 29 | 35 .. 68 => true, + _ => false, + }, + _ => false, } - return words; } -pub fn reserved_keyword_table() -> HashSet<~str> { - let mut words = HashSet::new(); - let keys = ~[ - ~"be" - ]; - do vec::consume(keys) |_, s| { - words.insert(s); +pub fn is_reserved_keyword(tok: &Token) -> bool { + match *tok { + token::IDENT(sid, false) => match sid.repr { + 69 => true, + _ => false, + }, + _ => false, } - return words; } From 196851c4c92cf850d28bed749ab8c3034c04b9e3 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 22 May 2013 13:29:49 -0700 Subject: [PATCH 237/248] core: Fail with a better error message when list_dir gets an empty path (Yes, this did happen in real life...) --- src/libstd/os.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/libstd/os.rs b/src/libstd/os.rs index a82f1c9891696..e612c8cfeff8f 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -675,6 +675,11 @@ pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool { /// Lists the contents of a directory #[allow(non_implicitly_copyable_typarams)] pub fn list_dir(p: &Path) -> ~[~str] { + if p.components.is_empty() { + // Not sure what the right behavior is here, but this + // prevents a bounds check failure later + return ~[]; + } unsafe { #[cfg(target_os = "linux")] #[cfg(target_os = "android")] @@ -1596,6 +1601,12 @@ mod tests { } } + #[test] + fn list_dir_empty_path() { + let dirs = os::list_dir(&Path("")); + assert!(dirs.is_empty()); + } + #[test] fn path_is_dir() { assert!((os::path_is_dir(&Path(".")))); From a243ea39c3c155ada813c129081772ede8bce3e4 Mon Sep 17 00:00:00 2001 From: Tim Chevalier Date: Wed, 22 May 2013 18:57:24 -0700 Subject: [PATCH 238/248] testsuite: Add a test for listing the root directory... ...and don't treat Path("/") like Path(""). --- src/libstd/os.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/libstd/os.rs b/src/libstd/os.rs index e612c8cfeff8f..44acdd4d6173e 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -675,7 +675,7 @@ pub fn mkdir_recursive(p: &Path, mode: c_int) -> bool { /// Lists the contents of a directory #[allow(non_implicitly_copyable_typarams)] pub fn list_dir(p: &Path) -> ~[~str] { - if p.components.is_empty() { + if p.components.is_empty() && !p.is_absolute() { // Not sure what the right behavior is here, but this // prevents a bounds check failure later return ~[]; @@ -1607,6 +1607,20 @@ mod tests { assert!(dirs.is_empty()); } + #[test] + #[cfg(not(windows))] + fn list_dir_root() { + let dirs = os::list_dir(&Path("/")); + assert!(dirs.len() > 1); + } + #[test] + #[cfg(windows)] + fn list_dir_root() { + let dirs = os::list_dir(&Path("C:\\")); + assert!(dirs.len() > 1); + } + + #[test] fn path_is_dir() { assert!((os::path_is_dir(&Path(".")))); From 2c2346e3d4f999b95a56444d978c3ea792828263 Mon Sep 17 00:00:00 2001 From: James Miller Date: Sun, 26 May 2013 17:40:07 +1200 Subject: [PATCH 239/248] Mark &mut parameters as noalias --- src/librustc/middle/trans/base.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index f92acbaf5c68c..f14ea279c2d59 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -1694,7 +1694,20 @@ pub fn create_llargs_for_fn_args(cx: fn_ctxt, vec::from_fn(args.len(), |i| { unsafe { let arg_n = first_real_arg + i; - llvm::LLVMGetParam(cx.llfn, arg_n as c_uint) + let arg = &args[i]; + let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint); + + // Mark `&mut T` as no-alias, as the borrowck pass ensures it's true + match arg.ty.node { + ast::ty_rptr(_, mt) => { + if mt.mutbl == ast::m_mutbl { + llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint); + } + } + _ => {} + } + + llarg } }) } From d89a6ceb1b36e7460afece5b3392c8f24f7ef6ce Mon Sep 17 00:00:00 2001 From: Benjamin Herr Date: Thu, 23 May 2013 09:30:15 +0200 Subject: [PATCH 240/248] rustdoc: properly nest markup within enum variant lists (fixes #6605) This indents all but the first line of multi-line annotations for individual enum variants with four spaces so that pandoc will recognize everything as belonging to the same list item. Since that introduces `

` tags for some list items, I've gone ahead and inserted blank lines after each list item so that consistently get `

` tags for all `

  • `s documenting variants. It's a bit less compact now but still tolerable, I think. --- src/librustdoc/markdown_pass.rs | 39 ++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/src/librustdoc/markdown_pass.rs b/src/librustdoc/markdown_pass.rs index c6f5dbefb6add..97de4627d6b4c 100644 --- a/src/librustdoc/markdown_pass.rs +++ b/src/librustdoc/markdown_pass.rs @@ -451,9 +451,13 @@ fn write_variants( fn write_variant(ctxt: &Ctxt, doc: doc::VariantDoc) { assert!(doc.sig.is_some()); let sig = (&doc.sig).get(); + + // space out list items so they all end up within paragraph elements + ctxt.w.put_line(~""); + match copy doc.desc { Some(desc) => { - ctxt.w.put_line(fmt!("* `%s` - %s", sig, desc)); + ctxt.w.put_line(list_item_indent(fmt!("* `%s` - %s", sig, desc))); } None => { ctxt.w.put_line(fmt!("* `%s`", sig)); @@ -461,6 +465,18 @@ fn write_variant(ctxt: &Ctxt, doc: doc::VariantDoc) { } } +fn list_item_indent(item: &str) -> ~str { + let mut indented = ~[]; + for str::each_line_any(item) |line| { + indented.push(line); + } + + // separate markdown elements within `*` lists must be indented by four + // spaces, or they will escape the list context. indenting everything + // seems fine though. + str::connect_slices(indented, "\n ") +} + fn write_trait(ctxt: &Ctxt, doc: doc::TraitDoc) { write_common(ctxt, doc.desc(), doc.sections()); write_methods(ctxt, doc.methods); @@ -807,7 +823,9 @@ mod test { assert!(str::contains( markdown, "\n\n#### Variants\n\ + \n\ \n* `b` - test\ + \n\ \n* `c` - test\n\n")); } @@ -817,7 +835,24 @@ mod test { assert!(str::contains( markdown, "\n\n#### Variants\n\ + \n\ \n* `b`\ + \n\ + \n* `c`\n\n")); + } + + #[test] + fn should_write_variant_list_with_indent() { + let markdown = render( + ~"enum a { #[doc = \"line 1\\n\\nline 2\"] b, c }"); + assert!(str::contains( + markdown, + "\n\n#### Variants\n\ + \n\ + \n* `b` - line 1\ + \n \ + \n line 2\ + \n\ \n* `c`\n\n")); } @@ -827,7 +862,9 @@ mod test { assert!(str::contains( markdown, "\n\n#### Variants\n\ + \n\ \n* `b(int)`\ + \n\ \n* `c(int)` - a\n\n")); } From 9bb8077c1816853527fdb1bc6333e266d7ae80a6 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Sun, 26 May 2013 09:39:55 -0500 Subject: [PATCH 241/248] Add documentation for libstd/bool.rs. There was some before, but now we have a big header, as well as lots of individual bits of documentation. --- src/libstd/bool.rs | 213 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 194 insertions(+), 19 deletions(-) diff --git a/src/libstd/bool.rs b/src/libstd/bool.rs index 5ab7f838a57cc..532e470e595b7 100644 --- a/src/libstd/bool.rs +++ b/src/libstd/bool.rs @@ -8,45 +8,190 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Boolean logic +/*! + +The `bool` module contains useful code to help work with boolean values. + +A quick summary: + +## Trait implementations for `bool` + +Implementations of the following traits: + +* `FromStr` +* `Ord` +* `TotalOrd` +* `Eq` + +## Various functions to compare `bool`s + +All of the standard comparison functions one would expect: `and`, `eq`, `or`, +and more. + +Also, a few conversion functions: `to_bit` and `to_str`. + +Finally, some inquries into the nature of truth: `is_true` and `is_false`. + +*/ #[cfg(not(test))] use cmp::{Eq, Ord, TotalOrd, Ordering}; use option::{None, Option, Some}; use from_str::FromStr; -/// Negation / inverse +/** +* Negation of a boolean value. +* +* # Examples +* ~~~ +* rusti> core::bool::not(true) +* false +* ~~~ +* rusti> core::bool::not(false) +* true +* ~~~ +*/ pub fn not(v: bool) -> bool { !v } -/// Conjunction +/** +* Conjunction of two boolean values. +* +* # Examples +* ~~~ +* rusti> core::bool::and(true, false) +* false +* ~~~ +* rusti> core::bool::and(true, true) +* true +* ~~~ +*/ pub fn and(a: bool, b: bool) -> bool { a && b } -/// Disjunction +/** +* Disjunction of two boolean values. +* +* # Examples +* ~~~ +* rusti> core::bool::or(true, false) +* true +* ~~~ +* rusti> core::bool::or(false, false) +* false +* ~~~ +*/ pub fn or(a: bool, b: bool) -> bool { a || b } /** - * Exclusive or - * - * Identical to `or(and(a, not(b)), and(not(a), b))` - */ +* An 'exclusive or' of two boolean values. +* +* 'exclusive or' is identical to `or(and(a, not(b)), and(not(a), b))`. +* +* # Examples +* ~~~ +* rusti> core::bool::xor(true, false) +* true +* ~~~ +* rusti> core::bool::xor(true, true) +* false +* ~~~ +*/ pub fn xor(a: bool, b: bool) -> bool { (a && !b) || (!a && b) } -/// Implication in the logic, i.e. from `a` follows `b` +/** +* Implication between two boolean values. +* +* Implication is often phrased as 'if a then b.' +* +* 'if a then b' is equivalent to `!a || b`. +* +* # Examples +* ~~~ +* rusti> core::bool::implies(true, true) +* true +* ~~~ +* rusti> core::bool::implies(true, false) +* false +* ~~~ +*/ pub fn implies(a: bool, b: bool) -> bool { !a || b } -/// true if truth values `a` and `b` are indistinguishable in the logic +/** +* Equality between two boolean values. +* +* Two booleans are equal if they have the same value. +* +* # Examples +* ~~~ +* rusti> core::bool::eq(false, true) +* false +* ~~~ +* rusti> core::bool::eq(false, false) +* true +* ~~~ +*/ pub fn eq(a: bool, b: bool) -> bool { a == b } -/// true if truth values `a` and `b` are distinguishable in the logic +/** +* Non-equality between two boolean values. +* +* Two booleans are not equal if they have different values. +* +* # Examples +* ~~~ +* rusti> core::bool::ne(false, true) +* true +* ~~~ +* rusti> core::bool::ne(false, false) +* false +* ~~~ +*/ pub fn ne(a: bool, b: bool) -> bool { a != b } -/// true if `v` represents truth in the logic +/** +* Is a given boolean value true? +* +* # Examples +* ~~~ +* rusti> core::bool::is_true(true) +* true +* ~~~ +* rusti> core::bool::is_true(false) +* false +* ~~~ +*/ pub fn is_true(v: bool) -> bool { v } -/// true if `v` represents falsehood in the logic +/** +* Is a given boolean value false? +* +* # Examples +* ~~~ +* rusti> core::bool::is_false(false) +* true +* ~~~ +* rusti> core::bool::is_false(true) +* false +* ~~~ +*/ pub fn is_false(v: bool) -> bool { !v } -/// Parse logic value from `s` +/** +* Parse a `bool` from a `str`. +* +* Yields an `Option`, because `str` may or may not actually be parseable. +* +* # Examples +* ~~~ +* rusti> FromStr::from_str::("true") +* Some(true) +* ~~~ +* rusti> FromStr::from_str::("false") +* Some(false) +* ~~~ +* rusti> FromStr::from_str::("not even a boolean") +* None +* ~~~ +*/ impl FromStr for bool { fn from_str(s: &str) -> Option { match s { @@ -57,19 +202,49 @@ impl FromStr for bool { } } -/// Convert `v` into a string +/** +* Convert a `bool` to a `str`. +* +* # Examples +* ~~~ +* rusti> std::bool::to_str(true) +* "true" +* ~~~ +* rusti> std::bool::to_str(false) +* "false" +* ~~~ +*/ pub fn to_str(v: bool) -> ~str { if v { ~"true" } else { ~"false" } } /** - * Iterates over all truth values by passing them to `blk` in an unspecified - * order - */ +* Iterates over all truth values, passing them to the given block. +* +* There are no guarantees about the order values will be given. +* +* # Examples +* ~~~ +* do core::bool::all_values |x: bool| { +* println(core::bool::to_str(x)); +* } +* ~~~ +*/ pub fn all_values(blk: &fn(v: bool)) { blk(true); blk(false); } -/// converts truth value to an 8 bit byte +/** +* Convert a `bool` to a `u8`. +* +* # Examples +* ~~~ +* rusti> std::bool::to_bit(true) +* 1 +* ~~~ +* rusti> std::bool::to_bit(false) +* 0 +* ~~~ +*/ #[inline(always)] pub fn to_bit(v: bool) -> u8 { if v { 1u8 } else { 0u8 } } From 998cbbd7390c6472a5770687f93c7a18bf9dc59f Mon Sep 17 00:00:00 2001 From: ILyoan Date: Mon, 27 May 2013 13:58:27 +0900 Subject: [PATCH 242/248] update ctags define --- src/etc/ctags.rust | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/etc/ctags.rust b/src/etc/ctags.rust index e08db63d0c925..4654116bc4d2b 100644 --- a/src/etc/ctags.rust +++ b/src/etc/ctags.rust @@ -4,9 +4,7 @@ --regex-rust=/[ \t]*type[ \t]+([a-zA-Z0-9_]+)/\1/T,types/ --regex-rust=/[ \t]*enum[ \t]+([a-zA-Z0-9_]+)/\1/T,types/ --regex-rust=/[ \t]*struct[ \t]+([a-zA-Z0-9_]+)/\1/m,types/ ---regex-rust=/[ \t]*class[ \t]+([a-zA-Z0-9_]+)/\1/m,types/ --regex-rust=/[ \t]*mod[ \t]+([a-zA-Z0-9_]+)/\1/m,modules/ ---regex-rust=/[ \t]*const[ \t]+([a-zA-Z0-9_]+)/\1/m,consts/ +--regex-rust=/[ \t]*static[ \t]+([a-zA-Z0-9_]+)/\1/m,consts/ --regex-rust=/[ \t]*trait[ \t]+([a-zA-Z0-9_]+)/\1/m,traits/ --regex-rust=/[ \t]*impl[ \t]+([a-zA-Z0-9_]+)/\1/m,impls/ ---regex-rust=/[ \t]*impl[ \t]+of[ \t]([a-zA-Z0-9_]+)/\1/m,impls/ From 76c31217bee0f80b096b33d8a1b499f491d92c9f Mon Sep 17 00:00:00 2001 From: gareth Date: Sun, 12 May 2013 13:58:00 +0100 Subject: [PATCH 243/248] Refactor core::run in order to address many of the issues mentioned in #2625. This change makes the module more oriented around Process values instead of having to deal with process ids directly. Apart from issues mentioned in #2625, other changes include: - Changing the naming to be more consistent - Process/process is now used instead of a mixture of Program/program and Process/process. - More docs/tests. Some io/scheduler related issues remain (mentioned in #2625). --- src/compiletest/procsrv.rs | 85 +- src/libextra/workcache.rs | 2 +- src/libfuzzer/fuzzer.rc | 38 +- src/librust/rust.rc | 4 +- src/librustc/back/link.rs | 10 +- src/librustdoc/config.rs | 48 +- src/librustdoc/markdown_writer.rs | 55 +- src/librustpkg/rustpkg.rc | 8 +- .../testsuite/pass/src/fancy-lib/pkg.rs | 4 +- src/libstd/os.rs | 2 +- src/libstd/run.rs | 909 ++++++++++++------ src/test/run-pass/core-run-destroy.rs | 11 +- 12 files changed, 693 insertions(+), 483 deletions(-) diff --git a/src/compiletest/procsrv.rs b/src/compiletest/procsrv.rs index 2a4cd08c1242d..a059f97daab7c 100644 --- a/src/compiletest/procsrv.rs +++ b/src/compiletest/procsrv.rs @@ -10,8 +10,6 @@ use core::prelude::*; -use core::libc::c_int; -use core::run::spawn_process; use core::run; #[cfg(target_os = "win32")] @@ -38,86 +36,35 @@ fn target_env(lib_path: &str, prog: &str) -> ~[(~str,~str)] { #[cfg(target_os = "macos")] #[cfg(target_os = "freebsd")] fn target_env(_lib_path: &str, _prog: &str) -> ~[(~str,~str)] { - ~[] + os::env() } pub struct Result {status: int, out: ~str, err: ~str} -// FIXME (#2659): This code is duplicated in core::run::program_output pub fn run(lib_path: &str, prog: &str, args: &[~str], env: ~[(~str, ~str)], input: Option<~str>) -> Result { - let pipe_in = os::pipe(); - let pipe_out = os::pipe(); - let pipe_err = os::pipe(); - let pid = spawn_process(prog, args, - &Some(env + target_env(lib_path, prog)), - &None, pipe_in.in, pipe_out.out, pipe_err.out); - - os::close(pipe_in.in); - os::close(pipe_out.out); - os::close(pipe_err.out); - if pid == -1i32 { - os::close(pipe_in.out); - os::close(pipe_out.in); - os::close(pipe_err.in); - fail!(); - } + let env = env + target_env(lib_path, prog); + let mut proc = run::Process::new(prog, args, run::ProcessOptions { + env: Some(env.slice(0, env.len())), + dir: None, + in_fd: None, + out_fd: None, + err_fd: None + }); - writeclose(pipe_in.out, input); - let p = comm::PortSet::new(); - let ch = p.chan(); - do task::spawn_sched(task::SingleThreaded) || { - let errput = readclose(pipe_err.in); - ch.send((2, errput)); + for input.each |input| { + proc.input().write_str(*input); } - let ch = p.chan(); - do task::spawn_sched(task::SingleThreaded) || { - let output = readclose(pipe_out.in); - ch.send((1, output)); - } - let status = run::waitpid(pid); - let mut errs = ~""; - let mut outs = ~""; - let mut count = 2; - while count > 0 { - match p.recv() { - (1, s) => { - outs = s; - } - (2, s) => { - errs = s; - } - _ => { fail!() } - }; - count -= 1; - }; - return Result {status: status, out: outs, err: errs}; -} + let output = proc.finish_with_output(); -fn writeclose(fd: c_int, s: Option<~str>) { - if s.is_some() { - let writer = io::fd_writer(fd, false); - writer.write_str(s.get()); + Result { + status: output.status, + out: str::from_bytes(output.output), + err: str::from_bytes(output.error) } - - os::close(fd); } -fn readclose(fd: c_int) -> ~str { - unsafe { - // Copied from run::program_output - let file = os::fdopen(fd); - let reader = io::FILE_reader(file, false); - let mut buf = ~""; - while !reader.eof() { - let bytes = reader.read_bytes(4096u); - str::push_str(&mut buf, str::from_bytes(bytes)); - } - os::fclose(file); - return buf; - } -} diff --git a/src/libextra/workcache.rs b/src/libextra/workcache.rs index 3c10b3d2ca770..9df9ffd9465c2 100644 --- a/src/libextra/workcache.rs +++ b/src/libextra/workcache.rs @@ -415,7 +415,7 @@ fn test() { prep.declare_input("file", pth.to_str(), digest_file(&pth)); do prep.exec |_exe| { let out = Path("foo.o"); - run::run_program("gcc", [~"foo.c", ~"-o", out.to_str()]); + run::process_status("gcc", [~"foo.c", ~"-o", out.to_str()]); out.to_str() } }; diff --git a/src/libfuzzer/fuzzer.rc b/src/libfuzzer/fuzzer.rc index 3be5593793347..90a93a9e57cc1 100644 --- a/src/libfuzzer/fuzzer.rc +++ b/src/libfuzzer/fuzzer.rc @@ -412,20 +412,20 @@ pub fn check_whole_compiler(code: &str, pub fn removeIfExists(filename: &Path) { // So sketchy! assert!(!contains(filename.to_str(), " ")); - run::program_output("bash", [~"-c", ~"rm " + filename.to_str()]); + run::process_status("bash", [~"-c", ~"rm " + filename.to_str()]); } pub fn removeDirIfExists(filename: &Path) { // So sketchy! assert!(!contains(filename.to_str(), " ")); - run::program_output("bash", [~"-c", ~"rm -r " + filename.to_str()]); + run::process_status("bash", [~"-c", ~"rm -r " + filename.to_str()]); } pub fn check_running(exe_filename: &Path) -> happiness { - let p = run::program_output( + let p = run::process_output( "/Users/jruderman/scripts/timed_run_rust_program.py", [exe_filename.to_str()]); - let comb = p.out + ~"\n" + p.err; + let comb = str::from_bytes(p.output) + ~"\n" + str::from_bytes(p.error); if str::len(comb) > 1u { error!("comb comb comb: %?", comb); } @@ -461,33 +461,35 @@ pub fn check_running(exe_filename: &Path) -> happiness { } pub fn check_compiling(filename: &Path) -> happiness { - let p = run::program_output( - "/Users/jruderman/code/rust/build/x86_64-apple-darwin/\ - stage1/bin/rustc", + let p = run::process_output( + "/Users/jruderman/code/rust/build/x86_64-apple-darwin/stage1/bin/rustc", [filename.to_str()]); + let out = str::from_bytes(p.output); + let err = str::from_bytes(p.error); + //error!("Status: %d", p.status); if p.status == 0 { passed - } else if p.err != ~"" { - if contains(p.err, "error:") { + } else if !err.is_empty() { + if err.contains("error:") { cleanly_rejected(~"rejected with span_error") } else { - error!("Stderr: %?", p.err); + error!("Stderr: %?", err); failed(~"Unfamiliar error message") } - } else if contains(p.out, "Assertion") && contains(p.out, "failed") { - error!("Stdout: %?", p.out); + } else if out.contains("Assertion") && out.contains("failed") { + error!("Stdout: %?", out); failed(~"Looks like an llvm assertion failure") - } else if contains(p.out, "internal compiler error unimplemented") { + } else if out.contains("internal compiler error unimplemented") { known_bug(~"Something unimplemented") - } else if contains(p.out, "internal compiler error") { - error!("Stdout: %?", p.out); + } else if out.contains("internal compiler error") { + error!("Stdout: %?", out); failed(~"internal compiler error") } else { error!("%?", p.status); - error!("!Stdout: %?", p.out); + error!("!Stdout: %?", out); failed(~"What happened?") } } @@ -608,9 +610,7 @@ pub fn check_roundtrip_convergence(code: @~str, maxIters: uint) { error!("Did not converge after %u iterations!", i); write_file(&Path("round-trip-a.rs"), *oldv); write_file(&Path("round-trip-b.rs"), *newv); - run::run_program("diff", - [~"-w", ~"-u", ~"round-trip-a.rs", - ~"round-trip-b.rs"]); + run::process_status("diff", [~"-w", ~"-u", ~"round-trip-a.rs", ~"round-trip-b.rs"]); fail!("Mismatch"); } } diff --git a/src/librust/rust.rc b/src/librust/rust.rc index 6449958e09c0c..36246b7a9a14c 100644 --- a/src/librust/rust.rc +++ b/src/librust/rust.rc @@ -163,7 +163,7 @@ fn cmd_test(args: &[~str]) -> ValidUsage { let test_exec = Path(filename).filestem().unwrap() + "test~"; invoke("rustc", &[~"--test", filename.to_owned(), ~"-o", test_exec.to_owned()], rustc::main); - let exit_code = run::run_program(~"./" + test_exec, []); + let exit_code = run::process_status(~"./" + test_exec, []); Valid(exit_code) } _ => Invalid @@ -176,7 +176,7 @@ fn cmd_run(args: &[~str]) -> ValidUsage { let exec = Path(filename).filestem().unwrap() + "~"; invoke("rustc", &[filename.to_owned(), ~"-o", exec.to_owned()], rustc::main); - let exit_code = run::run_program(~"./"+exec, prog_args); + let exit_code = run::process_status(~"./"+exec, prog_args); Valid(exit_code) } _ => Invalid diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index e230d839879e6..0dddbf395e024 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -403,14 +403,14 @@ pub mod write { cc_args.push(object.to_str()); cc_args.push(assembly.to_str()); - let prog = run::program_output(cc_prog, cc_args); + let prog = run::process_output(cc_prog, cc_args); if prog.status != 0 { sess.err(fmt!("building with `%s` failed with code %d", cc_prog, prog.status)); sess.note(fmt!("%s arguments: %s", cc_prog, str::connect(cc_args, " "))); - sess.note(prog.err + prog.out); + sess.note(str::from_bytes(prog.error + prog.output)); sess.abort_if_errors(); } } @@ -817,19 +817,19 @@ pub fn link_binary(sess: Session, let cc_args = link_args(sess, obj_filename, out_filename, lm); debug!("%s link args: %s", cc_prog, str::connect(cc_args, " ")); // We run 'cc' here - let prog = run::program_output(cc_prog, cc_args); + let prog = run::process_output(cc_prog, cc_args); if 0 != prog.status { sess.err(fmt!("linking with `%s` failed with code %d", cc_prog, prog.status)); sess.note(fmt!("%s arguments: %s", cc_prog, str::connect(cc_args, " "))); - sess.note(prog.err + prog.out); + sess.note(str::from_bytes(prog.error + prog.output)); sess.abort_if_errors(); } // Clean up on Darwin if sess.targ_cfg.os == session::os_macos { - run::run_program("dsymutil", [output.to_str()]); + run::process_status("dsymutil", [output.to_str()]); } // Remove the temporary object file if we aren't saving temps diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index 7366aca4c4f6f..603ce0de67d93 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -12,7 +12,7 @@ use core::prelude::*; use core::cell::Cell; use core::run; -use core::run::ProgramOutput; +use core::run::ProcessOutput; use core::result::Result; use extra::getopts; @@ -89,27 +89,27 @@ pub fn default_config(input_crate: &Path) -> Config { } } -type Process = ~fn((&str), (&[~str])) -> ProgramOutput; +type Process = ~fn((&str), (&[~str])) -> ProcessOutput; -pub fn mock_program_output(_prog: &str, _args: &[~str]) -> ProgramOutput { - ProgramOutput { +pub fn mock_process_output(_prog: &str, _args: &[~str]) -> ProcessOutput { + ProcessOutput { status: 0, - out: ~"", - err: ~"" + output: ~[], + error: ~[] } } -pub fn program_output(prog: &str, args: &[~str]) -> ProgramOutput { - run::program_output(prog, args) +pub fn process_output(prog: &str, args: &[~str]) -> ProcessOutput { + run::process_output(prog, args) } pub fn parse_config(args: &[~str]) -> Result { - parse_config_(args, program_output) + parse_config_(args, process_output) } pub fn parse_config_( args: &[~str], - program_output: Process + process_output: Process ) -> Result { let args = args.tail(); let opts = vec::unzip(opts()).first(); @@ -117,7 +117,7 @@ pub fn parse_config_( Ok(matches) => { if matches.free.len() == 1 { let input_crate = Path(*matches.free.head()); - config_from_opts(&input_crate, &matches, program_output) + config_from_opts(&input_crate, &matches, process_output) } else if matches.free.is_empty() { Err(~"no crates specified") } else { @@ -133,7 +133,7 @@ pub fn parse_config_( fn config_from_opts( input_crate: &Path, matches: &getopts::Matches, - program_output: Process + process_output: Process ) -> Result { let config = default_config(input_crate); @@ -175,11 +175,11 @@ fn config_from_opts( } } }; - let program_output = Cell(program_output); + let process_output = Cell(process_output); let result = do result::chain(result) |config| { let pandoc_cmd = getopts::opt_maybe_str(matches, opt_pandoc_cmd()); let pandoc_cmd = maybe_find_pandoc( - &config, pandoc_cmd, program_output.take()); + &config, pandoc_cmd, process_output.take()); do result::chain(pandoc_cmd) |pandoc_cmd| { result::Ok(Config { pandoc_cmd: pandoc_cmd, @@ -209,7 +209,7 @@ fn parse_output_style(output_style: &str) -> Result { pub fn maybe_find_pandoc( config: &Config, maybe_pandoc_cmd: Option<~str>, - program_output: Process + process_output: Process ) -> Result, ~str> { if config.output_format != PandocHtml { return result::Ok(maybe_pandoc_cmd); @@ -228,7 +228,7 @@ pub fn maybe_find_pandoc( }; let pandoc = do vec::find(possible_pandocs) |pandoc| { - let output = program_output(*pandoc, [~"--version"]); + let output = process_output(*pandoc, [~"--version"]); debug!("testing pandoc cmd %s: %?", *pandoc, output); output.status == 0 }; @@ -244,10 +244,10 @@ pub fn maybe_find_pandoc( mod test { use core::prelude::*; use config::*; - use core::run::ProgramOutput; + use core::run::ProcessOutput; fn parse_config(args: &[~str]) -> Result { - parse_config_(args, mock_program_output) + parse_config_(args, mock_process_output) } #[test] @@ -256,10 +256,10 @@ mod test { output_format: PandocHtml, .. default_config(&Path("test")) }; - let mock_program_output: ~fn(&str, &[~str]) -> ProgramOutput = |_, _| { - ProgramOutput { status: 0, out: ~"pandoc 1.8.2.1", err: ~"" } + let mock_process_output: ~fn(&str, &[~str]) -> ProcessOutput = |_, _| { + ProcessOutput { status: 0, output: "pandoc 1.8.2.1".to_bytes(), error: ~[] } }; - let result = maybe_find_pandoc(&config, None, mock_program_output); + let result = maybe_find_pandoc(&config, None, mock_process_output); assert!(result == result::Ok(Some(~"pandoc"))); } @@ -269,10 +269,10 @@ mod test { output_format: PandocHtml, .. default_config(&Path("test")) }; - let mock_program_output: ~fn(&str, &[~str]) -> ProgramOutput = |_, _| { - ProgramOutput { status: 1, out: ~"", err: ~"" } + let mock_process_output: ~fn(&str, &[~str]) -> ProcessOutput = |_, _| { + ProcessOutput { status: 1, output: ~[], error: ~[] } }; - let result = maybe_find_pandoc(&config, None, mock_program_output); + let result = maybe_find_pandoc(&config, None, mock_process_output); assert!(result == result::Err(~"couldn't find pandoc")); } diff --git a/src/librustdoc/markdown_writer.rs b/src/librustdoc/markdown_writer.rs index 3e90c1a53f4a5..8149dc61fb475 100644 --- a/src/librustdoc/markdown_writer.rs +++ b/src/librustdoc/markdown_writer.rs @@ -14,7 +14,6 @@ use config; use doc::ItemUtils; use doc; -use core::libc; use core::run; use core::comm::*; use extra::future; @@ -105,60 +104,20 @@ fn pandoc_writer( debug!("pandoc cmd: %s", pandoc_cmd); debug!("pandoc args: %s", str::connect(pandoc_args, " ")); - let pipe_in = os::pipe(); - let pipe_out = os::pipe(); - let pipe_err = os::pipe(); - let pid = run::spawn_process( - pandoc_cmd, pandoc_args, &None, &None, - pipe_in.in, pipe_out.out, pipe_err.out); + let mut proc = run::Process::new(pandoc_cmd, pandoc_args, run::ProcessOptions::new()); - let writer = io::fd_writer(pipe_in.out, false); - writer.write_str(markdown); + proc.input().write_str(markdown); + let output = proc.finish_with_output(); - os::close(pipe_in.in); - os::close(pipe_out.out); - os::close(pipe_err.out); - os::close(pipe_in.out); - - let (stdout_po, stdout_ch) = comm::stream(); - do task::spawn_sched(task::SingleThreaded) || { - stdout_ch.send(readclose(pipe_out.in)); - } - - let (stderr_po, stderr_ch) = comm::stream(); - do task::spawn_sched(task::SingleThreaded) || { - stderr_ch.send(readclose(pipe_err.in)); - } - let stdout = stdout_po.recv(); - let stderr = stderr_po.recv(); - - let status = run::waitpid(pid); - debug!("pandoc result: %i", status); - if status != 0 { - error!("pandoc-out: %s", stdout); - error!("pandoc-err: %s", stderr); + debug!("pandoc result: %i", output.status); + if output.status != 0 { + error!("pandoc-out: %s", str::from_bytes(output.output)); + error!("pandoc-err: %s", str::from_bytes(output.error)); fail!("pandoc failed"); } } } -fn readclose(fd: libc::c_int) -> ~str { - // Copied from run::program_output - unsafe { - let file = os::fdopen(fd); - let reader = io::FILE_reader(file, false); - let buf = io::with_bytes_writer(|writer| { - let mut bytes = [0, ..4096]; - while !reader.eof() { - let nread = reader.read(bytes, bytes.len()); - writer.write(bytes.slice(0, nread).to_owned()); - } - }); - os::fclose(file); - str::from_bytes(buf) - } -} - fn generic_writer(process: ~fn(markdown: ~str)) -> Writer { let (po, ch) = stream::(); do task::spawn || { diff --git a/src/librustpkg/rustpkg.rc b/src/librustpkg/rustpkg.rc index 79e978c01d1bb..a419bffece72b 100644 --- a/src/librustpkg/rustpkg.rc +++ b/src/librustpkg/rustpkg.rc @@ -131,17 +131,17 @@ impl<'self> PkgScript<'self> { &exe, @copy os::args()[0], driver::cu_everything); debug!("Running program: %s %s %s", exe.to_str(), root.to_str(), what); - let status = run::run_program(exe.to_str(), [root.to_str(), what]); + let status = run::process_status(exe.to_str(), [root.to_str(), what]); if status != 0 { return (~[], status); } else { debug!("Running program (configs): %s %s %s", exe.to_str(), root.to_str(), "configs"); - let output = run::program_output(exe.to_str(), [root.to_str(), ~"configs"]); + let output = run::process_output(exe.to_str(), [root.to_str(), ~"configs"]); // Run the configs() function to get the configs let mut cfgs = ~[]; - for str::each_word(output.out) |w| { + for str::each_word(str::from_bytes(output.output)) |w| { cfgs.push(w.to_owned()); } (cfgs, output.status) @@ -551,7 +551,7 @@ impl PkgSrc { let url = fmt!("https://%s", self.id.remote_path.to_str()); util::note(fmt!("git clone %s %s", url, local.to_str())); - if run::program_output("git", [~"clone", copy url, local.to_str()]).status != 0 { + if run::process_output("git", [~"clone", copy url, local.to_str()]).status != 0 { util::note(fmt!("fetching %s failed: can't clone repository", url)); return false; } diff --git a/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs b/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs index eeaa0f68ed531..2d3a75d9197bf 100644 --- a/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs +++ b/src/librustpkg/testsuite/pass/src/fancy-lib/pkg.rs @@ -23,6 +23,6 @@ pub fn main() { file.write_str("pub fn wheeeee() { for [1, 2, 3].each() |_| { assert!(true); } }"); // now compile the crate itself - run::run_program("rustc", ~[~"src/fancy-lib/fancy-lib.rs", ~"--lib", - ~"-o", out_path.push(~"fancy_lib").to_str()]); + run::process_status("rustc", [~"src/fancy-lib/fancy-lib.rs", ~"--lib", ~"-o", + out_path.push(~"fancy_lib").to_str()]); } \ No newline at end of file diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 44acdd4d6173e..49e3c17be1b3e 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -1671,7 +1671,7 @@ mod tests { fail!("%s doesn't exist", in.to_str()); } assert!((rs)); - let rslt = run::run_program("diff", [in.to_str(), out.to_str()]); + let rslt = run::process_status("diff", [in.to_str(), out.to_str()]); assert_eq!(rslt, 0); assert_eq!(out.get_mode(), in_mode); assert!((remove_file(&in))); diff --git a/src/libstd/run.rs b/src/libstd/run.rs index 02757ab489903..1956f4baba646 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -8,7 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Process spawning +//! Process spawning. + use cast; use io; use libc; @@ -22,80 +23,367 @@ use str; use task; use vec; -/// A value representing a child process -pub struct Program { +/** + * A value representing a child process. + * + * The lifetime of this value is linked to the lifetime of the actual + * process - the Process destructor calls self.finish() which waits + * for the process to terminate. + */ +pub struct Process { + + /// The unique id of the process (this should never be negative). priv pid: pid_t, + + /** + * A handle to the process - on unix this will always be NULL, but on + * windows it will be a HANDLE to the process, which will prevent the + * pid being re-used until the handle is closed. + */ priv handle: *(), - priv in_fd: c_int, - priv out_file: *libc::FILE, - priv err_file: *libc::FILE, - priv finished: bool, + + /// Some(fd), or None when stdin is being redirected from a fd not created by Process::new. + priv input: Option, + + /// Some(fd), or None when stdout is being redirected to a fd not created by Process::new. + priv output: Option<*libc::FILE>, + + /// Some(fd), or None when stderr is being redirected to a fd not created by Process::new. + priv error: Option<*libc::FILE>, + + /// None until finish() is called. + priv exit_code: Option, } -impl Drop for Program { - fn finalize(&self) { - // FIXME #4943: transmute is bad. - let mut_self: &mut Program = unsafe { cast::transmute(self) }; +/// Options that can be given when starting a Process. +pub struct ProcessOptions<'self> { - mut_self.finish(); - mut_self.close_outputs(); - free_handle(self.handle); + /** + * If this is None then the new process will have the same initial + * environment as the parent process. + * + * If this is Some(vec-of-names-and-values) then the new process will + * have an environment containing the given named values only. + */ + env: Option<&'self [(~str, ~str)]>, + + /** + * If this is None then the new process will use the same initial working + * directory as the parent process. + * + * If this is Some(path) then the new process will use the given path + * for its initial working directory. + */ + dir: Option<&'self Path>, + + /** + * If this is None then a new pipe will be created for the new process's + * input and Process.input() will provide a Writer to write to this pipe. + * + * If this is Some(file-descriptor) then the new process will read its input + * from the given file descriptor, Process.input_redirected() will return + * true, and Process.input() will fail. + */ + in_fd: Option, + + /** + * If this is None then a new pipe will be created for the new progam's + * output and Process.output() will provide a Reader to read from this pipe. + * + * If this is Some(file-descriptor) then the new process will write its output + * to the given file descriptor, Process.output_redirected() will return + * true, and Process.output() will fail. + */ + out_fd: Option, + + /** + * If this is None then a new pipe will be created for the new progam's + * error stream and Process.error() will provide a Reader to read from this pipe. + * + * If this is Some(file-descriptor) then the new process will write its error output + * to the given file descriptor, Process.error_redirected() will return true, and + * and Process.error() will fail. + */ + err_fd: Option, +} + +impl <'self> ProcessOptions<'self> { + /// Return a ProcessOptions that has None in every field. + pub fn new<'a>() -> ProcessOptions<'a> { + ProcessOptions { + env: None, + dir: None, + in_fd: None, + out_fd: None, + err_fd: None, + } } } -pub impl Program { +/// The output of a finished process. +pub struct ProcessOutput { + + /// The status (exit code) of the process. + status: int, + + /// The data that the process wrote to stdout. + output: ~[u8], + + /// The data that the process wrote to stderr. + error: ~[u8], +} + +pub impl Process { + + /** + * Spawns a new Process. + * + * # Arguments + * + * * prog - The path to an executable. + * * args - Vector of arguments to pass to the child process. + * * options - Options to configure the environment of the process, + * the working directory and the standard IO streams. + */ + pub fn new(prog: &str, args: &[~str], options: ProcessOptions) -> Process { + + let (in_pipe, in_fd) = match options.in_fd { + None => { + let pipe = os::pipe(); + (Some(pipe), pipe.in) + }, + Some(fd) => (None, fd) + }; + let (out_pipe, out_fd) = match options.out_fd { + None => { + let pipe = os::pipe(); + (Some(pipe), pipe.out) + }, + Some(fd) => (None, fd) + }; + let (err_pipe, err_fd) = match options.err_fd { + None => { + let pipe = os::pipe(); + (Some(pipe), pipe.out) + }, + Some(fd) => (None, fd) + }; + + let res = spawn_process_os(prog, args, options.env, options.dir, + in_fd, out_fd, err_fd); + + unsafe { + for in_pipe.each |pipe| { libc::close(pipe.in); } + for out_pipe.each |pipe| { libc::close(pipe.out); } + for err_pipe.each |pipe| { libc::close(pipe.out); } + } + + Process { + pid: res.pid, + handle: res.handle, + input: in_pipe.map(|pipe| pipe.out), + output: out_pipe.map(|pipe| os::fdopen(pipe.in)), + error: err_pipe.map(|pipe| os::fdopen(pipe.in)), + exit_code: None, + } + } + + /// Returns the unique id of the process + fn get_id(&self) -> pid_t { self.pid } + + priv fn unwrap_input(&mut self) -> c_int { + match self.input { + Some(fd) => fd, + None => fail!("This Process's stdin was redirected to an \ + existing file descriptor.") + } + } + + priv fn unwrap_output(&mut self) -> *libc::FILE { + match self.output { + Some(file) => file, + None => fail!("This Process's stdout was redirected to an \ + existing file descriptor.") + } + } + + priv fn unwrap_error(&mut self) -> *libc::FILE { + match self.error { + Some(file) => file, + None => fail!("This Process's stderr was redirected to an \ + existing file descriptor.") + } + } - /// Returns the process id of the program - fn get_id(&mut self) -> pid_t { self.pid } + /** + * Returns whether this process is reading its stdin from an existing file + * descriptor rather than a pipe that was created specifically for this + * process. + * + * If this method returns true then self.input() will fail. + */ + fn input_redirected(&self) -> bool { + self.input.is_none() + } - /// Returns an io::Writer that can be used to write to stdin + /** + * Returns whether this process is writing its stdout to an existing file + * descriptor rather than a pipe that was created specifically for this + * process. + * + * If this method returns true then self.output() will fail. + */ + fn output_redirected(&self) -> bool { + self.output.is_none() + } + + /** + * Returns whether this process is writing its stderr to an existing file + * descriptor rather than a pipe that was created specifically for this + * process. + * + * If this method returns true then self.error() will fail. + */ + fn error_redirected(&self) -> bool { + self.error.is_none() + } + + /** + * Returns an io::Writer that can be used to write to this Process's stdin. + * + * Fails if this Process's stdin was redirected to an existing file descriptor. + */ fn input(&mut self) -> @io::Writer { - io::fd_writer(self.in_fd, false) + // FIXME: the Writer can still be used after self is destroyed: #2625 + io::fd_writer(self.unwrap_input(), false) } - /// Returns an io::Reader that can be used to read from stdout + /** + * Returns an io::Reader that can be used to read from this Process's stdout. + * + * Fails if this Process's stdout was redirected to an existing file descriptor. + */ fn output(&mut self) -> @io::Reader { - io::FILE_reader(self.out_file, false) + // FIXME: the Reader can still be used after self is destroyed: #2625 + io::FILE_reader(self.unwrap_output(), false) } - /// Returns an io::Reader that can be used to read from stderr - fn err(&mut self) -> @io::Reader { - io::FILE_reader(self.err_file, false) + /** + * Returns an io::Reader that can be used to read from this Process's stderr. + * + * Fails if this Process's stderr was redirected to an existing file descriptor. + */ + fn error(&mut self) -> @io::Reader { + // FIXME: the Reader can still be used after self is destroyed: #2625 + io::FILE_reader(self.unwrap_error(), false) } - /// Closes the handle to the child processes standard input + /** + * Closes the handle to the child process's stdin. + * + * If this process is reading its stdin from an existing file descriptor, then this + * method does nothing. + */ fn close_input(&mut self) { - let invalid_fd = -1i32; - if self.in_fd != invalid_fd { - unsafe { - libc::close(self.in_fd); + match self.input { + Some(-1) | None => (), + Some(fd) => { + unsafe { + libc::close(fd); + } + self.input = Some(-1); } - self.in_fd = invalid_fd; } } priv fn close_outputs(&mut self) { - unsafe { - fclose_and_null(&mut self.out_file); - fclose_and_null(&mut self.err_file); + fclose_and_null(&mut self.output); + fclose_and_null(&mut self.error); + + fn fclose_and_null(f_opt: &mut Option<*libc::FILE>) { + match *f_opt { + Some(f) if !f.is_null() => { + unsafe { + libc::fclose(f); + *f_opt = Some(0 as *libc::FILE); + } + }, + _ => () + } } } /** - * Waits for the child process to terminate. Closes the handle - * to stdin if necessary. + * Closes the handle to stdin, waits for the child process to terminate, + * and returns the exit code. + * + * If the child has already been finished then the exit code is returned. */ fn finish(&mut self) -> int { - if self.finished { return 0; } - self.finished = true; + for self.exit_code.each |&code| { + return code; + } self.close_input(); - return waitpid(self.pid); + let code = waitpid(self.pid); + self.exit_code = Some(code); + return code; + } + + /** + * Closes the handle to stdin, waits for the child process to terminate, and reads + * and returns all remaining output of stdout and stderr, along with the exit code. + * + * If the child has already been finished then the exit code and any remaining + * unread output of stdout and stderr will be returned. + * + * This method will fail if the child process's stdout or stderr streams were + * redirected to existing file descriptors. + */ + fn finish_with_output(&mut self) -> ProcessOutput { + + let output_file = self.unwrap_output(); + let error_file = self.unwrap_error(); + + // Spawn two entire schedulers to read both stdout and sterr + // in parallel so we don't deadlock while blocking on one + // or the other. FIXME (#2625): Surely there's a much more + // clever way to do this. + let (p, ch) = stream(); + let ch = SharedChan::new(ch); + let ch_clone = ch.clone(); + do task::spawn_sched(task::SingleThreaded) { + let errput = io::FILE_reader(error_file, false); + ch.send((2, errput.read_whole_stream())); + } + do task::spawn_sched(task::SingleThreaded) { + let output = io::FILE_reader(output_file, false); + ch_clone.send((1, output.read_whole_stream())); + } + + let status = self.finish(); + + let (errs, outs) = match (p.recv(), p.recv()) { + ((1, o), (2, e)) => (e, o), + ((2, e), (1, o)) => (e, o), + ((x, _), (y, _)) => { + fail!("unexpected file numbers: %u, %u", x, y); + } + }; + + return ProcessOutput {status: status, + output: outs, + error: errs}; } priv fn destroy_internal(&mut self, force: bool) { - killpid(self.pid, force); - self.finish(); - self.close_outputs(); + + // if the process has finished, and therefore had waitpid called, + // and we kill it, then on unix we might ending up killing a + // newer process that happens to have the same (re-used) id + if self.exit_code.is_none() { + killpid(self.pid, force); + self.finish(); + } #[cfg(windows)] fn killpid(pid: pid_t, _force: bool) { @@ -120,7 +408,7 @@ pub impl Program { } /** - * Terminate the program, giving it a chance to clean itself up if + * Terminates the process, giving it a chance to clean itself up if * this is supported by the operating system. * * On Posix OSs SIGTERM will be sent to the process. On Win32 @@ -129,7 +417,7 @@ pub impl Program { fn destroy(&mut self) { self.destroy_internal(false); } /** - * Terminate the program as soon as possible without giving it a + * Terminates the process as soon as possible without giving it a * chance to clean itself up. * * On Posix OSs SIGKILL will be sent to the process. On Win32 @@ -138,47 +426,27 @@ pub impl Program { fn force_destroy(&mut self) { self.destroy_internal(true); } } +impl Drop for Process { + fn finalize(&self) { + // FIXME #4943: transmute is bad. + let mut_self: &mut Process = unsafe { cast::transmute(self) }; -/** - * Run a program, providing stdin, stdout and stderr handles - * - * # Arguments - * - * * prog - The path to an executable - * * args - Vector of arguments to pass to the child process - * * env - optional env-modification for child - * * dir - optional dir to run child in (default current dir) - * * in_fd - A file descriptor for the child to use as std input - * * out_fd - A file descriptor for the child to use as std output - * * err_fd - A file descriptor for the child to use as std error - * - * # Return value - * - * The process id of the spawned process - */ -pub fn spawn_process(prog: &str, args: &[~str], - env: &Option<~[(~str,~str)]>, - dir: &Option<~str>, - in_fd: c_int, out_fd: c_int, err_fd: c_int) -> pid_t { - - let res = spawn_process_internal(prog, args, env, dir, in_fd, out_fd, err_fd); - free_handle(res.handle); - return res.pid; + mut_self.finish(); + mut_self.close_outputs(); + free_handle(self.handle); + } } -struct RunProgramResult { - // the process id of the program (this should never be negative) +struct SpawnProcessResult { pid: pid_t, - // a handle to the process - on unix this will always be NULL, but on windows it will be a - // HANDLE to the process, which will prevent the pid being re-used until the handle is closed. handle: *(), } #[cfg(windows)] -fn spawn_process_internal(prog: &str, args: &[~str], - env: &Option<~[(~str,~str)]>, - dir: &Option<~str>, - in_fd: c_int, out_fd: c_int, err_fd: c_int) -> RunProgramResult { +fn spawn_process_os(prog: &str, args: &[~str], + env: Option<&[(~str, ~str)]>, + dir: Option<&Path>, + in_fd: c_int, out_fd: c_int, err_fd: c_int) -> SpawnProcessResult { use libc::types::os::arch::extra::{DWORD, HANDLE, STARTUPINFO}; use libc::consts::os::extra::{ @@ -203,7 +471,7 @@ fn spawn_process_internal(prog: &str, args: &[~str], let cur_proc = GetCurrentProcess(); - let orig_std_in = get_osfhandle(if in_fd > 0 { in_fd } else { 0 }) as HANDLE; + let orig_std_in = get_osfhandle(in_fd) as HANDLE; if orig_std_in == INVALID_HANDLE_VALUE as HANDLE { fail!("failure in get_osfhandle: %s", os::last_os_error()); } @@ -212,7 +480,7 @@ fn spawn_process_internal(prog: &str, args: &[~str], fail!("failure in DuplicateHandle: %s", os::last_os_error()); } - let orig_std_out = get_osfhandle(if out_fd > 0 { out_fd } else { 1 }) as HANDLE; + let orig_std_out = get_osfhandle(out_fd) as HANDLE; if orig_std_out == INVALID_HANDLE_VALUE as HANDLE { fail!("failure in get_osfhandle: %s", os::last_os_error()); } @@ -221,8 +489,8 @@ fn spawn_process_internal(prog: &str, args: &[~str], fail!("failure in DuplicateHandle: %s", os::last_os_error()); } - let orig_std_err = get_osfhandle(if err_fd > 0 { err_fd } else { 2 }) as HANDLE; - if orig_std_err as HANDLE == INVALID_HANDLE_VALUE as HANDLE { + let orig_std_err = get_osfhandle(err_fd) as HANDLE; + if orig_std_err == INVALID_HANDLE_VALUE as HANDLE { fail!("failure in get_osfhandle: %s", os::last_os_error()); } if DuplicateHandle(cur_proc, orig_std_err, cur_proc, &mut si.hStdError, @@ -261,7 +529,7 @@ fn spawn_process_internal(prog: &str, args: &[~str], // until the calling code closes the process handle. CloseHandle(pi.hThread); - RunProgramResult { + SpawnProcessResult { pid: pi.dwProcessId as pid_t, handle: pi.hProcess as *() } @@ -357,10 +625,10 @@ pub fn make_command_line(prog: &str, args: &[~str]) -> ~str { } #[cfg(unix)] -fn spawn_process_internal(prog: &str, args: &[~str], - env: &Option<~[(~str,~str)]>, - dir: &Option<~str>, - in_fd: c_int, out_fd: c_int, err_fd: c_int) -> RunProgramResult { +fn spawn_process_os(prog: &str, args: &[~str], + env: Option<&[(~str, ~str)]>, + dir: Option<&Path>, + in_fd: c_int, out_fd: c_int, err_fd: c_int) -> SpawnProcessResult { use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp}; use libc::funcs::bsd44::getdtablesize; @@ -381,18 +649,18 @@ fn spawn_process_internal(prog: &str, args: &[~str], if pid < 0 { fail!("failure in fork: %s", os::last_os_error()); } else if pid > 0 { - return RunProgramResult {pid: pid, handle: ptr::null()}; + return SpawnProcessResult {pid: pid, handle: ptr::null()}; } rustrt::rust_unset_sigprocmask(); - if in_fd > 0 && dup2(in_fd, 0) == -1 { + if dup2(in_fd, 0) == -1 { fail!("failure in dup2(in_fd, 0): %s", os::last_os_error()); } - if out_fd > 0 && dup2(out_fd, 1) == -1 { + if dup2(out_fd, 1) == -1 { fail!("failure in dup2(out_fd, 1): %s", os::last_os_error()); } - if err_fd > 0 && dup2(err_fd, 2) == -1 { + if dup2(err_fd, 2) == -1 { fail!("failure in dup3(err_fd, 2): %s", os::last_os_error()); } // close all other fds @@ -400,11 +668,9 @@ fn spawn_process_internal(prog: &str, args: &[~str], close(fd as c_int); } - for dir.each |dir| { - do str::as_c_str(*dir) |dirp| { - if chdir(dirp) == -1 { - fail!("failure in chdir: %s", os::last_os_error()); - } + do with_dirp(dir) |dirp| { + if !dirp.is_null() && chdir(dirp) == -1 { + fail!("failure in chdir: %s", os::last_os_error()); } } @@ -424,33 +690,32 @@ fn spawn_process_internal(prog: &str, args: &[~str], #[cfg(unix)] fn with_argv(prog: &str, args: &[~str], cb: &fn(**libc::c_char) -> T) -> T { - let mut argptrs = str::as_c_str(prog, |b| ~[b]); + let mut argptrs = ~[str::as_c_str(prog, |b| b)]; let mut tmps = ~[]; for args.each |arg| { let t = @copy *arg; tmps.push(t); - argptrs.push_all(str::as_c_str(*t, |b| ~[b])); + argptrs.push(str::as_c_str(*t, |b| b)); } argptrs.push(ptr::null()); vec::as_imm_buf(argptrs, |buf, _len| cb(buf)) } #[cfg(unix)] -fn with_envp(env: &Option<~[(~str,~str)]>, - cb: &fn(*c_void) -> T) -> T { +fn with_envp(env: Option<&[(~str, ~str)]>, cb: &fn(*c_void) -> T) -> T { // On posixy systems we can pass a char** for envp, which is // a null-terminated array of "k=v\n" strings. - match *env { - Some(ref es) if !vec::is_empty(*es) => { + match env { + Some(es) => { let mut tmps = ~[]; let mut ptrs = ~[]; - for (*es).each |e| { - let (k,v) = copy *e; - let t = @(fmt!("%s=%s", k, v)); - tmps.push(t); - ptrs.push_all(str::as_c_str(*t, |b| ~[b])); + for es.each |&(k, v)| { + let kv = @fmt!("%s=%s", k, v); + tmps.push(kv); + ptrs.push(str::as_c_str(*kv, |b| b)); } + ptrs.push(ptr::null()); vec::as_imm_buf(ptrs, |p, _len| unsafe { cb(::cast::transmute(p)) } @@ -461,47 +726,35 @@ fn with_envp(env: &Option<~[(~str,~str)]>, } #[cfg(windows)] -fn with_envp(env: &Option<~[(~str,~str)]>, - cb: &fn(*mut c_void) -> T) -> T { +fn with_envp(env: Option<&[(~str, ~str)]>, cb: &fn(*mut c_void) -> T) -> T { // On win32 we pass an "environment block" which is not a char**, but // rather a concatenation of null-terminated k=v\0 sequences, with a final // \0 to terminate. - unsafe { - match *env { - Some(ref es) if !vec::is_empty(*es) => { - let mut blk : ~[u8] = ~[]; - for (*es).each |e| { - let (k,v) = copy *e; - let t = fmt!("%s=%s", k, v); - let mut v : ~[u8] = ::cast::transmute(t); - blk += v; - ::cast::forget(v); - } - blk += ~[0_u8]; - vec::as_imm_buf(blk, |p, _len| cb(::cast::transmute(p))) - } - _ => cb(ptr::mut_null()) + match env { + Some(es) => { + let mut blk = ~[]; + for es.each |&(k, v)| { + let kv = fmt!("%s=%s", k, v); + blk.push_all(str::as_bytes_slice(kv)); + blk.push(0); } + blk.push(0); + vec::as_imm_buf(blk, |p, _len| + unsafe { cb(::cast::transmute(p)) } + ) + } + _ => cb(ptr::mut_null()) } } -#[cfg(windows)] -fn with_dirp(d: &Option<~str>, +fn with_dirp(d: Option<&Path>, cb: &fn(*libc::c_char) -> T) -> T { - match *d { - Some(ref dir) => str::as_c_str(*dir, cb), + match d { + Some(dir) => str::as_c_str(dir.to_str(), cb), None => cb(ptr::null()) } } -/// helper function that closes non-NULL files and then makes them NULL -priv unsafe fn fclose_and_null(f: &mut *libc::FILE) { - if *f != 0 as *libc::FILE { - libc::fclose(*f); - *f = 0 as *libc::FILE; - } -} - #[cfg(windows)] priv fn free_handle(handle: *()) { unsafe { @@ -515,7 +768,8 @@ priv fn free_handle(_handle: *()) { } /** - * Spawns a process and waits for it to terminate + * Spawns a process and waits for it to terminate. The process will + * inherit the current stdin/stdout/stderr file descriptors. * * # Arguments * @@ -526,71 +780,19 @@ priv fn free_handle(_handle: *()) { * * The process's exit code */ -pub fn run_program(prog: &str, args: &[~str]) -> int { - let res = spawn_process_internal(prog, args, &None, &None, - 0i32, 0i32, 0i32); - let code = waitpid(res.pid); - free_handle(res.handle); - return code; -} - -/** - * Spawns a process and returns a Program - * - * The returned value is a object that can be used for sending and - * receiving data over the standard file descriptors. The class will ensure - * that file descriptors are closed properly. - * - * # Arguments - * - * * prog - The path to an executable - * * args - Vector of arguments to pass to the child process - * - * # Return value - * - * A object - */ -pub fn start_program(prog: &str, args: &[~str]) -> Program { - let pipe_input = os::pipe(); - let pipe_output = os::pipe(); - let pipe_err = os::pipe(); - let res = - spawn_process_internal(prog, args, &None, &None, - pipe_input.in, pipe_output.out, - pipe_err.out); - - unsafe { - libc::close(pipe_input.in); - libc::close(pipe_output.out); - libc::close(pipe_err.out); - } - - Program { - pid: res.pid, - handle: res.handle, - in_fd: pipe_input.out, - out_file: os::fdopen(pipe_output.in), - err_file: os::fdopen(pipe_err.in), - finished: false, - } -} - -fn read_all(rd: @io::Reader) -> ~str { - let buf = io::with_bytes_writer(|wr| { - let mut bytes = [0, ..4096]; - while !rd.eof() { - let nread = rd.read(bytes, bytes.len()); - wr.write(bytes.slice(0, nread)); - } +pub fn process_status(prog: &str, args: &[~str]) -> int { + let mut prog = Process::new(prog, args, ProcessOptions { + env: None, + dir: None, + in_fd: Some(0), + out_fd: Some(1), + err_fd: Some(2) }); - str::from_bytes(buf) + prog.finish() } -pub struct ProgramOutput {status: int, out: ~str, err: ~str} - /** - * Spawns a process, waits for it to exit, and returns the exit code, and - * contents of stdout and stderr. + * Spawns a process, records all its output, and waits for it to terminate. * * # Arguments * @@ -599,94 +801,24 @@ pub struct ProgramOutput {status: int, out: ~str, err: ~str} * * # Return value * - * A record, {status: int, out: str, err: str} containing the exit code, - * the contents of stdout and the contents of stderr. + * The process's stdout/stderr output and exit code. */ -pub fn program_output(prog: &str, args: &[~str]) -> ProgramOutput { - let pipe_in = os::pipe(); - let pipe_out = os::pipe(); - let pipe_err = os::pipe(); - let res = spawn_process_internal(prog, args, &None, &None, - pipe_in.in, pipe_out.out, pipe_err.out); - - os::close(pipe_in.in); - os::close(pipe_out.out); - os::close(pipe_err.out); - os::close(pipe_in.out); - - // Spawn two entire schedulers to read both stdout and sterr - // in parallel so we don't deadlock while blocking on one - // or the other. FIXME (#2625): Surely there's a much more - // clever way to do this. - let (p, ch) = stream(); - let ch = SharedChan::new(ch); - let ch_clone = ch.clone(); - do task::spawn_sched(task::SingleThreaded) { - let errput = readclose(pipe_err.in); - ch.send((2, errput)); - }; - do task::spawn_sched(task::SingleThreaded) { - let output = readclose(pipe_out.in); - ch_clone.send((1, output)); - }; - - let status = waitpid(res.pid); - free_handle(res.handle); - - let mut errs = ~""; - let mut outs = ~""; - let mut count = 2; - while count > 0 { - let stream = p.recv(); - match stream { - (1, copy s) => { - outs = s; - } - (2, copy s) => { - errs = s; - } - (n, _) => { - fail!("program_output received an unexpected file number: %u", n); - } - }; - count -= 1; - }; - return ProgramOutput {status: status, - out: outs, - err: errs}; -} - -pub fn writeclose(fd: c_int, s: ~str) { - use io::WriterUtil; - - error!("writeclose %d, %s", fd as int, s); - let writer = io::fd_writer(fd, false); - writer.write_str(s); - - os::close(fd); -} - -pub fn readclose(fd: c_int) -> ~str { - unsafe { - let file = os::fdopen(fd); - let reader = io::FILE_reader(file, false); - let buf = io::with_bytes_writer(|writer| { - let mut bytes = [0, ..4096]; - while !reader.eof() { - let nread = reader.read(bytes, bytes.len()); - writer.write(bytes.slice(0, nread)); - } - }); - os::fclose(file); - str::from_bytes(buf) - } +pub fn process_output(prog: &str, args: &[~str]) -> ProcessOutput { + let mut prog = Process::new(prog, args, ProcessOptions::new()); + prog.finish_with_output() } /** * Waits for a process to exit and returns the exit code, failing * if there is no process with the specified id. + * + * Note that this is private to avoid race conditions on unix where if + * a user calls waitpid(some_process.get_id()) then some_process.finish() + * and some_process.destroy() and some_process.drop() will then either + * operate on a none-existant process or, even worse, on a newer process + * with the same id. */ -pub fn waitpid(pid: pid_t) -> int { +priv fn waitpid(pid: pid_t) -> int { return waitpid_os(pid); #[cfg(windows)] @@ -777,10 +909,13 @@ pub fn waitpid(pid: pid_t) -> int { #[cfg(test)] mod tests { - use option::None; + use io; + use libc::{c_int}; + use option::{Option, None, Some}; use os; - use run::{readclose, writeclose}; + use path::Path; use run; + use str; #[test] #[cfg(windows)] @@ -803,54 +938,222 @@ mod tests { ); } - // Regression test for memory leaks #[test] - fn test_leaks() { - run::run_program("echo", []); - run::start_program("echo", []); - run::program_output("echo", []); + fn test_process_status() { + assert_eq!(run::process_status("false", []), 1); + assert_eq!(run::process_status("true", []), 0); + } + + #[test] + fn test_process_output_output() { + + let run::ProcessOutput {status, output, error} + = run::process_output("echo", [~"hello"]); + let output_str = str::from_bytes(output); + + assert_eq!(status, 0); + assert_eq!(output_str.trim().to_owned(), ~"hello"); + assert_eq!(error, ~[]); + } + + #[test] + fn test_process_output_error() { + + let run::ProcessOutput {status, output, error} + = run::process_output("mkdir", [~"."]); + + assert_eq!(status, 1); + assert_eq!(output, ~[]); + assert!(!error.is_empty()); } #[test] - #[allow(non_implicitly_copyable_typarams)] fn test_pipes() { + let pipe_in = os::pipe(); let pipe_out = os::pipe(); let pipe_err = os::pipe(); - let pid = - run::spawn_process( - "cat", [], &None, &None, - pipe_in.in, pipe_out.out, pipe_err.out); + let mut proc = run::Process::new("cat", [], run::ProcessOptions { + dir: None, + env: None, + in_fd: Some(pipe_in.in), + out_fd: Some(pipe_out.out), + err_fd: Some(pipe_err.out) + }); + + assert!(proc.input_redirected()); + assert!(proc.output_redirected()); + assert!(proc.error_redirected()); + os::close(pipe_in.in); os::close(pipe_out.out); os::close(pipe_err.out); - if pid == -1i32 { fail!(); } let expected = ~"test"; - writeclose(pipe_in.out, copy expected); + writeclose(pipe_in.out, expected); let actual = readclose(pipe_out.in); readclose(pipe_err.in); - run::waitpid(pid); + proc.finish(); - debug!(copy expected); - debug!(copy actual); assert_eq!(expected, actual); } + fn writeclose(fd: c_int, s: &str) { + let writer = io::fd_writer(fd, false); + writer.write_str(s); + os::close(fd); + } + + fn readclose(fd: c_int) -> ~str { + unsafe { + let file = os::fdopen(fd); + let reader = io::FILE_reader(file, false); + let buf = reader.read_whole_stream(); + os::fclose(file); + str::from_bytes(buf) + } + } + #[test] - fn waitpid() { - let pid = run::spawn_process("false", [], - &None, &None, - 0i32, 0i32, 0i32); - let status = run::waitpid(pid); - assert_eq!(status, 1); + fn test_finish_once() { + let mut prog = run::Process::new("false", [], run::ProcessOptions::new()); + assert_eq!(prog.finish(), 1); + } + + #[test] + fn test_finish_twice() { + let mut prog = run::Process::new("false", [], run::ProcessOptions::new()); + assert_eq!(prog.finish(), 1); + assert_eq!(prog.finish(), 1); + } + + #[test] + fn test_finish_with_output_once() { + + let mut prog = run::Process::new("echo", [~"hello"], run::ProcessOptions::new()); + let run::ProcessOutput {status, output, error} + = prog.finish_with_output(); + let output_str = str::from_bytes(output); + + assert_eq!(status, 0); + assert_eq!(output_str.trim().to_owned(), ~"hello"); + assert_eq!(error, ~[]); + } + + #[test] + fn test_finish_with_output_twice() { + + let mut prog = run::Process::new("echo", [~"hello"], run::ProcessOptions::new()); + let run::ProcessOutput {status, output, error} + = prog.finish_with_output(); + + let output_str = str::from_bytes(output); + + assert_eq!(status, 0); + assert_eq!(output_str.trim().to_owned(), ~"hello"); + assert_eq!(error, ~[]); + + let run::ProcessOutput {status, output, error} + = prog.finish_with_output(); + + assert_eq!(status, 0); + assert_eq!(output, ~[]); + assert_eq!(error, ~[]); } #[test] #[should_fail] - #[ignore(cfg(windows))] - fn waitpid_non_existant_pid() { - run::waitpid(123456789); // assume that this pid doesn't exist + #[cfg(not(windows))] + fn test_finish_with_output_redirected() { + let mut prog = run::Process::new("echo", [~"hello"], run::ProcessOptions { + env: None, + dir: None, + in_fd: Some(0), + out_fd: Some(1), + err_fd: Some(2) + }); + // this should fail because it is not valid to read the output when it was redirected + prog.finish_with_output(); + } + + #[cfg(unix)] + fn run_pwd(dir: Option<&Path>) -> run::Process { + run::Process::new("pwd", [], run::ProcessOptions { + dir: dir, + .. run::ProcessOptions::new() + }) + } + + #[cfg(windows)] + fn run_pwd(dir: Option<&Path>) -> run::Process { + run::Process::new("cmd", [~"/c", ~"cd"], run::ProcessOptions { + dir: dir, + .. run::ProcessOptions::new() + }) + } + + #[test] + fn test_keep_current_working_dir() { + + let mut prog = run_pwd(None); + + let output = str::from_bytes(prog.finish_with_output().output); + let parent_dir = os::getcwd().normalize(); + let child_dir = Path(output.trim()).normalize(); + + assert_eq!(child_dir.to_str(), parent_dir.to_str()); + } + + #[test] + fn test_change_working_directory() { + + let tmp_path = os::tmpdir().normalize(); + let mut prog = run_pwd(Some(&tmp_path)); + + let output = str::from_bytes(prog.finish_with_output().output); + let child_dir = Path(output.trim()).normalize(); + + assert_eq!(child_dir.to_str(), tmp_path.to_str()); + } + + #[cfg(unix)] + fn run_env(env: Option<&[(~str, ~str)]>) -> run::Process { + run::Process::new("env", [], run::ProcessOptions { + env: env, + .. run::ProcessOptions::new() + }) + } + + #[cfg(windows)] + fn run_env(env: Option<&[(~str, ~str)]>) -> run::Process { + run::Process::new("cmd", [~"/c", ~"set"], run::ProcessOptions { + env: env, + .. run::ProcessOptions::new() + }) + } + + #[test] + fn test_inherit_env() { + + let mut prog = run_env(None); + let output = str::from_bytes(prog.finish_with_output().output); + + for os::env().each |&(k, v)| { + // don't check windows magical empty-named variables + assert!(k.is_empty() || output.contains(fmt!("%s=%s", k, v))); + } + } + + #[test] + fn test_add_to_env() { + + let mut new_env = os::env(); + new_env.push((~"RUN_TEST_NEW_ENV", ~"123")); + + let mut prog = run_env(Some(new_env.slice(0, new_env.len()))); + let output = str::from_bytes(prog.finish_with_output().output); + + assert!(output.contains("RUN_TEST_NEW_ENV=123")); } } diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index b2f444d39e242..a80d9661aa20e 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -20,13 +20,13 @@ use std::run::*; #[test] fn test_destroy_once() { - let mut p = run::start_program("echo", []); + let mut p = run::Process::new("echo", [], run::ProcessOptions::new()); p.destroy(); // this shouldn't crash (and nor should the destructor) } #[test] fn test_destroy_twice() { - let mut p = run::start_program("echo", []); + let mut p = run::Process::new("echo", [], run::ProcessOptions::new()); p.destroy(); // this shouldnt crash... p.destroy(); // ...and nor should this (and nor should the destructor) } @@ -41,7 +41,8 @@ fn test_destroy_actually_kills(force: bool) { #[cfg(unix)] fn process_exists(pid: libc::pid_t) -> bool { - run::program_output("ps", [~"-p", pid.to_str()]).out.contains(pid.to_str()) + let run::ProcessOutput {output, _} = run::process_output("ps", [~"-p", pid.to_str()]); + str::from_bytes(output).contains(pid.to_str()) } #[cfg(windows)] @@ -64,8 +65,8 @@ fn test_destroy_actually_kills(force: bool) { } } - // this program will stay alive indefinitely trying to read from stdin - let mut p = run::start_program(BLOCK_COMMAND, []); + // this process will stay alive indefinitely trying to read from stdin + let mut p = run::Process::new(BLOCK_COMMAND, [], run::ProcessOptions::new()); assert!(process_exists(p.get_id())); From 49a1ab8745338e6ac6da65c3fc4e541761f6c760 Mon Sep 17 00:00:00 2001 From: gareth Date: Tue, 14 May 2013 20:10:14 +0100 Subject: [PATCH 244/248] Make test_change_working_directory change the current directory to be the parent of the current-current directory, instead of changing to the tmp directory, which was causing issues with OS X and its /tmp => /private/tmp symlink. --- src/libstd/run.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/libstd/run.rs b/src/libstd/run.rs index 1956f4baba646..8f5076531242f 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -1108,13 +1108,15 @@ mod tests { #[test] fn test_change_working_directory() { - let tmp_path = os::tmpdir().normalize(); - let mut prog = run_pwd(Some(&tmp_path)); + // test changing to the parent of os::getcwd() because we know + // the path exists (and os::getcwd() is not expected to be root) + let parent_path = os::getcwd().dir_path().normalize(); + let mut prog = run_pwd(Some(&parent_path)); let output = str::from_bytes(prog.finish_with_output().output); let child_dir = Path(output.trim()).normalize(); - assert_eq!(child_dir.to_str(), tmp_path.to_str()); + assert_eq!(child_dir.to_str(), parent_path.to_str()); } #[cfg(unix)] From 04a39359f86e7bc9700027139c2e6c8d27c67eba Mon Sep 17 00:00:00 2001 From: gareth Date: Tue, 14 May 2013 22:47:30 +0100 Subject: [PATCH 245/248] Rename unwrap_input/unwrap_output as suggested by @brson. Also fix a few documentation bugs. --- src/libstd/run.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/libstd/run.rs b/src/libstd/run.rs index 8f5076531242f..3cdc5dcca0723 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -45,10 +45,10 @@ pub struct Process { /// Some(fd), or None when stdin is being redirected from a fd not created by Process::new. priv input: Option, - /// Some(fd), or None when stdout is being redirected to a fd not created by Process::new. + /// Some(file), or None when stdout is being redirected to a fd not created by Process::new. priv output: Option<*libc::FILE>, - /// Some(fd), or None when stderr is being redirected to a fd not created by Process::new. + /// Some(file), or None when stderr is being redirected to a fd not created by Process::new. priv error: Option<*libc::FILE>, /// None until finish() is called. @@ -191,7 +191,7 @@ pub impl Process { /// Returns the unique id of the process fn get_id(&self) -> pid_t { self.pid } - priv fn unwrap_input(&mut self) -> c_int { + priv fn input_fd(&mut self) -> c_int { match self.input { Some(fd) => fd, None => fail!("This Process's stdin was redirected to an \ @@ -199,7 +199,7 @@ pub impl Process { } } - priv fn unwrap_output(&mut self) -> *libc::FILE { + priv fn output_file(&mut self) -> *libc::FILE { match self.output { Some(file) => file, None => fail!("This Process's stdout was redirected to an \ @@ -207,7 +207,7 @@ pub impl Process { } } - priv fn unwrap_error(&mut self) -> *libc::FILE { + priv fn error_file(&mut self) -> *libc::FILE { match self.error { Some(file) => file, None => fail!("This Process's stderr was redirected to an \ @@ -255,7 +255,7 @@ pub impl Process { */ fn input(&mut self) -> @io::Writer { // FIXME: the Writer can still be used after self is destroyed: #2625 - io::fd_writer(self.unwrap_input(), false) + io::fd_writer(self.input_fd(), false) } /** @@ -265,7 +265,7 @@ pub impl Process { */ fn output(&mut self) -> @io::Reader { // FIXME: the Reader can still be used after self is destroyed: #2625 - io::FILE_reader(self.unwrap_output(), false) + io::FILE_reader(self.output_file(), false) } /** @@ -275,7 +275,7 @@ pub impl Process { */ fn error(&mut self) -> @io::Reader { // FIXME: the Reader can still be used after self is destroyed: #2625 - io::FILE_reader(self.unwrap_error(), false) + io::FILE_reader(self.error_file(), false) } /** @@ -341,8 +341,8 @@ pub impl Process { */ fn finish_with_output(&mut self) -> ProcessOutput { - let output_file = self.unwrap_output(); - let error_file = self.unwrap_error(); + let output_file = self.output_file(); + let error_file = self.error_file(); // Spawn two entire schedulers to read both stdout and sterr // in parallel so we don't deadlock while blocking on one @@ -814,7 +814,7 @@ pub fn process_output(prog: &str, args: &[~str]) -> ProcessOutput { * * Note that this is private to avoid race conditions on unix where if * a user calls waitpid(some_process.get_id()) then some_process.finish() - * and some_process.destroy() and some_process.drop() will then either + * and some_process.destroy() and some_process.finalize() will then either * operate on a none-existant process or, even worse, on a newer process * with the same id. */ From e2fcb92a6d5c92c6beddec92fa0514d2c5de0fab Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 27 May 2013 08:19:57 -0500 Subject: [PATCH 246/248] Fix docs to use std instead of core. When I submitted #6748 yesterday, I used the old name. --- src/libstd/bool.rs | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/libstd/bool.rs b/src/libstd/bool.rs index 532e470e595b7..f6f29534f94ed 100644 --- a/src/libstd/bool.rs +++ b/src/libstd/bool.rs @@ -44,10 +44,10 @@ use from_str::FromStr; * * # Examples * ~~~ -* rusti> core::bool::not(true) +* rusti> std::bool::not(true) * false * ~~~ -* rusti> core::bool::not(false) +* rusti> std::bool::not(false) * true * ~~~ */ @@ -58,10 +58,10 @@ pub fn not(v: bool) -> bool { !v } * * # Examples * ~~~ -* rusti> core::bool::and(true, false) +* rusti> std::bool::and(true, false) * false * ~~~ -* rusti> core::bool::and(true, true) +* rusti> std::bool::and(true, true) * true * ~~~ */ @@ -72,10 +72,10 @@ pub fn and(a: bool, b: bool) -> bool { a && b } * * # Examples * ~~~ -* rusti> core::bool::or(true, false) +* rusti> std::bool::or(true, false) * true * ~~~ -* rusti> core::bool::or(false, false) +* rusti> std::bool::or(false, false) * false * ~~~ */ @@ -88,10 +88,10 @@ pub fn or(a: bool, b: bool) -> bool { a || b } * * # Examples * ~~~ -* rusti> core::bool::xor(true, false) +* rusti> std::bool::xor(true, false) * true * ~~~ -* rusti> core::bool::xor(true, true) +* rusti> std::bool::xor(true, true) * false * ~~~ */ @@ -106,10 +106,10 @@ pub fn xor(a: bool, b: bool) -> bool { (a && !b) || (!a && b) } * * # Examples * ~~~ -* rusti> core::bool::implies(true, true) +* rusti> std::bool::implies(true, true) * true * ~~~ -* rusti> core::bool::implies(true, false) +* rusti> std::bool::implies(true, false) * false * ~~~ */ @@ -122,10 +122,10 @@ pub fn implies(a: bool, b: bool) -> bool { !a || b } * * # Examples * ~~~ -* rusti> core::bool::eq(false, true) +* rusti> std::bool::eq(false, true) * false * ~~~ -* rusti> core::bool::eq(false, false) +* rusti> std::bool::eq(false, false) * true * ~~~ */ @@ -138,10 +138,10 @@ pub fn eq(a: bool, b: bool) -> bool { a == b } * * # Examples * ~~~ -* rusti> core::bool::ne(false, true) +* rusti> std::bool::ne(false, true) * true * ~~~ -* rusti> core::bool::ne(false, false) +* rusti> std::bool::ne(false, false) * false * ~~~ */ @@ -152,10 +152,10 @@ pub fn ne(a: bool, b: bool) -> bool { a != b } * * # Examples * ~~~ -* rusti> core::bool::is_true(true) +* rusti> std::bool::is_true(true) * true * ~~~ -* rusti> core::bool::is_true(false) +* rusti> std::bool::is_true(false) * false * ~~~ */ @@ -166,10 +166,10 @@ pub fn is_true(v: bool) -> bool { v } * * # Examples * ~~~ -* rusti> core::bool::is_false(false) +* rusti> std::bool::is_false(false) * true * ~~~ -* rusti> core::bool::is_false(true) +* rusti> std::bool::is_false(true) * false * ~~~ */ @@ -223,8 +223,8 @@ pub fn to_str(v: bool) -> ~str { if v { ~"true" } else { ~"false" } } * * # Examples * ~~~ -* do core::bool::all_values |x: bool| { -* println(core::bool::to_str(x)); +* do std::bool::all_values |x: bool| { +* println(std::bool::to_str(x)); * } * ~~~ */ From 379460558b2dfd7ddbd0b29abfaa2642d9f0961e Mon Sep 17 00:00:00 2001 From: Daniel Farina Date: Mon, 27 May 2013 09:52:56 -0700 Subject: [PATCH 247/248] Use passing by-value in gmtime, mktime Per the recommendation of the now-removed FIXME. --- src/libextra/time.rs | 17 ++++++++--------- src/rt/rust_builtin.cpp | 12 ++++++------ 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/src/libextra/time.rs b/src/libextra/time.rs index 8a0d50ed52c71..2b43291c28a82 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -22,11 +22,11 @@ pub mod rustrt { pub unsafe fn precise_time_ns(ns: &mut u64); pub unsafe fn rust_tzset(); - // FIXME: The i64 values can be passed by-val when #2064 is fixed. + pub unsafe fn rust_gmtime(sec: i64, nsec: i32, result: &mut Tm); pub unsafe fn rust_localtime(sec: i64, nsec: i32, result: &mut Tm); - pub unsafe fn rust_timegm(tm: &Tm, sec: &mut i64); - pub unsafe fn rust_mktime(tm: &Tm, sec: &mut i64); + pub unsafe fn rust_timegm(tm: &Tm) -> i64; + pub unsafe fn rust_mktime(tm: &Tm) -> i64; } } @@ -177,12 +177,11 @@ pub impl Tm { /// Convert time to the seconds from January 1, 1970 fn to_timespec(&self) -> Timespec { unsafe { - let mut sec = 0i64; - if self.tm_gmtoff == 0_i32 { - rustrt::rust_timegm(self, &mut sec); - } else { - rustrt::rust_mktime(self, &mut sec); - } + let sec = match self.tm_gmtoff { + 0_i32 => rustrt::rust_timegm(self), + _ => rustrt::rust_mktime(self) + }; + Timespec::new(sec, self.tm_nsec) } } diff --git a/src/rt/rust_builtin.cpp b/src/rt/rust_builtin.cpp index a2f253550af16..b0a46d2ac2967 100644 --- a/src/rt/rust_builtin.cpp +++ b/src/rt/rust_builtin.cpp @@ -459,18 +459,18 @@ rust_localtime(int64_t sec, int32_t nsec, rust_tm *timeptr) { tm_to_rust_tm(&tm, timeptr, gmtoff, zone, nsec); } -extern "C" CDECL void -rust_timegm(rust_tm* timeptr, int64_t *out) { +extern "C" CDECL int64_t +rust_timegm(rust_tm* timeptr) { tm t; rust_tm_to_tm(timeptr, &t); - *out = TIMEGM(&t); + return TIMEGM(&t); } -extern "C" CDECL void -rust_mktime(rust_tm* timeptr, int64_t *out) { +extern "C" CDECL int64_t +rust_mktime(rust_tm* timeptr) { tm t; rust_tm_to_tm(timeptr, &t); - *out = mktime(&t); + return mktime(&t); } extern "C" CDECL rust_sched_id From c6f3577f72f752ad2d13fa081fe7b36efbe3de84 Mon Sep 17 00:00:00 2001 From: Daniel Farina Date: Mon, 27 May 2013 09:55:42 -0700 Subject: [PATCH 248/248] Increment copyright year of time.rs --- src/libextra/time.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libextra/time.rs b/src/libextra/time.rs index 2b43291c28a82..eb7955bfa8b62 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -1,4 +1,4 @@ -// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //