From 503709708c72401dbe091ed5c7e0494efabe0669 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Tue, 6 Jan 2015 14:03:46 +1300 Subject: Change `std::kinds` to `std::markers`; flatten `std::kinds::marker` [breaking-change] --- src/libstd/thread_local/mod.rs | 4 ++-- src/libstd/thread_local/scoped.rs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src/libstd/thread_local') diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index e0cbaa8ca50..bf01b578b1f 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -346,7 +346,7 @@ mod imp { pub dtor_running: UnsafeCell, // should be Cell } - unsafe impl ::kinds::Sync for Key { } + unsafe impl ::markers::Sync for Key { } #[doc(hidden)] impl Key { @@ -472,7 +472,7 @@ mod imp { pub os: OsStaticKey, } - unsafe impl ::kinds::Sync for Key { } + unsafe impl ::markers::Sync for Key { } struct Value { key: &'static Key, diff --git a/src/libstd/thread_local/scoped.rs b/src/libstd/thread_local/scoped.rs index 714b71d5dbd..a643d2cb8ee 100644 --- a/src/libstd/thread_local/scoped.rs +++ b/src/libstd/thread_local/scoped.rs @@ -108,7 +108,7 @@ macro_rules! __scoped_thread_local_inner { const _INIT: __Key<$t> = __Key { inner: ::std::thread_local::scoped::__impl::KeyInner { inner: ::std::thread_local::scoped::__impl::OS_INIT, - marker: ::std::kinds::marker::InvariantType, + marker: ::std::markers::InvariantType, } }; @@ -211,7 +211,7 @@ mod imp { #[doc(hidden)] pub struct KeyInner { pub inner: UnsafeCell<*mut T> } - unsafe impl ::kinds::Sync for KeyInner { } + unsafe impl ::markers::Sync for KeyInner { } #[doc(hidden)] impl KeyInner { @@ -224,16 +224,16 @@ mod imp { #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))] mod imp { - use kinds::marker; + use markers; use sys_common::thread_local::StaticKey as OsStaticKey; #[doc(hidden)] pub struct KeyInner { pub inner: OsStaticKey, - pub marker: marker::InvariantType, + pub marker: markers::InvariantType, } - unsafe impl ::kinds::Sync for KeyInner { } + unsafe impl ::markers::Sync for KeyInner { } #[doc(hidden)] impl KeyInner { -- cgit 1.4.1-3-g733a5 From caca9b2e7109a148d100a3c6851241d3815da3db Mon Sep 17 00:00:00 2001 From: Aaron Turon Date: Mon, 5 Jan 2015 21:59:45 -0800 Subject: Fallout from stabilization --- src/compiletest/runtest.rs | 2 +- src/doc/intro.md | 9 ++- src/liballoc/arc.rs | 6 +- src/libcollections/dlist.rs | 2 +- src/libcore/atomic.rs | 2 +- src/librustc_driver/lib.rs | 2 +- src/librustc_trans/back/write.rs | 2 +- src/librustdoc/lib.rs | 4 +- src/librustdoc/test.rs | 2 +- src/libstd/io/comm_adapters.rs | 6 +- src/libstd/io/mod.rs | 10 ++-- src/libstd/io/net/pipe.rs | 12 ++-- src/libstd/io/net/tcp.rs | 26 +++++---- src/libstd/io/process.rs | 2 +- src/libstd/io/timer.rs | 6 +- src/libstd/macros.rs | 4 +- src/libstd/path/posix.rs | 6 +- src/libstd/path/windows.rs | 6 +- src/libstd/rand/os.rs | 2 +- src/libstd/sync/barrier.rs | 4 +- src/libstd/sync/condvar.rs | 4 +- src/libstd/sync/future.rs | 2 +- src/libstd/sync/mpsc/mod.rs | 68 +++++++++++----------- src/libstd/sync/mpsc/mpsc_queue.rs | 2 +- src/libstd/sync/mutex.rs | 12 ++-- src/libstd/sync/once.rs | 2 +- src/libstd/sync/rwlock.rs | 16 ++--- src/libstd/sync/semaphore.rs | 2 +- src/libstd/sync/task_pool.rs | 2 +- src/libstd/sys/common/helper_thread.rs | 2 +- src/libstd/thread.rs | 41 ++++++------- src/libstd/thread_local/mod.rs | 8 +-- src/libtest/lib.rs | 4 +- src/test/auxiliary/cci_capture_clause.rs | 2 +- src/test/bench/msgsend-pipes-shared.rs | 4 +- src/test/bench/msgsend-pipes.rs | 6 +- src/test/bench/rt-messaging-ping-pong.rs | 4 +- src/test/bench/rt-parfib.rs | 2 +- src/test/bench/shootout-binarytrees.rs | 2 +- src/test/bench/shootout-chameneos-redux.rs | 2 +- src/test/bench/shootout-fannkuch-redux.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 2 +- src/test/bench/shootout-k-nucleotide.rs | 4 +- src/test/bench/shootout-mandelbrot.rs | 4 +- src/test/bench/shootout-meteor.rs | 2 +- src/test/bench/shootout-pfib.rs | 8 +-- src/test/bench/shootout-threadring.rs | 4 +- src/test/bench/task-perf-alloc-unwind.rs | 2 +- src/test/bench/task-perf-jargon-metal-smoke.rs | 2 +- src/test/bench/task-perf-spawnalot.rs | 4 +- src/test/run-fail/panic-task-name-none.rs | 2 +- src/test/run-fail/panic-task-name-owned.rs | 2 +- src/test/run-fail/task-spawn-barefn.rs | 2 +- src/test/run-make/static-unwinding/main.rs | 2 +- .../cleanup-rvalue-temp-during-incomplete-alloc.rs | 2 +- src/test/run-pass/core-run-destroy.rs | 2 +- src/test/run-pass/foreign-call-no-runtime.rs | 2 +- src/test/run-pass/hashmap-memory.rs | 3 +- src/test/run-pass/issue-12684.rs | 2 +- src/test/run-pass/issue-13494.rs | 2 +- src/test/run-pass/issue-16560.rs | 2 +- src/test/run-pass/issue-16671.rs | 2 +- src/test/run-pass/issue-2190-1.rs | 2 +- src/test/run-pass/issue-4446.rs | 2 +- src/test/run-pass/issue-4448.rs | 2 +- src/test/run-pass/issue-8460.rs | 40 ++++++------- src/test/run-pass/issue-8827.rs | 5 +- src/test/run-pass/logging-only-prints-once.rs | 2 +- .../run-pass/macro-with-braces-in-expr-position.rs | 2 +- src/test/run-pass/no-landing-pads.rs | 2 +- src/test/run-pass/panic-in-dtor-drops-fields.rs | 3 +- src/test/run-pass/sendfn-spawn-with-fn-arg.rs | 2 +- src/test/run-pass/sepcomp-unwind.rs | 2 +- src/test/run-pass/slice-panic-1.rs | 2 +- src/test/run-pass/slice-panic-2.rs | 2 +- src/test/run-pass/spawn-types.rs | 2 +- src/test/run-pass/spawn.rs | 2 +- src/test/run-pass/spawn2.rs | 2 +- src/test/run-pass/spawning-with-debug.rs | 2 +- src/test/run-pass/task-comm-1.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-14.rs | 2 +- src/test/run-pass/task-comm-17.rs | 2 +- src/test/run-pass/task-comm-3.rs | 2 +- src/test/run-pass/task-comm-9.rs | 2 +- src/test/run-pass/task-stderr.rs | 2 +- src/test/run-pass/tcp-accept-stress.rs | 4 +- src/test/run-pass/tcp-stress.rs | 6 +- src/test/run-pass/tempfile.rs | 14 ++--- src/test/run-pass/terminate-in-initializer.rs | 4 +- src/test/run-pass/threads.rs | 2 +- src/test/run-pass/unique-send-2.rs | 2 +- src/test/run-pass/unit-like-struct-drop-run.rs | 2 +- src/test/run-pass/vector-sort-panic-safe.rs | 2 +- src/test/run-pass/yield.rs | 2 +- src/test/run-pass/yield1.rs | 2 +- 97 files changed, 245 insertions(+), 248 deletions(-) (limited to 'src/libstd/thread_local') diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 875061e69b7..18d90dab51a 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -447,7 +447,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { loop { //waiting 1 second for gdbserver start timer::sleep(Duration::milliseconds(1000)); - let result = Thread::spawn(move || { + let result = Thread::scoped(move || { tcp::TcpStream::connect("127.0.0.1:5039").unwrap(); }).join(); if result.is_err() { diff --git a/src/doc/intro.md b/src/doc/intro.md index a4e9d85bffd..fbc96a577a4 100644 --- a/src/doc/intro.md +++ b/src/doc/intro.md @@ -395,7 +395,7 @@ fn main() { for _ in range(0u, 10u) { Thread::spawn(move || { println!("Hello, world!"); - }).detach(); + }); } } ``` @@ -405,8 +405,7 @@ This program creates ten threads, who all print `Hello, world!`. The double bars `||`. (The `move` keyword indicates that the closure takes ownership of any data it uses; we'll have more on the significance of this shortly.) This closure is executed in a new thread created by -`spawn`. The `detach` method means that the child thread is allowed to -outlive its parent. +`spawn`. One common form of problem in concurrent programs is a 'data race.' This occurs when two different threads attempt to access the same @@ -429,7 +428,7 @@ fn main() { for i in range(0u, 3u) { Thread::spawn(move || { for j in range(0, 3) { numbers[j] += 1 } - }).detach(); + }); } } ``` @@ -488,7 +487,7 @@ fn main() { (*array)[i] += 1; println!("numbers[{}] is {}", i, (*array)[i]); - }).detach(); + }); } } ``` diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 25f80ad11bd..ac3d2b00212 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -42,7 +42,7 @@ //! //! Thread::spawn(move || { //! println!("{}", five); -//! }).detach(); +//! }); //! } //! ``` //! @@ -63,7 +63,7 @@ //! *number += 1; //! //! println!("{}", *number); // prints 6 -//! }).detach(); +//! }); //! } //! ``` @@ -106,7 +106,7 @@ use heap::deallocate; /// let local_numbers = child_numbers.as_slice(); /// /// // Work with the local numbers -/// }).detach(); +/// }); /// } /// } /// ``` diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 5e08f90ce1c..d628bdc3643 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -924,7 +924,7 @@ mod tests { #[test] fn test_send() { let n = list_from(&[1i,2,3]); - Thread::spawn(move || { + Thread::scoped(move || { check_links(&n); let a: &[_] = &[&1,&2,&3]; assert_eq!(a, n.iter().collect::>()); diff --git a/src/libcore/atomic.rs b/src/libcore/atomic.rs index 15c20253c8b..cc4308b5294 100644 --- a/src/libcore/atomic.rs +++ b/src/libcore/atomic.rs @@ -50,7 +50,7 @@ //! let spinlock_clone = spinlock.clone(); //! Thread::spawn(move|| { //! spinlock_clone.store(0, Ordering::SeqCst); -//! }).detach(); +//! }); //! //! // Wait for the other task to release the lock //! while spinlock.load(Ordering::SeqCst) != 0 {} diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 89b2e0f257a..ef78da3fd0e 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -559,7 +559,7 @@ pub fn monitor(f: F) { cfg = cfg.stack_size(STACK_SIZE); } - match cfg.spawn(move || { std::io::stdio::set_stderr(box w); f() }).join() { + match cfg.scoped(move || { std::io::stdio::set_stderr(box w); f() }).join() { Ok(()) => { /* fallthrough */ } Err(value) => { // Thread panicked without emitting a fatal diagnostic diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 98e2b4b9ddd..aa82950257e 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -928,7 +928,7 @@ fn run_work_multithreaded(sess: &Session, } tx.take().unwrap().send(()).unwrap(); - }).detach(); + }); } let mut panicked = false; diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 6e42c50f974..c3a5a9e6dc9 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -116,7 +116,7 @@ struct Output { pub fn main() { static STACK_SIZE: uint = 32000000; // 32MB - let res = std::thread::Builder::new().stack_size(STACK_SIZE).spawn(move || { + let res = std::thread::Builder::new().stack_size(STACK_SIZE).scoped(move || { main_args(std::os::args().as_slice()) }).join(); std::os::set_exit_status(res.map_err(|_| ()).unwrap()); @@ -358,7 +358,7 @@ fn rust_input(cratefile: &str, externs: core::Externs, matches: &getopts::Matche let cr = Path::new(cratefile); info!("starting to run rustc"); - let (mut krate, analysis) = std::thread::Thread::spawn(move |:| { + let (mut krate, analysis) = std::thread::Thread::scoped(move |:| { let cr = cr; core::run_core(paths, cfgs, externs, &cr, triple) }).join().map_err(|_| "rustc failed").unwrap(); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index bded371e500..278260fd3e6 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -157,7 +157,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, None => box io::stderr() as Box, }; io::util::copy(&mut p, &mut err).unwrap(); - }).detach(); + }); let emitter = diagnostic::EmitterWriter::new(box w2, None); // Compile the code diff --git a/src/libstd/io/comm_adapters.rs b/src/libstd/io/comm_adapters.rs index f47f6237b72..9ccede09cfc 100644 --- a/src/libstd/io/comm_adapters.rs +++ b/src/libstd/io/comm_adapters.rs @@ -172,7 +172,7 @@ mod test { tx.send(vec![3u8, 4u8]).unwrap(); tx.send(vec![5u8, 6u8]).unwrap(); tx.send(vec![7u8, 8u8]).unwrap(); - }).detach(); + }); let mut reader = ChanReader::new(rx); let mut buf = [0u8; 3]; @@ -215,7 +215,7 @@ mod test { tx.send(b"rld\nhow ".to_vec()).unwrap(); tx.send(b"are you?".to_vec()).unwrap(); tx.send(b"".to_vec()).unwrap(); - }).detach(); + }); let mut reader = ChanReader::new(rx); @@ -234,7 +234,7 @@ mod test { writer.write_be_u32(42).unwrap(); let wanted = vec![0u8, 0u8, 0u8, 42u8]; - let got = match Thread::spawn(move|| { rx.recv().unwrap() }).join() { + let got = match Thread::scoped(move|| { rx.recv().unwrap() }).join() { Ok(got) => got, Err(_) => panic!(), }; diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 5bef473db99..46c59ec49c1 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -120,10 +120,12 @@ //! for stream in acceptor.incoming() { //! match stream { //! Err(e) => { /* connection failed */ } -//! Ok(stream) => Thread::spawn(move|| { -//! // connection succeeded -//! handle_client(stream) -//! }).detach() +//! Ok(stream) => { +//! Thread::spawn(move|| { +//! // connection succeeded +//! handle_client(stream) +//! }); +//! } //! } //! } //! diff --git a/src/libstd/io/net/pipe.rs b/src/libstd/io/net/pipe.rs index 738c70412f7..29295b5751c 100644 --- a/src/libstd/io/net/pipe.rs +++ b/src/libstd/io/net/pipe.rs @@ -608,7 +608,7 @@ mod tests { let mut a = a; let _s = a.accept().unwrap(); let _ = rx.recv(); - }).detach(); + }); let mut b = [0]; let mut s = UnixStream::connect(&addr).unwrap(); @@ -645,7 +645,7 @@ mod tests { let mut a = a; let _s = a.accept().unwrap(); let _ = rx.recv(); - }).detach(); + }); let mut s = UnixStream::connect(&addr).unwrap(); let s2 = s.clone(); @@ -672,7 +672,7 @@ mod tests { rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); s.set_timeout(Some(20)); @@ -716,7 +716,7 @@ mod tests { } } let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); s.set_read_timeout(Some(20)); @@ -739,7 +739,7 @@ mod tests { rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); s.set_write_timeout(Some(20)); @@ -766,7 +766,7 @@ mod tests { rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); let s2 = s.clone(); diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index 3e59aaa05ef..b1762ff26fc 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -146,7 +146,7 @@ impl TcpStream { /// timer::sleep(Duration::seconds(1)); /// let mut stream = stream2; /// stream.close_read(); - /// }).detach(); + /// }); /// /// // wait for some data, will get canceled after one second /// let mut buf = [0]; @@ -295,10 +295,12 @@ impl sys_common::AsInner for TcpStream { /// for stream in acceptor.incoming() { /// match stream { /// Err(e) => { /* connection failed */ } -/// Ok(stream) => Thread::spawn(move|| { -/// // connection succeeded -/// handle_client(stream) -/// }).detach() +/// Ok(stream) => { +/// Thread::spawn(move|| { +/// // connection succeeded +/// handle_client(stream) +/// }); +/// } /// } /// } /// @@ -432,7 +434,7 @@ impl TcpAcceptor { /// Err(e) => panic!("unexpected error: {}", e), /// } /// } - /// }).detach(); + /// }); /// /// # fn wait_for_sigint() {} /// // Now that our accept loop is running, wait for the program to be @@ -1186,7 +1188,7 @@ mod test { let mut a = a; let _s = a.accept().unwrap(); let _ = rx.recv().unwrap(); - }).detach(); + }); let mut b = [0]; let mut s = TcpStream::connect(addr).unwrap(); @@ -1223,7 +1225,7 @@ mod test { let mut a = a; let _s = a.accept().unwrap(); let _ = rx.recv().unwrap(); - }).detach(); + }); let mut s = TcpStream::connect(addr).unwrap(); let s2 = s.clone(); @@ -1250,7 +1252,7 @@ mod test { rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); s.set_timeout(Some(20)); @@ -1289,7 +1291,7 @@ mod test { } } let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); s.set_read_timeout(Some(20)); @@ -1312,7 +1314,7 @@ mod test { rx.recv().unwrap(); assert!(s.write(&[0]).is_ok()); let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); s.set_write_timeout(Some(20)); @@ -1340,7 +1342,7 @@ mod test { rx.recv().unwrap(); assert_eq!(s.write(&[0]), Ok(())); let _ = rx.recv(); - }).detach(); + }); let mut s = a.accept().unwrap(); let s2 = s.clone(); diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index ea232ad0c3f..d7452180ffa 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -705,7 +705,7 @@ impl Process { Thread::spawn(move |:| { let mut stream = stream; tx.send(stream.read_to_end()).unwrap(); - }).detach(); + }); } None => tx.send(Ok(Vec::new())).unwrap() } diff --git a/src/libstd/io/timer.rs b/src/libstd/io/timer.rs index e073f76af82..8a0445be471 100644 --- a/src/libstd/io/timer.rs +++ b/src/libstd/io/timer.rs @@ -358,7 +358,7 @@ mod test { Thread::spawn(move|| { let _ = timer_rx.recv(); - }).detach(); + }); // when we drop the TimerWatcher we're going to destroy the channel, // which must wake up the task on the other end @@ -372,7 +372,7 @@ mod test { Thread::spawn(move|| { let _ = timer_rx.recv(); - }).detach(); + }); timer.oneshot(Duration::milliseconds(1)); } @@ -385,7 +385,7 @@ mod test { Thread::spawn(move|| { let _ = timer_rx.recv(); - }).detach(); + }); timer.sleep(Duration::milliseconds(1)); } diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index d96441e09a8..092430bf082 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -303,8 +303,8 @@ macro_rules! try { /// # fn long_running_task() {} /// # fn calculate_the_answer() -> int { 42i } /// -/// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach(); -/// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach(); +/// Thread::spawn(move|| { long_running_task(); tx1.send(()).unwrap(); }); +/// Thread::spawn(move|| { tx2.send(calculate_the_answer()).unwrap(); }); /// /// select! ( /// _ = rx1.recv() => println!("the long running task finished first"), diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index d9981ace030..ece9a343841 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -502,17 +502,17 @@ mod tests { #[test] fn test_null_byte() { use thread::Thread; - let result = Thread::spawn(move|| { + let result = Thread::scoped(move|| { Path::new(b"foo/bar\0") }).join(); assert!(result.is_err()); - let result = Thread::spawn(move|| { + let result = Thread::scoped(move|| { Path::new("test").set_filename(b"f\0o") }).join(); assert!(result.is_err()); - let result = Thread::spawn(move|| { + let result = Thread::scoped(move|| { Path::new("test").push(b"f\0o"); }).join(); assert!(result.is_err()); diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 4b5d793355b..db3224e66e4 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -1287,17 +1287,17 @@ mod tests { #[test] fn test_null_byte() { use thread::Thread; - let result = Thread::spawn(move|| { + let result = Thread::scoped(move|| { Path::new(b"foo/bar\0") }).join(); assert!(result.is_err()); - let result = Thread::spawn(move|| { + let result = Thread::scoped(move|| { Path::new("test").set_filename(b"f\0o") }).join(); assert!(result.is_err()); - let result = Thread::spawn(move || { + let result = Thread::scoped(move || { Path::new("test").push(b"f\0o"); }).join(); assert!(result.is_err()); diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index a79a6e35ebc..d9c019e3ace 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -397,7 +397,7 @@ mod test { r.fill_bytes(&mut v); Thread::yield_now(); } - }).detach(); + }); } // start all the tasks diff --git a/src/libstd/sync/barrier.rs b/src/libstd/sync/barrier.rs index bf5da3e7cba..70939879400 100644 --- a/src/libstd/sync/barrier.rs +++ b/src/libstd/sync/barrier.rs @@ -26,7 +26,7 @@ use sync::{Mutex, Condvar}; /// println!("before wait"); /// c.wait(); /// println!("after wait"); -/// }).detach(); +/// }); /// } /// ``` #[stable] @@ -126,7 +126,7 @@ mod tests { let tx = tx.clone(); Thread::spawn(move|| { tx.send(c.wait().is_leader()).unwrap(); - }).detach(); + }); } // At this point, all spawned tasks should be blocked, diff --git a/src/libstd/sync/condvar.rs b/src/libstd/sync/condvar.rs index e97be51fdbc..3c0ae71255d 100644 --- a/src/libstd/sync/condvar.rs +++ b/src/libstd/sync/condvar.rs @@ -48,7 +48,7 @@ use sync::{mutex, MutexGuard}; /// let mut started = lock.lock().unwrap(); /// *started = true; /// cvar.notify_one(); -/// }).detach(); +/// }); /// /// // wait for the thread to start up /// let &(ref lock, ref cvar) = &*pair; @@ -338,7 +338,7 @@ mod tests { cnt = cond.wait(cnt).unwrap(); } tx.send(()).unwrap(); - }).detach(); + }); } drop(tx); diff --git a/src/libstd/sync/future.rs b/src/libstd/sync/future.rs index 4c6adcc04f6..568c24446e7 100644 --- a/src/libstd/sync/future.rs +++ b/src/libstd/sync/future.rs @@ -141,7 +141,7 @@ impl Future { Thread::spawn(move |:| { // Don't panic if the other end has hung up let _ = tx.send(blk()); - }).detach(); + }); Future::from_receiver(rx) } diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 7c18b8a43fa..72c453f7f71 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -60,7 +60,7 @@ //! let (tx, rx) = channel(); //! Thread::spawn(move|| { //! tx.send(10i).unwrap(); -//! }).detach(); +//! }); //! assert_eq!(rx.recv().unwrap(), 10i); //! ``` //! @@ -78,7 +78,7 @@ //! let tx = tx.clone(); //! Thread::spawn(move|| { //! tx.send(i).unwrap(); -//! }).detach() +//! }); //! } //! //! for _ in range(0i, 10i) { @@ -109,7 +109,7 @@ //! Thread::spawn(move|| { //! // This will wait for the parent task to start receiving //! tx.send(53).unwrap(); -//! }).detach(); +//! }); //! rx.recv().unwrap(); //! ``` //! @@ -476,7 +476,7 @@ impl UnsafeFlavor for Receiver { /// Thread::spawn(move|| { /// # fn expensive_computation() {} /// tx.send(expensive_computation()).unwrap(); -/// }).detach(); +/// }); /// /// // Do some useful work for awhile /// @@ -518,7 +518,7 @@ pub fn channel() -> (Sender, Receiver) { /// Thread::spawn(move|| { /// // this will block until the previous message has been received /// tx.send(2i).unwrap(); -/// }).detach(); +/// }); /// /// assert_eq!(rx.recv().unwrap(), 1i); /// assert_eq!(rx.recv().unwrap(), 2i); @@ -1144,7 +1144,7 @@ mod test { #[test] fn stress() { let (tx, rx) = channel::(); - let t = Thread::spawn(move|| { + let t = Thread::scoped(move|| { for _ in range(0u, 10000) { tx.send(1i).unwrap(); } }); for _ in range(0u, 10000) { @@ -1159,7 +1159,7 @@ mod test { static NTHREADS: uint = 8; let (tx, rx) = channel::(); - let t = Thread::spawn(move|| { + let t = Thread::scoped(move|| { for _ in range(0, AMT * NTHREADS) { assert_eq!(rx.recv().unwrap(), 1); } @@ -1173,7 +1173,7 @@ mod test { let tx = tx.clone(); Thread::spawn(move|| { for _ in range(0, AMT) { tx.send(1).unwrap(); } - }).detach(); + }); } drop(tx); t.join().ok().unwrap(); @@ -1183,14 +1183,14 @@ mod test { fn send_from_outside_runtime() { let (tx1, rx1) = channel::<()>(); let (tx2, rx2) = channel::(); - let t1 = Thread::spawn(move|| { + let t1 = Thread::scoped(move|| { tx1.send(()).unwrap(); for _ in range(0i, 40) { assert_eq!(rx2.recv().unwrap(), 1); } }); rx1.recv().unwrap(); - let t2 = Thread::spawn(move|| { + let t2 = Thread::scoped(move|| { for _ in range(0i, 40) { tx2.send(1).unwrap(); } @@ -1202,7 +1202,7 @@ mod test { #[test] fn recv_from_outside_runtime() { let (tx, rx) = channel::(); - let t = Thread::spawn(move|| { + let t = Thread::scoped(move|| { for _ in range(0i, 40) { assert_eq!(rx.recv().unwrap(), 1); } @@ -1217,11 +1217,11 @@ mod test { fn no_runtime() { let (tx1, rx1) = channel::(); let (tx2, rx2) = channel::(); - let t1 = Thread::spawn(move|| { + let t1 = Thread::scoped(move|| { assert_eq!(rx1.recv().unwrap(), 1); tx2.send(2).unwrap(); }); - let t2 = Thread::spawn(move|| { + let t2 = Thread::scoped(move|| { tx1.send(1).unwrap(); assert_eq!(rx2.recv().unwrap(), 2); }); @@ -1254,7 +1254,7 @@ mod test { #[test] fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic - let res = Thread::spawn(move|| { + let res = Thread::scoped(move|| { let (tx, rx) = channel::(); drop(tx); rx.recv().unwrap(); @@ -1336,7 +1336,7 @@ mod test { let _t = Thread::spawn(move|| { drop(tx); }); - let res = Thread::spawn(move|| { + let res = Thread::scoped(move|| { assert!(rx.recv().unwrap() == box 10); }).join(); assert!(res.is_err()); @@ -1360,7 +1360,7 @@ mod test { let _t = Thread::spawn(move|| { drop(rx); }); - let _ = Thread::spawn(move|| { + let _ = Thread::scoped(move|| { tx.send(1).unwrap(); }).join(); } @@ -1371,15 +1371,15 @@ mod test { for _ in range(0, stress_factor()) { let (tx, rx) = channel::(); Thread::spawn(move|| { - let res = Thread::spawn(move|| { + let res = Thread::scoped(move|| { rx.recv().unwrap(); }).join(); assert!(res.is_err()); - }).detach(); + }); let _t = Thread::spawn(move|| { Thread::spawn(move|| { drop(tx); - }).detach(); + }); }); } } @@ -1409,7 +1409,7 @@ mod test { Thread::spawn(move|| { tx.send(box i).unwrap(); send(tx, i + 1); - }).detach(); + }); } fn recv(rx: Receiver>, i: int) { @@ -1418,7 +1418,7 @@ mod test { Thread::spawn(move|| { assert!(rx.recv().unwrap() == box i); recv(rx, i + 1); - }).detach(); + }); } } } @@ -1439,7 +1439,7 @@ mod test { let tx = tx.clone(); Thread::spawn(move|| { tx.send(()).unwrap(); - }).detach(); + }); } for _ in range(0, total) { @@ -1644,7 +1644,7 @@ mod sync_tests { Thread::spawn(move|| { tx.send(1).unwrap(); tx.send(1).unwrap(); - }).detach(); + }); while rx.recv().is_ok() {} } @@ -1653,7 +1653,7 @@ mod sync_tests { let (tx, rx) = sync_channel::(0); Thread::spawn(move|| { for _ in range(0u, 10000) { tx.send(1).unwrap(); } - }).detach(); + }); for _ in range(0u, 10000) { assert_eq!(rx.recv().unwrap(), 1); } @@ -1675,13 +1675,13 @@ mod sync_tests { _ => {} } dtx.send(()).unwrap(); - }).detach(); + }); for _ in range(0, NTHREADS) { let tx = tx.clone(); Thread::spawn(move|| { for _ in range(0, AMT) { tx.send(1).unwrap(); } - }).detach(); + }); } drop(tx); drx.recv().unwrap(); @@ -1712,7 +1712,7 @@ mod sync_tests { #[test] fn oneshot_single_thread_recv_chan_close() { // Receiving on a closed chan will panic - let res = Thread::spawn(move|| { + let res = Thread::scoped(move|| { let (tx, rx) = sync_channel::(0); drop(tx); rx.recv().unwrap(); @@ -1800,7 +1800,7 @@ mod sync_tests { let _t = Thread::spawn(move|| { drop(tx); }); - let res = Thread::spawn(move|| { + let res = Thread::scoped(move|| { assert!(rx.recv().unwrap() == box 10); }).join(); assert!(res.is_err()); @@ -1824,7 +1824,7 @@ mod sync_tests { let _t = Thread::spawn(move|| { drop(rx); }); - let _ = Thread::spawn(move || { + let _ = Thread::scoped(move || { tx.send(1).unwrap(); }).join(); } @@ -1835,7 +1835,7 @@ mod sync_tests { for _ in range(0, stress_factor()) { let (tx, rx) = sync_channel::(0); let _t = Thread::spawn(move|| { - let res = Thread::spawn(move|| { + let res = Thread::scoped(move|| { rx.recv().unwrap(); }).join(); assert!(res.is_err()); @@ -1843,7 +1843,7 @@ mod sync_tests { let _t = Thread::spawn(move|| { Thread::spawn(move|| { drop(tx); - }).detach(); + }); }); } } @@ -1873,7 +1873,7 @@ mod sync_tests { Thread::spawn(move|| { tx.send(box i).unwrap(); send(tx, i + 1); - }).detach(); + }); } fn recv(rx: Receiver>, i: int) { @@ -1882,7 +1882,7 @@ mod sync_tests { Thread::spawn(move|| { assert!(rx.recv().unwrap() == box i); recv(rx, i + 1); - }).detach(); + }); } } } @@ -1903,7 +1903,7 @@ mod sync_tests { let tx = tx.clone(); Thread::spawn(move|| { tx.send(()).unwrap(); - }).detach(); + }); } for _ in range(0, total) { diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index 9ad24a5a11e..f8eae1322bf 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -188,7 +188,7 @@ mod tests { q.push(i); } tx.send(()).unwrap(); - }).detach(); + }); } let mut i = 0u; diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 6b3dd89f33b..6eef428f558 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -75,7 +75,7 @@ use sys_common::mutex as sys; /// tx.send(()).unwrap(); /// } /// // the lock is unlocked here when `data` goes out of scope. -/// }).detach(); +/// }); /// } /// /// rx.recv().unwrap(); @@ -90,7 +90,7 @@ use sys_common::mutex as sys; /// let lock = Arc::new(Mutex::new(0u)); /// let lock2 = lock.clone(); /// -/// let _ = Thread::spawn(move || -> () { +/// let _ = Thread::scoped(move || -> () { /// // This thread will acquire the mutex first, unwrapping the result of /// // `lock` because the lock has not been poisoned. /// let _lock = lock2.lock().unwrap(); @@ -376,9 +376,9 @@ mod test { let (tx, rx) = channel(); for _ in range(0, K) { let tx2 = tx.clone(); - Thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }).detach(); + Thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }); let tx2 = tx.clone(); - Thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }).detach(); + Thread::spawn(move|| { inc(); tx2.send(()).unwrap(); }); } drop(tx); @@ -453,7 +453,7 @@ mod test { fn test_mutex_arc_poison() { let arc = Arc::new(Mutex::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| { + let _ = Thread::scoped(move|| { let lock = arc2.lock().unwrap(); assert_eq!(*lock, 2); }).join(); @@ -480,7 +480,7 @@ mod test { fn test_mutex_arc_access_in_unwind() { let arc = Arc::new(Mutex::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| -> () { + let _ = Thread::scoped(move|| -> () { struct Unwinder { i: Arc>, } diff --git a/src/libstd/sync/once.rs b/src/libstd/sync/once.rs index aa2d957a3eb..b32faf2d03f 100644 --- a/src/libstd/sync/once.rs +++ b/src/libstd/sync/once.rs @@ -159,7 +159,7 @@ mod test { assert!(run); } tx.send(()).unwrap(); - }).detach(); + }); } unsafe { diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 4afd5bb63f4..00b783d9661 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -411,7 +411,7 @@ mod tests { } } drop(tx); - }).detach(); + }); } drop(tx); let _ = rx.recv(); @@ -422,7 +422,7 @@ mod tests { fn test_rw_arc_poison_wr() { let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); - let _: Result = Thread::spawn(move|| { + let _: Result = Thread::scoped(move|| { let _lock = arc2.write().unwrap(); panic!(); }).join(); @@ -433,7 +433,7 @@ mod tests { fn test_rw_arc_poison_ww() { let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); - let _: Result = Thread::spawn(move|| { + let _: Result = Thread::scoped(move|| { let _lock = arc2.write().unwrap(); panic!(); }).join(); @@ -444,7 +444,7 @@ mod tests { fn test_rw_arc_no_poison_rr() { let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); - let _: Result = Thread::spawn(move|| { + let _: Result = Thread::scoped(move|| { let _lock = arc2.read().unwrap(); panic!(); }).join(); @@ -455,7 +455,7 @@ mod tests { fn test_rw_arc_no_poison_rw() { let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); - let _: Result = Thread::spawn(move|| { + let _: Result = Thread::scoped(move|| { let _lock = arc2.read().unwrap(); panic!() }).join(); @@ -478,13 +478,13 @@ mod tests { *lock = tmp + 1; } tx.send(()).unwrap(); - }).detach(); + }); // Readers try to catch the writer in the act let mut children = Vec::new(); for _ in range(0u, 5) { let arc3 = arc.clone(); - children.push(Thread::spawn(move|| { + children.push(Thread::scoped(move|| { let lock = arc3.read().unwrap(); assert!(*lock >= 0); })); @@ -505,7 +505,7 @@ mod tests { fn test_rw_arc_access_in_unwind() { let arc = Arc::new(RwLock::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| -> () { + let _ = Thread::scoped(move|| -> () { struct Unwinder { i: Arc>, } diff --git a/src/libstd/sync/semaphore.rs b/src/libstd/sync/semaphore.rs index 505819fbf8a..8d44084671a 100644 --- a/src/libstd/sync/semaphore.rs +++ b/src/libstd/sync/semaphore.rs @@ -193,7 +193,7 @@ mod tests { tx.send(()).unwrap(); drop(s2.access()); tx.send(()).unwrap(); - }).detach(); + }); rx.recv().unwrap(); // wait for child to come alive } rx.recv().unwrap(); // wait for child to be done diff --git a/src/libstd/sync/task_pool.rs b/src/libstd/sync/task_pool.rs index 088827dc084..278528bdb38 100644 --- a/src/libstd/sync/task_pool.rs +++ b/src/libstd/sync/task_pool.rs @@ -132,7 +132,7 @@ fn spawn_in_pool(jobs: Arc>>) { } sentinel.cancel(); - }).detach(); + }); } #[cfg(test)] diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index bdf1bf3dfd0..f940b6ed368 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -99,7 +99,7 @@ impl Helper { let _g = self.lock.lock().unwrap(); *self.shutdown.get() = true; self.cond.notify_one() - }).detach(); + }); rt::at_exit(move|:| { self.shutdown() }); *self.initialized.get() = true; diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 9e12a7b592a..5153b6b90a7 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -332,9 +332,6 @@ pub struct Thread { inner: Arc, } -#[stable] -unsafe impl Sync for Thread {} - impl Thread { // Used only internally to construct a thread object without spawning fn new(name: Option) -> Thread { @@ -520,14 +517,14 @@ mod test { #[test] fn test_unnamed_thread() { - Thread::spawn(move|| { + Thread::scoped(move|| { assert!(Thread::current().name().is_none()); }).join().map_err(|_| ()).unwrap(); } #[test] fn test_named_thread() { - Builder::new().name("ada lovelace".to_string()).spawn(move|| { + Builder::new().name("ada lovelace".to_string()).scoped(move|| { assert!(Thread::current().name().unwrap() == "ada lovelace".to_string()); }).join().map_err(|_| ()).unwrap(); } @@ -537,13 +534,13 @@ mod test { let (tx, rx) = channel(); Thread::spawn(move|| { tx.send(()).unwrap(); - }).detach(); + }); rx.recv().unwrap(); } #[test] fn test_join_success() { - match Thread::spawn(move|| -> String { + match Thread::scoped(move|| -> String { "Success!".to_string() }).join().as_ref().map(|s| s.as_slice()) { result::Result::Ok("Success!") => (), @@ -553,7 +550,7 @@ mod test { #[test] fn test_join_panic() { - match Thread::spawn(move|| { + match Thread::scoped(move|| { panic!() }).join() { result::Result::Err(_) => (), @@ -575,7 +572,7 @@ mod test { } else { f(i - 1, tx); } - }).detach(); + }); } f(10, tx); @@ -589,8 +586,8 @@ mod test { Thread::spawn(move|| { Thread::spawn(move|| { tx.send(()).unwrap(); - }).detach(); - }).detach(); + }); + }); rx.recv().unwrap(); } @@ -613,7 +610,7 @@ mod test { #[test] fn test_avoid_copying_the_body_spawn() { avoid_copying_the_body(|v| { - Thread::spawn(move || v.invoke(())).detach(); + Thread::spawn(move || v.invoke(())); }); } @@ -622,14 +619,14 @@ mod test { avoid_copying_the_body(|f| { Thread::spawn(move|| { f.invoke(()); - }).detach(); + }); }) } #[test] fn test_avoid_copying_the_body_join() { avoid_copying_the_body(|f| { - let _ = Thread::spawn(move|| { + let _ = Thread::scoped(move|| { f.invoke(()) }).join(); }) @@ -645,21 +642,21 @@ mod test { fn child_no(x: uint) -> Thunk { return Thunk::new(move|| { if x < GENERATIONS { - Thread::spawn(move|| child_no(x+1).invoke(())).detach(); + Thread::spawn(move|| child_no(x+1).invoke(())); } }); } - Thread::spawn(|| child_no(0).invoke(())).detach(); + Thread::spawn(|| child_no(0).invoke(())); } #[test] fn test_simple_newsched_spawn() { - Thread::spawn(move || {}).detach(); + Thread::spawn(move || {}); } #[test] fn test_try_panic_message_static_str() { - match Thread::spawn(move|| { + match Thread::scoped(move|| { panic!("static string"); }).join() { Err(e) => { @@ -673,7 +670,7 @@ mod test { #[test] fn test_try_panic_message_owned_str() { - match Thread::spawn(move|| { + match Thread::scoped(move|| { panic!("owned string".to_string()); }).join() { Err(e) => { @@ -687,7 +684,7 @@ mod test { #[test] fn test_try_panic_message_any() { - match Thread::spawn(move|| { + match Thread::scoped(move|| { panic!(box 413u16 as Box); }).join() { Err(e) => { @@ -705,7 +702,7 @@ mod test { fn test_try_panic_message_unit_struct() { struct Juju; - match Thread::spawn(move|| { + match Thread::scoped(move|| { panic!(Juju) }).join() { Err(ref e) if e.is::() => {} @@ -719,7 +716,7 @@ mod test { let mut reader = ChanReader::new(rx); let stdout = ChanWriter::new(tx); - let r = Builder::new().stdout(box stdout as Box).spawn(move|| { + let r = Builder::new().stdout(box stdout as Box).scoped(move|| { print!("Hello, world!"); }).join(); assert!(r.is_ok()); diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index e0cbaa8ca50..c8cad7765e6 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -87,7 +87,7 @@ pub mod __impl { /// assert_eq!(*f.borrow(), 1); /// *f.borrow_mut() = 3; /// }); -/// }).detach(); +/// }); /// /// // we retain our original value of 2 despite the child thread /// FOO.with(|f| { @@ -581,7 +581,7 @@ mod tests { } thread_local!(static FOO: Foo = foo()); - Thread::spawn(|| { + Thread::scoped(|| { assert!(FOO.state() == State::Uninitialized); FOO.with(|_| { assert!(FOO.state() == State::Valid); @@ -645,7 +645,7 @@ mod tests { } } - Thread::spawn(move|| { + Thread::scoped(move|| { drop(S1); }).join().ok().unwrap(); } @@ -663,7 +663,7 @@ mod tests { } } - Thread::spawn(move|| unsafe { + Thread::scoped(move|| unsafe { K1.with(|s| *s.get() = Some(S1)); }).join().ok().unwrap(); } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index c417fd94e22..6d55848a583 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -1137,11 +1137,11 @@ pub fn run_test(opts: &TestOpts, cfg = cfg.stderr(box stderr as Box); } - let result_guard = cfg.spawn(move || { testfn.invoke(()) }); + let result_guard = cfg.scoped(move || { testfn.invoke(()) }); let stdout = reader.read_to_end().unwrap().into_iter().collect(); let test_result = calc_result(&desc, result_guard.join()); monitor_ch.send((desc.clone(), test_result, stdout)).unwrap(); - }).detach(); + }); } match testfn { diff --git a/src/test/auxiliary/cci_capture_clause.rs b/src/test/auxiliary/cci_capture_clause.rs index ec4c0281d55..673c38697b7 100644 --- a/src/test/auxiliary/cci_capture_clause.rs +++ b/src/test/auxiliary/cci_capture_clause.rs @@ -15,6 +15,6 @@ pub fn foo(x: T) -> Receiver { let (tx, rx) = channel(); Thread::spawn(move|| { tx.send(x.clone()); - }).detach(); + }); rx } diff --git a/src/test/bench/msgsend-pipes-shared.rs b/src/test/bench/msgsend-pipes-shared.rs index d1126e74252..387601de828 100644 --- a/src/test/bench/msgsend-pipes-shared.rs +++ b/src/test/bench/msgsend-pipes-shared.rs @@ -64,7 +64,7 @@ fn run(args: &[String]) { let mut worker_results = Vec::new(); for _ in range(0u, workers) { let to_child = to_child.clone(); - worker_results.push(Thread::spawn(move|| { + worker_results.push(Thread::scoped(move|| { for _ in range(0u, size / workers) { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)).unwrap(); @@ -74,7 +74,7 @@ fn run(args: &[String]) { } Thread::spawn(move|| { server(&from_parent, &to_parent); - }).detach(); + }); for r in worker_results.into_iter() { let _ = r.join(); diff --git a/src/test/bench/msgsend-pipes.rs b/src/test/bench/msgsend-pipes.rs index ef22aac776e..d6d01e5452b 100644 --- a/src/test/bench/msgsend-pipes.rs +++ b/src/test/bench/msgsend-pipes.rs @@ -59,7 +59,7 @@ fn run(args: &[String]) { let mut worker_results = Vec::new(); let from_parent = if workers == 1 { let (to_child, from_parent) = channel(); - worker_results.push(Thread::spawn(move|| { + worker_results.push(Thread::scoped(move|| { for _ in range(0u, size / workers) { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); @@ -71,7 +71,7 @@ fn run(args: &[String]) { let (to_child, from_parent) = channel(); for _ in range(0u, workers) { let to_child = to_child.clone(); - worker_results.push(Thread::spawn(move|| { + worker_results.push(Thread::scoped(move|| { for _ in range(0u, size / workers) { //println!("worker {}: sending {} bytes", i, num_bytes); to_child.send(request::bytes(num_bytes)); @@ -83,7 +83,7 @@ fn run(args: &[String]) { }; Thread::spawn(move|| { server(&from_parent, &to_parent); - }).detach(); + }); for r in worker_results.into_iter() { let _ = r.join(); diff --git a/src/test/bench/rt-messaging-ping-pong.rs b/src/test/bench/rt-messaging-ping-pong.rs index 5ecc580de08..b854dc11b98 100644 --- a/src/test/bench/rt-messaging-ping-pong.rs +++ b/src/test/bench/rt-messaging-ping-pong.rs @@ -35,7 +35,7 @@ fn ping_pong_bench(n: uint, m: uint) { // Create a channel: B->A let (btx, brx) = channel(); - let guard_a = Thread::spawn(move|| { + let guard_a = Thread::scoped(move|| { let (tx, rx) = (atx, brx); for _ in range(0, n) { tx.send(()).unwrap(); @@ -43,7 +43,7 @@ fn ping_pong_bench(n: uint, m: uint) { } }); - let guard_b = Thread::spawn(move|| { + let guard_b = Thread::scoped(move|| { let (tx, rx) = (btx, arx); for _ in range(0, n) { rx.recv().unwrap(); diff --git a/src/test/bench/rt-parfib.rs b/src/test/bench/rt-parfib.rs index 8b212555d40..37210cd93f1 100644 --- a/src/test/bench/rt-parfib.rs +++ b/src/test/bench/rt-parfib.rs @@ -25,7 +25,7 @@ fn parfib(n: uint) -> uint { let (tx, rx) = channel(); Thread::spawn(move|| { tx.send(parfib(n-1)); - }).detach(); + }); let m2 = parfib(n-2); return (rx.recv().unwrap() + m2); } diff --git a/src/test/bench/shootout-binarytrees.rs b/src/test/bench/shootout-binarytrees.rs index c7a43d61a9a..737776368dd 100644 --- a/src/test/bench/shootout-binarytrees.rs +++ b/src/test/bench/shootout-binarytrees.rs @@ -95,7 +95,7 @@ fn main() { let mut messages = range_step(min_depth, max_depth + 1, 2).map(|depth| { use std::num::Int; let iterations = 2i.pow((max_depth - depth + min_depth) as uint); - Thread::spawn(move|| { + Thread::scoped(move|| { let mut chk = 0; for i in range(1, iterations + 1) { let arena = TypedArena::new(); diff --git a/src/test/bench/shootout-chameneos-redux.rs b/src/test/bench/shootout-chameneos-redux.rs index 96bca25d1c4..5c36fccc7f5 100644 --- a/src/test/bench/shootout-chameneos-redux.rs +++ b/src/test/bench/shootout-chameneos-redux.rs @@ -195,7 +195,7 @@ fn rendezvous(nn: uint, set: Vec) { from_rendezvous, to_rendezvous, to_rendezvous_log); - }).detach(); + }); to_creature }).collect(); diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 7dca2b24fc1..2725c7cf6d6 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -168,7 +168,7 @@ fn fannkuch(n: i32) -> (i32, i32) { for (i, j) in range(0, N).zip(iter::count(0, k)) { let max = cmp::min(j+k, perm.max()); - futures.push(Thread::spawn(move|| { + futures.push(Thread::scoped(move|| { work(perm, j as uint, max as uint) })) } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index e6ef6a8c8c9..8ce4edccbd3 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -173,7 +173,7 @@ fn main() { Thread::spawn(move|| { make_sequence_processor(sz, &from_parent, &to_parent_); - }).detach(); + }); to_child }).collect:: >> >(); diff --git a/src/test/bench/shootout-k-nucleotide.rs b/src/test/bench/shootout-k-nucleotide.rs index 28d7488c9bf..760758a3406 100644 --- a/src/test/bench/shootout-k-nucleotide.rs +++ b/src/test/bench/shootout-k-nucleotide.rs @@ -304,11 +304,11 @@ fn main() { let nb_freqs: Vec<_> = range(1u, 3).map(|i| { let input = input.clone(); - (i, Thread::spawn(move|| generate_frequencies(input.as_slice(), i))) + (i, Thread::scoped(move|| generate_frequencies(input.as_slice(), i))) }).collect(); let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| { let input = input.clone(); - Thread::spawn(move|| generate_frequencies(input.as_slice(), occ.len())) + Thread::scoped(move|| generate_frequencies(input.as_slice(), occ.len())) }).collect(); for (i, freq) in nb_freqs.into_iter() { diff --git a/src/test/bench/shootout-mandelbrot.rs b/src/test/bench/shootout-mandelbrot.rs index 16d6036d4c4..f6124c1271f 100644 --- a/src/test/bench/shootout-mandelbrot.rs +++ b/src/test/bench/shootout-mandelbrot.rs @@ -82,7 +82,7 @@ fn mandelbrot(w: uint, mut out: W) -> io::IoResult<()> { let mut precalc_i = Vec::with_capacity(h); let precalc_futures = range(0, WORKERS).map(|i| { - Thread::spawn(move|| { + Thread::scoped(move|| { let mut rs = Vec::with_capacity(w / WORKERS); let mut is = Vec::with_capacity(w / WORKERS); @@ -123,7 +123,7 @@ fn mandelbrot(w: uint, mut out: W) -> io::IoResult<()> { let vec_init_r = arc_init_r.clone(); let vec_init_i = arc_init_i.clone(); - Thread::spawn(move|| { + Thread::scoped(move|| { let mut res: Vec = Vec::with_capacity((chunk_size * w) / 8); let init_r_slice = vec_init_r.as_slice(); diff --git a/src/test/bench/shootout-meteor.rs b/src/test/bench/shootout-meteor.rs index ca3d10afa5d..34a036eff37 100644 --- a/src/test/bench/shootout-meteor.rs +++ b/src/test/bench/shootout-meteor.rs @@ -321,7 +321,7 @@ fn par_search(masks: Vec>>) -> Data { let mut data = Data::new(); search(&*masks, m, 1, List::Cons(m, &List::Nil), &mut data); tx.send(data).unwrap(); - }).detach(); + }); } // collecting the results diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 84ceb432048..3953d3f9cdd 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -35,15 +35,15 @@ fn fib(n: int) -> int { } else { let (tx1, rx) = channel(); let tx2 = tx1.clone(); - Thread::spawn(move|| pfib(&tx2, n - 1)).detach(); + Thread::spawn(move|| pfib(&tx2, n - 1)); let tx2 = tx1.clone(); - Thread::spawn(move|| pfib(&tx2, n - 2)).detach(); + Thread::spawn(move|| pfib(&tx2, n - 2)); tx.send(rx.recv().unwrap() + rx.recv().unwrap()); } } let (tx, rx) = channel(); - Thread::spawn(move|| pfib(&tx, n) ).detach(); + Thread::spawn(move|| pfib(&tx, n) ); rx.recv().unwrap() } @@ -78,7 +78,7 @@ fn stress_task(id: int) { fn stress(num_tasks: int) { let mut results = Vec::new(); for i in range(0, num_tasks) { - results.push(Thread::spawn(move|| { + results.push(Thread::scoped(move|| { stress_task(i); })); } diff --git a/src/test/bench/shootout-threadring.rs b/src/test/bench/shootout-threadring.rs index 9dd10037850..da427b36e8d 100644 --- a/src/test/bench/shootout-threadring.rs +++ b/src/test/bench/shootout-threadring.rs @@ -46,10 +46,10 @@ fn start(n_tasks: int, token: int) { tx.send(token); for i in range(2, n_tasks + 1) { let (tx, next_rx) = channel(); - Thread::spawn(move|| roundtrip(i, tx, rx)).detach(); + Thread::spawn(move|| roundtrip(i, tx, rx)); rx = next_rx; } - Thread::spawn(move|| roundtrip(1, tx, rx)).detach(); + Thread::spawn(move|| roundtrip(1, tx, rx)); } fn roundtrip(id: int, tx: Sender, rx: Receiver) { diff --git a/src/test/bench/task-perf-alloc-unwind.rs b/src/test/bench/task-perf-alloc-unwind.rs index 9e78ede74ca..55e8dcbb6e8 100644 --- a/src/test/bench/task-perf-alloc-unwind.rs +++ b/src/test/bench/task-perf-alloc-unwind.rs @@ -36,7 +36,7 @@ fn main() { fn run(repeat: int, depth: int) { for _ in range(0, repeat) { let dur = Duration::span(|| { - let _ = Thread::spawn(move|| { + let _ = Thread::scoped(move|| { recurse_or_panic(depth, None) }).join(); }); diff --git a/src/test/bench/task-perf-jargon-metal-smoke.rs b/src/test/bench/task-perf-jargon-metal-smoke.rs index 30918d49090..a2a380279f3 100644 --- a/src/test/bench/task-perf-jargon-metal-smoke.rs +++ b/src/test/bench/task-perf-jargon-metal-smoke.rs @@ -35,7 +35,7 @@ fn child_generation(gens_left: uint, tx: Sender<()>) { } else { tx.send(()).unwrap() } - }).detach(); + }); } fn main() { diff --git a/src/test/bench/task-perf-spawnalot.rs b/src/test/bench/task-perf-spawnalot.rs index 488a5ec9eda..eb1e30e2846 100644 --- a/src/test/bench/task-perf-spawnalot.rs +++ b/src/test/bench/task-perf-spawnalot.rs @@ -15,7 +15,7 @@ use std::thread::Thread; fn f(n: uint) { let mut i = 0u; while i < n { - let _ = Thread::spawn(move|| g()).join(); + let _ = Thread::scoped(move|| g()).join(); i += 1u; } } @@ -33,5 +33,5 @@ fn main() { }; let n = args[1].parse().unwrap(); let mut i = 0u; - while i < n { Thread::spawn(move|| f(n) ).detach(); i += 1u; } + while i < n { Thread::spawn(move|| f(n) ); i += 1u; } } diff --git a/src/test/run-fail/panic-task-name-none.rs b/src/test/run-fail/panic-task-name-none.rs index c943dfe9f0c..9beee3b1843 100644 --- a/src/test/run-fail/panic-task-name-none.rs +++ b/src/test/run-fail/panic-task-name-none.rs @@ -13,7 +13,7 @@ use std::thread::Thread; fn main() { - let r: Result = Thread::spawn(move|| { + let r: Result = Thread::scoped(move|| { panic!("test"); 1i }).join(); diff --git a/src/test/run-fail/panic-task-name-owned.rs b/src/test/run-fail/panic-task-name-owned.rs index 57901ebcfc6..714cec6fb3d 100644 --- a/src/test/run-fail/panic-task-name-owned.rs +++ b/src/test/run-fail/panic-task-name-owned.rs @@ -13,7 +13,7 @@ use std::thread::Builder; fn main() { - let r: Result = Builder::new().name("owned name".to_string()).spawn(move|| { + let r: Result = Builder::new().name("owned name".to_string()).scoped(move|| { panic!("test"); 1i }).join(); diff --git a/src/test/run-fail/task-spawn-barefn.rs b/src/test/run-fail/task-spawn-barefn.rs index 8aade641630..d58148810da 100644 --- a/src/test/run-fail/task-spawn-barefn.rs +++ b/src/test/run-fail/task-spawn-barefn.rs @@ -15,7 +15,7 @@ use std::thread::Thread; fn main() { // the purpose of this test is to make sure that task::spawn() // works when provided with a bare function: - let r = Thread::spawn(startfn).join(); + let r = Thread::scoped(startfn).join(); if r.is_err() { panic!() } diff --git a/src/test/run-make/static-unwinding/main.rs b/src/test/run-make/static-unwinding/main.rs index faac858e76e..bd88cb19aa7 100644 --- a/src/test/run-make/static-unwinding/main.rs +++ b/src/test/run-make/static-unwinding/main.rs @@ -22,7 +22,7 @@ impl Drop for A { } fn main() { - Thread::spawn(move|| { + Thread::scoped(move|| { let _a = A; lib::callback(|| panic!()); 1i diff --git a/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs b/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs index 440b7afa984..526819940d0 100644 --- a/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs +++ b/src/test/run-pass/cleanup-rvalue-temp-during-incomplete-alloc.rs @@ -45,5 +45,5 @@ pub fn fails() { } pub fn main() { - Thread::spawn(fails).join(); + Thread::scoped(fails).join(); } diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index 3298976de6c..eeb044e5604 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -90,7 +90,7 @@ pub fn test_destroy_actually_kills(force: bool) { _ = rx2.recv() => unsafe { libc::exit(1) }, _ = rx1.recv() => {} } - }).detach(); + }); match p.wait().unwrap() { ExitStatus(..) => panic!("expected a signal"), ExitSignal(..) => tx.send(()).unwrap(), diff --git a/src/test/run-pass/foreign-call-no-runtime.rs b/src/test/run-pass/foreign-call-no-runtime.rs index ce3e447350d..c1df9d53ad4 100644 --- a/src/test/run-pass/foreign-call-no-runtime.rs +++ b/src/test/run-pass/foreign-call-no-runtime.rs @@ -21,7 +21,7 @@ extern { pub fn main() { unsafe { - Thread::spawn(move|| { + Thread::scoped(move|| { let i = &100i; rust_dbg_call(callback, mem::transmute(i)); }).join(); diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index 3bcce538871..f83698edc90 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -1,4 +1,3 @@ - // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. @@ -37,7 +36,7 @@ mod map_reduce { for i in inputs.iter() { let ctrl = ctrl.clone(); let i = i.clone(); - Thread::spawn(move|| map_task(ctrl.clone(), i.clone()) ).detach(); + Thread::spawn(move|| map_task(ctrl.clone(), i.clone()) ); } } diff --git a/src/test/run-pass/issue-12684.rs b/src/test/run-pass/issue-12684.rs index 856fbbd00b2..a6a4d21e8f2 100644 --- a/src/test/run-pass/issue-12684.rs +++ b/src/test/run-pass/issue-12684.rs @@ -12,7 +12,7 @@ use std::time::Duration; use std::thread::Thread; fn main() { - Thread::spawn(move|| customtask()).join().ok().unwrap(); + Thread::scoped(move|| customtask()).join().ok().unwrap(); } fn customtask() { diff --git a/src/test/run-pass/issue-13494.rs b/src/test/run-pass/issue-13494.rs index b9339c1cc0d..bef0ff5fc2c 100644 --- a/src/test/run-pass/issue-13494.rs +++ b/src/test/run-pass/issue-13494.rs @@ -22,7 +22,7 @@ fn helper(rx: Receiver>) { fn main() { let (tx, rx) = channel(); - let _t = Thread::spawn(move|| { helper(rx) }).detach(); + let _t = Thread::spawn(move|| { helper(rx) }); let (snd, rcv) = channel::(); for _ in range(1i, 100000i) { snd.send(1i).unwrap(); diff --git a/src/test/run-pass/issue-16560.rs b/src/test/run-pass/issue-16560.rs index b2b819a1103..6b03a499f15 100644 --- a/src/test/run-pass/issue-16560.rs +++ b/src/test/run-pass/issue-16560.rs @@ -20,7 +20,7 @@ fn main() { // Check that both closures are capturing by value assert_eq!(1, mem::size_of_val(&closure)); - Thread::spawn(move|| { + Thread::scoped(move|| { let ok = closure; }).join().ok().unwrap(); } diff --git a/src/test/run-pass/issue-16671.rs b/src/test/run-pass/issue-16671.rs index 99758f9f777..e25b3e8e89c 100644 --- a/src/test/run-pass/issue-16671.rs +++ b/src/test/run-pass/issue-16671.rs @@ -24,5 +24,5 @@ pub fn main() { let mut stdin = std::io::stdin(); Thread::spawn(move|| { let _ = stdin.read_to_end(); - }).detach(); + }); } diff --git a/src/test/run-pass/issue-2190-1.rs b/src/test/run-pass/issue-2190-1.rs index 4bbbe978192..810bf385d7e 100644 --- a/src/test/run-pass/issue-2190-1.rs +++ b/src/test/run-pass/issue-2190-1.rs @@ -14,7 +14,7 @@ use std::thunk::Thunk; static generations: uint = 1024+256+128+49; fn spawn(f: Thunk) { - Builder::new().stack_size(32 * 1024).spawn(move|| f.invoke(())).detach() + Builder::new().stack_size(32 * 1024).spawn(move|| f.invoke(())); } fn child_no(x: uint) -> Thunk { diff --git a/src/test/run-pass/issue-4446.rs b/src/test/run-pass/issue-4446.rs index 30e1a14ecff..9c00348ad6a 100644 --- a/src/test/run-pass/issue-4446.rs +++ b/src/test/run-pass/issue-4446.rs @@ -17,7 +17,7 @@ pub fn main() { tx.send("hello, world").unwrap(); - Thread::spawn(move|| { + Thread::scoped(move|| { println(rx.recv().unwrap()); }).join().ok().unwrap(); } diff --git a/src/test/run-pass/issue-4448.rs b/src/test/run-pass/issue-4448.rs index 7e53722726f..a19bfca721a 100644 --- a/src/test/run-pass/issue-4448.rs +++ b/src/test/run-pass/issue-4448.rs @@ -14,7 +14,7 @@ use std::thread::Thread; pub fn main() { let (tx, rx) = channel::<&'static str>(); - let t = Thread::spawn(move|| { + let t = Thread::scoped(move|| { assert_eq!(rx.recv().unwrap(), "hello, world"); }); diff --git a/src/test/run-pass/issue-8460.rs b/src/test/run-pass/issue-8460.rs index 3d5e32972e7..3ea6d5d4f2f 100644 --- a/src/test/run-pass/issue-8460.rs +++ b/src/test/run-pass/issue-8460.rs @@ -12,24 +12,24 @@ use std::{int, i8, i16, i32, i64}; use std::thread::Thread; fn main() { - assert!(Thread::spawn(move|| int::MIN / -1).join().is_err()); - assert!(Thread::spawn(move|| i8::MIN / -1).join().is_err()); - assert!(Thread::spawn(move|| i16::MIN / -1).join().is_err()); - assert!(Thread::spawn(move|| i32::MIN / -1).join().is_err()); - assert!(Thread::spawn(move|| i64::MIN / -1).join().is_err()); - assert!(Thread::spawn(move|| 1i / 0).join().is_err()); - assert!(Thread::spawn(move|| 1i8 / 0).join().is_err()); - assert!(Thread::spawn(move|| 1i16 / 0).join().is_err()); - assert!(Thread::spawn(move|| 1i32 / 0).join().is_err()); - assert!(Thread::spawn(move|| 1i64 / 0).join().is_err()); - assert!(Thread::spawn(move|| int::MIN % -1).join().is_err()); - assert!(Thread::spawn(move|| i8::MIN % -1).join().is_err()); - assert!(Thread::spawn(move|| i16::MIN % -1).join().is_err()); - assert!(Thread::spawn(move|| i32::MIN % -1).join().is_err()); - assert!(Thread::spawn(move|| i64::MIN % -1).join().is_err()); - assert!(Thread::spawn(move|| 1i % 0).join().is_err()); - assert!(Thread::spawn(move|| 1i8 % 0).join().is_err()); - assert!(Thread::spawn(move|| 1i16 % 0).join().is_err()); - assert!(Thread::spawn(move|| 1i32 % 0).join().is_err()); - assert!(Thread::spawn(move|| 1i64 % 0).join().is_err()); + assert!(Thread::scoped(move|| int::MIN / -1).join().is_err()); + assert!(Thread::scoped(move|| i8::MIN / -1).join().is_err()); + assert!(Thread::scoped(move|| i16::MIN / -1).join().is_err()); + assert!(Thread::scoped(move|| i32::MIN / -1).join().is_err()); + assert!(Thread::scoped(move|| i64::MIN / -1).join().is_err()); + assert!(Thread::scoped(move|| 1i / 0).join().is_err()); + assert!(Thread::scoped(move|| 1i8 / 0).join().is_err()); + assert!(Thread::scoped(move|| 1i16 / 0).join().is_err()); + assert!(Thread::scoped(move|| 1i32 / 0).join().is_err()); + assert!(Thread::scoped(move|| 1i64 / 0).join().is_err()); + assert!(Thread::scoped(move|| int::MIN % -1).join().is_err()); + assert!(Thread::scoped(move|| i8::MIN % -1).join().is_err()); + assert!(Thread::scoped(move|| i16::MIN % -1).join().is_err()); + assert!(Thread::scoped(move|| i32::MIN % -1).join().is_err()); + assert!(Thread::scoped(move|| i64::MIN % -1).join().is_err()); + assert!(Thread::scoped(move|| 1i % 0).join().is_err()); + assert!(Thread::scoped(move|| 1i8 % 0).join().is_err()); + assert!(Thread::scoped(move|| 1i16 % 0).join().is_err()); + assert!(Thread::scoped(move|| 1i32 % 0).join().is_err()); + assert!(Thread::scoped(move|| 1i64 % 0).join().is_err()); } diff --git a/src/test/run-pass/issue-8827.rs b/src/test/run-pass/issue-8827.rs index 39695a8339f..d8b7490124f 100644 --- a/src/test/run-pass/issue-8827.rs +++ b/src/test/run-pass/issue-8827.rs @@ -26,7 +26,7 @@ fn periodical(n: int) -> Receiver { Err(..) => break } } - }).detach(); + }); return port; } @@ -41,7 +41,7 @@ fn integers() -> Receiver { } i = i + 1; } - }).detach(); + }); return port; } @@ -58,4 +58,3 @@ fn main() { } } } - diff --git a/src/test/run-pass/logging-only-prints-once.rs b/src/test/run-pass/logging-only-prints-once.rs index 509afff3d13..54f74239daf 100644 --- a/src/test/run-pass/logging-only-prints-once.rs +++ b/src/test/run-pass/logging-only-prints-once.rs @@ -27,7 +27,7 @@ impl fmt::Show for Foo { } pub fn main() { - Thread::spawn(move|| { + Thread::scoped(move|| { let mut f = Foo(Cell::new(0)); println!("{}", f); let Foo(ref mut f) = f; diff --git a/src/test/run-pass/macro-with-braces-in-expr-position.rs b/src/test/run-pass/macro-with-braces-in-expr-position.rs index 93bb9557604..cb52ba74bbd 100644 --- a/src/test/run-pass/macro-with-braces-in-expr-position.rs +++ b/src/test/run-pass/macro-with-braces-in-expr-position.rs @@ -14,7 +14,7 @@ macro_rules! expr { ($e: expr) => { $e } } macro_rules! spawn { ($($code: tt)*) => { - expr!(Thread::spawn(move|| {$($code)*}).detach()) + expr!(Thread::spawn(move|| {$($code)*})) } } diff --git a/src/test/run-pass/no-landing-pads.rs b/src/test/run-pass/no-landing-pads.rs index 6b1553cd9f6..64e78c3483b 100644 --- a/src/test/run-pass/no-landing-pads.rs +++ b/src/test/run-pass/no-landing-pads.rs @@ -23,7 +23,7 @@ impl Drop for A { } fn main() { - Thread::spawn(move|| -> () { + Thread::scoped(move|| -> () { let _a = A; panic!(); }).join().unwrap_err(); diff --git a/src/test/run-pass/panic-in-dtor-drops-fields.rs b/src/test/run-pass/panic-in-dtor-drops-fields.rs index 5c692bf8801..3cc01b967ce 100644 --- a/src/test/run-pass/panic-in-dtor-drops-fields.rs +++ b/src/test/run-pass/panic-in-dtor-drops-fields.rs @@ -33,10 +33,9 @@ impl Drop for B { } pub fn main() { - let ret = Thread::spawn(move|| { + let ret = Thread::scoped(move|| { let _a = A { b: B { foo: 3 } }; }).join(); assert!(ret.is_err()); unsafe { assert!(dropped); } } - 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 3ed835dc5bd..a6e4716c3b8 100644 --- a/src/test/run-pass/sendfn-spawn-with-fn-arg.rs +++ b/src/test/run-pass/sendfn-spawn-with-fn-arg.rs @@ -22,7 +22,7 @@ fn test05() { println!("{}", *three + n); // will copy x into the closure assert_eq!(*three, 3); }; - Thread::spawn(move|| { + Thread::scoped(move|| { test05_start(fn_to_send); }).join().ok().unwrap(); } diff --git a/src/test/run-pass/sepcomp-unwind.rs b/src/test/run-pass/sepcomp-unwind.rs index 246957a4f46..b8bb3b4e7f8 100644 --- a/src/test/run-pass/sepcomp-unwind.rs +++ b/src/test/run-pass/sepcomp-unwind.rs @@ -36,5 +36,5 @@ mod b { } fn main() { - Thread::spawn(move|| { ::b::g() }).join().unwrap_err(); + Thread::scoped(move|| { ::b::g() }).join().unwrap_err(); } diff --git a/src/test/run-pass/slice-panic-1.rs b/src/test/run-pass/slice-panic-1.rs index 13f2971871b..c3612d26c93 100644 --- a/src/test/run-pass/slice-panic-1.rs +++ b/src/test/run-pass/slice-panic-1.rs @@ -28,6 +28,6 @@ fn foo() { } fn main() { - let _ = Thread::spawn(move|| foo()).join(); + let _ = Thread::scoped(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); } } diff --git a/src/test/run-pass/slice-panic-2.rs b/src/test/run-pass/slice-panic-2.rs index ccbb33d7768..c1e6d941d93 100644 --- a/src/test/run-pass/slice-panic-2.rs +++ b/src/test/run-pass/slice-panic-2.rs @@ -32,6 +32,6 @@ fn foo() { } fn main() { - let _ = Thread::spawn(move|| foo()).join(); + let _ = Thread::scoped(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); } } diff --git a/src/test/run-pass/spawn-types.rs b/src/test/run-pass/spawn-types.rs index bb9de7cecc9..eaad2abe8f7 100644 --- a/src/test/run-pass/spawn-types.rs +++ b/src/test/run-pass/spawn-types.rs @@ -25,6 +25,6 @@ fn iotask(_tx: &ctx, ip: String) { pub fn main() { let (tx, _rx) = channel::(); - let t = Thread::spawn(move|| iotask(&tx, "localhost".to_string()) ); + let t = Thread::scoped(move|| iotask(&tx, "localhost".to_string()) ); t.join().ok().unwrap(); } diff --git a/src/test/run-pass/spawn.rs b/src/test/run-pass/spawn.rs index 820dd49142a..8f937afa6b9 100644 --- a/src/test/run-pass/spawn.rs +++ b/src/test/run-pass/spawn.rs @@ -11,7 +11,7 @@ use std::thread::Thread; pub fn main() { - Thread::spawn(move|| child(10)).join().ok().unwrap(); + Thread::scoped(move|| child(10)).join().ok().unwrap(); } fn child(i: int) { println!("{}", i); assert!((i == 10)); } diff --git a/src/test/run-pass/spawn2.rs b/src/test/run-pass/spawn2.rs index 50c2d79132e..75104a4ddef 100644 --- a/src/test/run-pass/spawn2.rs +++ b/src/test/run-pass/spawn2.rs @@ -11,7 +11,7 @@ use std::thread::Thread; pub fn main() { - let t = Thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) ); + let t = Thread::scoped(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) ); t.join().ok().unwrap(); } diff --git a/src/test/run-pass/spawning-with-debug.rs b/src/test/run-pass/spawning-with-debug.rs index ea594977f90..858b7a83c62 100644 --- a/src/test/run-pass/spawning-with-debug.rs +++ b/src/test/run-pass/spawning-with-debug.rs @@ -17,5 +17,5 @@ use std::thread::Builder; pub fn main() { let mut t = Builder::new(); - t.spawn(move|| ()).detach(); + t.spawn(move|| ()); } diff --git a/src/test/run-pass/task-comm-1.rs b/src/test/run-pass/task-comm-1.rs index 966bb6aa735..180f6e09ba9 100644 --- a/src/test/run-pass/task-comm-1.rs +++ b/src/test/run-pass/task-comm-1.rs @@ -15,6 +15,6 @@ pub fn main() { test00(); } fn start() { println!("Started / Finished task."); } fn test00() { - let _ = Thread::spawn(move|| start() ).join(); + let _ = Thread::scoped(move|| start() ).join(); println!("Completing."); } diff --git a/src/test/run-pass/task-comm-12.rs b/src/test/run-pass/task-comm-12.rs index 561c9e91553..da080408ad1 100644 --- a/src/test/run-pass/task-comm-12.rs +++ b/src/test/run-pass/task-comm-12.rs @@ -16,7 +16,7 @@ fn start(_task_number: int) { println!("Started / Finished task."); } fn test00() { let i: int = 0; - let mut result = Thread::spawn(move|| { + let mut result = Thread::scoped(move|| { start(i) }); diff --git a/src/test/run-pass/task-comm-13.rs b/src/test/run-pass/task-comm-13.rs index 50667d375a1..429c6ce9fb3 100644 --- a/src/test/run-pass/task-comm-13.rs +++ b/src/test/run-pass/task-comm-13.rs @@ -19,6 +19,6 @@ fn start(tx: &Sender, start: int, number_of_messages: int) { pub fn main() { println!("Check that we don't deadlock."); let (tx, rx) = channel(); - let _ = Thread::spawn(move|| { start(&tx, 0, 10) }).join(); + let _ = Thread::scoped(move|| { start(&tx, 0, 10) }).join(); println!("Joined task"); } diff --git a/src/test/run-pass/task-comm-14.rs b/src/test/run-pass/task-comm-14.rs index 82e4bd8f6d2..0735e3996ee 100644 --- a/src/test/run-pass/task-comm-14.rs +++ b/src/test/run-pass/task-comm-14.rs @@ -19,7 +19,7 @@ pub fn main() { while (i > 0) { println!("{}", i); let tx = tx.clone(); - Thread::spawn({let i = i; move|| { child(i, &tx) }}).detach(); + Thread::spawn({let i = i; move|| { child(i, &tx) }}); i = i - 1; } diff --git a/src/test/run-pass/task-comm-17.rs b/src/test/run-pass/task-comm-17.rs index e9f7cdf96a8..9db5465f7e9 100644 --- a/src/test/run-pass/task-comm-17.rs +++ b/src/test/run-pass/task-comm-17.rs @@ -18,5 +18,5 @@ fn f() { } pub fn main() { - let _t = Thread::spawn(move|| f() ).join(); + let _t = Thread::scoped(move|| f() ).join(); } diff --git a/src/test/run-pass/task-comm-3.rs b/src/test/run-pass/task-comm-3.rs index a002a597481..306cc0ffcef 100644 --- a/src/test/run-pass/task-comm-3.rs +++ b/src/test/run-pass/task-comm-3.rs @@ -40,7 +40,7 @@ fn test00() { let mut results = Vec::new(); while i < number_of_tasks { let tx = tx.clone(); - results.push(Thread::spawn({ + results.push(Thread::scoped({ let i = i; move|| { test00_start(&tx, i, number_of_messages) diff --git a/src/test/run-pass/task-comm-9.rs b/src/test/run-pass/task-comm-9.rs index d9faf6ee4e4..6d8de4a6a53 100644 --- a/src/test/run-pass/task-comm-9.rs +++ b/src/test/run-pass/task-comm-9.rs @@ -24,7 +24,7 @@ fn test00() { let (tx, rx) = channel(); let number_of_messages: int = 10; - let result = Thread::spawn(move|| { + let result = Thread::scoped(move|| { test00_start(&tx, number_of_messages); }); diff --git a/src/test/run-pass/task-stderr.rs b/src/test/run-pass/task-stderr.rs index a7eabe0edb3..7ff5960375c 100644 --- a/src/test/run-pass/task-stderr.rs +++ b/src/test/run-pass/task-stderr.rs @@ -17,7 +17,7 @@ fn main() { let mut reader = ChanReader::new(rx); let stderr = ChanWriter::new(tx); - let res = thread::Builder::new().stderr(box stderr as Box).spawn(move|| -> () { + let res = thread::Builder::new().stderr(box stderr as Box).scoped(move|| -> () { panic!("Hello, world!") }).join(); assert!(res.is_err()); diff --git a/src/test/run-pass/tcp-accept-stress.rs b/src/test/run-pass/tcp-accept-stress.rs index 3e6158ca821..cd3cb872fd3 100644 --- a/src/test/run-pass/tcp-accept-stress.rs +++ b/src/test/run-pass/tcp-accept-stress.rs @@ -52,7 +52,7 @@ fn test() { } } srv_tx.send(()); - }).detach(); + }); } for _ in range(0, N) { @@ -62,7 +62,7 @@ fn test() { let _s = TcpStream::connect(addr).unwrap(); } cli_tx.send(()); - }).detach(); + }); } drop((cli_tx, srv_tx)); diff --git a/src/test/run-pass/tcp-stress.rs b/src/test/run-pass/tcp-stress.rs index 7d226aa9420..0109d64ad53 100644 --- a/src/test/run-pass/tcp-stress.rs +++ b/src/test/run-pass/tcp-stress.rs @@ -29,7 +29,7 @@ fn main() { timer::sleep(Duration::milliseconds(30 * 1000)); println!("timed out!"); unsafe { libc::exit(1) } - }).detach(); + }); let (tx, rx) = channel(); Thread::spawn(move || -> () { @@ -47,7 +47,7 @@ fn main() { stream.read_byte(); stream.write(&[2]); } - }).detach(); + }); let addr = rx.recv().unwrap(); let (tx, rx) = channel(); @@ -64,7 +64,7 @@ fn main() { Err(e) => debug!("{}", e) } tx.send(()).unwrap(); - }).detach(); + }); } // Wait for all clients to exit, but don't wait for the server to exit. The diff --git a/src/test/run-pass/tempfile.rs b/src/test/run-pass/tempfile.rs index bf108ecd676..b931bd9609c 100644 --- a/src/test/run-pass/tempfile.rs +++ b/src/test/run-pass/tempfile.rs @@ -42,7 +42,7 @@ fn test_rm_tempdir() { tx.send(tmp.path().clone()).unwrap(); panic!("panic to unwind past `tmp`"); }; - let _ = Thread::spawn(f).join(); + let _ = Thread::scoped(f).join(); let path = rx.recv().unwrap(); assert!(!path.exists()); @@ -52,7 +52,7 @@ fn test_rm_tempdir() { let _tmp = tmp; panic!("panic to unwind past `tmp`"); }; - let _ = Thread::spawn(f).join(); + let _ = Thread::scoped(f).join(); assert!(!path.exists()); let path; @@ -60,7 +60,7 @@ fn test_rm_tempdir() { let f = move|:| { TempDir::new("test_rm_tempdir").unwrap() }; - let tmp = Thread::spawn(f).join().ok().expect("test_rm_tmdir"); + let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); } @@ -84,7 +84,7 @@ fn test_rm_tempdir_close() { tmp.close(); panic!("panic when unwinding past `tmp`"); }; - let _ = Thread::spawn(f).join(); + let _ = Thread::scoped(f).join(); let path = rx.recv().unwrap(); assert!(!path.exists()); @@ -95,7 +95,7 @@ fn test_rm_tempdir_close() { tmp.close(); panic!("panic when unwinding past `tmp`"); }; - let _ = Thread::spawn(f).join(); + let _ = Thread::scoped(f).join(); assert!(!path.exists()); let path; @@ -103,7 +103,7 @@ fn test_rm_tempdir_close() { let f = move|:| { TempDir::new("test_rm_tempdir").unwrap() }; - let tmp = Thread::spawn(f).join().ok().expect("test_rm_tmdir"); + let tmp = Thread::scoped(f).join().ok().expect("test_rm_tmdir"); path = tmp.path().clone(); assert!(path.exists()); tmp.close(); @@ -177,7 +177,7 @@ pub fn test_rmdir_recursive_ok() { } pub fn dont_double_panic() { - let r: Result<(), _> = Thread::spawn(move|| { + let r: Result<(), _> = Thread::scoped(move|| { let tmpdir = TempDir::new("test").unwrap(); // Remove the temporary directory so that TempDir sees // an error on drop diff --git a/src/test/run-pass/terminate-in-initializer.rs b/src/test/run-pass/terminate-in-initializer.rs index 4270ecc7450..bfd1f5f4a74 100644 --- a/src/test/run-pass/terminate-in-initializer.rs +++ b/src/test/run-pass/terminate-in-initializer.rs @@ -22,13 +22,13 @@ fn test_ret() { let _x: Box = return; } fn test_panic() { fn f() { let _x: Box = panic!(); } - Thread::spawn(move|| f() ).join().err().unwrap(); + Thread::scoped(move|| f() ).join().err().unwrap(); } fn test_panic_indirect() { fn f() -> ! { panic!(); } fn g() { let _x: Box = f(); } - Thread::spawn(move|| g() ).join().err().unwrap(); + Thread::scoped(move|| g() ).join().err().unwrap(); } pub fn main() { diff --git a/src/test/run-pass/threads.rs b/src/test/run-pass/threads.rs index 02817a285dd..c47ca0db2a1 100644 --- a/src/test/run-pass/threads.rs +++ b/src/test/run-pass/threads.rs @@ -13,7 +13,7 @@ use std::thread::Thread; pub fn main() { let mut i = 10; while i > 0 { - Thread::spawn({let i = i; move|| child(i)}).detach(); + Thread::spawn({let i = i; move|| child(i)}); i = i - 1; } println!("main thread exiting"); diff --git a/src/test/run-pass/unique-send-2.rs b/src/test/run-pass/unique-send-2.rs index bd4143348b8..bb3019ede4b 100644 --- a/src/test/run-pass/unique-send-2.rs +++ b/src/test/run-pass/unique-send-2.rs @@ -23,7 +23,7 @@ pub fn main() { let tx = tx.clone(); Thread::spawn(move|| { child(&tx, i) - }).detach(); + }); expected += i; } diff --git a/src/test/run-pass/unit-like-struct-drop-run.rs b/src/test/run-pass/unit-like-struct-drop-run.rs index 9aeb5b10cf5..4c866503282 100644 --- a/src/test/run-pass/unit-like-struct-drop-run.rs +++ b/src/test/run-pass/unit-like-struct-drop-run.rs @@ -22,7 +22,7 @@ impl Drop for Foo { } pub fn main() { - let x = Thread::spawn(move|| { + let x = Thread::scoped(move|| { let _b = Foo; }).join(); diff --git a/src/test/run-pass/vector-sort-panic-safe.rs b/src/test/run-pass/vector-sort-panic-safe.rs index bdd62995e0a..29bf82a81d6 100644 --- a/src/test/run-pass/vector-sort-panic-safe.rs +++ b/src/test/run-pass/vector-sort-panic-safe.rs @@ -77,7 +77,7 @@ pub fn main() { let v = main.clone(); - let _ = Thread::spawn(move|| { + let _ = Thread::scoped(move|| { let mut v = v; let mut panic_countdown = panic_countdown; v.as_mut_slice().sort_by(|a, b| { diff --git a/src/test/run-pass/yield.rs b/src/test/run-pass/yield.rs index 9a96b483f2c..9ad6dd9d2b1 100644 --- a/src/test/run-pass/yield.rs +++ b/src/test/run-pass/yield.rs @@ -11,7 +11,7 @@ use std::thread::Thread; pub fn main() { - let mut result = Thread::spawn(child); + let mut result = Thread::scoped(child); println!("1"); Thread::yield_now(); println!("2"); diff --git a/src/test/run-pass/yield1.rs b/src/test/run-pass/yield1.rs index 13119e5d909..3d3a36021da 100644 --- a/src/test/run-pass/yield1.rs +++ b/src/test/run-pass/yield1.rs @@ -11,7 +11,7 @@ use std::thread::Thread; pub fn main() { - let mut result = Thread::spawn(child); + let mut result = Thread::scoped(child); println!("1"); Thread::yield_now(); result.join(); -- cgit 1.4.1-3-g733a5 From 9f07d055f7823ac0e17e014f3effa2a0be0947e9 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Wed, 7 Jan 2015 11:33:42 +1300 Subject: markers -> marker --- src/liballoc/arc.rs | 2 +- src/liballoc/boxed.rs | 2 +- src/liballoc/rc.rs | 24 +- src/libcollections/btree/map.rs | 10 +- src/libcollections/lib.rs | 6 +- src/libcollections/ring_buf.rs | 6 +- src/libcollections/slice.rs | 2 +- src/libcollections/vec.rs | 2 +- src/libcore/array.rs | 2 +- src/libcore/atomic.rs | 2 +- src/libcore/borrow.rs | 2 +- src/libcore/cell.rs | 6 +- src/libcore/clone.rs | 2 +- src/libcore/cmp.rs | 4 +- src/libcore/fmt/mod.rs | 2 +- src/libcore/iter.rs | 2 +- src/libcore/lib.rs | 6 +- src/libcore/marker.rs | 314 +++++++++++++++++++++ src/libcore/markers.rs | 314 --------------------- src/libcore/mem.rs | 2 +- src/libcore/num/mod.rs | 4 +- src/libcore/ops.rs | 2 +- src/libcore/prelude.rs | 2 +- src/libcore/ptr.rs | 2 +- src/libcore/raw.rs | 2 +- src/libcore/slice.rs | 16 +- src/libcore/str/mod.rs | 2 +- src/libcore/ty.rs | 2 +- src/libcoretest/hash/mod.rs | 2 +- src/libcoretest/num/mod.rs | 2 +- src/libcoretest/option.rs | 4 +- src/liblibc/lib.rs | 4 +- src/librand/lib.rs | 4 +- src/librustc/middle/expr_use_visitor.rs | 4 +- src/librustc/middle/infer/unify.rs | 6 +- src/librustc_typeck/variance.rs | 4 +- src/libstd/collections/hash/map.rs | 2 +- src/libstd/collections/hash/set.rs | 2 +- src/libstd/collections/hash/table.rs | 22 +- src/libstd/hash.rs | 2 +- src/libstd/io/mod.rs | 2 +- src/libstd/io/stdio.rs | 2 +- src/libstd/lib.rs | 10 +- src/libstd/num/mod.rs | 2 +- src/libstd/os.rs | 2 +- src/libstd/path/mod.rs | 2 +- src/libstd/path/posix.rs | 2 +- src/libstd/prelude/v1.rs | 2 +- src/libstd/rand/os.rs | 2 +- src/libstd/rt/mod.rs | 2 +- src/libstd/sync/mpsc/blocking.rs | 4 +- src/libstd/sync/mpsc/mod.rs | 6 +- src/libstd/sync/mpsc/select.rs | 6 +- src/libstd/sync/mutex.rs | 6 +- src/libstd/sync/once.rs | 2 +- src/libstd/sync/rwlock.rs | 10 +- src/libstd/sys/common/mutex.rs | 2 +- src/libstd/sys/unix/c.rs | 8 +- src/libstd/sys/unix/mutex.rs | 2 +- src/libstd/thread.rs | 2 +- src/libstd/thread_local/mod.rs | 4 +- src/libstd/thread_local/scoped.rs | 10 +- src/libstd/thunk.rs | 2 +- src/libsyntax/ext/deriving/bounds.rs | 2 +- src/libunicode/tables.rs | 2 +- src/test/compile-fail/associated-types-unsized.rs | 2 +- src/test/compile-fail/bad-method-typaram-kind.rs | 2 +- src/test/compile-fail/bad-sized.rs | 6 +- .../borrowck-move-out-of-static-item.rs | 6 +- .../borrowck-struct-update-with-dtor.rs | 2 +- .../builtin-superkinds-double-superkind.rs | 4 +- .../compile-fail/builtin-superkinds-in-metadata.rs | 2 +- .../builtin-superkinds-typaram-not-send.rs | 2 +- .../check-static-values-constraints.rs | 2 +- ...sure-bounds-cant-promote-superkind-in-struct.rs | 2 +- src/test/compile-fail/closure-bounds-subtype.rs | 2 +- src/test/compile-fail/comm-not-freeze-receiver.rs | 2 +- src/test/compile-fail/comm-not-freeze.rs | 2 +- src/test/compile-fail/dst-bad-assign-2.rs | 2 +- src/test/compile-fail/dst-bad-assign.rs | 2 +- src/test/compile-fail/dst-bad-deep.rs | 2 +- .../compile-fail/dst-object-from-unsized-type.rs | 8 +- src/test/compile-fail/dst-sized-trait-param.rs | 4 +- .../compile-fail/error-should-say-copy-not-pod.rs | 2 +- src/test/compile-fail/issue-14366.rs | 2 +- src/test/compile-fail/issue-15756.rs | 2 +- src/test/compile-fail/issue-16538.rs | 2 +- src/test/compile-fail/issue-17718-static-move.rs | 6 +- src/test/compile-fail/issue-17718-static-sync.rs | 8 +- src/test/compile-fail/issue-18107.rs | 2 +- src/test/compile-fail/issue-19883.rs | 6 +- src/test/compile-fail/issue-20005.rs | 4 +- src/test/compile-fail/issue-3907-2.rs | 2 +- src/test/compile-fail/issue-5035-2.rs | 2 +- src/test/compile-fail/issue-5543.rs | 2 +- src/test/compile-fail/issue-5883.rs | 4 +- src/test/compile-fail/issue-7013.rs | 4 +- src/test/compile-fail/issue-7364.rs | 4 +- src/test/compile-fail/kindck-copy.rs | 22 +- src/test/compile-fail/kindck-impl-type-params-2.rs | 2 +- src/test/compile-fail/kindck-impl-type-params.rs | 12 +- .../compile-fail/kindck-inherited-copy-bound.rs | 4 +- src/test/compile-fail/kindck-nonsendable-1.rs | 4 +- src/test/compile-fail/kindck-send-object.rs | 4 +- src/test/compile-fail/kindck-send-object1.rs | 4 +- src/test/compile-fail/kindck-send-object2.rs | 4 +- src/test/compile-fail/kindck-send-unsafe.rs | 2 +- src/test/compile-fail/lint-dead-code-4.rs | 4 +- src/test/compile-fail/marker-no-copy.rs | 4 +- src/test/compile-fail/marker-no-send.rs | 4 +- src/test/compile-fail/marker-no-share.rs | 4 +- src/test/compile-fail/mut-not-freeze.rs | 4 +- src/test/compile-fail/mutable-enum-indirect.rs | 8 +- src/test/compile-fail/no-send-res-ports.rs | 4 +- src/test/compile-fail/no_send-enum.rs | 8 +- src/test/compile-fail/no_send-rc.rs | 4 +- src/test/compile-fail/no_send-struct.rs | 8 +- src/test/compile-fail/no_share-enum.rs | 8 +- src/test/compile-fail/no_share-rc.rs | 4 +- src/test/compile-fail/no_share-struct.rs | 8 +- src/test/compile-fail/opt-out-copy-bad.rs | 2 +- src/test/compile-fail/range-1.rs | 2 +- .../regions-infer-contravariance-due-to-decl.rs | 4 +- .../regions-infer-covariance-due-to-decl.rs | 4 +- .../regions-infer-invariance-due-to-decl.rs | 4 +- src/test/compile-fail/repeat-to-run-dtor-twice.rs | 2 +- src/test/compile-fail/static-items-cant-move.rs | 6 +- .../syntax-trait-polarity-feature-gate.rs | 2 +- src/test/compile-fail/syntax-trait-polarity.rs | 2 +- src/test/compile-fail/task-rng-isnt-sendable.rs | 4 +- .../compile-fail/trait-bounds-not-on-bare-trait.rs | 2 +- .../compile-fail/typeck-unsafe-always-share.rs | 16 +- .../compile-fail/unboxed-closure-sugar-region.rs | 2 +- src/test/compile-fail/unique-unique-kind.rs | 4 +- src/test/compile-fail/unsendable-class.rs | 4 +- src/test/compile-fail/unsized-bare-typaram.rs | 2 +- src/test/compile-fail/unsized-enum.rs | 4 +- src/test/compile-fail/unsized-struct.rs | 4 +- .../compile-fail/unsized-trait-impl-trait-arg.rs | 2 +- src/test/compile-fail/unsized3.rs | 12 +- src/test/compile-fail/unsized5.rs | 12 +- src/test/compile-fail/unsized6.rs | 26 +- src/test/compile-fail/unsized7.rs | 2 +- ...ause-constraints-are-local-for-inherent-impl.rs | 2 +- ...-clause-constraints-are-local-for-trait-impl.rs | 2 +- .../run-pass/associated-types-impl-redirect.rs | 2 +- ...associated-types-where-clause-impl-ambiguity.rs | 2 +- src/test/run-pass/const-block.rs | 2 +- src/test/run-pass/fsu-moves-and-copies.rs | 2 +- src/test/run-pass/hrtb-opt-in-copy.rs | 4 +- .../run-pass/issue-17718-static-unsafe-interior.rs | 2 +- src/test/run-pass/issue-2718.rs | 2 +- src/test/run-pass/method-recursive-blanket-impl.rs | 2 +- src/test/run-pass/regions-infer-bivariance.rs | 2 +- src/test/run-pass/syntax-trait-polarity.rs | 2 +- 155 files changed, 642 insertions(+), 642 deletions(-) create mode 100644 src/libcore/marker.rs delete mode 100644 src/libcore/markers.rs (limited to 'src/libstd/thread_local') diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index a3b77ccb6db..841882b4719 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -74,7 +74,7 @@ use core::clone::Clone; use core::fmt::{self, Show}; use core::cmp::{Eq, Ord, PartialEq, PartialOrd, Ordering}; use core::default::Default; -use core::markers::{Sync, Send}; +use core::marker::{Sync, Send}; use core::mem::{min_align_of, size_of, drop}; use core::mem; use core::nonzero::NonZero; diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 0b211c7c212..a7f76c02bd8 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -18,7 +18,7 @@ use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; use core::fmt; use core::hash::{self, Hash}; -use core::markers::Sized; +use core::marker::Sized; use core::mem; use core::option::Option; use core::ptr::Unique; diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index c6eaaaeecca..69a0d596644 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -148,7 +148,7 @@ use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering}; use core::default::Default; use core::fmt; use core::hash::{self, Hash}; -use core::markers; +use core::marker; use core::mem::{transmute, min_align_of, size_of, forget}; use core::nonzero::NonZero; use core::ops::{Deref, Drop}; @@ -175,8 +175,8 @@ pub struct Rc { // FIXME #12808: strange names to try to avoid interfering with field accesses of the contained // type via Deref _ptr: NonZero<*mut RcBox>, - _nosend: markers::NoSend, - _noshare: markers::NoSync + _nosend: marker::NoSend, + _noshare: marker::NoSync } impl Rc { @@ -201,8 +201,8 @@ impl Rc { strong: Cell::new(1), weak: Cell::new(1) })), - _nosend: markers::NoSend, - _noshare: markers::NoSync + _nosend: marker::NoSend, + _noshare: marker::NoSync } } } @@ -223,8 +223,8 @@ impl Rc { self.inc_weak(); Weak { _ptr: self._ptr, - _nosend: markers::NoSend, - _noshare: markers::NoSync + _nosend: marker::NoSend, + _noshare: marker::NoSync } } } @@ -431,7 +431,7 @@ impl Clone for Rc { #[inline] fn clone(&self) -> Rc { self.inc_strong(); - Rc { _ptr: self._ptr, _nosend: markers::NoSend, _noshare: markers::NoSync } + Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync } } } @@ -622,8 +622,8 @@ pub struct Weak { // FIXME #12808: strange names to try to avoid interfering with // field accesses of the contained type via Deref _ptr: NonZero<*mut RcBox>, - _nosend: markers::NoSend, - _noshare: markers::NoSync + _nosend: marker::NoSend, + _noshare: marker::NoSync } #[experimental = "Weak pointers may not belong in this module."] @@ -650,7 +650,7 @@ impl Weak { None } else { self.inc_strong(); - Some(Rc { _ptr: self._ptr, _nosend: markers::NoSend, _noshare: markers::NoSync }) + Some(Rc { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync }) } } } @@ -717,7 +717,7 @@ impl Clone for Weak { #[inline] fn clone(&self) -> Weak { self.inc_weak(); - Weak { _ptr: self._ptr, _nosend: markers::NoSend, _noshare: markers::NoSync } + Weak { _ptr: self._ptr, _nosend: marker::NoSend, _noshare: marker::NoSync } } } diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 73cc46091e9..66c28375d7a 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -480,7 +480,7 @@ enum Continuation { /// boilerplate gets cut out. mod stack { use core::prelude::*; - use core::markers; + use core::marker; use core::mem; use core::ops::{Deref, DerefMut}; use super::BTreeMap; @@ -494,7 +494,7 @@ mod stack { /// where `&'static` can be used in any function expecting any lifetime reference. pub struct IdRef<'id, T: 'id> { inner: &'id mut T, - marker: markers::InvariantLifetime<'id> + marker: marker::InvariantLifetime<'id> } impl<'id, T> Deref for IdRef<'id, T> { @@ -536,7 +536,7 @@ mod stack { pub struct Pusher<'id, 'a, K:'a, V:'a> { map: &'a mut BTreeMap, stack: Stack, - marker: markers::InvariantLifetime<'id> + marker: marker::InvariantLifetime<'id> } impl<'a, K, V> PartialSearchStack<'a, K, V> { @@ -571,11 +571,11 @@ mod stack { let pusher = Pusher { map: self.map, stack: self.stack, - marker: markers::InvariantLifetime + marker: marker::InvariantLifetime }; let node = IdRef { inner: unsafe { &mut *self.next }, - marker: markers::InvariantLifetime + marker: marker::InvariantLifetime }; closure(pusher, node) diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index cbe5d2404e7..5463d135c08 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -124,8 +124,8 @@ mod std { pub use core::clone; // deriving(Clone) pub use core::cmp; // deriving(Eq, Ord, etc.) #[cfg(stage0)] - pub use core::markers as kinds; - pub use core::markers; // deriving(Copy) + pub use core::marker as kinds; + pub use core::marker; // deriving(Copy) pub use core::hash; // deriving(Hash) } @@ -140,7 +140,7 @@ mod prelude { pub use core::iter::{FromIterator, Extend, IteratorExt}; pub use core::iter::{Iterator, DoubleEndedIterator, RandomAccessIterator}; pub use core::iter::{ExactSizeIterator}; - pub use core::markers::{Copy, Send, Sized, Sync}; + pub use core::marker::{Copy, Send, Sized, Sync}; pub use core::mem::drop; pub use core::ops::{Drop, Fn, FnMut, FnOnce}; pub use core::option::Option; diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index 3c1cd101e3b..38993520da1 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -20,7 +20,7 @@ use core::cmp::Ordering; use core::default::Default; use core::fmt; use core::iter::{self, repeat, FromIterator, RandomAccessIterator}; -use core::markers; +use core::marker; use core::mem; use core::num::{Int, UnsignedInt}; use core::ops::{Index, IndexMut}; @@ -534,7 +534,7 @@ impl RingBuf { head: self.head, cap: self.cap, ptr: self.ptr, - marker: markers::ContravariantLifetime::<'a>, + marker: marker::ContravariantLifetime::<'a>, } } @@ -1414,7 +1414,7 @@ pub struct IterMut<'a, T:'a> { tail: uint, head: uint, cap: uint, - marker: markers::ContravariantLifetime<'a>, + marker: marker::ContravariantLifetime<'a>, } #[stable] diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index d7e0b3d9353..6acb75387fd 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -95,7 +95,7 @@ use core::cmp::Ordering::{self, Greater, Less}; use core::cmp::{self, Ord, PartialEq}; use core::iter::{Iterator, IteratorExt}; use core::iter::{range, range_step, MultiplicativeIterator}; -use core::markers::Sized; +use core::marker::Sized; use core::mem::size_of; use core::mem; use core::ops::{FnMut, SliceMut}; diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index b3b560a23bd..9979fe128fc 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -55,7 +55,7 @@ use core::default::Default; use core::fmt; use core::hash::{self, Hash}; use core::iter::{repeat, FromIterator}; -use core::markers::{ContravariantLifetime, InvariantType}; +use core::marker::{ContravariantLifetime, InvariantType}; use core::mem; use core::nonzero::NonZero; use core::num::{Int, UnsignedInt}; diff --git a/src/libcore/array.rs b/src/libcore/array.rs index f85b17fb7f0..2013c398c55 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -17,7 +17,7 @@ use clone::Clone; use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use fmt; -use markers::Copy; +use marker::Copy; use ops::Deref; use option::Option; diff --git a/src/libcore/atomic.rs b/src/libcore/atomic.rs index 9e5bda4bf43..aee1d825bc2 100644 --- a/src/libcore/atomic.rs +++ b/src/libcore/atomic.rs @@ -72,7 +72,7 @@ use self::Ordering::*; -use markers::Sync; +use marker::Sync; use intrinsics; use cell::UnsafeCell; diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs index c4adf724b2f..de9c79614b3 100644 --- a/src/libcore/borrow.rs +++ b/src/libcore/borrow.rs @@ -47,7 +47,7 @@ use clone::Clone; use cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use fmt; -use markers::Sized; +use marker::Sized; use ops::Deref; use option::Option; use self::Cow::*; diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index ae590b1de06..7217468c74e 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -161,7 +161,7 @@ use clone::Clone; use cmp::PartialEq; use default::Default; use fmt; -use markers::{Copy, Send}; +use marker::{Copy, Send}; use ops::{Deref, DerefMut, Drop}; use option::Option; use option::Option::{None, Some}; @@ -520,11 +520,11 @@ impl<'b, T> DerefMut for RefMut<'b, T> { /// /// ```rust /// use std::cell::UnsafeCell; -/// use std::markers; +/// use std::marker; /// /// struct NotThreadSafe { /// value: UnsafeCell, -/// marker: markers::NoSync +/// marker: marker::NoSync /// } /// ``` /// diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 78a5848f34d..3149247a83a 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -21,7 +21,7 @@ #![stable] -use markers::Sized; +use marker::Sized; /// A common trait for cloning an object. #[stable] diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 01f1073a5d3..c3dfd5f5159 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -43,7 +43,7 @@ use self::Ordering::*; -use markers::Sized; +use marker::Sized; use option::Option::{self, Some, None}; /// Trait for equality comparisons which are [partial equivalence relations]( @@ -316,7 +316,7 @@ pub fn partial_max(v1: T, v2: T) -> Option { mod impls { use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering}; use cmp::Ordering::{Less, Greater, Equal}; - use markers::Sized; + use marker::Sized; use option::Option; use option::Option::{Some, None}; diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index ed01cf64769..c7ff0f938b6 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -15,7 +15,7 @@ use any; use cell::{Cell, Ref, RefMut}; use iter::{Iterator, IteratorExt, range}; -use markers::{Copy, Sized}; +use marker::{Copy, Sized}; use mem; use option::Option; use option::Option::{Some, None}; diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index ac5804c910d..97d26b5333a 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -67,7 +67,7 @@ use num::{ToPrimitive, Int}; use ops::{Add, Deref, FnMut}; use option::Option; use option::Option::{Some, None}; -use std::markers::Sized; +use std::marker::Sized; use uint; /// An interface for dealing with "external iterators". These types of iterators diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index c06dc056d20..98b1e8db89f 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -111,7 +111,7 @@ pub mod ptr; /* Core language traits */ -pub mod markers; +pub mod marker; pub mod ops; pub mod cmp; pub mod clone; @@ -151,8 +151,8 @@ mod std { pub use clone; pub use cmp; #[cfg(stage0)] - pub use markers as kinds; - pub use markers; + pub use marker as kinds; + pub use marker; pub use option; pub use fmt; pub use hash; diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs new file mode 100644 index 00000000000..d400cb47cbf --- /dev/null +++ b/src/libcore/marker.rs @@ -0,0 +1,314 @@ +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! Primitive traits and marker types representing basic 'kinds' of types. +//! +//! Rust types can be classified in various useful ways according to +//! intrinsic properties of the type. These classifications, often called +//! 'kinds', are represented as traits. +//! +//! They cannot be implemented by user code, but are instead implemented +//! by the compiler automatically for the types to which they apply. +//! +//! Marker types are special types that are used with unsafe code to +//! inform the compiler of special constraints. Marker types should +//! only be needed when you are creating an abstraction that is +//! implemented using unsafe code. In that case, you may want to embed +//! some of the marker types below into your type. + +#![stable] + +use clone::Clone; + +/// Types able to be transferred across task boundaries. +#[unstable = "will be overhauled with new lifetime rules; see RFC 458"] +#[lang="send"] +pub unsafe trait Send: 'static { + // empty. +} + +/// Types with a constant size known at compile-time. +#[stable] +#[lang="sized"] +pub trait Sized { + // Empty. +} + +/// Types that can be copied by simply copying bits (i.e. `memcpy`). +#[stable] +#[lang="copy"] +pub trait Copy { + // Empty. +} + +/// Types that can be safely shared between tasks when aliased. +/// +/// The precise definition is: a type `T` is `Sync` if `&T` is +/// thread-safe. In other words, there is no possibility of data races +/// when passing `&T` references between tasks. +/// +/// As one would expect, primitive types like `u8` and `f64` are all +/// `Sync`, and so are simple aggregate types containing them (like +/// tuples, structs and enums). More instances of basic `Sync` types +/// include "immutable" types like `&T` and those with simple +/// inherited mutability, such as `Box`, `Vec` and most other +/// collection types. (Generic parameters need to be `Sync` for their +/// container to be `Sync`.) +/// +/// A somewhat surprising consequence of the definition is `&mut T` is +/// `Sync` (if `T` is `Sync`) even though it seems that it might +/// provide unsynchronised mutation. The trick is a mutable reference +/// stored in an aliasable reference (that is, `& &mut T`) becomes +/// read-only, as if it were a `& &T`, hence there is no risk of a data +/// race. +/// +/// Types that are not `Sync` are those that have "interior +/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell` +/// in `std::cell`. These types allow for mutation of their contents +/// even when in an immutable, aliasable slot, e.g. the contents of +/// `&Cell` can be `.set`, and do not ensure data races are +/// impossible, hence they cannot be `Sync`. A higher level example +/// of a non-`Sync` type is the reference counted pointer +/// `std::rc::Rc`, because any reference `&Rc` can clone a new +/// reference, which modifies the reference counts in a non-atomic +/// way. +/// +/// For cases when one does need thread-safe interior mutability, +/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in +/// the `sync` crate do ensure that any mutation cannot cause data +/// races. Hence these types are `Sync`. +/// +/// Users writing their own types with interior mutability (or anything +/// else that is not thread-safe) should use the `NoSync` marker type +/// (from `std::marker`) to ensure that the compiler doesn't +/// consider the user-defined type to be `Sync`. Any types with +/// interior mutability must also use the `std::cell::UnsafeCell` wrapper +/// around the value(s) which can be mutated when behind a `&` +/// reference; not doing this is undefined behaviour (for example, +/// `transmute`-ing from `&T` to `&mut T` is illegal). +#[unstable = "will be overhauled with new lifetime rules; see RFC 458"] +#[lang="sync"] +pub unsafe trait Sync { + // Empty +} + + +/// A marker type whose type parameter `T` is considered to be +/// covariant with respect to the type itself. This is (typically) +/// used to indicate that an instance of the type `T` is being stored +/// into memory and read from, even though that may not be apparent. +/// +/// For more information about variance, refer to this Wikipedia +/// article . +/// +/// *Note:* It is very unusual to have to add a covariant constraint. +/// If you are not sure, you probably want to use `InvariantType`. +/// +/// # Example +/// +/// Given a struct `S` that includes a type parameter `T` +/// but does not actually *reference* that type parameter: +/// +/// ```ignore +/// use std::mem; +/// +/// struct S { x: *() } +/// fn get(s: &S) -> T { +/// unsafe { +/// let x: *T = mem::transmute(s.x); +/// *x +/// } +/// } +/// ``` +/// +/// The type system would currently infer that the value of +/// the type parameter `T` is irrelevant, and hence a `S` is +/// a subtype of `S>` (or, for that matter, `S` for +/// any `U`). But this is incorrect because `get()` converts the +/// `*()` into a `*T` and reads from it. Therefore, we should include the +/// a marker field `CovariantType` to inform the type checker that +/// `S` is a subtype of `S` if `T` is a subtype of `U` +/// (for example, `S<&'static int>` is a subtype of `S<&'a int>` +/// for some lifetime `'a`, but not the other way around). +#[unstable = "likely to change with new variance strategy"] +#[lang="covariant_type"] +#[derive(PartialEq, Eq, PartialOrd, Ord)] +pub struct CovariantType; + +impl Copy for CovariantType {} +impl Clone for CovariantType { + fn clone(&self) -> CovariantType { *self } +} + +/// A marker type whose type parameter `T` is considered to be +/// contravariant with respect to the type itself. This is (typically) +/// used to indicate that an instance of the type `T` will be consumed +/// (but not read from), even though that may not be apparent. +/// +/// For more information about variance, refer to this Wikipedia +/// article . +/// +/// *Note:* It is very unusual to have to add a contravariant constraint. +/// If you are not sure, you probably want to use `InvariantType`. +/// +/// # Example +/// +/// Given a struct `S` that includes a type parameter `T` +/// but does not actually *reference* that type parameter: +/// +/// ``` +/// use std::mem; +/// +/// struct S { x: *const () } +/// fn get(s: &S, v: T) { +/// unsafe { +/// let x: fn(T) = mem::transmute(s.x); +/// x(v) +/// } +/// } +/// ``` +/// +/// The type system would currently infer that the value of +/// the type parameter `T` is irrelevant, and hence a `S` is +/// a subtype of `S>` (or, for that matter, `S` for +/// any `U`). But this is incorrect because `get()` converts the +/// `*()` into a `fn(T)` and then passes a value of type `T` to it. +/// +/// Supplying a `ContravariantType` marker would correct the +/// problem, because it would mark `S` so that `S` is only a +/// subtype of `S` if `U` is a subtype of `T`; given that the +/// function requires arguments of type `T`, it must also accept +/// arguments of type `U`, hence such a conversion is safe. +#[unstable = "likely to change with new variance strategy"] +#[lang="contravariant_type"] +#[derive(PartialEq, Eq, PartialOrd, Ord)] +pub struct ContravariantType; + +impl Copy for ContravariantType {} +impl Clone for ContravariantType { + fn clone(&self) -> ContravariantType { *self } +} + +/// A marker type whose type parameter `T` is considered to be +/// invariant with respect to the type itself. This is (typically) +/// used to indicate that instances of the type `T` may be read or +/// written, even though that may not be apparent. +/// +/// For more information about variance, refer to this Wikipedia +/// article . +/// +/// # Example +/// +/// The Cell type is an example which uses unsafe code to achieve +/// "interior" mutability: +/// +/// ``` +/// pub struct Cell { value: T } +/// # fn main() {} +/// ``` +/// +/// The type system would infer that `value` is only read here and +/// never written, but in fact `Cell` uses unsafe code to achieve +/// interior mutability. +#[unstable = "likely to change with new variance strategy"] +#[lang="invariant_type"] +#[derive(PartialEq, Eq, PartialOrd, Ord)] +pub struct InvariantType; + +#[unstable = "likely to change with new variance strategy"] +impl Copy for InvariantType {} +#[unstable = "likely to change with new variance strategy"] +impl Clone for InvariantType { + fn clone(&self) -> InvariantType { *self } +} + +/// As `CovariantType`, but for lifetime parameters. Using +/// `CovariantLifetime<'a>` indicates that it is ok to substitute +/// a *longer* lifetime for `'a` than the one you originally +/// started with (e.g., you could convert any lifetime `'foo` to +/// `'static`). You almost certainly want `ContravariantLifetime` +/// instead, or possibly `InvariantLifetime`. The only case where +/// it would be appropriate is that you have a (type-casted, and +/// hence hidden from the type system) function pointer with a +/// signature like `fn(&'a T)` (and no other uses of `'a`). In +/// this case, it is ok to substitute a larger lifetime for `'a` +/// (e.g., `fn(&'static T)`), because the function is only +/// becoming more selective in terms of what it accepts as +/// argument. +/// +/// For more information about variance, refer to this Wikipedia +/// article . +#[unstable = "likely to change with new variance strategy"] +#[lang="covariant_lifetime"] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct CovariantLifetime<'a>; + +/// As `ContravariantType`, but for lifetime parameters. Using +/// `ContravariantLifetime<'a>` indicates that it is ok to +/// substitute a *shorter* lifetime for `'a` than the one you +/// originally started with (e.g., you could convert `'static` to +/// any lifetime `'foo`). This is appropriate for cases where you +/// have an unsafe pointer that is actually a pointer into some +/// memory with lifetime `'a`, and thus you want to limit the +/// lifetime of your data structure to `'a`. An example of where +/// this is used is the iterator for vectors. +/// +/// For more information about variance, refer to this Wikipedia +/// article . +#[unstable = "likely to change with new variance strategy"] +#[lang="contravariant_lifetime"] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct ContravariantLifetime<'a>; + +/// As `InvariantType`, but for lifetime parameters. Using +/// `InvariantLifetime<'a>` indicates that it is not ok to +/// substitute any other lifetime for `'a` besides its original +/// value. This is appropriate for cases where you have an unsafe +/// pointer that is actually a pointer into memory with lifetime `'a`, +/// and this pointer is itself stored in an inherently mutable +/// location (such as a `Cell`). +#[unstable = "likely to change with new variance strategy"] +#[lang="invariant_lifetime"] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct InvariantLifetime<'a>; + +/// A type which is considered "not sendable", meaning that it cannot +/// be safely sent between tasks, even if it is owned. This is +/// typically embedded in other types, such as `Gc`, to ensure that +/// their instances remain thread-local. +#[unstable = "likely to change with new variance strategy"] +#[lang="no_send_bound"] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct NoSend; + +/// A type which is considered "not POD", meaning that it is not +/// implicitly copyable. This is typically embedded in other types to +/// ensure that they are never copied, even if they lack a destructor. +#[unstable = "likely to change with new variance strategy"] +#[lang="no_copy_bound"] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] +#[allow(missing_copy_implementations)] +pub struct NoCopy; + +/// A type which is considered "not sync", meaning that +/// its contents are not threadsafe, hence they cannot be +/// shared between tasks. +#[unstable = "likely to change with new variance strategy"] +#[lang="no_sync_bound"] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct NoSync; + +/// A type which is considered managed by the GC. This is typically +/// embedded in other types. +#[unstable = "likely to change with new variance strategy"] +#[lang="managed_bound"] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] +#[allow(missing_copy_implementations)] +pub struct Managed; diff --git a/src/libcore/markers.rs b/src/libcore/markers.rs deleted file mode 100644 index f218eaceee2..00000000000 --- a/src/libcore/markers.rs +++ /dev/null @@ -1,314 +0,0 @@ -// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Primitive traits and marker types representing basic 'kinds' of types. -//! -//! Rust types can be classified in various useful ways according to -//! intrinsic properties of the type. These classifications, often called -//! 'kinds', are represented as traits. -//! -//! They cannot be implemented by user code, but are instead implemented -//! by the compiler automatically for the types to which they apply. -//! -//! Marker types are special types that are used with unsafe code to -//! inform the compiler of special constraints. Marker types should -//! only be needed when you are creating an abstraction that is -//! implemented using unsafe code. In that case, you may want to embed -//! some of the marker types below into your type. - -#![stable] - -use clone::Clone; - -/// Types able to be transferred across task boundaries. -#[unstable = "will be overhauled with new lifetime rules; see RFC 458"] -#[lang="send"] -pub unsafe trait Send: 'static { - // empty. -} - -/// Types with a constant size known at compile-time. -#[stable] -#[lang="sized"] -pub trait Sized { - // Empty. -} - -/// Types that can be copied by simply copying bits (i.e. `memcpy`). -#[stable] -#[lang="copy"] -pub trait Copy { - // Empty. -} - -/// Types that can be safely shared between tasks when aliased. -/// -/// The precise definition is: a type `T` is `Sync` if `&T` is -/// thread-safe. In other words, there is no possibility of data races -/// when passing `&T` references between tasks. -/// -/// As one would expect, primitive types like `u8` and `f64` are all -/// `Sync`, and so are simple aggregate types containing them (like -/// tuples, structs and enums). More instances of basic `Sync` types -/// include "immutable" types like `&T` and those with simple -/// inherited mutability, such as `Box`, `Vec` and most other -/// collection types. (Generic parameters need to be `Sync` for their -/// container to be `Sync`.) -/// -/// A somewhat surprising consequence of the definition is `&mut T` is -/// `Sync` (if `T` is `Sync`) even though it seems that it might -/// provide unsynchronised mutation. The trick is a mutable reference -/// stored in an aliasable reference (that is, `& &mut T`) becomes -/// read-only, as if it were a `& &T`, hence there is no risk of a data -/// race. -/// -/// Types that are not `Sync` are those that have "interior -/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell` -/// in `std::cell`. These types allow for mutation of their contents -/// even when in an immutable, aliasable slot, e.g. the contents of -/// `&Cell` can be `.set`, and do not ensure data races are -/// impossible, hence they cannot be `Sync`. A higher level example -/// of a non-`Sync` type is the reference counted pointer -/// `std::rc::Rc`, because any reference `&Rc` can clone a new -/// reference, which modifies the reference counts in a non-atomic -/// way. -/// -/// For cases when one does need thread-safe interior mutability, -/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in -/// the `sync` crate do ensure that any mutation cannot cause data -/// races. Hence these types are `Sync`. -/// -/// Users writing their own types with interior mutability (or anything -/// else that is not thread-safe) should use the `NoSync` marker type -/// (from `std::markers`) to ensure that the compiler doesn't -/// consider the user-defined type to be `Sync`. Any types with -/// interior mutability must also use the `std::cell::UnsafeCell` wrapper -/// around the value(s) which can be mutated when behind a `&` -/// reference; not doing this is undefined behaviour (for example, -/// `transmute`-ing from `&T` to `&mut T` is illegal). -#[unstable = "will be overhauled with new lifetime rules; see RFC 458"] -#[lang="sync"] -pub unsafe trait Sync { - // Empty -} - - -/// A marker type whose type parameter `T` is considered to be -/// covariant with respect to the type itself. This is (typically) -/// used to indicate that an instance of the type `T` is being stored -/// into memory and read from, even though that may not be apparent. -/// -/// For more information about variance, refer to this Wikipedia -/// article . -/// -/// *Note:* It is very unusual to have to add a covariant constraint. -/// If you are not sure, you probably want to use `InvariantType`. -/// -/// # Example -/// -/// Given a struct `S` that includes a type parameter `T` -/// but does not actually *reference* that type parameter: -/// -/// ```ignore -/// use std::mem; -/// -/// struct S { x: *() } -/// fn get(s: &S) -> T { -/// unsafe { -/// let x: *T = mem::transmute(s.x); -/// *x -/// } -/// } -/// ``` -/// -/// The type system would currently infer that the value of -/// the type parameter `T` is irrelevant, and hence a `S` is -/// a subtype of `S>` (or, for that matter, `S` for -/// any `U`). But this is incorrect because `get()` converts the -/// `*()` into a `*T` and reads from it. Therefore, we should include the -/// a marker field `CovariantType` to inform the type checker that -/// `S` is a subtype of `S` if `T` is a subtype of `U` -/// (for example, `S<&'static int>` is a subtype of `S<&'a int>` -/// for some lifetime `'a`, but not the other way around). -#[unstable = "likely to change with new variance strategy"] -#[lang="covariant_type"] -#[derive(PartialEq, Eq, PartialOrd, Ord)] -pub struct CovariantType; - -impl Copy for CovariantType {} -impl Clone for CovariantType { - fn clone(&self) -> CovariantType { *self } -} - -/// A marker type whose type parameter `T` is considered to be -/// contravariant with respect to the type itself. This is (typically) -/// used to indicate that an instance of the type `T` will be consumed -/// (but not read from), even though that may not be apparent. -/// -/// For more information about variance, refer to this Wikipedia -/// article . -/// -/// *Note:* It is very unusual to have to add a contravariant constraint. -/// If you are not sure, you probably want to use `InvariantType`. -/// -/// # Example -/// -/// Given a struct `S` that includes a type parameter `T` -/// but does not actually *reference* that type parameter: -/// -/// ``` -/// use std::mem; -/// -/// struct S { x: *const () } -/// fn get(s: &S, v: T) { -/// unsafe { -/// let x: fn(T) = mem::transmute(s.x); -/// x(v) -/// } -/// } -/// ``` -/// -/// The type system would currently infer that the value of -/// the type parameter `T` is irrelevant, and hence a `S` is -/// a subtype of `S>` (or, for that matter, `S` for -/// any `U`). But this is incorrect because `get()` converts the -/// `*()` into a `fn(T)` and then passes a value of type `T` to it. -/// -/// Supplying a `ContravariantType` marker would correct the -/// problem, because it would mark `S` so that `S` is only a -/// subtype of `S` if `U` is a subtype of `T`; given that the -/// function requires arguments of type `T`, it must also accept -/// arguments of type `U`, hence such a conversion is safe. -#[unstable = "likely to change with new variance strategy"] -#[lang="contravariant_type"] -#[derive(PartialEq, Eq, PartialOrd, Ord)] -pub struct ContravariantType; - -impl Copy for ContravariantType {} -impl Clone for ContravariantType { - fn clone(&self) -> ContravariantType { *self } -} - -/// A marker type whose type parameter `T` is considered to be -/// invariant with respect to the type itself. This is (typically) -/// used to indicate that instances of the type `T` may be read or -/// written, even though that may not be apparent. -/// -/// For more information about variance, refer to this Wikipedia -/// article . -/// -/// # Example -/// -/// The Cell type is an example which uses unsafe code to achieve -/// "interior" mutability: -/// -/// ``` -/// pub struct Cell { value: T } -/// # fn main() {} -/// ``` -/// -/// The type system would infer that `value` is only read here and -/// never written, but in fact `Cell` uses unsafe code to achieve -/// interior mutability. -#[unstable = "likely to change with new variance strategy"] -#[lang="invariant_type"] -#[derive(PartialEq, Eq, PartialOrd, Ord)] -pub struct InvariantType; - -#[unstable = "likely to change with new variance strategy"] -impl Copy for InvariantType {} -#[unstable = "likely to change with new variance strategy"] -impl Clone for InvariantType { - fn clone(&self) -> InvariantType { *self } -} - -/// As `CovariantType`, but for lifetime parameters. Using -/// `CovariantLifetime<'a>` indicates that it is ok to substitute -/// a *longer* lifetime for `'a` than the one you originally -/// started with (e.g., you could convert any lifetime `'foo` to -/// `'static`). You almost certainly want `ContravariantLifetime` -/// instead, or possibly `InvariantLifetime`. The only case where -/// it would be appropriate is that you have a (type-casted, and -/// hence hidden from the type system) function pointer with a -/// signature like `fn(&'a T)` (and no other uses of `'a`). In -/// this case, it is ok to substitute a larger lifetime for `'a` -/// (e.g., `fn(&'static T)`), because the function is only -/// becoming more selective in terms of what it accepts as -/// argument. -/// -/// For more information about variance, refer to this Wikipedia -/// article . -#[unstable = "likely to change with new variance strategy"] -#[lang="covariant_lifetime"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct CovariantLifetime<'a>; - -/// As `ContravariantType`, but for lifetime parameters. Using -/// `ContravariantLifetime<'a>` indicates that it is ok to -/// substitute a *shorter* lifetime for `'a` than the one you -/// originally started with (e.g., you could convert `'static` to -/// any lifetime `'foo`). This is appropriate for cases where you -/// have an unsafe pointer that is actually a pointer into some -/// memory with lifetime `'a`, and thus you want to limit the -/// lifetime of your data structure to `'a`. An example of where -/// this is used is the iterator for vectors. -/// -/// For more information about variance, refer to this Wikipedia -/// article . -#[unstable = "likely to change with new variance strategy"] -#[lang="contravariant_lifetime"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct ContravariantLifetime<'a>; - -/// As `InvariantType`, but for lifetime parameters. Using -/// `InvariantLifetime<'a>` indicates that it is not ok to -/// substitute any other lifetime for `'a` besides its original -/// value. This is appropriate for cases where you have an unsafe -/// pointer that is actually a pointer into memory with lifetime `'a`, -/// and this pointer is itself stored in an inherently mutable -/// location (such as a `Cell`). -#[unstable = "likely to change with new variance strategy"] -#[lang="invariant_lifetime"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct InvariantLifetime<'a>; - -/// A type which is considered "not sendable", meaning that it cannot -/// be safely sent between tasks, even if it is owned. This is -/// typically embedded in other types, such as `Gc`, to ensure that -/// their instances remain thread-local. -#[unstable = "likely to change with new variance strategy"] -#[lang="no_send_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct NoSend; - -/// A type which is considered "not POD", meaning that it is not -/// implicitly copyable. This is typically embedded in other types to -/// ensure that they are never copied, even if they lack a destructor. -#[unstable = "likely to change with new variance strategy"] -#[lang="no_copy_bound"] -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] -#[allow(missing_copy_implementations)] -pub struct NoCopy; - -/// A type which is considered "not sync", meaning that -/// its contents are not threadsafe, hence they cannot be -/// shared between tasks. -#[unstable = "likely to change with new variance strategy"] -#[lang="no_sync_bound"] -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub struct NoSync; - -/// A type which is considered managed by the GC. This is typically -/// embedded in other types. -#[unstable = "likely to change with new variance strategy"] -#[lang="managed_bound"] -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] -#[allow(missing_copy_implementations)] -pub struct Managed; diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 24cb649ce55..8438c9b206e 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -15,7 +15,7 @@ #![stable] -use markers::Sized; +use marker::Sized; use intrinsics; use ptr; diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 25833741024..046406ee4d9 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -21,7 +21,7 @@ use cmp::{PartialEq, Eq}; use cmp::{PartialOrd, Ord}; use intrinsics; use iter::IteratorExt; -use markers::Copy; +use marker::Copy; use mem::size_of; use ops::{Add, Sub, Mul, Div, Rem, Neg}; use ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr}; @@ -992,7 +992,7 @@ impl_to_primitive_float! { f64 } /// A generic trait for converting a number to a value. #[experimental = "trait is likely to be removed"] -pub trait FromPrimitive : ::markers::Sized { +pub trait FromPrimitive : ::marker::Sized { /// Convert an `int` to return an optional value of this type. If the /// value cannot be represented by this value, the `None` is returned. #[inline] diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 287a725a33c..239aa6058cc 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -63,7 +63,7 @@ use clone::Clone; use iter::{Step, Iterator,DoubleEndedIterator,ExactSizeIterator}; -use markers::Sized; +use marker::Sized; use option::Option::{self, Some, None}; /// The `Drop` trait is used to run some code when a value goes out of scope. This diff --git a/src/libcore/prelude.rs b/src/libcore/prelude.rs index 558e451ee8c..c175b83e760 100644 --- a/src/libcore/prelude.rs +++ b/src/libcore/prelude.rs @@ -29,7 +29,7 @@ //! ``` // Reexported core operators -pub use markers::{Copy, Send, Sized, Sync}; +pub use marker::{Copy, Send, Sized, Sync}; pub use ops::{Drop, Fn, FnMut, FnOnce}; // Reexported functions diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 40c7d60a205..c35d948165a 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -92,7 +92,7 @@ use mem; use clone::Clone; use intrinsics; use option::Option::{self, Some, None}; -use markers::{Send, Sized, Sync}; +use marker::{Send, Sized, Sync}; use cmp::{PartialEq, Eq, Ord, PartialOrd}; use cmp::Ordering::{self, Less, Equal, Greater}; diff --git a/src/libcore/raw.rs b/src/libcore/raw.rs index 57f1706dc43..1ad6d43f76f 100644 --- a/src/libcore/raw.rs +++ b/src/libcore/raw.rs @@ -18,7 +18,7 @@ //! //! Their definition should always match the ABI defined in `rustc::back::abi`. -use markers::Copy; +use marker::Copy; use mem; /// The representation of a Rust slice diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index e4a15d38535..3d55d09ccf1 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -41,7 +41,7 @@ use cmp::Ordering::{Less, Equal, Greater}; use cmp; use default::Default; use iter::*; -use markers::Copy; +use marker::Copy; use num::Int; use ops::{FnMut, self}; use option::Option; @@ -52,7 +52,7 @@ use ptr; use ptr::PtrExt; use mem; use mem::size_of; -use markers::{Sized, self}; +use marker::{Sized, self}; use raw::Repr; // Avoid conflicts with *both* the Slice trait (buggy) and the `slice::raw` module. use raw::Slice as RawSlice; @@ -169,11 +169,11 @@ impl SliceExt for [T] { if mem::size_of::() == 0 { Iter {ptr: p, end: (p as uint + self.len()) as *const T, - marker: markers::ContravariantLifetime::<'a>} + marker: marker::ContravariantLifetime::<'a>} } else { Iter {ptr: p, end: p.offset(self.len() as int), - marker: markers::ContravariantLifetime::<'a>} + marker: marker::ContravariantLifetime::<'a>} } } } @@ -322,11 +322,11 @@ impl SliceExt for [T] { if mem::size_of::() == 0 { IterMut {ptr: p, end: (p as uint + self.len()) as *mut T, - marker: markers::ContravariantLifetime::<'a>} + marker: marker::ContravariantLifetime::<'a>} } else { IterMut {ptr: p, end: p.offset(self.len() as int), - marker: markers::ContravariantLifetime::<'a>} + marker: marker::ContravariantLifetime::<'a>} } } } @@ -734,7 +734,7 @@ macro_rules! make_slice { pub struct Iter<'a, T: 'a> { ptr: *const T, end: *const T, - marker: markers::ContravariantLifetime<'a> + marker: marker::ContravariantLifetime<'a> } #[experimental] @@ -809,7 +809,7 @@ impl<'a, T> RandomAccessIterator for Iter<'a, T> { pub struct IterMut<'a, T: 'a> { ptr: *mut T, end: *mut T, - marker: markers::ContravariantLifetime<'a>, + marker: marker::ContravariantLifetime<'a>, } #[experimental] diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index f1f3cabb66b..d9db50b0d5a 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -23,7 +23,7 @@ use default::Default; use iter::range; use iter::ExactSizeIterator; use iter::{Map, Iterator, IteratorExt, DoubleEndedIterator}; -use markers::Sized; +use marker::Sized; use mem; use num::Int; use ops::{Fn, FnMut}; diff --git a/src/libcore/ty.rs b/src/libcore/ty.rs index 9de3cf30dc9..35c1cb09281 100644 --- a/src/libcore/ty.rs +++ b/src/libcore/ty.rs @@ -10,4 +10,4 @@ //! Types dealing with unsafe actions. -use markers; +use marker; diff --git a/src/libcoretest/hash/mod.rs b/src/libcoretest/hash/mod.rs index 3af38f9035d..63bf9ec3314 100644 --- a/src/libcoretest/hash/mod.rs +++ b/src/libcoretest/hash/mod.rs @@ -7,7 +7,7 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. -use core::markers::Sized; +use core::marker::Sized; use std::mem; use core::slice::SliceExt; diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs index 57e0737e909..1e8d2d4bc61 100644 --- a/src/libcoretest/num/mod.rs +++ b/src/libcoretest/num/mod.rs @@ -12,7 +12,7 @@ use core::cmp::PartialEq; use core::fmt::Show; use core::num::{NumCast, cast}; use core::ops::{Add, Sub, Mul, Div, Rem}; -use core::markers::Copy; +use core::marker::Copy; #[cfg_attr(stage0, macro_escape)] #[cfg_attr(not(stage0), macro_use)] diff --git a/src/libcoretest/option.rs b/src/libcoretest/option.rs index 5588fbce26a..1169f910238 100644 --- a/src/libcoretest/option.rs +++ b/src/libcoretest/option.rs @@ -9,7 +9,7 @@ // except according to those terms. use core::option::*; -use core::markers; +use core::marker; use core::mem; use core::clone::Clone; @@ -82,7 +82,7 @@ fn test_option_dance() { #[test] #[should_fail] fn test_option_too_much_dance() { - let mut y = Some(markers::NoCopy); + let mut y = Some(marker::NoCopy); let _y2 = y.take().unwrap(); let _y3 = y.take().unwrap(); } diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index 4255114243c..86ed8794e1a 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -5082,6 +5082,6 @@ pub fn issue_14344_workaround() {} // FIXME #14344 force linkage to happen corre #[cfg(not(test))] mod std { #[cfg(stage0)] - pub use core::markers as kinds; - pub use core::markers; + pub use core::marker as kinds; + pub use core::marker; } diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 9e900fcb3db..95dbbf9efcf 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -517,8 +517,8 @@ mod std { pub use core::{option, fmt}; // panic!() pub use core::clone; // derive Clone #[cfg(stage0)] - pub use core::markers as kinds; - pub use core::markers; + pub use core::marker as kinds; + pub use core::marker; } #[cfg(test)] diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 780e3da4684..3818ab45e06 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -29,7 +29,7 @@ use middle::ty::{MethodOrigin, MethodParam, MethodTypeParam}; use middle::ty::{MethodStatic, MethodStaticUnboxedClosure}; use util::ppaux::Repr; -use std::markers; +use std::marker; use syntax::{ast, ast_util}; use syntax::ptr::P; use syntax::codemap::Span; @@ -135,7 +135,7 @@ enum TrackMatchMode { Conflicting, } -impl markers::Copy for TrackMatchMode {} +impl marker::Copy for TrackMatchMode {} impl TrackMatchMode { // Builds up the whole match mode for a pattern from its constituent diff --git a/src/librustc/middle/infer/unify.rs b/src/librustc/middle/infer/unify.rs index b73142b4051..59f53d5fb39 100644 --- a/src/librustc/middle/infer/unify.rs +++ b/src/librustc/middle/infer/unify.rs @@ -10,7 +10,7 @@ pub use self::VarValue::*; -use std::markers; +use std::marker; use middle::ty::{expected_found, IntVarValue}; use middle::ty::{self, Ty}; @@ -78,7 +78,7 @@ pub struct UnificationTable { /// made during the snapshot may either be *committed* or *rolled back*. pub struct Snapshot { // Link snapshot to the key type `K` of the table. - marker: markers::CovariantType, + marker: marker::CovariantType, snapshot: sv::Snapshot, } @@ -108,7 +108,7 @@ impl<'tcx, V:PartialEq+Clone+Repr<'tcx>, K:UnifyKey<'tcx, V>> UnificationTable Snapshot { - Snapshot { marker: markers::CovariantType::, + Snapshot { marker: marker::CovariantType::, snapshot: self.values.start_snapshot() } } diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 62c46c435bc..bf102acb8b1 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -402,8 +402,8 @@ impl<'a, 'tcx, 'v> Visitor<'v> for TermsContext<'a, 'tcx> { struct ConstraintContext<'a, 'tcx: 'a> { terms_cx: TermsContext<'a, 'tcx>, - // These are the def-id of the std::markers::InvariantType, - // std::markers::InvariantLifetime, and so on. The arrays + // These are the def-id of the std::marker::InvariantType, + // std::marker::InvariantLifetime, and so on. The arrays // are indexed by the `ParamKind` (type, lifetime, self). Note // that there are no marker types for self, so the entries for // self are always None. diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index ce9857f8243..27ea2e895f6 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -21,7 +21,7 @@ use default::Default; use fmt::{self, Show}; use hash::{Hash, Hasher, RandomSipHasher}; use iter::{self, Iterator, IteratorExt, FromIterator, Extend, Map}; -use markers::Sized; +use marker::Sized; use mem::{self, replace}; use num::{Int, UnsignedInt}; use ops::{Deref, FnMut, Index, IndexMut}; diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index d67581a12b3..5c9bbf1144c 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -13,7 +13,7 @@ use borrow::BorrowFrom; use clone::Clone; use cmp::{Eq, PartialEq}; -use core::markers::Sized; +use core::marker::Sized; use default::Default; use fmt::Show; use fmt; diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index cdfde1958c6..6eb98da4da4 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -16,7 +16,7 @@ use clone::Clone; use cmp; use hash::{Hash, Hasher}; use iter::{Iterator, count}; -use markers::{Copy, Sized, self}; +use marker::{Copy, Sized, self}; use mem::{min_align_of, size_of}; use mem; use num::{Int, UnsignedInt}; @@ -72,7 +72,7 @@ pub struct RawTable { hashes: Unique, // Because K/V do not appear directly in any of the types in the struct, // inform rustc that in fact instances of K and V are reachable from here. - marker: markers::CovariantType<(K,V)>, + marker: marker::CovariantType<(K,V)>, } struct RawBucket { @@ -562,7 +562,7 @@ impl RawTable { size: 0, capacity: 0, hashes: Unique::null(), - marker: markers::CovariantType, + marker: marker::CovariantType, }; } // No need for `checked_mul` before a more restrictive check performed @@ -601,7 +601,7 @@ impl RawTable { capacity: capacity, size: 0, hashes: Unique(hashes), - marker: markers::CovariantType, + marker: marker::CovariantType, } } @@ -651,7 +651,7 @@ impl RawTable { hashes_end: unsafe { self.hashes.0.offset(self.capacity as int) }, - marker: markers::ContravariantLifetime, + marker: marker::ContravariantLifetime, } } @@ -676,7 +676,7 @@ impl RawTable { iter: RawBuckets { raw: raw, hashes_end: hashes_end, - marker: markers::ContravariantLifetime, + marker: marker::ContravariantLifetime, }, table: self, } @@ -689,7 +689,7 @@ impl RawTable { iter: RawBuckets { raw: raw, hashes_end: hashes_end, - marker: markers::ContravariantLifetime::<'static>, + marker: marker::ContravariantLifetime::<'static>, }, table: self, } @@ -703,7 +703,7 @@ impl RawTable { raw: raw_bucket.offset(self.capacity as int), hashes_end: raw_bucket.hash, elems_left: self.size, - marker: markers::ContravariantLifetime, + marker: marker::ContravariantLifetime, } } } @@ -713,7 +713,7 @@ impl RawTable { struct RawBuckets<'a, K, V> { raw: RawBucket, hashes_end: *mut u64, - marker: markers::ContravariantLifetime<'a>, + marker: marker::ContravariantLifetime<'a>, } // FIXME(#19839) Remove in favor of `#[derive(Clone)]` @@ -722,7 +722,7 @@ impl<'a, K, V> Clone for RawBuckets<'a, K, V> { RawBuckets { raw: self.raw, hashes_end: self.hashes_end, - marker: markers::ContravariantLifetime, + marker: marker::ContravariantLifetime, } } } @@ -754,7 +754,7 @@ struct RevMoveBuckets<'a, K, V> { raw: RawBucket, hashes_end: *mut u64, elems_left: uint, - marker: markers::ContravariantLifetime<'a>, + marker: marker::ContravariantLifetime<'a>, } impl<'a, K, V> Iterator for RevMoveBuckets<'a, K, V> { diff --git a/src/libstd/hash.rs b/src/libstd/hash.rs index 34facdc7de6..69e7e429d07 100644 --- a/src/libstd/hash.rs +++ b/src/libstd/hash.rs @@ -63,7 +63,7 @@ pub use core::hash::{Hash, Hasher, Writer, hash, sip}; -use core::markers::Sized; +use core::marker::Sized; use default::Default; use rand::Rng; use rand; diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index deae56d8a30..b9c7ab15313 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -232,7 +232,7 @@ use error::{FromError, Error}; use fmt; use int; use iter::{Iterator, IteratorExt}; -use markers::Sized; +use marker::Sized; use mem::transmute; use ops::FnOnce; use option::Option; diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 43d37543e16..ad3fb71d949 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -34,7 +34,7 @@ use failure::LOCAL_STDERR; use fmt; use io::{Reader, Writer, IoResult, IoError, OtherIoError, Buffer, standard_error, EndOfFile, LineBufferedWriter, BufferedReader}; -use markers::{Sync, Send}; +use marker::{Sync, Send}; use libc; use mem; use option::Option; diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index b258c13f12e..dd4a0287ca6 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -151,7 +151,7 @@ extern crate libc; // Make std testable by not duplicating lang items. See #2912 #[cfg(test)] extern crate "std" as realstd; -#[cfg(test)] pub use realstd::markers; +#[cfg(test)] pub use realstd::marker; #[cfg(test)] pub use realstd::ops; #[cfg(test)] pub use realstd::cmp; #[cfg(test)] pub use realstd::boxed; @@ -168,8 +168,8 @@ pub use core::default; pub use core::finally; pub use core::intrinsics; pub use core::iter; -#[cfg(stage0)] #[cfg(not(test))] pub use core::markers as kinds; -#[cfg(not(test))] pub use core::markers; +#[cfg(stage0)] #[cfg(not(test))] pub use core::marker as kinds; +#[cfg(not(test))] pub use core::marker; pub use core::mem; #[cfg(not(test))] pub use core::ops; pub use core::ptr; @@ -313,8 +313,8 @@ mod std { pub use cell; // used for tls! pub use thread_local; // used for thread_local! #[cfg(stage0)] - pub use markers as kinds; - pub use markers; // used for tls! + pub use marker as kinds; + pub use marker; // used for tls! pub use ops; // used for bitflags! // The test runner calls ::std::os::args() but really wants realstd diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index cd78489cb85..f433cd1e664 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -19,7 +19,7 @@ #[cfg(test)] use fmt::Show; use ops::{Add, Sub, Mul, Div, Rem, Neg}; -use markers::Copy; +use marker::Copy; use clone::Clone; use cmp::{PartialOrd, PartialEq}; diff --git a/src/libstd/os.rs b/src/libstd/os.rs index 0e41d608086..2bc6d0869a5 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -37,7 +37,7 @@ use error::{FromError, Error}; use fmt; use io::{IoResult, IoError}; use iter::{Iterator, IteratorExt}; -use markers::Copy; +use marker::Copy; use libc::{c_void, c_int, c_char}; use libc; use boxed::Box; diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index e263761acd1..18b8d1d46aa 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -61,7 +61,7 @@ #![experimental] -use core::markers::Sized; +use core::marker::Sized; use ffi::CString; use clone::Clone; use fmt; diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 03811364d30..d8bb989e19f 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -16,7 +16,7 @@ use hash; use io::Writer; use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map}; -use markers::Sized; +use marker::Sized; use option::Option::{self, Some, None}; use slice::{AsSlice, Split, SliceExt, SliceConcatExt}; use str::{self, FromStr, StrExt}; diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index bf8d2a3d63b..1aab52edd8e 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -13,7 +13,7 @@ #![stable] // Reexported core operators -#[stable] #[doc(no_inline)] pub use markers::{Copy, Send, Sized, Sync}; +#[stable] #[doc(no_inline)] pub use marker::{Copy, Send, Sized, Sync}; #[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce}; // Reexported functions diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index 512bd2a3d6e..a7d2fb169b6 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -185,7 +185,7 @@ mod imp { extern crate libc; use io::{IoResult}; - use markers::Sync; + use marker::Sync; use mem; use os; use rand::Rng; diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index 036bb7b637b..91d9ff46b86 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -23,7 +23,7 @@ #![allow(dead_code)] -use markers::Send; +use marker::Send; use ops::FnOnce; use sys; use thunk::Thunk; diff --git a/src/libstd/sync/mpsc/blocking.rs b/src/libstd/sync/mpsc/blocking.rs index af6aa803f99..f174771a3e0 100644 --- a/src/libstd/sync/mpsc/blocking.rs +++ b/src/libstd/sync/mpsc/blocking.rs @@ -13,8 +13,8 @@ use thread::Thread; use sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use sync::Arc; -use markers::{Sync, Send}; -use markers::{NoSend, NoSync}; +use marker::{Sync, Send}; +use marker::{NoSend, NoSync}; use mem; use clone::Clone; diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 4d18d9e6e9d..5dc58add665 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -319,7 +319,7 @@ use prelude::v1::*; use sync::Arc; use fmt; -use markers; +use marker; use mem; use cell::UnsafeCell; @@ -373,7 +373,7 @@ unsafe impl Send for Sender { } pub struct SyncSender { inner: Arc>>, // can't share in an arc - _marker: markers::NoSync, + _marker: marker::NoSync, } /// An error returned from the `send` function on channels. @@ -678,7 +678,7 @@ impl Drop for Sender { impl SyncSender { fn new(inner: Arc>>) -> SyncSender { - SyncSender { inner: inner, _marker: markers::NoSync } + SyncSender { inner: inner, _marker: marker::NoSync } } /// Sends a value on this synchronous channel. diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index ca7120b5ead..b7bb22b3ef3 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -57,7 +57,7 @@ use core::prelude::*; use core::cell::Cell; -use core::markers; +use core::marker; use core::mem; use core::uint; @@ -70,7 +70,7 @@ pub struct Select { head: *mut Handle<'static, ()>, tail: *mut Handle<'static, ()>, next_id: Cell, - marker1: markers::NoSend, + marker1: marker::NoSend, } /// A handle to a receiver which is currently a member of a `Select` set of @@ -115,7 +115,7 @@ impl Select { /// rather much easier through the `select!` macro. pub fn new() -> Select { Select { - marker1: markers::NoSend, + marker1: marker::NoSend, head: 0 as *mut Handle<'static, ()>, tail: 0 as *mut Handle<'static, ()>, next_id: Cell::new(1), diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index bb5a6337646..9756d086193 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -11,7 +11,7 @@ use prelude::v1::*; use cell::UnsafeCell; -use markers; +use marker; use ops::{Deref, DerefMut}; use sync::poison::{self, TryLockError, TryLockResult, LockResult}; use sys_common::mutex as sys; @@ -166,7 +166,7 @@ pub struct MutexGuard<'a, T: 'a> { __lock: &'a StaticMutex, __data: &'a UnsafeCell, __poison: poison::Guard, - __marker: markers::NoSend, + __marker: marker::NoSend, } /// Static initialization of a mutex. This constant can be used to initialize @@ -286,7 +286,7 @@ impl<'mutex, T> MutexGuard<'mutex, T> { __lock: lock, __data: data, __poison: guard, - __marker: markers::NoSend, + __marker: marker::NoSend, } }) } diff --git a/src/libstd/sync/once.rs b/src/libstd/sync/once.rs index 11a5cad2c25..15ca4783700 100644 --- a/src/libstd/sync/once.rs +++ b/src/libstd/sync/once.rs @@ -14,7 +14,7 @@ //! example use case would be for initializing an FFI library. use int; -use markers::Sync; +use marker::Sync; use mem::drop; use ops::FnOnce; use sync::atomic::{AtomicInt, Ordering, ATOMIC_INT_INIT}; diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index f40c0cc0c0e..36f9d4228b3 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -11,7 +11,7 @@ use prelude::v1::*; use cell::UnsafeCell; -use markers; +use marker; use ops::{Deref, DerefMut}; use sync::poison::{self, LockResult, TryLockError, TryLockResult}; use sys_common::rwlock as sys; @@ -113,7 +113,7 @@ pub const RW_LOCK_INIT: StaticRwLock = StaticRwLock { pub struct RwLockReadGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, - __marker: markers::NoSend, + __marker: marker::NoSend, } /// RAII structure used to release the exclusive write access of a lock when @@ -124,7 +124,7 @@ pub struct RwLockWriteGuard<'a, T: 'a> { __lock: &'a StaticRwLock, __data: &'a UnsafeCell, __poison: poison::Guard, - __marker: markers::NoSend, + __marker: marker::NoSend, } impl RwLock { @@ -309,7 +309,7 @@ impl<'rwlock, T> RwLockReadGuard<'rwlock, T> { RwLockReadGuard { __lock: lock, __data: data, - __marker: markers::NoSend, + __marker: marker::NoSend, } }) } @@ -322,7 +322,7 @@ impl<'rwlock, T> RwLockWriteGuard<'rwlock, T> { __lock: lock, __data: data, __poison: guard, - __marker: markers::NoSend, + __marker: marker::NoSend, } }) } diff --git a/src/libstd/sys/common/mutex.rs b/src/libstd/sys/common/mutex.rs index b86e6ce254a..9aea0fb3b31 100644 --- a/src/libstd/sys/common/mutex.rs +++ b/src/libstd/sys/common/mutex.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use markers::Sync; +use marker::Sync; use sys::mutex as imp; /// An OS-based mutual exclusion lock. diff --git a/src/libstd/sys/unix/c.rs b/src/libstd/sys/unix/c.rs index 968347bbfbc..cc661877bc0 100644 --- a/src/libstd/sys/unix/c.rs +++ b/src/libstd/sys/unix/c.rs @@ -165,8 +165,8 @@ mod signal { sa_restorer: *mut libc::c_void, } - unsafe impl ::markers::Send for sigaction { } - unsafe impl ::markers::Sync for sigaction { } + unsafe impl ::marker::Send for sigaction { } + unsafe impl ::marker::Sync for sigaction { } #[repr(C)] #[cfg(target_word_size = "32")] @@ -217,8 +217,8 @@ mod signal { sa_resv: [libc::c_int; 1], } - unsafe impl ::markers::Send for sigaction { } - unsafe impl ::markers::Sync for sigaction { } + unsafe impl ::marker::Send for sigaction { } + unsafe impl ::marker::Sync for sigaction { } #[repr(C)] pub struct sigset_t { diff --git a/src/libstd/sys/unix/mutex.rs b/src/libstd/sys/unix/mutex.rs index 8da25c7880d..ada8a7f2349 100644 --- a/src/libstd/sys/unix/mutex.rs +++ b/src/libstd/sys/unix/mutex.rs @@ -9,7 +9,7 @@ // except according to those terms. use cell::UnsafeCell; -use markers::Sync; +use marker::Sync; use sys::sync as ffi; use sys_common::mutex; diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 630087e2291..43abd96e46d 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -128,7 +128,7 @@ use any::Any; use boxed::Box; use cell::UnsafeCell; use clone::Clone; -use markers::{Send, Sync}; +use marker::{Send, Sync}; use ops::{Drop, FnOnce}; use option::Option::{self, Some, None}; use result::Result::{Err, Ok}; diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index bf01b578b1f..15b98e1aff0 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -346,7 +346,7 @@ mod imp { pub dtor_running: UnsafeCell, // should be Cell } - unsafe impl ::markers::Sync for Key { } + unsafe impl ::marker::Sync for Key { } #[doc(hidden)] impl Key { @@ -472,7 +472,7 @@ mod imp { pub os: OsStaticKey, } - unsafe impl ::markers::Sync for Key { } + unsafe impl ::marker::Sync for Key { } struct Value { key: &'static Key, diff --git a/src/libstd/thread_local/scoped.rs b/src/libstd/thread_local/scoped.rs index a643d2cb8ee..1fb5652bc0c 100644 --- a/src/libstd/thread_local/scoped.rs +++ b/src/libstd/thread_local/scoped.rs @@ -108,7 +108,7 @@ macro_rules! __scoped_thread_local_inner { const _INIT: __Key<$t> = __Key { inner: ::std::thread_local::scoped::__impl::KeyInner { inner: ::std::thread_local::scoped::__impl::OS_INIT, - marker: ::std::markers::InvariantType, + marker: ::std::marker::InvariantType, } }; @@ -211,7 +211,7 @@ mod imp { #[doc(hidden)] pub struct KeyInner { pub inner: UnsafeCell<*mut T> } - unsafe impl ::markers::Sync for KeyInner { } + unsafe impl ::marker::Sync for KeyInner { } #[doc(hidden)] impl KeyInner { @@ -224,16 +224,16 @@ mod imp { #[cfg(any(windows, target_os = "android", target_os = "ios", target_arch = "aarch64"))] mod imp { - use markers; + use marker; use sys_common::thread_local::StaticKey as OsStaticKey; #[doc(hidden)] pub struct KeyInner { pub inner: OsStaticKey, - pub marker: markers::InvariantType, + pub marker: marker::InvariantType, } - unsafe impl ::markers::Sync for KeyInner { } + unsafe impl ::marker::Sync for KeyInner { } #[doc(hidden)] impl KeyInner { diff --git a/src/libstd/thunk.rs b/src/libstd/thunk.rs index ec9dd86f941..1830a4df54a 100644 --- a/src/libstd/thunk.rs +++ b/src/libstd/thunk.rs @@ -12,7 +12,7 @@ #![allow(missing_docs)] use alloc::boxed::Box; -use core::markers::Send; +use core::marker::Send; use core::ops::FnOnce; pub struct Thunk { diff --git a/src/libsyntax/ext/deriving/bounds.rs b/src/libsyntax/ext/deriving/bounds.rs index 50c91c13343..b4c171388db 100644 --- a/src/libsyntax/ext/deriving/bounds.rs +++ b/src/libsyntax/ext/deriving/bounds.rs @@ -47,7 +47,7 @@ pub fn expand_deriving_bound(cx: &mut ExtCtxt, let trait_def = TraitDef { span: span, attributes: Vec::new(), - path: Path::new(vec!("std", "markers", name)), + path: Path::new(vec!("std", "marker", name)), additional_bounds: Vec::new(), generics: LifetimeBounds::empty(), methods: vec!() diff --git a/src/libunicode/tables.rs b/src/libunicode/tables.rs index 094d45a10d1..3f089d62e4e 100644 --- a/src/libunicode/tables.rs +++ b/src/libunicode/tables.rs @@ -7801,7 +7801,7 @@ pub mod charwidth { } pub mod grapheme { - use core::markers::Copy; + use core::marker::Copy; use core::slice::SliceExt; pub use self::GraphemeCat::*; use core::result::Result::{Ok, Err}; diff --git a/src/test/compile-fail/associated-types-unsized.rs b/src/test/compile-fail/associated-types-unsized.rs index 28483abda3c..e4b97ab5933 100644 --- a/src/test/compile-fail/associated-types-unsized.rs +++ b/src/test/compile-fail/associated-types-unsized.rs @@ -14,7 +14,7 @@ trait Get { } fn foo(t: T) { - let x = t.get(); //~ ERROR the trait `core::markers::Sized` is not implemented + let x = t.get(); //~ ERROR the trait `core::marker::Sized` is not implemented } fn main() { diff --git a/src/test/compile-fail/bad-method-typaram-kind.rs b/src/test/compile-fail/bad-method-typaram-kind.rs index 33907dc4c46..349c33a30a5 100644 --- a/src/test/compile-fail/bad-method-typaram-kind.rs +++ b/src/test/compile-fail/bad-method-typaram-kind.rs @@ -9,7 +9,7 @@ // except according to those terms. fn foo() { - 1u.bar::(); //~ ERROR `core::markers::Send` is not implemented + 1u.bar::(); //~ ERROR `core::marker::Send` is not implemented } trait bar { diff --git a/src/test/compile-fail/bad-sized.rs b/src/test/compile-fail/bad-sized.rs index 6e8fcba8c8a..69be6414e4c 100644 --- a/src/test/compile-fail/bad-sized.rs +++ b/src/test/compile-fail/bad-sized.rs @@ -16,8 +16,8 @@ trait Trait {} pub fn main() { let x: Vec = Vec::new(); - //~^ ERROR the trait `core::markers::Sized` is not implemented - //~^^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented + //~^^ ERROR the trait `core::marker::Sized` is not implemented let x: Vec>> = Vec::new(); - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/borrowck-move-out-of-static-item.rs b/src/test/compile-fail/borrowck-move-out-of-static-item.rs index 310da28dd49..730a0c3e235 100644 --- a/src/test/compile-fail/borrowck-move-out-of-static-item.rs +++ b/src/test/compile-fail/borrowck-move-out-of-static-item.rs @@ -10,14 +10,14 @@ // Ensure that moves out of static items is forbidden -use std::markers; +use std::marker; struct Foo { foo: int, - nocopy: markers::NoCopy + nocopy: marker::NoCopy } -static BAR: Foo = Foo{foo: 5, nocopy: markers::NoCopy}; +static BAR: Foo = Foo{foo: 5, nocopy: marker::NoCopy}; fn test(f: Foo) { diff --git a/src/test/compile-fail/borrowck-struct-update-with-dtor.rs b/src/test/compile-fail/borrowck-struct-update-with-dtor.rs index 36d430ddeaa..98a29f01faf 100644 --- a/src/test/compile-fail/borrowck-struct-update-with-dtor.rs +++ b/src/test/compile-fail/borrowck-struct-update-with-dtor.rs @@ -12,7 +12,7 @@ // move, when the struct implements Drop. // NoCopy -use std::markers::NoCopy as NP; +use std::marker::NoCopy as NP; struct S { a: int, np: NP } diff --git a/src/test/compile-fail/builtin-superkinds-double-superkind.rs b/src/test/compile-fail/builtin-superkinds-double-superkind.rs index 03c1aa2a05d..cd215a73737 100644 --- a/src/test/compile-fail/builtin-superkinds-double-superkind.rs +++ b/src/test/compile-fail/builtin-superkinds-double-superkind.rs @@ -13,9 +13,9 @@ trait Foo : Send+Sync { } -impl Foo for (T,) { } //~ ERROR the trait `core::markers::Send` is not implemented +impl Foo for (T,) { } //~ ERROR the trait `core::marker::Send` is not implemented -impl Foo for (T,T) { } //~ ERROR the trait `core::markers::Sync` is not implemented +impl Foo for (T,T) { } //~ ERROR the trait `core::marker::Sync` is not implemented impl Foo for (T,T,T) { } // (ok) diff --git a/src/test/compile-fail/builtin-superkinds-in-metadata.rs b/src/test/compile-fail/builtin-superkinds-in-metadata.rs index 1fa663640d8..138fcfa8b64 100644 --- a/src/test/compile-fail/builtin-superkinds-in-metadata.rs +++ b/src/test/compile-fail/builtin-superkinds-in-metadata.rs @@ -22,6 +22,6 @@ struct X(T); impl RequiresShare for X { } impl RequiresRequiresShareAndSend for X { } -//~^ ERROR the trait `core::markers::Send` is not implemented +//~^ ERROR the trait `core::marker::Send` is not implemented fn main() { } diff --git a/src/test/compile-fail/builtin-superkinds-typaram-not-send.rs b/src/test/compile-fail/builtin-superkinds-typaram-not-send.rs index 2c295768e7a..534bb6d37ec 100644 --- a/src/test/compile-fail/builtin-superkinds-typaram-not-send.rs +++ b/src/test/compile-fail/builtin-superkinds-typaram-not-send.rs @@ -12,6 +12,6 @@ trait Foo : Send { } -impl Foo for T { } //~ ERROR the trait `core::markers::Send` is not implemented +impl Foo for T { } //~ ERROR the trait `core::marker::Send` is not implemented fn main() { } diff --git a/src/test/compile-fail/check-static-values-constraints.rs b/src/test/compile-fail/check-static-values-constraints.rs index 8b7d2457d3c..1c7ae05961e 100644 --- a/src/test/compile-fail/check-static-values-constraints.rs +++ b/src/test/compile-fail/check-static-values-constraints.rs @@ -10,7 +10,7 @@ // Verifies all possible restrictions for statics values. -use std::markers; +use std::marker; struct WithDtor; diff --git a/src/test/compile-fail/closure-bounds-cant-promote-superkind-in-struct.rs b/src/test/compile-fail/closure-bounds-cant-promote-superkind-in-struct.rs index a02d6b7f517..b88040cbd54 100644 --- a/src/test/compile-fail/closure-bounds-cant-promote-superkind-in-struct.rs +++ b/src/test/compile-fail/closure-bounds-cant-promote-superkind-in-struct.rs @@ -13,7 +13,7 @@ struct X where F: FnOnce() + 'static + Send { } fn foo(blk: F) -> X where F: FnOnce() + 'static { - //~^ ERROR the trait `core::kinds::Send` is not implemented for the type + //~^ ERROR the trait `core::marker::Send` is not implemented for the type return X { field: blk }; } diff --git a/src/test/compile-fail/closure-bounds-subtype.rs b/src/test/compile-fail/closure-bounds-subtype.rs index 509fffc5c9a..fadaa84f19d 100644 --- a/src/test/compile-fail/closure-bounds-subtype.rs +++ b/src/test/compile-fail/closure-bounds-subtype.rs @@ -21,7 +21,7 @@ fn give_any(f: F) where F: FnOnce() { fn give_owned(f: F) where F: FnOnce() + Send { take_any(f); - take_const_owned(f); //~ ERROR the trait `core::kinds::Sync` is not implemented for the type + take_const_owned(f); //~ ERROR the trait `core::marker::Sync` is not implemented for the type } fn main() {} diff --git a/src/test/compile-fail/comm-not-freeze-receiver.rs b/src/test/compile-fail/comm-not-freeze-receiver.rs index 5dce6ba8133..a7962c09fb3 100644 --- a/src/test/compile-fail/comm-not-freeze-receiver.rs +++ b/src/test/compile-fail/comm-not-freeze-receiver.rs @@ -13,5 +13,5 @@ use std::sync::mpsc::Receiver; fn test() {} fn main() { - test::>(); //~ ERROR: `core::markers::Sync` is not implemented + test::>(); //~ ERROR: `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/comm-not-freeze.rs b/src/test/compile-fail/comm-not-freeze.rs index 0f34ccf4a52..1977438d423 100644 --- a/src/test/compile-fail/comm-not-freeze.rs +++ b/src/test/compile-fail/comm-not-freeze.rs @@ -13,5 +13,5 @@ use std::sync::mpsc::Sender; fn test() {} fn main() { - test::>(); //~ ERROR: `core::markers::Sync` is not implemented + test::>(); //~ ERROR: `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/dst-bad-assign-2.rs b/src/test/compile-fail/dst-bad-assign-2.rs index b9c06c60a5d..ebd0ee97efe 100644 --- a/src/test/compile-fail/dst-bad-assign-2.rs +++ b/src/test/compile-fail/dst-bad-assign-2.rs @@ -43,5 +43,5 @@ pub fn main() { let f5: &mut Fat = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} }; let z: Box = box Bar1 {f: 36}; f5.ptr = *z; - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/dst-bad-assign.rs b/src/test/compile-fail/dst-bad-assign.rs index 2516d987455..f52c990ca52 100644 --- a/src/test/compile-fail/dst-bad-assign.rs +++ b/src/test/compile-fail/dst-bad-assign.rs @@ -43,5 +43,5 @@ pub fn main() { let f5: &mut Fat = &mut Fat { f1: 5, f2: "some str", ptr: Bar1 {f :42} }; let z: Box = box Bar1 {f: 36}; f5.ptr = Bar1 {f: 36}; //~ ERROR mismatched types: expected `ToBar`, found `Bar1` - //~^ ERROR the trait `core::markers::Sized` is not implemented for the type `ToBar` + //~^ ERROR the trait `core::marker::Sized` is not implemented for the type `ToBar` } diff --git a/src/test/compile-fail/dst-bad-deep.rs b/src/test/compile-fail/dst-bad-deep.rs index ed2ccc9d9cc..0276e2e418d 100644 --- a/src/test/compile-fail/dst-bad-deep.rs +++ b/src/test/compile-fail/dst-bad-deep.rs @@ -21,5 +21,5 @@ pub fn main() { let f: Fat<[int; 3]> = Fat { ptr: [5i, 6, 7] }; let g: &Fat<[int]> = &f; let h: &Fat> = &Fat { ptr: *g }; - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/dst-object-from-unsized-type.rs b/src/test/compile-fail/dst-object-from-unsized-type.rs index b28952d2b33..87ff4291f50 100644 --- a/src/test/compile-fail/dst-object-from-unsized-type.rs +++ b/src/test/compile-fail/dst-object-from-unsized-type.rs @@ -15,22 +15,22 @@ impl Foo for str {} fn test1(t: &T) { let u: &Foo = t; - //~^ ERROR `core::markers::Sized` is not implemented for the type `T` + //~^ ERROR `core::marker::Sized` is not implemented for the type `T` } fn test2(t: &T) { let v: &Foo = t as &Foo; - //~^ ERROR `core::markers::Sized` is not implemented for the type `T` + //~^ ERROR `core::marker::Sized` is not implemented for the type `T` } fn test3() { let _: &[&Foo] = &["hi"]; - //~^ ERROR `core::markers::Sized` is not implemented for the type `str` + //~^ ERROR `core::marker::Sized` is not implemented for the type `str` } fn test4() { let _: &Foo = "hi" as &Foo; - //~^ ERROR `core::markers::Sized` is not implemented for the type `str` + //~^ ERROR `core::marker::Sized` is not implemented for the type `str` } fn main() { } diff --git a/src/test/compile-fail/dst-sized-trait-param.rs b/src/test/compile-fail/dst-sized-trait-param.rs index af0b780b3b7..d68d6676515 100644 --- a/src/test/compile-fail/dst-sized-trait-param.rs +++ b/src/test/compile-fail/dst-sized-trait-param.rs @@ -15,9 +15,9 @@ trait Foo : Sized { fn take(self, x: &T) { } } // Note: T is sized impl Foo<[int]> for uint { } -//~^ ERROR the trait `core::markers::Sized` is not implemented for the type `[int]` +//~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[int]` impl Foo for [uint] { } -//~^ ERROR the trait `core::markers::Sized` is not implemented for the type `[uint]` +//~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[uint]` pub fn main() { } diff --git a/src/test/compile-fail/error-should-say-copy-not-pod.rs b/src/test/compile-fail/error-should-say-copy-not-pod.rs index 581a06db745..d79b3f472d0 100644 --- a/src/test/compile-fail/error-should-say-copy-not-pod.rs +++ b/src/test/compile-fail/error-should-say-copy-not-pod.rs @@ -13,5 +13,5 @@ fn check_bound(_: T) {} fn main() { - check_bound("nocopy".to_string()); //~ ERROR the trait `core::markers::Copy` is not implemented + check_bound("nocopy".to_string()); //~ ERROR the trait `core::marker::Copy` is not implemented } diff --git a/src/test/compile-fail/issue-14366.rs b/src/test/compile-fail/issue-14366.rs index d9b8c4db031..c7cac71af03 100644 --- a/src/test/compile-fail/issue-14366.rs +++ b/src/test/compile-fail/issue-14366.rs @@ -10,5 +10,5 @@ fn main() { let _x = "test" as &::std::any::Any; -//~^ ERROR the trait `core::markers::Sized` is not implemented for the type `str` +//~^ ERROR the trait `core::marker::Sized` is not implemented for the type `str` } diff --git a/src/test/compile-fail/issue-15756.rs b/src/test/compile-fail/issue-15756.rs index 5e305313fcf..c2d30224dc8 100644 --- a/src/test/compile-fail/issue-15756.rs +++ b/src/test/compile-fail/issue-15756.rs @@ -15,7 +15,7 @@ fn dft_iter<'a, T>(arg1: Chunks<'a,T>, arg2: ChunksMut<'a,T>) { for &something -//~^ ERROR the trait `core::markers::Sized` is not implemented for the type `[T]` +//~^ ERROR the trait `core::marker::Sized` is not implemented for the type `[T]` in arg2 { } diff --git a/src/test/compile-fail/issue-16538.rs b/src/test/compile-fail/issue-16538.rs index 505a59b484d..af686b86813 100644 --- a/src/test/compile-fail/issue-16538.rs +++ b/src/test/compile-fail/issue-16538.rs @@ -20,6 +20,6 @@ mod Y { static foo: *const Y::X = Y::foo(Y::x as *const Y::X); //~^ ERROR cannot refer to other statics by value -//~| ERROR: the trait `core::markers::Sync` is not implemented for the type +//~| ERROR: the trait `core::marker::Sync` is not implemented for the type fn main() {} diff --git a/src/test/compile-fail/issue-17718-static-move.rs b/src/test/compile-fail/issue-17718-static-move.rs index 730344f5763..4f3668b819a 100644 --- a/src/test/compile-fail/issue-17718-static-move.rs +++ b/src/test/compile-fail/issue-17718-static-move.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; -struct Foo { nc: markers::NoCopy } -const INIT: Foo = Foo { nc: markers::NoCopy }; +struct Foo { nc: marker::NoCopy } +const INIT: Foo = Foo { nc: marker::NoCopy }; static FOO: Foo = INIT; fn main() { diff --git a/src/test/compile-fail/issue-17718-static-sync.rs b/src/test/compile-fail/issue-17718-static-sync.rs index da343cc81ac..147bff2e977 100644 --- a/src/test/compile-fail/issue-17718-static-sync.rs +++ b/src/test/compile-fail/issue-17718-static-sync.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; -struct Foo { marker: markers::NoSync } +struct Foo { marker: marker::NoSync } static FOO: uint = 3; -static BAR: Foo = Foo { marker: markers::NoSync }; -//~^ ERROR: the trait `core::markers::Sync` is not implemented +static BAR: Foo = Foo { marker: marker::NoSync }; +//~^ ERROR: the trait `core::marker::Sync` is not implemented fn main() {} diff --git a/src/test/compile-fail/issue-18107.rs b/src/test/compile-fail/issue-18107.rs index a17b2ee0c68..b8249ebd479 100644 --- a/src/test/compile-fail/issue-18107.rs +++ b/src/test/compile-fail/issue-18107.rs @@ -14,7 +14,7 @@ pub trait AbstractRenderer {} fn _create_render(_: &()) -> AbstractRenderer -//~^ ERROR: the trait `core::markers::Sized` is not implemented +//~^ ERROR: the trait `core::marker::Sized` is not implemented { match 0u { _ => unimplemented!() diff --git a/src/test/compile-fail/issue-19883.rs b/src/test/compile-fail/issue-19883.rs index b9fbc37828f..bbc5ee6c8f3 100644 --- a/src/test/compile-fail/issue-19883.rs +++ b/src/test/compile-fail/issue-19883.rs @@ -18,13 +18,13 @@ trait To { // This is a typo, the return type should be `>::Output` fn to>( self - //~^ error: the trait `core::markers::Sized` is not implemented + //~^ error: the trait `core::marker::Sized` is not implemented ) -> >::Dst - //~^ error: the trait `core::markers::Sized` is not implemented + //~^ error: the trait `core::marker::Sized` is not implemented { From::from( - //~^ error: the trait `core::markers::Sized` is not implemented + //~^ error: the trait `core::marker::Sized` is not implemented self ) } diff --git a/src/test/compile-fail/issue-20005.rs b/src/test/compile-fail/issue-20005.rs index 8076df39db9..d91479a2e4e 100644 --- a/src/test/compile-fail/issue-20005.rs +++ b/src/test/compile-fail/issue-20005.rs @@ -16,9 +16,9 @@ trait From { trait To { fn to( - self //~ error: the trait `core::markers::Sized` is not implemented + self //~ error: the trait `core::marker::Sized` is not implemented ) -> >::Result where Dst: From { - From::from( //~ error: the trait `core::markers::Sized` is not implemented + From::from( //~ error: the trait `core::marker::Sized` is not implemented self ) } diff --git a/src/test/compile-fail/issue-3907-2.rs b/src/test/compile-fail/issue-3907-2.rs index da60fee65c6..546b808a38f 100644 --- a/src/test/compile-fail/issue-3907-2.rs +++ b/src/test/compile-fail/issue-3907-2.rs @@ -17,6 +17,6 @@ struct S { name: int } -fn bar(_x: Foo) {} //~ ERROR the trait `core::markers::Sized` is not implemented +fn bar(_x: Foo) {} //~ ERROR the trait `core::marker::Sized` is not implemented fn main() {} diff --git a/src/test/compile-fail/issue-5035-2.rs b/src/test/compile-fail/issue-5035-2.rs index 05073927beb..9e324cdd61e 100644 --- a/src/test/compile-fail/issue-5035-2.rs +++ b/src/test/compile-fail/issue-5035-2.rs @@ -11,6 +11,6 @@ trait I {} type K = I+'static; -fn foo(_x: K) {} //~ ERROR: the trait `core::markers::Sized` is not implemented +fn foo(_x: K) {} //~ ERROR: the trait `core::marker::Sized` is not implemented fn main() {} diff --git a/src/test/compile-fail/issue-5543.rs b/src/test/compile-fail/issue-5543.rs index 6981c4451ca..2d64013dc27 100644 --- a/src/test/compile-fail/issue-5543.rs +++ b/src/test/compile-fail/issue-5543.rs @@ -14,5 +14,5 @@ impl Foo for u8 {} fn main() { let r: Box = box 5; let _m: Box = r as Box; - //~^ ERROR `core::markers::Sized` is not implemented for the type `Foo` + //~^ ERROR `core::marker::Sized` is not implemented for the type `Foo` } diff --git a/src/test/compile-fail/issue-5883.rs b/src/test/compile-fail/issue-5883.rs index 2f601a8ba58..9ff957b6e6d 100644 --- a/src/test/compile-fail/issue-5883.rs +++ b/src/test/compile-fail/issue-5883.rs @@ -15,8 +15,8 @@ struct Struct { } fn new_struct(r: A+'static) - -> Struct { //~^ ERROR the trait `core::markers::Sized` is not implemented - //~^ ERROR the trait `core::markers::Sized` is not implemented + -> Struct { //~^ ERROR the trait `core::marker::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented Struct { r: r } } diff --git a/src/test/compile-fail/issue-7013.rs b/src/test/compile-fail/issue-7013.rs index 30a59c52faa..d2f9ee47603 100644 --- a/src/test/compile-fail/issue-7013.rs +++ b/src/test/compile-fail/issue-7013.rs @@ -32,6 +32,6 @@ struct A { fn main() { let a = A {v: box B{v: None} as Box}; - //~^ ERROR the trait `core::markers::Send` is not implemented - //~^^ ERROR the trait `core::markers::Send` is not implemented + //~^ ERROR the trait `core::marker::Send` is not implemented + //~^^ ERROR the trait `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/issue-7364.rs b/src/test/compile-fail/issue-7364.rs index c4217029a93..c8c7ef4ed89 100644 --- a/src/test/compile-fail/issue-7364.rs +++ b/src/test/compile-fail/issue-7364.rs @@ -14,7 +14,7 @@ use std::cell::RefCell; // Regresion test for issue 7364 static boxed: Box> = box RefCell::new(0); //~^ ERROR statics are not allowed to have custom pointers -//~| ERROR: the trait `core::markers::Sync` is not implemented for the type -//~| ERROR: the trait `core::markers::Sync` is not implemented for the type +//~| ERROR: the trait `core::marker::Sync` is not implemented for the type +//~| ERROR: the trait `core::marker::Sync` is not implemented for the type fn main() { } diff --git a/src/test/compile-fail/kindck-copy.rs b/src/test/compile-fail/kindck-copy.rs index 583fbedfcbc..ac088e69a28 100644 --- a/src/test/compile-fail/kindck-copy.rs +++ b/src/test/compile-fail/kindck-copy.rs @@ -36,14 +36,14 @@ fn test<'a,T,U:Copy>(_: &'a int) { assert_copy::<&'a [int]>(); // ...unless they are mutable - assert_copy::<&'static mut int>(); //~ ERROR `core::markers::Copy` is not implemented - assert_copy::<&'a mut int>(); //~ ERROR `core::markers::Copy` is not implemented + assert_copy::<&'static mut int>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::<&'a mut int>(); //~ ERROR `core::marker::Copy` is not implemented // ~ pointers are not ok - assert_copy::>(); //~ ERROR `core::markers::Copy` is not implemented - assert_copy::(); //~ ERROR `core::markers::Copy` is not implemented - assert_copy:: >(); //~ ERROR `core::markers::Copy` is not implemented - assert_copy::>(); //~ ERROR `core::markers::Copy` is not implemented + assert_copy::>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy:: >(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::>(); //~ ERROR `core::marker::Copy` is not implemented // borrowed object types are generally ok assert_copy::<&'a Dummy>(); @@ -51,11 +51,11 @@ fn test<'a,T,U:Copy>(_: &'a int) { assert_copy::<&'static (Dummy+Copy)>(); // owned object types are not ok - assert_copy::>(); //~ ERROR `core::markers::Copy` is not implemented - assert_copy::>(); //~ ERROR `core::markers::Copy` is not implemented + assert_copy::>(); //~ ERROR `core::marker::Copy` is not implemented + assert_copy::>(); //~ ERROR `core::marker::Copy` is not implemented // mutable object types are not ok - assert_copy::<&'a mut (Dummy+Copy)>(); //~ ERROR `core::markers::Copy` is not implemented + assert_copy::<&'a mut (Dummy+Copy)>(); //~ ERROR `core::marker::Copy` is not implemented // unsafe ptrs are ok assert_copy::<*const int>(); @@ -73,10 +73,10 @@ fn test<'a,T,U:Copy>(_: &'a int) { assert_copy::(); // structs containing non-POD are not ok - assert_copy::(); //~ ERROR `core::markers::Copy` is not implemented + assert_copy::(); //~ ERROR `core::marker::Copy` is not implemented // ref counted types are not ok - assert_copy::>(); //~ ERROR `core::markers::Copy` is not implemented + assert_copy::>(); //~ ERROR `core::marker::Copy` is not implemented } pub fn main() { diff --git a/src/test/compile-fail/kindck-impl-type-params-2.rs b/src/test/compile-fail/kindck-impl-type-params-2.rs index 2ec22ceb63f..9e7c983195a 100644 --- a/src/test/compile-fail/kindck-impl-type-params-2.rs +++ b/src/test/compile-fail/kindck-impl-type-params-2.rs @@ -19,5 +19,5 @@ fn take_param(foo: &T) { } fn main() { let x = box 3i; take_param(&x); - //~^ ERROR the trait `core::markers::Copy` is not implemented + //~^ ERROR the trait `core::marker::Copy` is not implemented } diff --git a/src/test/compile-fail/kindck-impl-type-params.rs b/src/test/compile-fail/kindck-impl-type-params.rs index ad62fd98560..6ecf2593d00 100644 --- a/src/test/compile-fail/kindck-impl-type-params.rs +++ b/src/test/compile-fail/kindck-impl-type-params.rs @@ -20,15 +20,15 @@ impl Gettable for S {} fn f(val: T) { let t: S = S; let a = &t as &Gettable; - //~^ ERROR the trait `core::markers::Send` is not implemented - //~^^ ERROR the trait `core::markers::Copy` is not implemented + //~^ ERROR the trait `core::marker::Send` is not implemented + //~^^ ERROR the trait `core::marker::Copy` is not implemented } fn g(val: T) { let t: S = S; let a: &Gettable = &t; - //~^ ERROR the trait `core::markers::Send` is not implemented - //~^^ ERROR the trait `core::markers::Copy` is not implemented + //~^ ERROR the trait `core::marker::Send` is not implemented + //~^^ ERROR the trait `core::marker::Copy` is not implemented } fn foo<'a>() { @@ -40,13 +40,13 @@ fn foo<'a>() { fn foo2<'a>() { let t: Box> = box S; let a = t as Box>; - //~^ ERROR the trait `core::markers::Copy` is not implemented + //~^ ERROR the trait `core::marker::Copy` is not implemented } fn foo3<'a>() { let t: Box> = box S; let a: Box> = t; - //~^ ERROR the trait `core::markers::Copy` is not implemented + //~^ ERROR the trait `core::marker::Copy` is not implemented } fn main() { } diff --git a/src/test/compile-fail/kindck-inherited-copy-bound.rs b/src/test/compile-fail/kindck-inherited-copy-bound.rs index 238f495187c..7f610176b65 100644 --- a/src/test/compile-fail/kindck-inherited-copy-bound.rs +++ b/src/test/compile-fail/kindck-inherited-copy-bound.rs @@ -22,13 +22,13 @@ fn take_param(foo: &T) { } fn a() { let x = box 3i; - take_param(&x); //~ ERROR `core::markers::Copy` is not implemented + take_param(&x); //~ ERROR `core::marker::Copy` is not implemented } fn b() { let x = box 3i; let y = &x; - let z = &x as &Foo; //~ ERROR `core::markers::Copy` is not implemented + let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented } fn main() { } diff --git a/src/test/compile-fail/kindck-nonsendable-1.rs b/src/test/compile-fail/kindck-nonsendable-1.rs index b46f91413a4..a13a3f7c4ab 100644 --- a/src/test/compile-fail/kindck-nonsendable-1.rs +++ b/src/test/compile-fail/kindck-nonsendable-1.rs @@ -18,7 +18,7 @@ fn bar(_: F) { } fn main() { let x = Rc::new(3u); bar(move|| foo(x)); - //~^ ERROR `core::markers::Send` is not implemented - //~^^ ERROR `core::markers::Send` is not implemented + //~^ ERROR `core::marker::Send` is not implemented + //~^^ ERROR `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/kindck-send-object.rs b/src/test/compile-fail/kindck-send-object.rs index 1235a0a1228..7984b3b32c2 100644 --- a/src/test/compile-fail/kindck-send-object.rs +++ b/src/test/compile-fail/kindck-send-object.rs @@ -20,11 +20,11 @@ trait Message : Send { } fn object_ref_with_static_bound_not_ok() { assert_send::<&'static (Dummy+'static)>(); - //~^ ERROR the trait `core::markers::Send` is not implemented + //~^ ERROR the trait `core::marker::Send` is not implemented } fn box_object_with_no_bound_not_ok<'a>() { - assert_send::>(); //~ ERROR the trait `core::markers::Send` is not implemented + assert_send::>(); //~ ERROR the trait `core::marker::Send` is not implemented } fn object_with_send_bound_ok() { diff --git a/src/test/compile-fail/kindck-send-object1.rs b/src/test/compile-fail/kindck-send-object1.rs index 4f1a95859ae..c781fffff2d 100644 --- a/src/test/compile-fail/kindck-send-object1.rs +++ b/src/test/compile-fail/kindck-send-object1.rs @@ -18,7 +18,7 @@ trait Dummy { } // careful with object types, who knows what they close over... fn test51<'a>() { assert_send::<&'a Dummy>(); - //~^ ERROR the trait `core::markers::Send` is not implemented + //~^ ERROR the trait `core::marker::Send` is not implemented } fn test52<'a>() { assert_send::<&'a (Dummy+Send)>(); @@ -37,7 +37,7 @@ fn test61() { // them not ok fn test_71<'a>() { assert_send::>(); - //~^ ERROR the trait `core::markers::Send` is not implemented + //~^ ERROR the trait `core::marker::Send` is not implemented } fn main() { } diff --git a/src/test/compile-fail/kindck-send-object2.rs b/src/test/compile-fail/kindck-send-object2.rs index 06b8cf20258..75bae09b37f 100644 --- a/src/test/compile-fail/kindck-send-object2.rs +++ b/src/test/compile-fail/kindck-send-object2.rs @@ -14,11 +14,11 @@ fn assert_send() { } trait Dummy { } fn test50() { - assert_send::<&'static Dummy>(); //~ ERROR the trait `core::markers::Send` is not implemented + assert_send::<&'static Dummy>(); //~ ERROR the trait `core::marker::Send` is not implemented } fn test53() { - assert_send::>(); //~ ERROR the trait `core::markers::Send` is not implemented + assert_send::>(); //~ ERROR the trait `core::marker::Send` is not implemented } // ...unless they are properly bounded diff --git a/src/test/compile-fail/kindck-send-unsafe.rs b/src/test/compile-fail/kindck-send-unsafe.rs index 0a2f4cbce85..1bfd0d4a11f 100644 --- a/src/test/compile-fail/kindck-send-unsafe.rs +++ b/src/test/compile-fail/kindck-send-unsafe.rs @@ -14,7 +14,7 @@ fn assert_send() { } fn test71<'a>() { assert_send::<*mut &'a int>(); - //~^ ERROR the trait `core::markers::Send` is not implemented for the type + //~^ ERROR the trait `core::marker::Send` is not implemented for the type } fn main() { diff --git a/src/test/compile-fail/lint-dead-code-4.rs b/src/test/compile-fail/lint-dead-code-4.rs index 3bdc44ec363..21e1ab4c33e 100644 --- a/src/test/compile-fail/lint-dead-code-4.rs +++ b/src/test/compile-fail/lint-dead-code-4.rs @@ -19,7 +19,7 @@ use std::num::Int; struct Foo { x: uint, b: bool, //~ ERROR: struct field is never used - marker: std::markers::NoCopy + marker: std::marker::NoCopy } fn field_read(f: Foo) -> uint { @@ -59,7 +59,7 @@ fn field_match_in_let(f: Bar) -> bool { } fn main() { - field_read(Foo { x: 1, b: false, marker: std::markers::NoCopy }); + field_read(Foo { x: 1, b: false, marker: std::marker::NoCopy }); field_match_in_patterns(XYZ::Z); field_match_in_let(Bar { x: 42u, b: true, _guard: () }); let _ = Baz { x: 0 }; diff --git a/src/test/compile-fail/marker-no-copy.rs b/src/test/compile-fail/marker-no-copy.rs index e329cdc32d3..d9e139cc9db 100644 --- a/src/test/compile-fail/marker-no-copy.rs +++ b/src/test/compile-fail/marker-no-copy.rs @@ -8,11 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; fn foo(p: P) { } fn main() { - foo(markers::NoCopy); //~ ERROR the trait `core::markers::Copy` is not implemented + foo(marker::NoCopy); //~ ERROR the trait `core::marker::Copy` is not implemented } diff --git a/src/test/compile-fail/marker-no-send.rs b/src/test/compile-fail/marker-no-send.rs index dcbe63a417d..032718d7e9a 100644 --- a/src/test/compile-fail/marker-no-send.rs +++ b/src/test/compile-fail/marker-no-send.rs @@ -8,11 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; fn foo(p: P) { } fn main() { - foo(markers::NoSend); //~ ERROR the trait `core::markers::Send` is not implemented + foo(marker::NoSend); //~ ERROR the trait `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/marker-no-share.rs b/src/test/compile-fail/marker-no-share.rs index 77d5fc23a35..b29f7fab2cc 100644 --- a/src/test/compile-fail/marker-no-share.rs +++ b/src/test/compile-fail/marker-no-share.rs @@ -8,11 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; fn foo(p: P) { } fn main() { - foo(markers::NoSync); //~ ERROR the trait `core::markers::Sync` is not implemented + foo(marker::NoSync); //~ ERROR the trait `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/mut-not-freeze.rs b/src/test/compile-fail/mut-not-freeze.rs index 711763c20c6..d7529c86aa5 100644 --- a/src/test/compile-fail/mut-not-freeze.rs +++ b/src/test/compile-fail/mut-not-freeze.rs @@ -15,6 +15,6 @@ fn f(_: T) {} fn main() { let x = RefCell::new(0i); f(x); - //~^ ERROR `core::markers::Sync` is not implemented - //~^^ ERROR `core::markers::Sync` is not implemented + //~^ ERROR `core::marker::Sync` is not implemented + //~^^ ERROR `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/mutable-enum-indirect.rs b/src/test/compile-fail/mutable-enum-indirect.rs index 01c977dc62c..f90bb610d37 100644 --- a/src/test/compile-fail/mutable-enum-indirect.rs +++ b/src/test/compile-fail/mutable-enum-indirect.rs @@ -11,13 +11,13 @@ // Tests that an `&` pointer to something inherently mutable is itself // to be considered mutable. -use std::markers; +use std::marker; -enum Foo { A(markers::NoSync) } +enum Foo { A(marker::NoSync) } fn bar(_: T) {} fn main() { - let x = Foo::A(markers::NoSync); - bar(&x); //~ ERROR the trait `core::markers::Sync` is not implemented + let x = Foo::A(marker::NoSync); + bar(&x); //~ ERROR the trait `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/no-send-res-ports.rs b/src/test/compile-fail/no-send-res-ports.rs index 66082d46549..0b0a83a4196 100644 --- a/src/test/compile-fail/no-send-res-ports.rs +++ b/src/test/compile-fail/no-send-res-ports.rs @@ -36,8 +36,8 @@ fn main() { let x = foo(Port(Rc::new(()))); Thread::spawn(move|| { - //~^ ERROR `core::markers::Send` is not implemented - //~^^ ERROR `core::markers::Send` is not implemented + //~^ ERROR `core::marker::Send` is not implemented + //~^^ ERROR `core::marker::Send` is not implemented let y = x; println!("{}", y); }); diff --git a/src/test/compile-fail/no_send-enum.rs b/src/test/compile-fail/no_send-enum.rs index 2a0ffd93208..cf1f13e8bb8 100644 --- a/src/test/compile-fail/no_send-enum.rs +++ b/src/test/compile-fail/no_send-enum.rs @@ -8,16 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; enum Foo { - A(markers::NoSend) + A(marker::NoSend) } fn bar(_: T) {} fn main() { - let x = Foo::A(markers::NoSend); + let x = Foo::A(marker::NoSend); bar(x); - //~^ ERROR `core::markers::Send` is not implemented + //~^ ERROR `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/no_send-rc.rs b/src/test/compile-fail/no_send-rc.rs index e604fd9f838..95855ed584b 100644 --- a/src/test/compile-fail/no_send-rc.rs +++ b/src/test/compile-fail/no_send-rc.rs @@ -15,6 +15,6 @@ fn bar(_: T) {} fn main() { let x = Rc::new(5i); bar(x); - //~^ ERROR `core::markers::Send` is not implemented - //~^^ ERROR `core::markers::Send` is not implemented + //~^ ERROR `core::marker::Send` is not implemented + //~^^ ERROR `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/no_send-struct.rs b/src/test/compile-fail/no_send-struct.rs index 7e2f7c55bd2..c2d6f04c7d4 100644 --- a/src/test/compile-fail/no_send-struct.rs +++ b/src/test/compile-fail/no_send-struct.rs @@ -8,17 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; struct Foo { a: int, - ns: markers::NoSend + ns: marker::NoSend } fn bar(_: T) {} fn main() { - let x = Foo { a: 5, ns: markers::NoSend }; + let x = Foo { a: 5, ns: marker::NoSend }; bar(x); - //~^ ERROR the trait `core::markers::Send` is not implemented + //~^ ERROR the trait `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/no_share-enum.rs b/src/test/compile-fail/no_share-enum.rs index aeaa56c35a8..33222eef44e 100644 --- a/src/test/compile-fail/no_share-enum.rs +++ b/src/test/compile-fail/no_share-enum.rs @@ -8,14 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; -enum Foo { A(markers::NoSync) } +enum Foo { A(marker::NoSync) } fn bar(_: T) {} fn main() { - let x = Foo::A(markers::NoSync); + let x = Foo::A(marker::NoSync); bar(x); - //~^ ERROR the trait `core::markers::Sync` is not implemented + //~^ ERROR the trait `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/no_share-rc.rs b/src/test/compile-fail/no_share-rc.rs index 66e8571527d..0f3573e0ad5 100644 --- a/src/test/compile-fail/no_share-rc.rs +++ b/src/test/compile-fail/no_share-rc.rs @@ -16,6 +16,6 @@ fn bar(_: T) {} fn main() { let x = Rc::new(RefCell::new(5i)); bar(x); - //~^ ERROR the trait `core::markers::Sync` is not implemented - //~^^ ERROR the trait `core::markers::Sync` is not implemented + //~^ ERROR the trait `core::marker::Sync` is not implemented + //~^^ ERROR the trait `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/no_share-struct.rs b/src/test/compile-fail/no_share-struct.rs index ee6a29d3176..59864b63b04 100644 --- a/src/test/compile-fail/no_share-struct.rs +++ b/src/test/compile-fail/no_share-struct.rs @@ -8,14 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; -struct Foo { a: int, m: markers::NoSync } +struct Foo { a: int, m: marker::NoSync } fn bar(_: T) {} fn main() { - let x = Foo { a: 5, m: markers::NoSync }; + let x = Foo { a: 5, m: marker::NoSync }; bar(x); - //~^ ERROR the trait `core::markers::Sync` is not implemented + //~^ ERROR the trait `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/opt-out-copy-bad.rs b/src/test/compile-fail/opt-out-copy-bad.rs index f949e89fcac..9e425fa8f2e 100644 --- a/src/test/compile-fail/opt-out-copy-bad.rs +++ b/src/test/compile-fail/opt-out-copy-bad.rs @@ -30,7 +30,7 @@ impl Copy for IWantToCopyThis {} enum CantCopyThisEither { A, - B(::std::markers::NoCopy), + B(::std::marker::NoCopy), } enum IWantToCopyThisToo { diff --git a/src/test/compile-fail/range-1.rs b/src/test/compile-fail/range-1.rs index b05117a7185..0ade2975044 100644 --- a/src/test/compile-fail/range-1.rs +++ b/src/test/compile-fail/range-1.rs @@ -23,5 +23,5 @@ pub fn main() { // Unsized type. let arr: &[_] = &[1u, 2, 3]; let range = (*arr)..; - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } diff --git a/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs b/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs index d8bad0f9103..4d31d2c8e69 100644 --- a/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs +++ b/src/test/compile-fail/regions-infer-contravariance-due-to-decl.rs @@ -14,13 +14,13 @@ // Note: see variance-regions-*.rs for the tests that check that the // variance inference works in the first place. -use std::markers; +use std::marker; // This is contravariant with respect to 'a, meaning that // Contravariant<'foo> <: Contravariant<'static> because // 'foo <= 'static struct Contravariant<'a> { - marker: markers::ContravariantLifetime<'a> + marker: marker::ContravariantLifetime<'a> } fn use_<'short,'long>(c: Contravariant<'short>, diff --git a/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs b/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs index 58c1f0c4721..1c3b7bb5960 100644 --- a/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs +++ b/src/test/compile-fail/regions-infer-covariance-due-to-decl.rs @@ -14,10 +14,10 @@ // Note: see variance-regions-*.rs for the tests that check that the // variance inference works in the first place. -use std::markers; +use std::marker; struct Covariant<'a> { - marker: markers::CovariantLifetime<'a> + marker: marker::CovariantLifetime<'a> } fn use_<'short,'long>(c: Covariant<'long>, diff --git a/src/test/compile-fail/regions-infer-invariance-due-to-decl.rs b/src/test/compile-fail/regions-infer-invariance-due-to-decl.rs index d3d6aa06cdb..5f4a1af6bf9 100644 --- a/src/test/compile-fail/regions-infer-invariance-due-to-decl.rs +++ b/src/test/compile-fail/regions-infer-invariance-due-to-decl.rs @@ -8,10 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; struct invariant<'a> { - marker: markers::InvariantLifetime<'a> + marker: marker::InvariantLifetime<'a> } fn to_same_lifetime<'r>(bi: invariant<'r>) { diff --git a/src/test/compile-fail/repeat-to-run-dtor-twice.rs b/src/test/compile-fail/repeat-to-run-dtor-twice.rs index d8a183c0e46..762c976a943 100644 --- a/src/test/compile-fail/repeat-to-run-dtor-twice.rs +++ b/src/test/compile-fail/repeat-to-run-dtor-twice.rs @@ -25,5 +25,5 @@ impl Drop for Foo { fn main() { let a = Foo { x: 3 }; let _ = [ a; 5 ]; - //~^ ERROR the trait `core::markers::Copy` is not implemented for the type `Foo` + //~^ ERROR the trait `core::marker::Copy` is not implemented for the type `Foo` } diff --git a/src/test/compile-fail/static-items-cant-move.rs b/src/test/compile-fail/static-items-cant-move.rs index e0f241f87a7..14ad1b3041f 100644 --- a/src/test/compile-fail/static-items-cant-move.rs +++ b/src/test/compile-fail/static-items-cant-move.rs @@ -10,14 +10,14 @@ // Verifies that static items can't be moved -use std::markers; +use std::marker; struct Foo { foo: int, - nocopy: markers::NoCopy + nocopy: marker::NoCopy } -static BAR: Foo = Foo{foo: 5, nocopy: markers::NoCopy}; +static BAR: Foo = Foo{foo: 5, nocopy: marker::NoCopy}; fn test(f: Foo) { diff --git a/src/test/compile-fail/syntax-trait-polarity-feature-gate.rs b/src/test/compile-fail/syntax-trait-polarity-feature-gate.rs index 186f5f91eee..a7ca5e3bf09 100644 --- a/src/test/compile-fail/syntax-trait-polarity-feature-gate.rs +++ b/src/test/compile-fail/syntax-trait-polarity-feature-gate.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers::Send; +use std::marker::Send; struct TestType; diff --git a/src/test/compile-fail/syntax-trait-polarity.rs b/src/test/compile-fail/syntax-trait-polarity.rs index bdfadcad2bf..1ab79f5c80e 100644 --- a/src/test/compile-fail/syntax-trait-polarity.rs +++ b/src/test/compile-fail/syntax-trait-polarity.rs @@ -10,7 +10,7 @@ #![feature(optin_builtin_traits)] -use std::markers::Send; +use std::marker::Send; struct TestType; diff --git a/src/test/compile-fail/task-rng-isnt-sendable.rs b/src/test/compile-fail/task-rng-isnt-sendable.rs index 5bc96cae0bb..fe31d81983e 100644 --- a/src/test/compile-fail/task-rng-isnt-sendable.rs +++ b/src/test/compile-fail/task-rng-isnt-sendable.rs @@ -16,6 +16,6 @@ fn test_send() {} pub fn main() { test_send::(); - //~^ ERROR `core::markers::Send` is not implemented - //~^^ ERROR `core::markers::Send` is not implemented + //~^ ERROR `core::marker::Send` is not implemented + //~^^ ERROR `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs b/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs index f569bed126d..434d803d718 100644 --- a/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs +++ b/src/test/compile-fail/trait-bounds-not-on-bare-trait.rs @@ -14,7 +14,7 @@ trait Foo { // This should emit the less confusing error, not the more confusing one. fn foo(_x: Foo + Send) { - //~^ERROR the trait `core::markers::Sized` is not implemented + //~^ERROR the trait `core::marker::Sized` is not implemented } fn main() { } diff --git a/src/test/compile-fail/typeck-unsafe-always-share.rs b/src/test/compile-fail/typeck-unsafe-always-share.rs index d3199ff982e..5166a4e9654 100644 --- a/src/test/compile-fail/typeck-unsafe-always-share.rs +++ b/src/test/compile-fail/typeck-unsafe-always-share.rs @@ -13,14 +13,14 @@ // ignore-tidy-linelength use std::cell::UnsafeCell; -use std::markers; +use std::marker; struct MySync { u: UnsafeCell } struct NoSync { - m: markers::NoSync + m: marker::NoSync } fn test(s: T){ @@ -30,17 +30,17 @@ fn test(s: T){ fn main() { let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)}); test(us); - //~^ ERROR `core::markers::Sync` is not implemented + //~^ ERROR `core::marker::Sync` is not implemented - let uns = UnsafeCell::new(NoSync{m: markers::NoSync}); + let uns = UnsafeCell::new(NoSync{m: marker::NoSync}); test(uns); - //~^ ERROR `core::markers::Sync` is not implemented + //~^ ERROR `core::marker::Sync` is not implemented let ms = MySync{u: uns}; test(ms); - //~^ ERROR `core::markers::Sync` is not implemented + //~^ ERROR `core::marker::Sync` is not implemented - let ns = NoSync{m: markers::NoSync}; + let ns = NoSync{m: marker::NoSync}; test(ns); - //~^ ERROR `core::markers::Sync` is not implemented + //~^ ERROR `core::marker::Sync` is not implemented } diff --git a/src/test/compile-fail/unboxed-closure-sugar-region.rs b/src/test/compile-fail/unboxed-closure-sugar-region.rs index ee7d2cc168c..e0783b09cbd 100644 --- a/src/test/compile-fail/unboxed-closure-sugar-region.rs +++ b/src/test/compile-fail/unboxed-closure-sugar-region.rs @@ -15,7 +15,7 @@ #![feature(unboxed_closures)] #![allow(dead_code)] -use std::markers; +use std::marker; trait Foo<'a,T,U> { fn dummy(&'a self) -> &'a (T,U); diff --git a/src/test/compile-fail/unique-unique-kind.rs b/src/test/compile-fail/unique-unique-kind.rs index 98d8b2d36cd..49cebbf5255 100644 --- a/src/test/compile-fail/unique-unique-kind.rs +++ b/src/test/compile-fail/unique-unique-kind.rs @@ -17,6 +17,6 @@ fn f(_i: T) { fn main() { let i = box Rc::new(100i); f(i); - //~^ ERROR `core::markers::Send` is not implemented - //~^^ ERROR `core::markers::Send` is not implemented + //~^ ERROR `core::marker::Send` is not implemented + //~^^ ERROR `core::marker::Send` is not implemented } diff --git a/src/test/compile-fail/unsendable-class.rs b/src/test/compile-fail/unsendable-class.rs index 6398623e75b..96f36af53aa 100644 --- a/src/test/compile-fail/unsendable-class.rs +++ b/src/test/compile-fail/unsendable-class.rs @@ -30,7 +30,7 @@ fn foo(i:int, j: Rc) -> foo { fn main() { let cat = "kitty".to_string(); let (tx, _) = channel(); - //~^ ERROR `core::markers::Send` is not implemented - //~^^ ERROR `core::markers::Send` is not implemented + //~^ ERROR `core::marker::Send` is not implemented + //~^^ ERROR `core::marker::Send` is not implemented tx.send(foo(42, Rc::new(cat))); } diff --git a/src/test/compile-fail/unsized-bare-typaram.rs b/src/test/compile-fail/unsized-bare-typaram.rs index b6078cd3af4..e28c082c80c 100644 --- a/src/test/compile-fail/unsized-bare-typaram.rs +++ b/src/test/compile-fail/unsized-bare-typaram.rs @@ -9,5 +9,5 @@ // except according to those terms. fn bar() { } -fn foo() { bar::() } //~ ERROR the trait `core::markers::Sized` is not implemented +fn foo() { bar::() } //~ ERROR the trait `core::marker::Sized` is not implemented fn main() { } diff --git a/src/test/compile-fail/unsized-enum.rs b/src/test/compile-fail/unsized-enum.rs index a78ffb13408..df961978086 100644 --- a/src/test/compile-fail/unsized-enum.rs +++ b/src/test/compile-fail/unsized-enum.rs @@ -15,14 +15,14 @@ fn not_sized() { } enum Foo { FooSome(U), FooNone } fn foo1() { not_sized::>() } // Hunky dory. fn foo2() { not_sized::>() } -//~^ ERROR the trait `core::markers::Sized` is not implemented +//~^ ERROR the trait `core::marker::Sized` is not implemented // // Not OK: `T` is not sized. enum Bar { BarSome(U), BarNone } fn bar1() { not_sized::>() } fn bar2() { is_sized::>() } -//~^ ERROR the trait `core::markers::Sized` is not implemented +//~^ ERROR the trait `core::marker::Sized` is not implemented // // Not OK: `Bar` is not sized, but it should be. diff --git a/src/test/compile-fail/unsized-struct.rs b/src/test/compile-fail/unsized-struct.rs index c6812679155..7b9fc2b468b 100644 --- a/src/test/compile-fail/unsized-struct.rs +++ b/src/test/compile-fail/unsized-struct.rs @@ -15,14 +15,14 @@ fn not_sized() { } struct Foo { data: T } fn foo1() { not_sized::>() } // Hunky dory. fn foo2() { not_sized::>() } -//~^ ERROR the trait `core::markers::Sized` is not implemented +//~^ ERROR the trait `core::marker::Sized` is not implemented // // Not OK: `T` is not sized. struct Bar { data: T } fn bar1() { not_sized::>() } fn bar2() { is_sized::>() } -//~^ ERROR the trait `core::markers::Sized` is not implemented +//~^ ERROR the trait `core::marker::Sized` is not implemented // // Not OK: `Bar` is not sized, but it should be. diff --git a/src/test/compile-fail/unsized-trait-impl-trait-arg.rs b/src/test/compile-fail/unsized-trait-impl-trait-arg.rs index 9a29775f7c9..ac8043d6852 100644 --- a/src/test/compile-fail/unsized-trait-impl-trait-arg.rs +++ b/src/test/compile-fail/unsized-trait-impl-trait-arg.rs @@ -15,7 +15,7 @@ trait T2 { } struct S4; impl T2 for S4 { - //~^ ERROR `core::markers::Sized` is not implemented for the type `X` + //~^ ERROR `core::marker::Sized` is not implemented for the type `X` } fn main() { } diff --git a/src/test/compile-fail/unsized3.rs b/src/test/compile-fail/unsized3.rs index 7e4a1d13557..2d330654881 100644 --- a/src/test/compile-fail/unsized3.rs +++ b/src/test/compile-fail/unsized3.rs @@ -14,7 +14,7 @@ // Unbounded. fn f1(x: &X) { f2::(x); - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } fn f2(x: &X) { } @@ -23,7 +23,7 @@ fn f2(x: &X) { trait T {} fn f3(x: &X) { f4::(x); - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } fn f4(x: &X) { } @@ -37,7 +37,7 @@ fn f5(x: &Y) {} fn f6(x: &X) {} fn f7(x1: &E, x2: &E) { f5(x1); - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented f6(x2); // ok } @@ -49,19 +49,19 @@ struct S { fn f8(x1: &S, x2: &S) { f5(x1); - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented f6(x2); // ok } // Test some tuples. fn f9(x1: Box>, x2: Box>) { f5(&(*x1, 34i)); - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } fn f10(x1: Box>, x2: Box>) { f5(&(32i, *x2)); - //~^ ERROR the trait `core::markers::Sized` is not implemented + //~^ ERROR the trait `core::marker::Sized` is not implemented } pub fn main() { diff --git a/src/test/compile-fail/unsized5.rs b/src/test/compile-fail/unsized5.rs index a714b7d9238..026d496aa43 100644 --- a/src/test/compile-fail/unsized5.rs +++ b/src/test/compile-fail/unsized5.rs @@ -11,27 +11,27 @@ // Test `?Sized` types not allowed in fields (except the last one). struct S1 { - f1: X, //~ ERROR `core::markers::Sized` is not implemented + f1: X, //~ ERROR `core::marker::Sized` is not implemented f2: int, } struct S2 { f: int, - g: X, //~ ERROR `core::markers::Sized` is not implemented + g: X, //~ ERROR `core::marker::Sized` is not implemented h: int, } struct S3 { - f: str, //~ ERROR `core::markers::Sized` is not implemented + f: str, //~ ERROR `core::marker::Sized` is not implemented g: [uint] } struct S4 { - f: str, //~ ERROR `core::markers::Sized` is not implemented + f: str, //~ ERROR `core::marker::Sized` is not implemented g: uint } enum E { - V1(X, int), //~ERROR `core::markers::Sized` is not implemented + V1(X, int), //~ERROR `core::marker::Sized` is not implemented } enum F { - V2{f1: X, f: int}, //~ERROR `core::markers::Sized` is not implemented + V2{f1: X, f: int}, //~ERROR `core::marker::Sized` is not implemented } pub fn main() { diff --git a/src/test/compile-fail/unsized6.rs b/src/test/compile-fail/unsized6.rs index d3b03493fdc..02f3404b72b 100644 --- a/src/test/compile-fail/unsized6.rs +++ b/src/test/compile-fail/unsized6.rs @@ -16,27 +16,27 @@ trait T {} fn f1(x: &X) { let _: X; // <-- this is OK, no bindings created, no initializer. let _: (int, (X, int)); // same - let y: X; //~ERROR the trait `core::markers::Sized` is not implemented - let y: (int, (X, int)); //~ERROR the trait `core::markers::Sized` is not implemented + let y: X; //~ERROR the trait `core::marker::Sized` is not implemented + let y: (int, (X, int)); //~ERROR the trait `core::marker::Sized` is not implemented } fn f2(x: &X) { - let y: X; //~ERROR the trait `core::markers::Sized` is not implemented - let y: (int, (X, int)); //~ERROR the trait `core::markers::Sized` is not implemented + let y: X; //~ERROR the trait `core::marker::Sized` is not implemented + let y: (int, (X, int)); //~ERROR the trait `core::marker::Sized` is not implemented } fn f3(x1: Box, x2: Box, x3: Box) { - let y: X = *x1; //~ERROR the trait `core::markers::Sized` is not implemented - let y = *x2; //~ERROR the trait `core::markers::Sized` is not implemented - let (y, z) = (*x3, 4i); //~ERROR the trait `core::markers::Sized` is not implemented + let y: X = *x1; //~ERROR the trait `core::marker::Sized` is not implemented + let y = *x2; //~ERROR the trait `core::marker::Sized` is not implemented + let (y, z) = (*x3, 4i); //~ERROR the trait `core::marker::Sized` is not implemented } -fn f4(x1: Box, x2: Box, x3: Box) { - let y: X = *x1; //~ERROR the trait `core::markers::Sized` is not implemented - let y = *x2; //~ERROR the trait `core::markers::Sized` is not implemented - let (y, z) = (*x3, 4i); //~ERROR the trait `core::markers::Sized` is not implemented +fn f4(x1: Box, x2: Box, x3: Box) { + let y: X = *x1; //~ERROR the trait `core::marker::Sized` is not implemented + let y = *x2; //~ERROR the trait `core::marker::Sized` is not implemented + let (y, z) = (*x3, 4i); //~ERROR the trait `core::marker::Sized` is not implemented } -fn g1(x: X) {} //~ERROR the trait `core::markers::Sized` is not implemented -fn g2(x: X) {} //~ERROR the trait `core::markers::Sized` is not implemented +fn g1(x: X) {} //~ERROR the trait `core::marker::Sized` is not implemented +fn g2(x: X) {} //~ERROR the trait `core::marker::Sized` is not implemented pub fn main() { } diff --git a/src/test/compile-fail/unsized7.rs b/src/test/compile-fail/unsized7.rs index 32daa2a246e..6fc547c0b8e 100644 --- a/src/test/compile-fail/unsized7.rs +++ b/src/test/compile-fail/unsized7.rs @@ -18,7 +18,7 @@ trait T1 { } struct S3; impl T1 for S3 { - //~^ ERROR `core::markers::Sized` is not implemented for the type `X` + //~^ ERROR `core::marker::Sized` is not implemented for the type `X` } fn main() { } diff --git a/src/test/compile-fail/where-clause-constraints-are-local-for-inherent-impl.rs b/src/test/compile-fail/where-clause-constraints-are-local-for-inherent-impl.rs index c584c30448f..74342cfedd3 100644 --- a/src/test/compile-fail/where-clause-constraints-are-local-for-inherent-impl.rs +++ b/src/test/compile-fail/where-clause-constraints-are-local-for-inherent-impl.rs @@ -21,7 +21,7 @@ impl Foo { fn fails_copy(self) { require_copy(self.x); - //~^ ERROR the trait `core::markers::Copy` is not implemented for the type `T` + //~^ ERROR the trait `core::marker::Copy` is not implemented for the type `T` } } diff --git a/src/test/compile-fail/where-clause-constraints-are-local-for-trait-impl.rs b/src/test/compile-fail/where-clause-constraints-are-local-for-trait-impl.rs index 45df3af08d4..8e01e89b687 100644 --- a/src/test/compile-fail/where-clause-constraints-are-local-for-trait-impl.rs +++ b/src/test/compile-fail/where-clause-constraints-are-local-for-trait-impl.rs @@ -26,7 +26,7 @@ impl Foo for Bar { fn fails_copy(self) { require_copy(self.x); - //~^ ERROR the trait `core::markers::Copy` is not implemented for the type `T` + //~^ ERROR the trait `core::marker::Copy` is not implemented for the type `T` } } diff --git a/src/test/run-pass/associated-types-impl-redirect.rs b/src/test/run-pass/associated-types-impl-redirect.rs index d18d6ffd7d0..d9d11c95adb 100644 --- a/src/test/run-pass/associated-types-impl-redirect.rs +++ b/src/test/run-pass/associated-types-impl-redirect.rs @@ -19,7 +19,7 @@ #![feature(lang_items, unboxed_closures)] #![no_implicit_prelude] -use std::markers::Sized; +use std::marker::Sized; use std::option::Option::{None, Some, self}; trait Iterator { diff --git a/src/test/run-pass/associated-types-where-clause-impl-ambiguity.rs b/src/test/run-pass/associated-types-where-clause-impl-ambiguity.rs index 4ebf071cbc1..4152321cab8 100644 --- a/src/test/run-pass/associated-types-where-clause-impl-ambiguity.rs +++ b/src/test/run-pass/associated-types-where-clause-impl-ambiguity.rs @@ -19,7 +19,7 @@ #![feature(lang_items, unboxed_closures)] #![no_implicit_prelude] -use std::markers::Sized; +use std::marker::Sized; use std::option::Option::{None, Some, self}; trait Iterator { diff --git a/src/test/run-pass/const-block.rs b/src/test/run-pass/const-block.rs index 9ec68264076..84acd3c4ecd 100644 --- a/src/test/run-pass/const-block.rs +++ b/src/test/run-pass/const-block.rs @@ -11,7 +11,7 @@ #![allow(dead_code)] #![allow(unused_unsafe)] -use std::markers::Sync; +use std::marker::Sync; struct Foo { a: uint, diff --git a/src/test/run-pass/fsu-moves-and-copies.rs b/src/test/run-pass/fsu-moves-and-copies.rs index 5ce8eb64318..a08cd33362f 100644 --- a/src/test/run-pass/fsu-moves-and-copies.rs +++ b/src/test/run-pass/fsu-moves-and-copies.rs @@ -11,7 +11,7 @@ // Issue 4691: Ensure that functional-struct-updates operates // correctly and moves rather than copy when appropriate. -use std::markers::NoCopy as NP; +use std::marker::NoCopy as NP; struct ncint { np: NP, v: int } fn ncint(v: int) -> ncint { ncint { np: NP, v: v } } diff --git a/src/test/run-pass/hrtb-opt-in-copy.rs b/src/test/run-pass/hrtb-opt-in-copy.rs index e364cb0c9a2..8eaf8427bfd 100644 --- a/src/test/run-pass/hrtb-opt-in-copy.rs +++ b/src/test/run-pass/hrtb-opt-in-copy.rs @@ -18,7 +18,7 @@ #![allow(dead_code)] -use std::markers; +use std::marker; #[derive(Copy)] struct Foo { x: T } @@ -26,7 +26,7 @@ struct Foo { x: T } type Ty<'tcx> = &'tcx TyS<'tcx>; enum TyS<'tcx> { - Boop(markers::InvariantLifetime<'tcx>) + Boop(marker::InvariantLifetime<'tcx>) } enum Bar<'tcx> { diff --git a/src/test/run-pass/issue-17718-static-unsafe-interior.rs b/src/test/run-pass/issue-17718-static-unsafe-interior.rs index ac9a70379f8..cdd03244df1 100644 --- a/src/test/run-pass/issue-17718-static-unsafe-interior.rs +++ b/src/test/run-pass/issue-17718-static-unsafe-interior.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::markers; +use std::marker; use std::cell::UnsafeCell; struct MyUnsafePack(UnsafeCell); diff --git a/src/test/run-pass/issue-2718.rs b/src/test/run-pass/issue-2718.rs index 435b1699883..3ca3e0592e7 100644 --- a/src/test/run-pass/issue-2718.rs +++ b/src/test/run-pass/issue-2718.rs @@ -23,7 +23,7 @@ pub mod pipes { use std::mem::{replace, swap}; use std::mem; use std::thread::Thread; - use std::markers::Send; + use std::marker::Send; pub struct Stuff { state: state, diff --git a/src/test/run-pass/method-recursive-blanket-impl.rs b/src/test/run-pass/method-recursive-blanket-impl.rs index 279f05ea1c9..338bd89ab5c 100644 --- a/src/test/run-pass/method-recursive-blanket-impl.rs +++ b/src/test/run-pass/method-recursive-blanket-impl.rs @@ -13,7 +13,7 @@ // know not to stop at the blanket, we have to recursively evaluate // the `T:Foo` bound. -use std::markers::Sized; +use std::marker::Sized; // Note: this must be generic for the problem to show up trait Foo { diff --git a/src/test/run-pass/regions-infer-bivariance.rs b/src/test/run-pass/regions-infer-bivariance.rs index a750b3f4b4e..a3288e2e1b9 100644 --- a/src/test/run-pass/regions-infer-bivariance.rs +++ b/src/test/run-pass/regions-infer-bivariance.rs @@ -11,7 +11,7 @@ // Test that a type whose lifetime parameters is never used is // inferred to be bivariant. -use std::markers; +use std::marker; struct Bivariant<'a>; diff --git a/src/test/run-pass/syntax-trait-polarity.rs b/src/test/run-pass/syntax-trait-polarity.rs index 244e084e65b..a91e5da1537 100644 --- a/src/test/run-pass/syntax-trait-polarity.rs +++ b/src/test/run-pass/syntax-trait-polarity.rs @@ -10,7 +10,7 @@ #![feature(optin_builtin_traits)] -use std::markers::Send; +use std::marker::Send; struct TestType; -- cgit 1.4.1-3-g733a5 From e2f97f51ad4cf902e5a5835b5332447fe59089c4 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Tue, 6 Jan 2015 09:24:46 -0800 Subject: Register new snapshots Conflicts: src/librbml/lib.rs src/libserialize/json_stage0.rs src/libserialize/serialize_stage0.rs src/libsyntax/ast.rs src/libsyntax/ext/deriving/generic/mod.rs src/libsyntax/parse/token.rs --- src/compiletest/compiletest.rs | 6 - src/liballoc/lib.rs | 26 +- src/libcollections/lib.rs | 31 +- src/libcollections/macros.rs | 14 - src/libcore/fmt/mod.rs | 3 - src/libcore/lib.rs | 18 +- src/libcore/macros.rs | 7 - src/libcoretest/num/mod.rs | 6 +- src/libflate/lib.rs | 1 - src/libfmt_macros/lib.rs | 3 +- src/libgetopts/lib.rs | 3 +- src/libgraphviz/lib.rs | 3 +- src/liblibc/lib.rs | 3 +- src/liblog/lib.rs | 5 +- src/librand/lib.rs | 25 +- src/librbml/lib.rs | 473 +--- src/libregex/lib.rs | 4 +- src/librustc/lib.rs | 24 +- src/librustc/metadata/decoder.rs | 4 +- src/librustc/metadata/encoder.rs | 2 +- src/librustc/middle/astencode.rs | 23 - src/librustc/middle/intrinsicck.rs | 2 +- src/librustc/middle/ty_fold.rs | 2 +- src/librustc_back/lib.rs | 15 +- src/librustc_borrowck/lib.rs | 21 +- src/librustc_driver/lib.rs | 22 +- src/librustc_llvm/lib.rs | 3 - src/librustc_resolve/lib.rs | 21 +- src/librustc_trans/lib.rs | 23 +- src/librustc_trans/trans/mod.rs | 3 +- src/librustc_typeck/lib.rs | 20 +- src/librustdoc/lib.rs | 19 +- src/libserialize/collection_impls_stage0.rs | 289 -- src/libserialize/json_stage0.rs | 3864 --------------------------- src/libserialize/lib.rs | 31 +- src/libserialize/serialize_stage0.rs | 630 ----- src/libstd/collections/hash/set.rs | 3 - src/libstd/io/buffered.rs | 3 - src/libstd/io/mod.rs | 3 +- src/libstd/lib.rs | 50 +- src/libstd/macros_stage0.rs | 648 ----- src/libstd/rand/os.rs | 3 - src/libstd/rt/mod.rs | 3 +- src/libstd/thread_local/mod.rs | 3 +- src/libstd/time/duration.rs | 3 - src/libsyntax/ast.rs | 16 - src/libsyntax/codemap.rs | 17 - src/libsyntax/ext/deriving/generic/mod.rs | 10 +- src/libsyntax/ext/deriving/mod.rs | 2 +- src/libsyntax/feature_gate.rs | 2 +- src/libsyntax/lib.rs | 14 +- src/libsyntax/owned_slice.rs | 19 - src/libsyntax/parse/mod.rs | 3 +- src/libsyntax/parse/token.rs | 17 - src/libsyntax/ptr.rs | 16 - src/libterm/lib.rs | 11 +- src/libtest/lib.rs | 6 +- src/libunicode/lib.rs | 3 +- src/snapshots.txt | 9 + 59 files changed, 94 insertions(+), 6419 deletions(-) delete mode 100644 src/libserialize/collection_impls_stage0.rs delete mode 100644 src/libserialize/json_stage0.rs delete mode 100644 src/libserialize/serialize_stage0.rs delete mode 100644 src/libstd/macros_stage0.rs (limited to 'src/libstd/thread_local') diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index 23674efe968..ff9b2de3ccf 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -16,14 +16,8 @@ extern crate test; extern crate getopts; -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] #[macro_use] extern crate log; - extern crate regex; use std::os; diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index 001e02f9c0d..d5a814d83e4 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -65,36 +65,16 @@ #![no_std] #![allow(unknown_features)] -#![feature(lang_items, phase, unsafe_destructor, default_type_params, old_orphan_check)] -#![feature(associated_types)] +#![feature(lang_items, phase, unsafe_destructor)] -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate core; - -#[cfg(not(stage0))] #[macro_use] extern crate core; - extern crate libc; // Allow testing this library -#[cfg(all(test, stage0))] -#[phase(plugin, link)] -extern crate std; - -#[cfg(all(test, not(stage0)))] -#[macro_use] -extern crate std; - -#[cfg(all(test, stage0))] -#[phase(plugin, link)] -extern crate log; - -#[cfg(all(test, not(stage0)))] -#[macro_use] -extern crate log; +#[cfg(test)] #[macro_use] extern crate std; +#[cfg(test)] #[macro_use] extern crate log; // Heaps provided for low-level allocation strategies diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index 5bf5f78af94..82dfa41d9d8 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -21,19 +21,9 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] -#![allow(unknown_features)] -#![feature(macro_rules, default_type_params, phase, globs)] #![feature(unsafe_destructor, slicing_syntax)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] -#![feature(associated_types)] #![no_std] -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate core; - -#[cfg(not(stage0))] #[macro_use] extern crate core; @@ -41,22 +31,8 @@ extern crate unicode; extern crate alloc; #[cfg(test)] extern crate test; - -#[cfg(all(test, stage0))] -#[phase(plugin, link)] -extern crate std; - -#[cfg(all(test, not(stage0)))] -#[macro_use] -extern crate std; - -#[cfg(all(test, stage0))] -#[phase(plugin, link)] -extern crate log; - -#[cfg(all(test, not(stage0)))] -#[macro_use] -extern crate log; +#[cfg(test)] #[macro_use] extern crate std; +#[cfg(test)] #[macro_use] extern crate log; pub use binary_heap::BinaryHeap; pub use bitv::Bitv; @@ -73,8 +49,7 @@ pub use vec_map::VecMap; // Needed for the vec! macro pub use alloc::boxed; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod macros; pub mod binary_heap; diff --git a/src/libcollections/macros.rs b/src/libcollections/macros.rs index 0c5929e8661..68e2482964d 100644 --- a/src/libcollections/macros.rs +++ b/src/libcollections/macros.rs @@ -8,21 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/// Creates a `std::vec::Vec` containing the arguments. -// NOTE: remove after the next snapshot -#[cfg(stage0)] -macro_rules! vec { - ($($e:expr),*) => ({ - // leading _ to allow empty construction without a warning. - let mut _temp = ::vec::Vec::new(); - $(_temp.push($e);)* - _temp - }); - ($($e:expr),+,) => (vec!($($e),+)) -} - /// Creates a `Vec` containing the arguments. -#[cfg(not(stage0))] #[macro_export] macro_rules! vec { ($($x:expr),*) => ({ diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index fe2511d1f7f..fdd758cedac 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -27,9 +27,6 @@ use slice::SliceExt; use slice; use str::{self, StrExt, Utf8Error}; -// NOTE: for old macros; remove after the next snapshot -#[cfg(stage0)] use result::Result::Err; - pub use self::num::radix; pub use self::num::Radix; pub use self::num::RadixFmt; diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index aff0065c527..4b598fd5033 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -56,29 +56,25 @@ html_playground_url = "http://play.rust-lang.org/")] #![no_std] -#![allow(unknown_features, raw_pointer_deriving)] -#![feature(globs, intrinsics, lang_items, macro_rules, phase)] +#![allow(unknown_features, raw_pointer_derive)] +#![feature(intrinsics, lang_items)] #![feature(simd, unsafe_destructor, slicing_syntax)] -#![feature(default_type_params, unboxed_closures, associated_types)] +#![feature(unboxed_closures)] #![deny(missing_docs)] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod macros; #[path = "num/float_macros.rs"] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod float_macros; #[path = "num/int_macros.rs"] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod int_macros; #[path = "num/uint_macros.rs"] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod uint_macros; #[path = "num/int.rs"] pub mod int; diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index 99e49cc21ed..d01621fc6d8 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -142,16 +142,9 @@ macro_rules! debug_assert_eq { ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); }) } -#[cfg(stage0)] -#[macro_export] -macro_rules! try { - ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) }) -} - /// Short circuiting evaluation on Err /// /// `libstd` contains a more general `try!` macro that uses `FromError`. -#[cfg(not(stage0))] #[macro_export] macro_rules! try { ($e:expr) => ({ diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs index f86c85f8216..9be7917e0a0 100644 --- a/src/libcoretest/num/mod.rs +++ b/src/libcoretest/num/mod.rs @@ -14,8 +14,7 @@ use core::num::{NumCast, cast}; use core::ops::{Add, Sub, Mul, Div, Rem}; use core::kinds::Copy; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod int_macros; mod i8; @@ -24,8 +23,7 @@ mod i32; mod i64; mod int; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod uint_macros; mod u8; diff --git a/src/libflate/lib.rs b/src/libflate/lib.rs index 6ac311fe4b6..f38440d86c6 100644 --- a/src/libflate/lib.rs +++ b/src/libflate/lib.rs @@ -21,7 +21,6 @@ #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![feature(unboxed_closures, associated_types)] #[cfg(test)] #[macro_use] extern crate log; diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index 19173baf166..47cc072a636 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -23,8 +23,7 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] -#![feature(globs, slicing_syntax)] -#![feature(associated_types)] +#![feature(slicing_syntax)] pub use self::Piece::*; pub use self::Position::*; diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 64d4de7cc8a..f50e24c6354 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -85,8 +85,7 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] -#![feature(globs, slicing_syntax)] -#![feature(unboxed_closures)] +#![feature(slicing_syntax)] #![deny(missing_docs)] #[cfg(test)] #[macro_use] extern crate log; diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 7e8382b26c4..83bad70e7b1 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -271,8 +271,7 @@ #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![feature(globs, slicing_syntax)] -#![feature(unboxed_closures)] +#![feature(slicing_syntax)] use self::LabelText::*; diff --git a/src/liblibc/lib.rs b/src/liblibc/lib.rs index e3f02146a75..1aaa0528a68 100644 --- a/src/liblibc/lib.rs +++ b/src/liblibc/lib.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(globs)] #![crate_name = "libc"] #![experimental] #![no_std] // we don't need std, and we can't have std, since it doesn't exist @@ -76,7 +75,7 @@ #![allow(non_upper_case_globals)] #![allow(missing_docs)] #![allow(non_snake_case)] -#![allow(raw_pointer_deriving)] +#![allow(raw_pointer_derive)] extern crate core; diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index 332dd5e558e..08b01e956e1 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -163,7 +163,7 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] -#![feature(macro_rules, unboxed_closures, slicing_syntax)] +#![feature(slicing_syntax)] #![deny(missing_docs)] extern crate regex; @@ -182,8 +182,7 @@ use regex::Regex; use directive::LOG_LEVEL_NAMES; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod macros; mod directive; diff --git a/src/librand/lib.rs b/src/librand/lib.rs index aeecd69e205..9e5fcdc8df5 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -23,35 +23,14 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] -#![feature(macro_rules, phase, globs)] -#![feature(unboxed_closures)] -#![feature(associated_types)] #![no_std] #![experimental] -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate core; - -#[cfg(not(stage0))] #[macro_use] extern crate core; -#[cfg(all(test, stage0))] -#[phase(plugin, link)] -extern crate std; - -#[cfg(all(test, not(stage0)))] -#[macro_use] -extern crate std; - -#[cfg(all(test, stage0))] -#[phase(plugin, link)] -extern crate log; - -#[cfg(all(test, not(stage0)))] -#[macro_use] -extern crate log; +#[cfg(test)] #[macro_use] extern crate std; +#[cfg(test)] #[macro_use] extern crate log; use core::prelude::*; diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index 80a3a88f70c..a66d1dd08c1 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -24,19 +24,10 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] -#![feature(macro_rules, phase, slicing_syntax, globs)] -#![feature(unboxed_closures, associated_types)] -#![allow(missing_docs)] +#![feature(slicing_syntax)] extern crate serialize; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; +#[macro_use] extern crate log; #[cfg(test)] extern crate test; @@ -424,263 +415,6 @@ pub mod reader { } } - #[cfg(stage0)] - impl<'doc> serialize::Decoder for Decoder<'doc> { - fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) } - - fn read_u64(&mut self) -> DecodeResult { Ok(doc_as_u64(try!(self.next_doc(EsU64)))) } - fn read_u32(&mut self) -> DecodeResult { Ok(doc_as_u32(try!(self.next_doc(EsU32)))) } - fn read_u16(&mut self) -> DecodeResult { Ok(doc_as_u16(try!(self.next_doc(EsU16)))) } - fn read_u8 (&mut self) -> DecodeResult { Ok(doc_as_u8 (try!(self.next_doc(EsU8 )))) } - fn read_uint(&mut self) -> DecodeResult { - let v = doc_as_u64(try!(self.next_doc(EsUint))); - if v > (::std::uint::MAX as u64) { - Err(IntTooBig(v as uint)) - } else { - Ok(v as uint) - } - } - - fn read_i64(&mut self) -> DecodeResult { - Ok(doc_as_u64(try!(self.next_doc(EsI64))) as i64) - } - fn read_i32(&mut self) -> DecodeResult { - Ok(doc_as_u32(try!(self.next_doc(EsI32))) as i32) - } - fn read_i16(&mut self) -> DecodeResult { - Ok(doc_as_u16(try!(self.next_doc(EsI16))) as i16) - } - fn read_i8 (&mut self) -> DecodeResult { - Ok(doc_as_u8(try!(self.next_doc(EsI8 ))) as i8) - } - fn read_int(&mut self) -> DecodeResult { - let v = doc_as_u64(try!(self.next_doc(EsInt))) as i64; - if v > (int::MAX as i64) || v < (int::MIN as i64) { - debug!("FIXME \\#6122: Removing this makes this function miscompile"); - Err(IntTooBig(v as uint)) - } else { - Ok(v as int) - } - } - - fn read_bool(&mut self) -> DecodeResult { - Ok(doc_as_u8(try!(self.next_doc(EsBool))) != 0) - } - - fn read_f64(&mut self) -> DecodeResult { - let bits = doc_as_u64(try!(self.next_doc(EsF64))); - Ok(unsafe { transmute(bits) }) - } - fn read_f32(&mut self) -> DecodeResult { - let bits = doc_as_u32(try!(self.next_doc(EsF32))); - Ok(unsafe { transmute(bits) }) - } - fn read_char(&mut self) -> DecodeResult { - Ok(char::from_u32(doc_as_u32(try!(self.next_doc(EsChar)))).unwrap()) - } - fn read_str(&mut self) -> DecodeResult { - Ok(try!(self.next_doc(EsStr)).as_str()) - } - - // Compound types: - fn read_enum(&mut self, name: &str, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_enum({:?})", name); - try!(self._check_label(name)); - - let doc = try!(self.next_doc(EsEnum)); - - let (old_parent, old_pos) = (self.parent, self.pos); - self.parent = doc; - self.pos = self.parent.start; - - let result = try!(f(self)); - - self.parent = old_parent; - self.pos = old_pos; - Ok(result) - } - - fn read_enum_variant(&mut self, _: &[&str], - mut f: F) -> DecodeResult - where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult, - { - debug!("read_enum_variant()"); - let idx = try!(self._next_uint(EsEnumVid)); - debug!(" idx={:?}", idx); - - let doc = try!(self.next_doc(EsEnumBody)); - - let (old_parent, old_pos) = (self.parent, self.pos); - self.parent = doc; - self.pos = self.parent.start; - - let result = try!(f(self, idx)); - - self.parent = old_parent; - self.pos = old_pos; - Ok(result) - } - - fn read_enum_variant_arg(&mut self, idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_enum_variant_arg(idx={:?})", idx); - f(self) - } - - fn read_enum_struct_variant(&mut self, _: &[&str], - mut f: F) -> DecodeResult - where F: FnMut(&mut Decoder<'doc>, uint) -> DecodeResult, - { - debug!("read_enum_struct_variant()"); - let idx = try!(self._next_uint(EsEnumVid)); - debug!(" idx={:?}", idx); - - let doc = try!(self.next_doc(EsEnumBody)); - - let (old_parent, old_pos) = (self.parent, self.pos); - self.parent = doc; - self.pos = self.parent.start; - - let result = try!(f(self, idx)); - - self.parent = old_parent; - self.pos = old_pos; - Ok(result) - } - - fn read_enum_struct_variant_field(&mut self, - name: &str, - idx: uint, - f: F) - -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_enum_struct_variant_arg(name={:?}, idx={:?})", name, idx); - f(self) - } - - fn read_struct(&mut self, name: &str, _: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_struct(name={:?})", name); - f(self) - } - - fn read_struct_field(&mut self, name: &str, idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_struct_field(name={:?}, idx={:?})", name, idx); - try!(self._check_label(name)); - f(self) - } - - fn read_tuple(&mut self, tuple_len: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_tuple()"); - self.read_seq(move |d, len| { - if len == tuple_len { - f(d) - } else { - Err(Expected(format!("Expected tuple of length `{}`, \ - found tuple of length `{}`", tuple_len, len))) - } - }) - } - - fn read_tuple_arg(&mut self, idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_tuple_arg(idx={:?})", idx); - self.read_seq_elt(idx, f) - } - - fn read_tuple_struct(&mut self, name: &str, len: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_tuple_struct(name={:?})", name); - self.read_tuple(len, f) - } - - fn read_tuple_struct_arg(&mut self, - idx: uint, - f: F) - -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_tuple_struct_arg(idx={:?})", idx); - self.read_tuple_arg(idx, f) - } - - fn read_option(&mut self, mut f: F) -> DecodeResult where - F: FnMut(&mut Decoder<'doc>, bool) -> DecodeResult, - { - debug!("read_option()"); - self.read_enum("Option", move |this| { - this.read_enum_variant(&["None", "Some"], move |this, idx| { - match idx { - 0 => f(this, false), - 1 => f(this, true), - _ => { - Err(Expected(format!("Expected None or Some"))) - } - } - }) - }) - } - - fn read_seq(&mut self, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult, - { - debug!("read_seq()"); - self.push_doc(EsVec, move |d| { - let len = try!(d._next_uint(EsVecLen)); - debug!(" len={:?}", len); - f(d, len) - }) - } - - fn read_seq_elt(&mut self, idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_seq_elt(idx={:?})", idx); - self.push_doc(EsVecElt, f) - } - - fn read_map(&mut self, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>, uint) -> DecodeResult, - { - debug!("read_map()"); - self.push_doc(EsMap, move |d| { - let len = try!(d._next_uint(EsMapLen)); - debug!(" len={:?}", len); - f(d, len) - }) - } - - fn read_map_elt_key(&mut self, idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_map_elt_key(idx={:?})", idx); - self.push_doc(EsMapKey, f) - } - - fn read_map_elt_val(&mut self, idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, - { - debug!("read_map_elt_val(idx={:?})", idx); - self.push_doc(EsMapVal, f) - } - - fn error(&mut self, err: &str) -> Error { - ApplicationError(err.to_string()) - } - } - - #[cfg(not(stage0))] impl<'doc> serialize::Decoder for Decoder<'doc> { type Error = Error; fn read_nil(&mut self) -> DecodeResult<()> { Ok(()) } @@ -1137,209 +871,6 @@ pub mod writer { } } - #[cfg(stage0)] - impl<'a, W: Writer + Seek> serialize::Encoder for Encoder<'a, W> { - - fn emit_nil(&mut self) -> EncodeResult { - Ok(()) - } - - fn emit_uint(&mut self, v: uint) -> EncodeResult { - self.wr_tagged_u64(EsUint as uint, v as u64) - } - fn emit_u64(&mut self, v: u64) -> EncodeResult { - self.wr_tagged_u64(EsU64 as uint, v) - } - fn emit_u32(&mut self, v: u32) -> EncodeResult { - self.wr_tagged_u32(EsU32 as uint, v) - } - fn emit_u16(&mut self, v: u16) -> EncodeResult { - self.wr_tagged_u16(EsU16 as uint, v) - } - fn emit_u8(&mut self, v: u8) -> EncodeResult { - self.wr_tagged_u8(EsU8 as uint, v) - } - - fn emit_int(&mut self, v: int) -> EncodeResult { - self.wr_tagged_i64(EsInt as uint, v as i64) - } - fn emit_i64(&mut self, v: i64) -> EncodeResult { - self.wr_tagged_i64(EsI64 as uint, v) - } - fn emit_i32(&mut self, v: i32) -> EncodeResult { - self.wr_tagged_i32(EsI32 as uint, v) - } - fn emit_i16(&mut self, v: i16) -> EncodeResult { - self.wr_tagged_i16(EsI16 as uint, v) - } - fn emit_i8(&mut self, v: i8) -> EncodeResult { - self.wr_tagged_i8(EsI8 as uint, v) - } - - fn emit_bool(&mut self, v: bool) -> EncodeResult { - self.wr_tagged_u8(EsBool as uint, v as u8) - } - - fn emit_f64(&mut self, v: f64) -> EncodeResult { - let bits = unsafe { mem::transmute(v) }; - self.wr_tagged_u64(EsF64 as uint, bits) - } - fn emit_f32(&mut self, v: f32) -> EncodeResult { - let bits = unsafe { mem::transmute(v) }; - self.wr_tagged_u32(EsF32 as uint, bits) - } - fn emit_char(&mut self, v: char) -> EncodeResult { - self.wr_tagged_u32(EsChar as uint, v as u32) - } - - fn emit_str(&mut self, v: &str) -> EncodeResult { - self.wr_tagged_str(EsStr as uint, v) - } - - fn emit_enum(&mut self, name: &str, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - try!(self._emit_label(name)); - try!(self.start_tag(EsEnum as uint)); - try!(f(self)); - self.end_tag() - } - - fn emit_enum_variant(&mut self, - _: &str, - v_id: uint, - _: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - try!(self._emit_tagged_uint(EsEnumVid, v_id)); - try!(self.start_tag(EsEnumBody as uint)); - try!(f(self)); - self.end_tag() - } - - fn emit_enum_variant_arg(&mut self, _: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - f(self) - } - - fn emit_enum_struct_variant(&mut self, - v_name: &str, - v_id: uint, - cnt: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - self.emit_enum_variant(v_name, v_id, cnt, f) - } - - fn emit_enum_struct_variant_field(&mut self, - _: &str, - idx: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - self.emit_enum_variant_arg(idx, f) - } - - fn emit_struct(&mut self, _: &str, _len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - f(self) - } - - fn emit_struct_field(&mut self, name: &str, _: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - try!(self._emit_label(name)); - f(self) - } - - fn emit_tuple(&mut self, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - self.emit_seq(len, f) - } - fn emit_tuple_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - self.emit_seq_elt(idx, f) - } - - fn emit_tuple_struct(&mut self, _: &str, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - self.emit_seq(len, f) - } - fn emit_tuple_struct_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - self.emit_seq_elt(idx, f) - } - - fn emit_option(&mut self, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - self.emit_enum("Option", f) - } - fn emit_option_none(&mut self) -> EncodeResult { - self.emit_enum_variant("None", 0, 0, |_| Ok(())) - } - fn emit_option_some(&mut self, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - - self.emit_enum_variant("Some", 1, 1, f) - } - - fn emit_seq(&mut self, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - - try!(self.start_tag(EsVec as uint)); - try!(self._emit_tagged_uint(EsVecLen, len)); - try!(f(self)); - self.end_tag() - } - - fn emit_seq_elt(&mut self, _idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - - try!(self.start_tag(EsVecElt as uint)); - try!(f(self)); - self.end_tag() - } - - fn emit_map(&mut self, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - - try!(self.start_tag(EsMap as uint)); - try!(self._emit_tagged_uint(EsMapLen, len)); - try!(f(self)); - self.end_tag() - } - - fn emit_map_elt_key(&mut self, _idx: uint, mut f: F) -> EncodeResult where - F: FnMut(&mut Encoder<'a, W>) -> EncodeResult, - { - - try!(self.start_tag(EsMapKey as uint)); - try!(f(self)); - self.end_tag() - } - - fn emit_map_elt_val(&mut self, _idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a, W>) -> EncodeResult, - { - try!(self.start_tag(EsMapVal as uint)); - try!(f(self)); - self.end_tag() - } - } - #[cfg(not(stage0))] impl<'a, W: Writer + Seek> serialize::Encoder for Encoder<'a, W> { type Error = io::IoError; diff --git a/src/libregex/lib.rs b/src/libregex/lib.rs index 92ed048bae0..c039abc9aff 100644 --- a/src/libregex/lib.rs +++ b/src/libregex/lib.rs @@ -23,9 +23,7 @@ html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] -#![feature(macro_rules, slicing_syntax, globs)] -#![feature(unboxed_closures)] -#![feature(associated_types)] +#![feature(slicing_syntax)] #![deny(missing_docs)] #[cfg(test)] diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index 3ed712b15df..0aebbf2970f 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -22,13 +22,9 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![allow(unknown_features)] -#![feature(default_type_params, globs, macro_rules, phase, quote)] +#![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] #![feature(rustc_diagnostic_macros)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] -#![feature(associated_types)] extern crate arena; extern crate flate; @@ -40,22 +36,8 @@ extern crate rustc_back; extern crate serialize; extern crate rbml; extern crate collections; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate syntax; - -#[cfg(not(stage0))] -#[macro_use] -extern crate syntax; +#[macro_use] extern crate log; +#[macro_use] extern crate syntax; extern crate "serialize" as rustc_serialize; // used by deriving diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index 25ce8a6889d..9e71c867efa 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -675,14 +675,14 @@ pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>, id: ast::NodeI debug!("Looking up item: {}", id); let item_doc = lookup_item(id, cdata.data()); let path = item_path(item_doc).init().to_vec(); - match decode_inlined_item.call_mut((cdata, tcx, path, item_doc)) { + match decode_inlined_item(cdata, tcx, path, item_doc) { Ok(ii) => csearch::found(ii), Err(path) => { match item_parent_item(item_doc) { Some(did) => { let did = translate_def_id(cdata, did); let parent_item = lookup_item(did.node, cdata.data()); - match decode_inlined_item.call_mut((cdata, tcx, path, parent_item)) { + match decode_inlined_item(cdata, tcx, path, parent_item) { Ok(ii) => csearch::found_parent(did, ii), Err(_) => csearch::not_found } diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index a13df5a220f..28ad36194ef 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -953,7 +953,7 @@ fn encode_inlined_item(ecx: &EncodeContext, ii: InlinedItemRef) { let mut eii = ecx.encode_inlined_item.borrow_mut(); let eii: &mut EncodeInlinedItem = &mut *eii; - eii.call_mut((ecx, rbml_w, ii)) + eii(ecx, rbml_w, ii) } const FN_FAMILY: char = 'f'; diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 39e15832bb7..32ce131c57a 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -263,14 +263,6 @@ trait def_id_encoder_helpers { fn emit_def_id(&mut self, did: ast::DefId); } -#[cfg(stage0)] -impl, E> def_id_encoder_helpers for S { - fn emit_def_id(&mut self, did: ast::DefId) { - did.encode(self).ok().unwrap() - } -} - -#[cfg(not(stage0))] impl def_id_encoder_helpers for S { fn emit_def_id(&mut self, did: ast::DefId) { did.encode(self).ok().unwrap() @@ -283,21 +275,6 @@ trait def_id_decoder_helpers { cdata: &cstore::crate_metadata) -> ast::DefId; } -#[cfg(stage0)] -impl, E> def_id_decoder_helpers for D { - fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId { - let did: ast::DefId = Decodable::decode(self).ok().unwrap(); - did.tr(dcx) - } - - fn read_def_id_nodcx(&mut self, - cdata: &cstore::crate_metadata) -> ast::DefId { - let did: ast::DefId = Decodable::decode(self).ok().unwrap(); - decoder::translate_def_id(cdata, did) - } -} - -#[cfg(not(stage0))] impl def_id_decoder_helpers for D { fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId { let did: ast::DefId = Decodable::decode(self).ok().unwrap(); diff --git a/src/librustc/middle/intrinsicck.rs b/src/librustc/middle/intrinsicck.rs index 41f293cfca5..bd96a8a0f2c 100644 --- a/src/librustc/middle/intrinsicck.rs +++ b/src/librustc/middle/intrinsicck.rs @@ -205,7 +205,7 @@ impl<'a, 'tcx> IntrinsicCheckingVisitor<'a, 'tcx> { debug!("with_each_combination(substs={})", substs.repr(self.tcx)); - callback.call_mut((substs,)); + callback(substs); } Some((space, index, ¶m_ty)) => { diff --git a/src/librustc/middle/ty_fold.rs b/src/librustc/middle/ty_fold.rs index 1bc0d709458..15c2845882c 100644 --- a/src/librustc/middle/ty_fold.rs +++ b/src/librustc/middle/ty_fold.rs @@ -844,7 +844,7 @@ impl<'a, 'tcx> TypeFolder<'tcx> for RegionFolder<'a, 'tcx> _ => { debug!("RegionFolder.fold_region({}) folding free region (current_depth={})", r.repr(self.tcx()), self.current_depth); - self.fld_r.call_mut((r, self.current_depth)) + (self.fld_r)(r, self.current_depth) } } } diff --git a/src/librustc_back/lib.rs b/src/librustc_back/lib.rs index 238c84e88a9..ca39477fbdc 100644 --- a/src/librustc_back/lib.rs +++ b/src/librustc_back/lib.rs @@ -28,22 +28,11 @@ #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] - -#![allow(unknown_features)] -#![feature(globs, phase, macro_rules, slicing_syntax)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; +#![feature(slicing_syntax)] extern crate syntax; extern crate serialize; +#[macro_use] extern crate log; pub mod abi; pub mod archive; diff --git a/src/librustc_borrowck/lib.rs b/src/librustc_borrowck/lib.rs index 0600ddba018..26bcd5f4c10 100644 --- a/src/librustc_borrowck/lib.rs +++ b/src/librustc_borrowck/lib.rs @@ -17,28 +17,13 @@ html_root_url = "http://doc.rust-lang.org/nightly/")] #![allow(unknown_features)] -#![feature(default_type_params, globs, macro_rules, phase, quote)] +#![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] #![feature(rustc_diagnostic_macros)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] #![allow(non_camel_case_types)] -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate syntax; - -#[cfg(not(stage0))] -#[macro_use] -extern crate syntax; +#[macro_use] extern crate log; +#[macro_use] extern crate syntax; // for "clarity", rename the graphviz crate to dot; graphviz within `borrowck` // refers to the borrowck-specific graphviz adapter traits. diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 3fd5198ee4c..4164a8551cc 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -22,11 +22,9 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![feature(default_type_params, globs, macro_rules, phase, quote)] +#![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] #![feature(rustc_diagnostic_macros)] -#![feature(unboxed_closures)] -#![feature(associated_types)] extern crate arena; extern crate flate; @@ -41,22 +39,8 @@ extern crate rustc_trans; extern crate rustc_typeck; extern crate serialize; extern crate "rustc_llvm" as llvm; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate syntax; - -#[cfg(not(stage0))] -#[macro_use] -extern crate syntax; +#[macro_use] extern crate log; +#[macro_use] extern crate syntax; pub use syntax::diagnostic; diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 8a9334be985..0bed754aa3c 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -21,10 +21,7 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![feature(globs)] #![feature(link_args)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] extern crate libc; diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index dc13f2e331b..653cdb1c42c 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -16,26 +16,11 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![feature(globs, phase, slicing_syntax)] +#![feature(slicing_syntax)] #![feature(rustc_diagnostic_macros)] -#![feature(associated_types)] -#![feature(old_orphan_check)] -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate syntax; - -#[cfg(not(stage0))] -#[macro_use] -extern crate syntax; +#[macro_use] extern crate log; +#[macro_use] extern crate syntax; extern crate rustc; diff --git a/src/librustc_trans/lib.rs b/src/librustc_trans/lib.rs index 705fecf4d19..b6f90a4c2f5 100644 --- a/src/librustc_trans/lib.rs +++ b/src/librustc_trans/lib.rs @@ -22,13 +22,9 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![allow(unknown_features)] -#![feature(default_type_params, globs, macro_rules, phase, quote)] +#![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] #![feature(rustc_diagnostic_macros)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] -#![feature(associated_types)] extern crate arena; extern crate flate; @@ -40,21 +36,8 @@ extern crate rustc_back; extern crate serialize; extern crate "rustc_llvm" as llvm; -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate syntax; - -#[cfg(not(stage0))] -#[macro_use] -extern crate syntax; +#[macro_use] extern crate log; +#[macro_use] extern crate syntax; pub use rustc::session; pub use rustc::metadata; diff --git a/src/librustc_trans/trans/mod.rs b/src/librustc_trans/trans/mod.rs index fa9cd5a698b..42134789546 100644 --- a/src/librustc_trans/trans/mod.rs +++ b/src/librustc_trans/trans/mod.rs @@ -16,8 +16,7 @@ pub use self::base::trans_crate; pub use self::context::CrateContext; pub use self::common::gensym_name; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod macros; mod doc; diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index f7abd8a1cc6..ae8731dfa47 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -71,27 +71,13 @@ This API is completely unstable and subject to change. html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] -#![feature(default_type_params, globs, macro_rules, phase, quote)] +#![feature(quote)] #![feature(slicing_syntax, unsafe_destructor)] #![feature(rustc_diagnostic_macros)] -#![feature(unboxed_closures)] #![allow(non_camel_case_types)] -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate syntax; - -#[cfg(not(stage0))] -#[macro_use] -extern crate syntax; +#[macro_use] extern crate log; +#[macro_use] extern crate syntax; extern crate arena; extern crate rustc; diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 99c5fde47ea..6c6c7c4d378 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -16,12 +16,7 @@ html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] - -#![allow(unknown_features)] -#![feature(globs, macro_rules, phase, slicing_syntax)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] -#![feature(associated_types)] +#![feature(slicing_syntax)] extern crate arena; extern crate getopts; @@ -32,14 +27,7 @@ extern crate rustc_driver; extern crate serialize; extern crate syntax; extern crate "test" as testing; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; +#[macro_use] extern crate log; extern crate "serialize" as rustc_serialize; // used by deriving @@ -56,8 +44,7 @@ use rustc::session::search_paths::SearchPaths; // reexported from `clean` so it can be easily updated with the mod itself pub use clean::SCHEMA_VERSION; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod externalfiles; pub mod clean; diff --git a/src/libserialize/collection_impls_stage0.rs b/src/libserialize/collection_impls_stage0.rs deleted file mode 100644 index f2d79b13346..00000000000 --- a/src/libserialize/collection_impls_stage0.rs +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Implementations of serialization for structures found in libcollections - -use std::uint; -use std::default::Default; -use std::hash::{Hash, Hasher}; - -use {Decodable, Encodable, Decoder, Encoder}; -use std::collections::{DList, RingBuf, BTreeMap, BTreeSet, HashMap, HashSet, VecMap}; -use collections::enum_set::{EnumSet, CLike}; - -impl< - E, - S: Encoder, - T: Encodable -> Encodable for DList { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_seq(self.len(), |s| { - for (i, e) in self.iter().enumerate() { - try!(s.emit_seq_elt(i, |s| e.encode(s))); - } - Ok(()) - }) - } -} - -impl,T:Decodable> Decodable for DList { - fn decode(d: &mut D) -> Result, E> { - d.read_seq(|d, len| { - let mut list = DList::new(); - for i in range(0u, len) { - list.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); - } - Ok(list) - }) - } -} - -impl< - E, - S: Encoder, - T: Encodable -> Encodable for RingBuf { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_seq(self.len(), |s| { - for (i, e) in self.iter().enumerate() { - try!(s.emit_seq_elt(i, |s| e.encode(s))); - } - Ok(()) - }) - } -} - -impl,T:Decodable> Decodable for RingBuf { - fn decode(d: &mut D) -> Result, E> { - d.read_seq(|d, len| { - let mut deque: RingBuf = RingBuf::new(); - for i in range(0u, len) { - deque.push_back(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); - } - Ok(deque) - }) - } -} - -impl< - E, - S: Encoder, - K: Encodable + PartialEq + Ord, - V: Encodable + PartialEq -> Encodable for BTreeMap { - fn encode(&self, e: &mut S) -> Result<(), E> { - e.emit_map(self.len(), |e| { - let mut i = 0; - for (key, val) in self.iter() { - try!(e.emit_map_elt_key(i, |e| key.encode(e))); - try!(e.emit_map_elt_val(i, |e| val.encode(e))); - i += 1; - } - Ok(()) - }) - } -} - -impl< - E, - D: Decoder, - K: Decodable + PartialEq + Ord, - V: Decodable + PartialEq -> Decodable for BTreeMap { - fn decode(d: &mut D) -> Result, E> { - d.read_map(|d, len| { - let mut map = BTreeMap::new(); - for i in range(0u, len) { - let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d))); - let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d))); - map.insert(key, val); - } - Ok(map) - }) - } -} - -impl< - E, - S: Encoder, - T: Encodable + PartialEq + Ord -> Encodable for BTreeSet { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_seq(self.len(), |s| { - let mut i = 0; - for e in self.iter() { - try!(s.emit_seq_elt(i, |s| e.encode(s))); - i += 1; - } - Ok(()) - }) - } -} - -impl< - E, - D: Decoder, - T: Decodable + PartialEq + Ord -> Decodable for BTreeSet { - fn decode(d: &mut D) -> Result, E> { - d.read_seq(|d, len| { - let mut set = BTreeSet::new(); - for i in range(0u, len) { - set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); - } - Ok(set) - }) - } -} - -impl< - E, - S: Encoder, - T: Encodable + CLike -> Encodable for EnumSet { - fn encode(&self, s: &mut S) -> Result<(), E> { - let mut bits = 0; - for item in self.iter() { - bits |= item.to_uint(); - } - s.emit_uint(bits) - } -} - -impl< - E, - D: Decoder, - T: Decodable + CLike -> Decodable for EnumSet { - fn decode(d: &mut D) -> Result, E> { - let bits = try!(d.read_uint()); - let mut set = EnumSet::new(); - for bit in range(0, uint::BITS) { - if bits & (1 << bit) != 0 { - set.insert(CLike::from_uint(1 << bit)); - } - } - Ok(set) - } -} - -impl< - E, - S: Encoder, - K: Encodable + Hash + Eq, - V: Encodable, - X, - H: Hasher -> Encodable for HashMap { - fn encode(&self, e: &mut S) -> Result<(), E> { - e.emit_map(self.len(), |e| { - let mut i = 0; - for (key, val) in self.iter() { - try!(e.emit_map_elt_key(i, |e| key.encode(e))); - try!(e.emit_map_elt_val(i, |e| val.encode(e))); - i += 1; - } - Ok(()) - }) - } -} - -impl< - E, - D: Decoder, - K: Decodable + Hash + Eq, - V: Decodable, - S, - H: Hasher + Default -> Decodable for HashMap { - fn decode(d: &mut D) -> Result, E> { - d.read_map(|d, len| { - let hasher = Default::default(); - let mut map = HashMap::with_capacity_and_hasher(len, hasher); - for i in range(0u, len) { - let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d))); - let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d))); - map.insert(key, val); - } - Ok(map) - }) - } -} - -impl< - E, - S: Encoder, - T: Encodable + Hash + Eq, - X, - H: Hasher -> Encodable for HashSet { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_seq(self.len(), |s| { - let mut i = 0; - for e in self.iter() { - try!(s.emit_seq_elt(i, |s| e.encode(s))); - i += 1; - } - Ok(()) - }) - } -} - -impl< - E, - D: Decoder, - T: Decodable + Hash + Eq, - S, - H: Hasher + Default -> Decodable for HashSet { - fn decode(d: &mut D) -> Result, E> { - d.read_seq(|d, len| { - let mut set = HashSet::with_capacity_and_hasher(len, Default::default()); - for i in range(0u, len) { - set.insert(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); - } - Ok(set) - }) - } -} - -impl< - E, - S: Encoder, - V: Encodable -> Encodable for VecMap { - fn encode(&self, e: &mut S) -> Result<(), E> { - e.emit_map(self.len(), |e| { - for (i, (key, val)) in self.iter().enumerate() { - try!(e.emit_map_elt_key(i, |e| key.encode(e))); - try!(e.emit_map_elt_val(i, |e| val.encode(e))); - } - Ok(()) - }) - } -} - -impl< - E, - D: Decoder, - V: Decodable -> Decodable for VecMap { - fn decode(d: &mut D) -> Result, E> { - d.read_map(|d, len| { - let mut map = VecMap::new(); - for i in range(0u, len) { - let key = try!(d.read_map_elt_key(i, |d| Decodable::decode(d))); - let val = try!(d.read_map_elt_val(i, |d| Decodable::decode(d))); - map.insert(key, val); - } - Ok(map) - }) - } -} diff --git a/src/libserialize/json_stage0.rs b/src/libserialize/json_stage0.rs deleted file mode 100644 index 1c2855f6745..00000000000 --- a/src/libserialize/json_stage0.rs +++ /dev/null @@ -1,3864 +0,0 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// Rust JSON serialization library -// Copyright (c) 2011 Google Inc. - -#![forbid(non_camel_case_types)] -#![allow(missing_docs)] - -//! JSON parsing and serialization -//! -//! # What is JSON? -//! -//! JSON (JavaScript Object Notation) is a way to write data in Javascript. -//! Like XML, it allows to encode structured data in a text format that can be easily read by humans -//! Its simple syntax and native compatibility with JavaScript have made it a widely used format. -//! -//! Data types that can be encoded are JavaScript types (see the `Json` enum for more details): -//! -//! * `Boolean`: equivalent to rust's `bool` -//! * `Number`: equivalent to rust's `f64` -//! * `String`: equivalent to rust's `String` -//! * `Array`: equivalent to rust's `Vec`, but also allowing objects of different types in the -//! same array -//! * `Object`: equivalent to rust's `BTreeMap` -//! * `Null` -//! -//! An object is a series of string keys mapping to values, in `"key": value` format. -//! Arrays are enclosed in square brackets ([ ... ]) and objects in curly brackets ({ ... }). -//! A simple JSON document encoding a person, his/her age, address and phone numbers could look like -//! -//! ```ignore -//! { -//! "FirstName": "John", -//! "LastName": "Doe", -//! "Age": 43, -//! "Address": { -//! "Street": "Downing Street 10", -//! "City": "London", -//! "Country": "Great Britain" -//! }, -//! "PhoneNumbers": [ -//! "+44 1234567", -//! "+44 2345678" -//! ] -//! } -//! ``` -//! -//! # Rust Type-based Encoding and Decoding -//! -//! Rust provides a mechanism for low boilerplate encoding & decoding of values to and from JSON via -//! the serialization API. -//! To be able to encode a piece of data, it must implement the `serialize::RustcEncodable` trait. -//! To be able to decode a piece of data, it must implement the `serialize::RustcDecodable` trait. -//! The Rust compiler provides an annotation to automatically generate the code for these traits: -//! `#[derive(RustcDecodable, RustcEncodable)]` -//! -//! The JSON API provides an enum `json::Json` and a trait `ToJson` to encode objects. -//! The `ToJson` trait provides a `to_json` method to convert an object into a `json::Json` value. -//! A `json::Json` value can be encoded as a string or buffer using the functions described above. -//! You can also use the `json::Encoder` object, which implements the `Encoder` trait. -//! -//! When using `ToJson` the `RustcEncodable` trait implementation is not mandatory. -//! -//! # Examples of use -//! -//! ## Using Autoserialization -//! -//! Create a struct called `TestStruct` and serialize and deserialize it to and from JSON using the -//! serialization API, using the derived serialization code. -//! -//! ```notrust -//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment -//! extern crate serialize; -//! use serialize::json; -//! -//! // Automatically generate `Decodable` and `Encodable` trait implementations -//! #[derive(RustcDecodable, RustcEncodable)] -//! pub struct TestStruct { -//! data_int: u8, -//! data_str: String, -//! data_vector: Vec, -//! } -//! -//! fn main() { -//! let object = TestStruct { -//! data_int: 1, -//! data_str: "homura".to_string(), -//! data_vector: vec![2,3,4,5], -//! }; -//! -//! // Serialize using `json::encode` -//! let encoded = json::encode(&object); -//! -//! // Deserialize using `json::decode` -//! let decoded: TestStruct = json::decode(encoded.as_slice()).unwrap(); -//! } -//! ``` -//! -//! ## Using the `ToJson` trait -//! -//! The examples above use the `ToJson` trait to generate the JSON string, which is required -//! for custom mappings. -//! -//! ### Simple example of `ToJson` usage -//! -//! ```notrust -//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment -//! extern crate serialize; -//! use serialize::json::{mod, ToJson, Json}; -//! -//! // A custom data structure -//! struct ComplexNum { -//! a: f64, -//! b: f64, -//! } -//! -//! // JSON value representation -//! impl ToJson for ComplexNum { -//! fn to_json(&self) -> Json { -//! Json::String(format!("{}+{}i", self.a, self.b)) -//! } -//! } -//! -//! // Only generate `RustcEncodable` trait implementation -//! #[derive(Encodable)] -//! pub struct ComplexNumRecord { -//! uid: u8, -//! dsc: String, -//! val: Json, -//! } -//! -//! fn main() { -//! let num = ComplexNum { a: 0.0001, b: 12.539 }; -//! let data: String = json::encode(&ComplexNumRecord{ -//! uid: 1, -//! dsc: "test".to_string(), -//! val: num.to_json(), -//! }); -//! println!("data: {}", data); -//! // data: {"uid":1,"dsc":"test","val":"0.0001+12.539j"}; -//! } -//! ``` -//! -//! ### Verbose example of `ToJson` usage -//! -//! ```notrust -//! // FIXME(#19470): this cannot be ```rust``` because it fails orphan checking at the moment -//! extern crate serialize; -//! use std::collections::BTreeMap; -//! use serialize::json::{mod, Json, ToJson}; -//! -//! // Only generate `Decodable` trait implementation -//! #[derive(Decodable)] -//! pub struct TestStruct { -//! data_int: u8, -//! data_str: String, -//! data_vector: Vec, -//! } -//! -//! // Specify encoding method manually -//! impl ToJson for TestStruct { -//! fn to_json(&self) -> Json { -//! let mut d = BTreeMap::new(); -//! // All standard types implement `to_json()`, so use it -//! d.insert("data_int".to_string(), self.data_int.to_json()); -//! d.insert("data_str".to_string(), self.data_str.to_json()); -//! d.insert("data_vector".to_string(), self.data_vector.to_json()); -//! Json::Object(d) -//! } -//! } -//! -//! fn main() { -//! // Serialize using `ToJson` -//! let input_data = TestStruct { -//! data_int: 1, -//! data_str: "madoka".to_string(), -//! data_vector: vec![2,3,4,5], -//! }; -//! let json_obj: Json = input_data.to_json(); -//! let json_str: String = json_obj.to_string(); -//! -//! // Deserialize like before -//! let decoded: TestStruct = json::decode(json_str.as_slice()).unwrap(); -//! } -//! ``` - -use self::JsonEvent::*; -use self::StackElement::*; -use self::ErrorCode::*; -use self::ParserError::*; -use self::DecoderError::*; -use self::ParserState::*; -use self::InternalStackElement::*; - -use std; -use std::collections::{HashMap, BTreeMap}; -use std::{char, f64, fmt, io, num, str}; -use std::mem::{swap, transmute}; -use std::num::{Float, Int}; -use std::num::FpCategory as Fp; -use std::str::FromStr; -use std::string; -use std::ops; -use unicode::str as unicode_str; -use unicode::str::Utf16Item; -use std::ops::Index as IndexOp; - -use Encodable; - -/// Represents a json value -#[derive(Clone, PartialEq, PartialOrd)] -pub enum Json { - I64(i64), - U64(u64), - F64(f64), - String(string::String), - Boolean(bool), - Array(self::Array), - Object(self::Object), - Null, -} - -pub type Array = Vec; -pub type Object = BTreeMap; - -pub struct PrettyJson<'a> { inner: &'a Json } - -pub struct AsJson<'a, T: 'a> { inner: &'a T } -pub struct AsPrettyJson<'a, T: 'a> { inner: &'a T, indent: Option } - -/// The errors that can arise while parsing a JSON stream. -#[derive(Clone, Copy, PartialEq)] -pub enum ErrorCode { - InvalidSyntax, - InvalidNumber, - EOFWhileParsingObject, - EOFWhileParsingArray, - EOFWhileParsingValue, - EOFWhileParsingString, - KeyMustBeAString, - ExpectedColon, - TrailingCharacters, - TrailingComma, - InvalidEscape, - InvalidUnicodeCodePoint, - LoneLeadingSurrogateInHexEscape, - UnexpectedEndOfHexEscape, - UnrecognizedHex, - NotFourDigit, - NotUtf8, -} - -#[derive(Clone, Copy, PartialEq, Show)] -pub enum ParserError { - /// msg, line, col - SyntaxError(ErrorCode, uint, uint), - IoError(io::IoErrorKind, &'static str), -} - -// Builder and Parser have the same errors. -pub type BuilderError = ParserError; - -#[derive(Clone, PartialEq, Show)] -pub enum DecoderError { - ParseError(ParserError), - ExpectedError(string::String, string::String), - MissingFieldError(string::String), - UnknownVariantError(string::String), - ApplicationError(string::String) -} - -/// Returns a readable error string for a given error code. -pub fn error_str(error: ErrorCode) -> &'static str { - match error { - InvalidSyntax => "invalid syntax", - InvalidNumber => "invalid number", - EOFWhileParsingObject => "EOF While parsing object", - EOFWhileParsingArray => "EOF While parsing array", - EOFWhileParsingValue => "EOF While parsing value", - EOFWhileParsingString => "EOF While parsing string", - KeyMustBeAString => "key must be a string", - ExpectedColon => "expected `:`", - TrailingCharacters => "trailing characters", - TrailingComma => "trailing comma", - InvalidEscape => "invalid escape", - UnrecognizedHex => "invalid \\u{ esc}ape (unrecognized hex)", - NotFourDigit => "invalid \\u{ esc}ape (not four digits)", - NotUtf8 => "contents not utf-8", - InvalidUnicodeCodePoint => "invalid Unicode code point", - LoneLeadingSurrogateInHexEscape => "lone leading surrogate in hex escape", - UnexpectedEndOfHexEscape => "unexpected end of hex escape", - } -} - -/// Shortcut function to decode a JSON `&str` into an object -pub fn decode>(s: &str) -> DecodeResult { - let json = match from_str(s) { - Ok(x) => x, - Err(e) => return Err(ParseError(e)) - }; - - let mut decoder = Decoder::new(json); - ::Decodable::decode(&mut decoder) -} - -/// Shortcut function to encode a `T` into a JSON `String` -pub fn encode(object: &T) -> string::String - where T: for<'a> Encodable, fmt::Error> -{ - let mut s = String::new(); - { - let mut encoder = Encoder::new(&mut s); - let _ = object.encode(&mut encoder); - } - s -} - -impl fmt::Show for ErrorCode { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - error_str(*self).fmt(f) - } -} - -fn io_error_to_error(io: io::IoError) -> ParserError { - IoError(io.kind, io.desc) -} - -impl std::error::Error for DecoderError { - fn description(&self) -> &str { "decoder error" } - fn detail(&self) -> Option { Some(self.to_string()) } -} - -pub type EncodeResult = fmt::Result; -pub type DecodeResult = Result; - -fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { - try!(wr.write_str("\"")); - - let mut start = 0; - - for (i, byte) in v.bytes().enumerate() { - let escaped = match byte { - b'"' => "\\\"", - b'\\' => "\\\\", - b'\x00' => "\\u0000", - b'\x01' => "\\u0001", - b'\x02' => "\\u0002", - b'\x03' => "\\u0003", - b'\x04' => "\\u0004", - b'\x05' => "\\u0005", - b'\x06' => "\\u0006", - b'\x07' => "\\u0007", - b'\x08' => "\\b", - b'\t' => "\\t", - b'\n' => "\\n", - b'\x0b' => "\\u000b", - b'\x0c' => "\\f", - b'\r' => "\\r", - b'\x0e' => "\\u000e", - b'\x0f' => "\\u000f", - b'\x10' => "\\u0010", - b'\x11' => "\\u0011", - b'\x12' => "\\u0012", - b'\x13' => "\\u0013", - b'\x14' => "\\u0014", - b'\x15' => "\\u0015", - b'\x16' => "\\u0016", - b'\x17' => "\\u0017", - b'\x18' => "\\u0018", - b'\x19' => "\\u0019", - b'\x1a' => "\\u001a", - b'\x1b' => "\\u001b", - b'\x1c' => "\\u001c", - b'\x1d' => "\\u001d", - b'\x1e' => "\\u001e", - b'\x1f' => "\\u001f", - b'\x7f' => "\\u007f", - _ => { continue; } - }; - - if start < i { - try!(wr.write_str(v.index(&(start..i)))); - } - - try!(wr.write_str(escaped)); - - start = i + 1; - } - - if start != v.len() { - try!(wr.write_str(v.index(&(start..)))); - } - - wr.write_str("\"") -} - -fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result { - let mut buf = [0; 4]; - let n = v.encode_utf8(&mut buf).unwrap(); - let buf = unsafe { str::from_utf8_unchecked(buf.index(&(0..n))) }; - escape_str(writer, buf) -} - -fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result { - const BUF: &'static str = " "; - - while n >= BUF.len() { - try!(wr.write_str(BUF)); - n -= BUF.len(); - } - - if n > 0 { - wr.write_str(BUF.index(&(..n))) - } else { - Ok(()) - } -} - -fn fmt_number_or_null(v: f64) -> string::String { - match v.classify() { - Fp::Nan | Fp::Infinite => string::String::from_str("null"), - _ if v.fract() != 0f64 => f64::to_str_digits(v, 6u), - _ => f64::to_str_digits(v, 6u) + ".0", - } -} - -/// A structure for implementing serialization to JSON. -pub struct Encoder<'a> { - writer: &'a mut (fmt::Writer+'a), -} - -impl<'a> Encoder<'a> { - /// Creates a new JSON encoder whose output will be written to the writer - /// specified. - pub fn new(writer: &'a mut fmt::Writer) -> Encoder<'a> { - Encoder { writer: writer } - } -} - -impl<'a> ::Encoder for Encoder<'a> { - fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") } - - fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) } - - fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) } - - fn emit_bool(&mut self, v: bool) -> EncodeResult { - if v { - write!(self.writer, "true") - } else { - write!(self.writer, "false") - } - } - - fn emit_f64(&mut self, v: f64) -> EncodeResult { - write!(self.writer, "{}", fmt_number_or_null(v)) - } - fn emit_f32(&mut self, v: f32) -> EncodeResult { - self.emit_f64(v as f64) - } - - fn emit_char(&mut self, v: char) -> EncodeResult { - escape_char(self.writer, v) - } - fn emit_str(&mut self, v: &str) -> EncodeResult { - escape_str(self.writer, v) - } - - fn emit_enum(&mut self, _name: &str, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - f(self) - } - - fn emit_enum_variant(&mut self, - name: &str, - _id: uint, - cnt: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - // enums are encoded as strings or objects - // Bunny => "Bunny" - // Kangaroo(34,"William") => {"variant": "Kangaroo", "fields": [34,"William"]} - if cnt == 0 { - escape_str(self.writer, name) - } else { - try!(write!(self.writer, "{{\"variant\":")); - try!(escape_str(self.writer, name)); - try!(write!(self.writer, ",\"fields\":[")); - try!(f(self)); - write!(self.writer, "]}}") - } - } - - fn emit_enum_variant_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - if idx != 0 { - try!(write!(self.writer, ",")); - } - f(self) - } - - fn emit_enum_struct_variant(&mut self, - name: &str, - id: uint, - cnt: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - self.emit_enum_variant(name, id, cnt, f) - } - - fn emit_enum_struct_variant_field(&mut self, - _: &str, - idx: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - self.emit_enum_variant_arg(idx, f) - } - - fn emit_struct(&mut self, _: &str, _: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - try!(write!(self.writer, "{{")); - try!(f(self)); - write!(self.writer, "}}") - } - - fn emit_struct_field(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - if idx != 0 { try!(write!(self.writer, ",")); } - try!(escape_str(self.writer, name)); - try!(write!(self.writer, ":")); - f(self) - } - - fn emit_tuple(&mut self, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - self.emit_seq(len, f) - } - fn emit_tuple_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - self.emit_seq_elt(idx, f) - } - - fn emit_tuple_struct(&mut self, _name: &str, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - self.emit_seq(len, f) - } - fn emit_tuple_struct_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - self.emit_seq_elt(idx, f) - } - - fn emit_option(&mut self, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - f(self) - } - fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() } - fn emit_option_some(&mut self, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - f(self) - } - - fn emit_seq(&mut self, _len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - try!(write!(self.writer, "[")); - try!(f(self)); - write!(self.writer, "]") - } - - fn emit_seq_elt(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - if idx != 0 { - try!(write!(self.writer, ",")); - } - f(self) - } - - fn emit_map(&mut self, _len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - try!(write!(self.writer, "{{")); - try!(f(self)); - write!(self.writer, "}}") - } - - fn emit_map_elt_key(&mut self, idx: uint, mut f: F) -> EncodeResult where - F: FnMut(&mut Encoder<'a>) -> EncodeResult, - { - if idx != 0 { try!(write!(self.writer, ",")) } - // ref #12967, make sure to wrap a key in double quotes, - // in the event that its of a type that omits them (eg numbers) - let mut buf = Vec::new(); - // FIXME(14302) remove the transmute and unsafe block. - unsafe { - let mut check_encoder = Encoder::new(&mut buf); - try!(f(transmute(&mut check_encoder))); - } - let out = str::from_utf8(buf.index(&FullRange)).unwrap(); - let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; - if needs_wrapping { try!(write!(self.writer, "\"")); } - try!(f(self)); - if needs_wrapping { try!(write!(self.writer, "\"")); } - Ok(()) - } - - fn emit_map_elt_val(&mut self, _idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut Encoder<'a>) -> EncodeResult, - { - try!(write!(self.writer, ":")); - f(self) - } -} - -/// Another encoder for JSON, but prints out human-readable JSON instead of -/// compact data -pub struct PrettyEncoder<'a> { - writer: &'a mut (fmt::Writer+'a), - curr_indent: uint, - indent: uint, -} - -impl<'a> PrettyEncoder<'a> { - /// Creates a new encoder whose output will be written to the specified writer - pub fn new(writer: &'a mut fmt::Writer) -> PrettyEncoder<'a> { - PrettyEncoder { writer: writer, curr_indent: 0, indent: 2, } - } - - /// Set the number of spaces to indent for each level. - /// This is safe to set during encoding. - pub fn set_indent(&mut self, indent: uint) { - // self.indent very well could be 0 so we need to use checked division. - let level = self.curr_indent.checked_div(self.indent).unwrap_or(0); - self.indent = indent; - self.curr_indent = level * self.indent; - } -} - -impl<'a> ::Encoder for PrettyEncoder<'a> { - fn emit_nil(&mut self) -> EncodeResult { write!(self.writer, "null") } - - fn emit_uint(&mut self, v: uint) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u64(&mut self, v: u64) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u32(&mut self, v: u32) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u16(&mut self, v: u16) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_u8(&mut self, v: u8) -> EncodeResult { write!(self.writer, "{}", v) } - - fn emit_int(&mut self, v: int) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i64(&mut self, v: i64) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i32(&mut self, v: i32) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i16(&mut self, v: i16) -> EncodeResult { write!(self.writer, "{}", v) } - fn emit_i8(&mut self, v: i8) -> EncodeResult { write!(self.writer, "{}", v) } - - fn emit_bool(&mut self, v: bool) -> EncodeResult { - if v { - write!(self.writer, "true") - } else { - write!(self.writer, "false") - } - } - - fn emit_f64(&mut self, v: f64) -> EncodeResult { - write!(self.writer, "{}", fmt_number_or_null(v)) - } - fn emit_f32(&mut self, v: f32) -> EncodeResult { - self.emit_f64(v as f64) - } - - fn emit_char(&mut self, v: char) -> EncodeResult { - escape_char(self.writer, v) - } - fn emit_str(&mut self, v: &str) -> EncodeResult { - escape_str(self.writer, v) - } - - fn emit_enum(&mut self, _name: &str, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - f(self) - } - - fn emit_enum_variant(&mut self, - name: &str, - _id: uint, - cnt: uint, - f: F) - -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if cnt == 0 { - escape_str(self.writer, name) - } else { - try!(write!(self.writer, "{{\n")); - self.curr_indent += self.indent; - try!(spaces(self.writer, self.curr_indent)); - try!(write!(self.writer, "\"variant\": ")); - try!(escape_str(self.writer, name)); - try!(write!(self.writer, ",\n")); - try!(spaces(self.writer, self.curr_indent)); - try!(write!(self.writer, "\"fields\": [\n")); - self.curr_indent += self.indent; - try!(f(self)); - self.curr_indent -= self.indent; - try!(write!(self.writer, "\n")); - try!(spaces(self.writer, self.curr_indent)); - self.curr_indent -= self.indent; - try!(write!(self.writer, "]\n")); - try!(spaces(self.writer, self.curr_indent)); - write!(self.writer, "}}") - } - } - - fn emit_enum_variant_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if idx != 0 { - try!(write!(self.writer, ",\n")); - } - try!(spaces(self.writer, self.curr_indent)); - f(self) - } - - fn emit_enum_struct_variant(&mut self, - name: &str, - id: uint, - cnt: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - self.emit_enum_variant(name, id, cnt, f) - } - - fn emit_enum_struct_variant_field(&mut self, - _: &str, - idx: uint, - f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - self.emit_enum_variant_arg(idx, f) - } - - - fn emit_struct(&mut self, _: &str, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if len == 0 { - write!(self.writer, "{{}}") - } else { - try!(write!(self.writer, "{{")); - self.curr_indent += self.indent; - try!(f(self)); - self.curr_indent -= self.indent; - try!(write!(self.writer, "\n")); - try!(spaces(self.writer, self.curr_indent)); - write!(self.writer, "}}") - } - } - - fn emit_struct_field(&mut self, name: &str, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if idx == 0 { - try!(write!(self.writer, "\n")); - } else { - try!(write!(self.writer, ",\n")); - } - try!(spaces(self.writer, self.curr_indent)); - try!(escape_str(self.writer, name)); - try!(write!(self.writer, ": ")); - f(self) - } - - fn emit_tuple(&mut self, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - self.emit_seq(len, f) - } - fn emit_tuple_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - self.emit_seq_elt(idx, f) - } - - fn emit_tuple_struct(&mut self, _: &str, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - self.emit_seq(len, f) - } - fn emit_tuple_struct_arg(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - self.emit_seq_elt(idx, f) - } - - fn emit_option(&mut self, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - f(self) - } - fn emit_option_none(&mut self) -> EncodeResult { self.emit_nil() } - fn emit_option_some(&mut self, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - f(self) - } - - fn emit_seq(&mut self, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if len == 0 { - write!(self.writer, "[]") - } else { - try!(write!(self.writer, "[")); - self.curr_indent += self.indent; - try!(f(self)); - self.curr_indent -= self.indent; - try!(write!(self.writer, "\n")); - try!(spaces(self.writer, self.curr_indent)); - write!(self.writer, "]") - } - } - - fn emit_seq_elt(&mut self, idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if idx == 0 { - try!(write!(self.writer, "\n")); - } else { - try!(write!(self.writer, ",\n")); - } - try!(spaces(self.writer, self.curr_indent)); - f(self) - } - - fn emit_map(&mut self, len: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if len == 0 { - write!(self.writer, "{{}}") - } else { - try!(write!(self.writer, "{{")); - self.curr_indent += self.indent; - try!(f(self)); - self.curr_indent -= self.indent; - try!(write!(self.writer, "\n")); - try!(spaces(self.writer, self.curr_indent)); - write!(self.writer, "}}") - } - } - - fn emit_map_elt_key(&mut self, idx: uint, mut f: F) -> EncodeResult where - F: FnMut(&mut PrettyEncoder<'a>) -> EncodeResult, - { - if idx == 0 { - try!(write!(self.writer, "\n")); - } else { - try!(write!(self.writer, ",\n")); - } - try!(spaces(self.writer, self.curr_indent)); - // ref #12967, make sure to wrap a key in double quotes, - // in the event that its of a type that omits them (eg numbers) - let mut buf = Vec::new(); - // FIXME(14302) remove the transmute and unsafe block. - unsafe { - let mut check_encoder = PrettyEncoder::new(&mut buf); - try!(f(transmute(&mut check_encoder))); - } - let out = str::from_utf8(buf.index(&FullRange)).unwrap(); - let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; - if needs_wrapping { try!(write!(self.writer, "\"")); } - try!(f(self)); - if needs_wrapping { try!(write!(self.writer, "\"")); } - Ok(()) - } - - fn emit_map_elt_val(&mut self, _idx: uint, f: F) -> EncodeResult where - F: FnOnce(&mut PrettyEncoder<'a>) -> EncodeResult, - { - try!(write!(self.writer, ": ")); - f(self) - } -} - -impl, S> Encodable for Json { - fn encode(&self, e: &mut E) -> Result<(), S> { - match *self { - Json::I64(v) => v.encode(e), - Json::U64(v) => v.encode(e), - Json::F64(v) => v.encode(e), - Json::String(ref v) => v.encode(e), - Json::Boolean(v) => v.encode(e), - Json::Array(ref v) => v.encode(e), - Json::Object(ref v) => v.encode(e), - Json::Null => e.emit_nil(), - } - } -} - -/// Create an `AsJson` wrapper which can be used to print a value as JSON -/// on-the-fly via `write!` -pub fn as_json(t: &T) -> AsJson { - AsJson { inner: t } -} - -/// Create an `AsPrettyJson` wrapper which can be used to print a value as JSON -/// on-the-fly via `write!` -pub fn as_pretty_json(t: &T) -> AsPrettyJson { - AsPrettyJson { inner: t, indent: None } -} - -impl Json { - /// Borrow this json object as a pretty object to generate a pretty - /// representation for it via `Show`. - pub fn pretty(&self) -> PrettyJson { - PrettyJson { inner: self } - } - - /// If the Json value is an Object, returns the value associated with the provided key. - /// Otherwise, returns None. - pub fn find<'a>(&'a self, key: &str) -> Option<&'a Json>{ - match self { - &Json::Object(ref map) => map.get(key), - _ => None - } - } - - /// Attempts to get a nested Json Object for each key in `keys`. - /// If any key is found not to exist, find_path will return None. - /// Otherwise, it will return the Json value associated with the final key. - pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{ - let mut target = self; - for key in keys.iter() { - match target.find(*key) { - Some(t) => { target = t; }, - None => return None - } - } - Some(target) - } - - /// If the Json value is an Object, performs a depth-first search until - /// a value associated with the provided key is found. If no value is found - /// or the Json value is not an Object, returns None. - pub fn search<'a>(&'a self, key: &str) -> Option<&'a Json> { - match self { - &Json::Object(ref map) => { - match map.get(key) { - Some(json_value) => Some(json_value), - None => { - for (_, v) in map.iter() { - match v.search(key) { - x if x.is_some() => return x, - _ => () - } - } - None - } - } - }, - _ => None - } - } - - /// Returns true if the Json value is an Object. Returns false otherwise. - pub fn is_object<'a>(&'a self) -> bool { - self.as_object().is_some() - } - - /// If the Json value is an Object, returns the associated BTreeMap. - /// Returns None otherwise. - pub fn as_object<'a>(&'a self) -> Option<&'a Object> { - match self { - &Json::Object(ref map) => Some(map), - _ => None - } - } - - /// Returns true if the Json value is an Array. Returns false otherwise. - pub fn is_array<'a>(&'a self) -> bool { - self.as_array().is_some() - } - - /// If the Json value is an Array, returns the associated vector. - /// Returns None otherwise. - pub fn as_array<'a>(&'a self) -> Option<&'a Array> { - match self { - &Json::Array(ref array) => Some(&*array), - _ => None - } - } - - /// Returns true if the Json value is a String. Returns false otherwise. - pub fn is_string<'a>(&'a self) -> bool { - self.as_string().is_some() - } - - /// If the Json value is a String, returns the associated str. - /// Returns None otherwise. - pub fn as_string<'a>(&'a self) -> Option<&'a str> { - match *self { - Json::String(ref s) => Some(s.index(&FullRange)), - _ => None - } - } - - /// Returns true if the Json value is a Number. Returns false otherwise. - pub fn is_number(&self) -> bool { - match *self { - Json::I64(_) | Json::U64(_) | Json::F64(_) => true, - _ => false, - } - } - - /// Returns true if the Json value is a i64. Returns false otherwise. - pub fn is_i64(&self) -> bool { - match *self { - Json::I64(_) => true, - _ => false, - } - } - - /// Returns true if the Json value is a u64. Returns false otherwise. - pub fn is_u64(&self) -> bool { - match *self { - Json::U64(_) => true, - _ => false, - } - } - - /// Returns true if the Json value is a f64. Returns false otherwise. - pub fn is_f64(&self) -> bool { - match *self { - Json::F64(_) => true, - _ => false, - } - } - - /// If the Json value is a number, return or cast it to a i64. - /// Returns None otherwise. - pub fn as_i64(&self) -> Option { - match *self { - Json::I64(n) => Some(n), - Json::U64(n) => num::cast(n), - _ => None - } - } - - /// If the Json value is a number, return or cast it to a u64. - /// Returns None otherwise. - pub fn as_u64(&self) -> Option { - match *self { - Json::I64(n) => num::cast(n), - Json::U64(n) => Some(n), - _ => None - } - } - - /// If the Json value is a number, return or cast it to a f64. - /// Returns None otherwise. - pub fn as_f64(&self) -> Option { - match *self { - Json::I64(n) => num::cast(n), - Json::U64(n) => num::cast(n), - Json::F64(n) => Some(n), - _ => None - } - } - - /// Returns true if the Json value is a Boolean. Returns false otherwise. - pub fn is_boolean(&self) -> bool { - self.as_boolean().is_some() - } - - /// If the Json value is a Boolean, returns the associated bool. - /// Returns None otherwise. - pub fn as_boolean(&self) -> Option { - match self { - &Json::Boolean(b) => Some(b), - _ => None - } - } - - /// Returns true if the Json value is a Null. Returns false otherwise. - pub fn is_null(&self) -> bool { - self.as_null().is_some() - } - - /// If the Json value is a Null, returns (). - /// Returns None otherwise. - pub fn as_null(&self) -> Option<()> { - match self { - &Json::Null => Some(()), - _ => None - } - } -} - -impl<'a> ops::Index<&'a str> for Json { - type Output = Json; - - fn index(&self, idx: & &str) -> &Json { - self.find(*idx).unwrap() - } -} - -impl ops::Index for Json { - type Output = Json; - - fn index<'a>(&'a self, idx: &uint) -> &'a Json { - match self { - &Json::Array(ref v) => v.index(idx), - _ => panic!("can only index Json with uint if it is an array") - } - } -} - -/// The output of the streaming parser. -#[derive(PartialEq, Clone, Show)] -pub enum JsonEvent { - ObjectStart, - ObjectEnd, - ArrayStart, - ArrayEnd, - BooleanValue(bool), - I64Value(i64), - U64Value(u64), - F64Value(f64), - StringValue(string::String), - NullValue, - Error(ParserError), -} - -#[derive(PartialEq, Show)] -enum ParserState { - // Parse a value in an array, true means first element. - ParseArray(bool), - // Parse ',' or ']' after an element in an array. - ParseArrayComma, - // Parse a key:value in an object, true means first element. - ParseObject(bool), - // Parse ',' or ']' after an element in an object. - ParseObjectComma, - // Initial state. - ParseStart, - // Expecting the stream to end. - ParseBeforeFinish, - // Parsing can't continue. - ParseFinished, -} - -/// A Stack represents the current position of the parser in the logical -/// structure of the JSON stream. -/// For example foo.bar[3].x -pub struct Stack { - stack: Vec, - str_buffer: Vec, -} - -/// StackElements compose a Stack. -/// For example, Key("foo"), Key("bar"), Index(3) and Key("x") are the -/// StackElements compositing the stack that represents foo.bar[3].x -#[derive(PartialEq, Clone, Show)] -pub enum StackElement<'l> { - Index(u32), - Key(&'l str), -} - -// Internally, Key elements are stored as indices in a buffer to avoid -// allocating a string for every member of an object. -#[derive(PartialEq, Clone, Show)] -enum InternalStackElement { - InternalIndex(u32), - InternalKey(u16, u16), // start, size -} - -impl Stack { - pub fn new() -> Stack { - Stack { stack: Vec::new(), str_buffer: Vec::new() } - } - - /// Returns The number of elements in the Stack. - pub fn len(&self) -> uint { self.stack.len() } - - /// Returns true if the stack is empty. - pub fn is_empty(&self) -> bool { self.stack.is_empty() } - - /// Provides access to the StackElement at a given index. - /// lower indices are at the bottom of the stack while higher indices are - /// at the top. - pub fn get<'l>(&'l self, idx: uint) -> StackElement<'l> { - match self.stack[idx] { - InternalIndex(i) => Index(i), - InternalKey(start, size) => { - Key(str::from_utf8( - self.str_buffer.index( - &((start as uint) .. (start as uint + size as uint)))).unwrap()) - } - } - } - - /// Compares this stack with an array of StackElements. - pub fn is_equal_to(&self, rhs: &[StackElement]) -> bool { - if self.stack.len() != rhs.len() { return false; } - for i in range(0, rhs.len()) { - if self.get(i) != rhs[i] { return false; } - } - return true; - } - - /// Returns true if the bottom-most elements of this stack are the same as - /// the ones passed as parameter. - pub fn starts_with(&self, rhs: &[StackElement]) -> bool { - if self.stack.len() < rhs.len() { return false; } - for i in range(0, rhs.len()) { - if self.get(i) != rhs[i] { return false; } - } - return true; - } - - /// Returns true if the top-most elements of this stack are the same as - /// the ones passed as parameter. - pub fn ends_with(&self, rhs: &[StackElement]) -> bool { - if self.stack.len() < rhs.len() { return false; } - let offset = self.stack.len() - rhs.len(); - for i in range(0, rhs.len()) { - if self.get(i + offset) != rhs[i] { return false; } - } - return true; - } - - /// Returns the top-most element (if any). - pub fn top<'l>(&'l self) -> Option> { - return match self.stack.last() { - None => None, - Some(&InternalIndex(i)) => Some(Index(i)), - Some(&InternalKey(start, size)) => { - Some(Key(str::from_utf8( - self.str_buffer.index(&(start as uint) .. ((start+size) as uint)) - ).unwrap())) - } - } - } - - // Used by Parser to insert Key elements at the top of the stack. - fn push_key(&mut self, key: string::String) { - self.stack.push(InternalKey(self.str_buffer.len() as u16, key.len() as u16)); - for c in key.as_bytes().iter() { - self.str_buffer.push(*c); - } - } - - // Used by Parser to insert Index elements at the top of the stack. - fn push_index(&mut self, index: u32) { - self.stack.push(InternalIndex(index)); - } - - // Used by Parser to remove the top-most element of the stack. - fn pop(&mut self) { - assert!(!self.is_empty()); - match *self.stack.last().unwrap() { - InternalKey(_, sz) => { - let new_size = self.str_buffer.len() - sz as uint; - self.str_buffer.truncate(new_size); - } - InternalIndex(_) => {} - } - self.stack.pop(); - } - - // Used by Parser to test whether the top-most element is an index. - fn last_is_index(&self) -> bool { - if self.is_empty() { return false; } - return match *self.stack.last().unwrap() { - InternalIndex(_) => true, - _ => false, - } - } - - // Used by Parser to increment the index of the top-most element. - fn bump_index(&mut self) { - let len = self.stack.len(); - let idx = match *self.stack.last().unwrap() { - InternalIndex(i) => { i + 1 } - _ => { panic!(); } - }; - self.stack[len - 1] = InternalIndex(idx); - } -} - -/// A streaming JSON parser implemented as an iterator of JsonEvent, consuming -/// an iterator of char. -pub struct Parser { - rdr: T, - ch: Option, - line: uint, - col: uint, - // We maintain a stack representing where we are in the logical structure - // of the JSON stream. - stack: Stack, - // A state machine is kept to make it possible to interrupt and resume parsing. - state: ParserState, -} - -impl> Iterator for Parser { - type Item = JsonEvent; - - fn next(&mut self) -> Option { - if self.state == ParseFinished { - return None; - } - - if self.state == ParseBeforeFinish { - self.parse_whitespace(); - // Make sure there is no trailing characters. - if self.eof() { - self.state = ParseFinished; - return None; - } else { - return Some(self.error_event(TrailingCharacters)); - } - } - - return Some(self.parse()); - } -} - -impl> Parser { - /// Creates the JSON parser. - pub fn new(rdr: T) -> Parser { - let mut p = Parser { - rdr: rdr, - ch: Some('\x00'), - line: 1, - col: 0, - stack: Stack::new(), - state: ParseStart, - }; - p.bump(); - return p; - } - - /// Provides access to the current position in the logical structure of the - /// JSON stream. - pub fn stack<'l>(&'l self) -> &'l Stack { - return &self.stack; - } - - fn eof(&self) -> bool { self.ch.is_none() } - fn ch_or_null(&self) -> char { self.ch.unwrap_or('\x00') } - fn bump(&mut self) { - self.ch = self.rdr.next(); - - if self.ch_is('\n') { - self.line += 1u; - self.col = 1u; - } else { - self.col += 1u; - } - } - - fn next_char(&mut self) -> Option { - self.bump(); - self.ch - } - fn ch_is(&self, c: char) -> bool { - self.ch == Some(c) - } - - fn error(&self, reason: ErrorCode) -> Result { - Err(SyntaxError(reason, self.line, self.col)) - } - - fn parse_whitespace(&mut self) { - while self.ch_is(' ') || - self.ch_is('\n') || - self.ch_is('\t') || - self.ch_is('\r') { self.bump(); } - } - - fn parse_number(&mut self) -> JsonEvent { - let mut neg = false; - - if self.ch_is('-') { - self.bump(); - neg = true; - } - - let res = match self.parse_u64() { - Ok(res) => res, - Err(e) => { return Error(e); } - }; - - if self.ch_is('.') || self.ch_is('e') || self.ch_is('E') { - let mut res = res as f64; - - if self.ch_is('.') { - res = match self.parse_decimal(res) { - Ok(res) => res, - Err(e) => { return Error(e); } - }; - } - - if self.ch_is('e') || self.ch_is('E') { - res = match self.parse_exponent(res) { - Ok(res) => res, - Err(e) => { return Error(e); } - }; - } - - if neg { - res *= -1.0; - } - - F64Value(res) - } else { - if neg { - let res = -(res as i64); - - // Make sure we didn't underflow. - if res > 0 { - Error(SyntaxError(InvalidNumber, self.line, self.col)) - } else { - I64Value(res) - } - } else { - U64Value(res) - } - } - } - - fn parse_u64(&mut self) -> Result { - let mut accum = 0; - let last_accum = 0; // necessary to detect overflow. - - match self.ch_or_null() { - '0' => { - self.bump(); - - // A leading '0' must be the only digit before the decimal point. - match self.ch_or_null() { - '0' ... '9' => return self.error(InvalidNumber), - _ => () - } - }, - '1' ... '9' => { - while !self.eof() { - match self.ch_or_null() { - c @ '0' ... '9' => { - accum *= 10; - accum += (c as u64) - ('0' as u64); - - // Detect overflow by comparing to the last value. - if accum <= last_accum { return self.error(InvalidNumber); } - - self.bump(); - } - _ => break, - } - } - } - _ => return self.error(InvalidNumber), - } - - Ok(accum) - } - - fn parse_decimal(&mut self, mut res: f64) -> Result { - self.bump(); - - // Make sure a digit follows the decimal place. - match self.ch_or_null() { - '0' ... '9' => (), - _ => return self.error(InvalidNumber) - } - - let mut dec = 1.0; - while !self.eof() { - match self.ch_or_null() { - c @ '0' ... '9' => { - dec /= 10.0; - res += (((c as int) - ('0' as int)) as f64) * dec; - self.bump(); - } - _ => break, - } - } - - Ok(res) - } - - fn parse_exponent(&mut self, mut res: f64) -> Result { - self.bump(); - - let mut exp = 0u; - let mut neg_exp = false; - - if self.ch_is('+') { - self.bump(); - } else if self.ch_is('-') { - self.bump(); - neg_exp = true; - } - - // Make sure a digit follows the exponent place. - match self.ch_or_null() { - '0' ... '9' => (), - _ => return self.error(InvalidNumber) - } - while !self.eof() { - match self.ch_or_null() { - c @ '0' ... '9' => { - exp *= 10; - exp += (c as uint) - ('0' as uint); - - self.bump(); - } - _ => break - } - } - - let exp = 10_f64.powi(exp as i32); - if neg_exp { - res /= exp; - } else { - res *= exp; - } - - Ok(res) - } - - fn decode_hex_escape(&mut self) -> Result { - let mut i = 0u; - let mut n = 0u16; - while i < 4 && !self.eof() { - self.bump(); - n = match self.ch_or_null() { - c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)), - 'a' | 'A' => n * 16 + 10, - 'b' | 'B' => n * 16 + 11, - 'c' | 'C' => n * 16 + 12, - 'd' | 'D' => n * 16 + 13, - 'e' | 'E' => n * 16 + 14, - 'f' | 'F' => n * 16 + 15, - _ => return self.error(InvalidEscape) - }; - - i += 1u; - } - - // Error out if we didn't parse 4 digits. - if i != 4 { - return self.error(InvalidEscape); - } - - Ok(n) - } - - fn parse_str(&mut self) -> Result { - let mut escape = false; - let mut res = string::String::new(); - - loop { - self.bump(); - if self.eof() { - return self.error(EOFWhileParsingString); - } - - if escape { - match self.ch_or_null() { - '"' => res.push('"'), - '\\' => res.push('\\'), - '/' => res.push('/'), - 'b' => res.push('\x08'), - 'f' => res.push('\x0c'), - 'n' => res.push('\n'), - 'r' => res.push('\r'), - 't' => res.push('\t'), - 'u' => match try!(self.decode_hex_escape()) { - 0xDC00 ... 0xDFFF => { - return self.error(LoneLeadingSurrogateInHexEscape) - } - - // Non-BMP characters are encoded as a sequence of - // two hex escapes, representing UTF-16 surrogates. - n1 @ 0xD800 ... 0xDBFF => { - match (self.next_char(), self.next_char()) { - (Some('\\'), Some('u')) => (), - _ => return self.error(UnexpectedEndOfHexEscape), - } - - let buf = [n1, try!(self.decode_hex_escape())]; - match unicode_str::utf16_items(&buf).next() { - Some(Utf16Item::ScalarValue(c)) => res.push(c), - _ => return self.error(LoneLeadingSurrogateInHexEscape), - } - } - - n => match char::from_u32(n as u32) { - Some(c) => res.push(c), - None => return self.error(InvalidUnicodeCodePoint), - }, - }, - _ => return self.error(InvalidEscape), - } - escape = false; - } else if self.ch_is('\\') { - escape = true; - } else { - match self.ch { - Some('"') => { - self.bump(); - return Ok(res); - }, - Some(c) => res.push(c), - None => unreachable!() - } - } - } - } - - // Invoked at each iteration, consumes the stream until it has enough - // information to return a JsonEvent. - // Manages an internal state so that parsing can be interrupted and resumed. - // Also keeps track of the position in the logical structure of the json - // stream int the form of a stack that can be queried by the user using the - // stack() method. - fn parse(&mut self) -> JsonEvent { - loop { - // The only paths where the loop can spin a new iteration - // are in the cases ParseArrayComma and ParseObjectComma if ',' - // is parsed. In these cases the state is set to (respectively) - // ParseArray(false) and ParseObject(false), which always return, - // so there is no risk of getting stuck in an infinite loop. - // All other paths return before the end of the loop's iteration. - self.parse_whitespace(); - - match self.state { - ParseStart => { - return self.parse_start(); - } - ParseArray(first) => { - return self.parse_array(first); - } - ParseArrayComma => { - match self.parse_array_comma_or_end() { - Some(evt) => { return evt; } - None => {} - } - } - ParseObject(first) => { - return self.parse_object(first); - } - ParseObjectComma => { - self.stack.pop(); - if self.ch_is(',') { - self.state = ParseObject(false); - self.bump(); - } else { - return self.parse_object_end(); - } - } - _ => { - return self.error_event(InvalidSyntax); - } - } - } - } - - fn parse_start(&mut self) -> JsonEvent { - let val = self.parse_value(); - self.state = match val { - Error(_) => ParseFinished, - ArrayStart => ParseArray(true), - ObjectStart => ParseObject(true), - _ => ParseBeforeFinish, - }; - return val; - } - - fn parse_array(&mut self, first: bool) -> JsonEvent { - if self.ch_is(']') { - if !first { - self.error_event(InvalidSyntax) - } else { - self.state = if self.stack.is_empty() { - ParseBeforeFinish - } else if self.stack.last_is_index() { - ParseArrayComma - } else { - ParseObjectComma - }; - self.bump(); - ArrayEnd - } - } else { - if first { - self.stack.push_index(0); - } - let val = self.parse_value(); - self.state = match val { - Error(_) => ParseFinished, - ArrayStart => ParseArray(true), - ObjectStart => ParseObject(true), - _ => ParseArrayComma, - }; - val - } - } - - fn parse_array_comma_or_end(&mut self) -> Option { - if self.ch_is(',') { - self.stack.bump_index(); - self.state = ParseArray(false); - self.bump(); - None - } else if self.ch_is(']') { - self.stack.pop(); - self.state = if self.stack.is_empty() { - ParseBeforeFinish - } else if self.stack.last_is_index() { - ParseArrayComma - } else { - ParseObjectComma - }; - self.bump(); - Some(ArrayEnd) - } else if self.eof() { - Some(self.error_event(EOFWhileParsingArray)) - } else { - Some(self.error_event(InvalidSyntax)) - } - } - - fn parse_object(&mut self, first: bool) -> JsonEvent { - if self.ch_is('}') { - if !first { - if self.stack.is_empty() { - return self.error_event(TrailingComma); - } else { - self.stack.pop(); - } - } - self.state = if self.stack.is_empty() { - ParseBeforeFinish - } else if self.stack.last_is_index() { - ParseArrayComma - } else { - ParseObjectComma - }; - self.bump(); - return ObjectEnd; - } - if self.eof() { - return self.error_event(EOFWhileParsingObject); - } - if !self.ch_is('"') { - return self.error_event(KeyMustBeAString); - } - let s = match self.parse_str() { - Ok(s) => s, - Err(e) => { - self.state = ParseFinished; - return Error(e); - } - }; - self.parse_whitespace(); - if self.eof() { - return self.error_event(EOFWhileParsingObject); - } else if self.ch_or_null() != ':' { - return self.error_event(ExpectedColon); - } - self.stack.push_key(s); - self.bump(); - self.parse_whitespace(); - - let val = self.parse_value(); - - self.state = match val { - Error(_) => ParseFinished, - ArrayStart => ParseArray(true), - ObjectStart => ParseObject(true), - _ => ParseObjectComma, - }; - return val; - } - - fn parse_object_end(&mut self) -> JsonEvent { - if self.ch_is('}') { - self.state = if self.stack.is_empty() { - ParseBeforeFinish - } else if self.stack.last_is_index() { - ParseArrayComma - } else { - ParseObjectComma - }; - self.bump(); - ObjectEnd - } else if self.eof() { - self.error_event(EOFWhileParsingObject) - } else { - self.error_event(InvalidSyntax) - } - } - - fn parse_value(&mut self) -> JsonEvent { - if self.eof() { return self.error_event(EOFWhileParsingValue); } - match self.ch_or_null() { - 'n' => { self.parse_ident("ull", NullValue) } - 't' => { self.parse_ident("rue", BooleanValue(true)) } - 'f' => { self.parse_ident("alse", BooleanValue(false)) } - '0' ... '9' | '-' => self.parse_number(), - '"' => match self.parse_str() { - Ok(s) => StringValue(s), - Err(e) => Error(e), - }, - '[' => { - self.bump(); - ArrayStart - } - '{' => { - self.bump(); - ObjectStart - } - _ => { self.error_event(InvalidSyntax) } - } - } - - fn parse_ident(&mut self, ident: &str, value: JsonEvent) -> JsonEvent { - if ident.chars().all(|c| Some(c) == self.next_char()) { - self.bump(); - value - } else { - Error(SyntaxError(InvalidSyntax, self.line, self.col)) - } - } - - fn error_event(&mut self, reason: ErrorCode) -> JsonEvent { - self.state = ParseFinished; - Error(SyntaxError(reason, self.line, self.col)) - } -} - -/// A Builder consumes a json::Parser to create a generic Json structure. -pub struct Builder { - parser: Parser, - token: Option, -} - -impl> Builder { - /// Create a JSON Builder. - pub fn new(src: T) -> Builder { - Builder { parser: Parser::new(src), token: None, } - } - - // Decode a Json value from a Parser. - pub fn build(&mut self) -> Result { - self.bump(); - let result = self.build_value(); - self.bump(); - match self.token { - None => {} - Some(Error(e)) => { return Err(e); } - ref tok => { panic!("unexpected token {}", tok.clone()); } - } - result - } - - fn bump(&mut self) { - self.token = self.parser.next(); - } - - fn build_value(&mut self) -> Result { - return match self.token { - Some(NullValue) => Ok(Json::Null), - Some(I64Value(n)) => Ok(Json::I64(n)), - Some(U64Value(n)) => Ok(Json::U64(n)), - Some(F64Value(n)) => Ok(Json::F64(n)), - Some(BooleanValue(b)) => Ok(Json::Boolean(b)), - Some(StringValue(ref mut s)) => { - let mut temp = string::String::new(); - swap(s, &mut temp); - Ok(Json::String(temp)) - } - Some(Error(e)) => Err(e), - Some(ArrayStart) => self.build_array(), - Some(ObjectStart) => self.build_object(), - Some(ObjectEnd) => self.parser.error(InvalidSyntax), - Some(ArrayEnd) => self.parser.error(InvalidSyntax), - None => self.parser.error(EOFWhileParsingValue), - } - } - - fn build_array(&mut self) -> Result { - self.bump(); - let mut values = Vec::new(); - - loop { - if self.token == Some(ArrayEnd) { - return Ok(Json::Array(values.into_iter().collect())); - } - match self.build_value() { - Ok(v) => values.push(v), - Err(e) => { return Err(e) } - } - self.bump(); - } - } - - fn build_object(&mut self) -> Result { - self.bump(); - - let mut values = BTreeMap::new(); - - loop { - match self.token { - Some(ObjectEnd) => { return Ok(Json::Object(values)); } - Some(Error(e)) => { return Err(e); } - None => { break; } - _ => {} - } - let key = match self.parser.stack().top() { - Some(Key(k)) => { k.to_string() } - _ => { panic!("invalid state"); } - }; - match self.build_value() { - Ok(value) => { values.insert(key, value); } - Err(e) => { return Err(e); } - } - self.bump(); - } - return self.parser.error(EOFWhileParsingObject); - } -} - -/// Decodes a json value from an `&mut io::Reader` -pub fn from_reader(rdr: &mut io::Reader) -> Result { - let contents = match rdr.read_to_end() { - Ok(c) => c, - Err(e) => return Err(io_error_to_error(e)) - }; - let s = match str::from_utf8(contents.as_slice()).ok() { - Some(s) => s, - _ => return Err(SyntaxError(NotUtf8, 0, 0)) - }; - let mut builder = Builder::new(s.chars()); - builder.build() -} - -/// Decodes a json value from a string -pub fn from_str(s: &str) -> Result { - let mut builder = Builder::new(s.chars()); - builder.build() -} - -/// A structure to decode JSON to values in rust. -pub struct Decoder { - stack: Vec, -} - -impl Decoder { - /// Creates a new decoder instance for decoding the specified JSON value. - pub fn new(json: Json) -> Decoder { - Decoder { stack: vec![json] } - } -} - -impl Decoder { - fn pop(&mut self) -> Json { - self.stack.pop().unwrap() - } -} - -macro_rules! expect { - ($e:expr, Null) => ({ - match $e { - Json::Null => Ok(()), - other => Err(ExpectedError("Null".to_string(), - format!("{}", other))) - } - }); - ($e:expr, $t:ident) => ({ - match $e { - Json::$t(v) => Ok(v), - other => { - Err(ExpectedError(stringify!($t).to_string(), - format!("{}", other))) - } - } - }) -} - -macro_rules! read_primitive { - ($name:ident, $ty:ty) => { - fn $name(&mut self) -> DecodeResult<$ty> { - match self.pop() { - Json::I64(f) => match num::cast(f) { - Some(f) => Ok(f), - None => Err(ExpectedError("Number".to_string(), format!("{}", f))), - }, - Json::U64(f) => match num::cast(f) { - Some(f) => Ok(f), - None => Err(ExpectedError("Number".to_string(), format!("{}", f))), - }, - Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))), - // re: #12967.. a type w/ numeric keys (ie HashMap etc) - // is going to have a string here, as per JSON spec. - Json::String(s) => match s.parse() { - Some(f) => Ok(f), - None => Err(ExpectedError("Number".to_string(), s)), - }, - value => Err(ExpectedError("Number".to_string(), format!("{}", value))), - } - } - } -} - -impl ::Decoder for Decoder { - fn read_nil(&mut self) -> DecodeResult<()> { - expect!(self.pop(), Null) - } - - read_primitive! { read_uint, uint } - read_primitive! { read_u8, u8 } - read_primitive! { read_u16, u16 } - read_primitive! { read_u32, u32 } - read_primitive! { read_u64, u64 } - read_primitive! { read_int, int } - read_primitive! { read_i8, i8 } - read_primitive! { read_i16, i16 } - read_primitive! { read_i32, i32 } - read_primitive! { read_i64, i64 } - - fn read_f32(&mut self) -> DecodeResult { self.read_f64().map(|x| x as f32) } - - fn read_f64(&mut self) -> DecodeResult { - match self.pop() { - Json::I64(f) => Ok(f as f64), - Json::U64(f) => Ok(f as f64), - Json::F64(f) => Ok(f), - Json::String(s) => { - // re: #12967.. a type w/ numeric keys (ie HashMap etc) - // is going to have a string here, as per JSON spec. - match s.parse() { - Some(f) => Ok(f), - None => Err(ExpectedError("Number".to_string(), s)), - } - }, - Json::Null => Ok(f64::NAN), - value => Err(ExpectedError("Number".to_string(), format!("{}", value))) - } - } - - fn read_bool(&mut self) -> DecodeResult { - expect!(self.pop(), Boolean) - } - - fn read_char(&mut self) -> DecodeResult { - let s = try!(self.read_str()); - { - let mut it = s.chars(); - match (it.next(), it.next()) { - // exactly one character - (Some(c), None) => return Ok(c), - _ => () - } - } - Err(ExpectedError("single character string".to_string(), format!("{}", s))) - } - - fn read_str(&mut self) -> DecodeResult { - expect!(self.pop(), String) - } - - fn read_enum(&mut self, _name: &str, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - f(self) - } - - fn read_enum_variant(&mut self, names: &[&str], - mut f: F) -> DecodeResult - where F: FnMut(&mut Decoder, uint) -> DecodeResult, - { - let name = match self.pop() { - Json::String(s) => s, - Json::Object(mut o) => { - let n = match o.remove(&"variant".to_string()) { - Some(Json::String(s)) => s, - Some(val) => { - return Err(ExpectedError("String".to_string(), format!("{}", val))) - } - None => { - return Err(MissingFieldError("variant".to_string())) - } - }; - match o.remove(&"fields".to_string()) { - Some(Json::Array(l)) => { - for field in l.into_iter().rev() { - self.stack.push(field); - } - }, - Some(val) => { - return Err(ExpectedError("Array".to_string(), format!("{}", val))) - } - None => { - return Err(MissingFieldError("fields".to_string())) - } - } - n - } - json => { - return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) - } - }; - let idx = match names.iter().position(|n| *n == name.index(&FullRange)) { - Some(idx) => idx, - None => return Err(UnknownVariantError(name)) - }; - f(self, idx) - } - - fn read_enum_variant_arg(&mut self, _idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - f(self) - } - - fn read_enum_struct_variant(&mut self, names: &[&str], f: F) -> DecodeResult where - F: FnMut(&mut Decoder, uint) -> DecodeResult, - { - self.read_enum_variant(names, f) - } - - - fn read_enum_struct_variant_field(&mut self, - _name: &str, - idx: uint, - f: F) - -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - self.read_enum_variant_arg(idx, f) - } - - fn read_struct(&mut self, _name: &str, _len: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - let value = try!(f(self)); - self.pop(); - Ok(value) - } - - fn read_struct_field(&mut self, - name: &str, - _idx: uint, - f: F) - -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - let mut obj = try!(expect!(self.pop(), Object)); - - let value = match obj.remove(&name.to_string()) { - None => { - // Add a Null and try to parse it as an Option<_> - // to get None as a default value. - self.stack.push(Json::Null); - match f(self) { - Ok(x) => x, - Err(_) => return Err(MissingFieldError(name.to_string())), - } - }, - Some(json) => { - self.stack.push(json); - try!(f(self)) - } - }; - self.stack.push(Json::Object(obj)); - Ok(value) - } - - fn read_tuple(&mut self, tuple_len: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - self.read_seq(move |d, len| { - if len == tuple_len { - f(d) - } else { - Err(ExpectedError(format!("Tuple{}", tuple_len), format!("Tuple{}", len))) - } - }) - } - - fn read_tuple_arg(&mut self, idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - self.read_seq_elt(idx, f) - } - - fn read_tuple_struct(&mut self, - _name: &str, - len: uint, - f: F) - -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - self.read_tuple(len, f) - } - - fn read_tuple_struct_arg(&mut self, - idx: uint, - f: F) - -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - self.read_tuple_arg(idx, f) - } - - fn read_option(&mut self, mut f: F) -> DecodeResult where - F: FnMut(&mut Decoder, bool) -> DecodeResult, - { - match self.pop() { - Json::Null => f(self, false), - value => { self.stack.push(value); f(self, true) } - } - } - - fn read_seq(&mut self, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder, uint) -> DecodeResult, - { - let array = try!(expect!(self.pop(), Array)); - let len = array.len(); - for v in array.into_iter().rev() { - self.stack.push(v); - } - f(self, len) - } - - fn read_seq_elt(&mut self, _idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - f(self) - } - - fn read_map(&mut self, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder, uint) -> DecodeResult, - { - let obj = try!(expect!(self.pop(), Object)); - let len = obj.len(); - for (key, value) in obj.into_iter() { - self.stack.push(value); - self.stack.push(Json::String(key)); - } - f(self, len) - } - - fn read_map_elt_key(&mut self, _idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - f(self) - } - - fn read_map_elt_val(&mut self, _idx: uint, f: F) -> DecodeResult where - F: FnOnce(&mut Decoder) -> DecodeResult, - { - f(self) - } - - fn error(&mut self, err: &str) -> DecoderError { - ApplicationError(err.to_string()) - } -} - -/// A trait for converting values to JSON -pub trait ToJson { - /// Converts the value of `self` to an instance of JSON - fn to_json(&self) -> Json; -} - -macro_rules! to_json_impl_i64 { - ($($t:ty), +) => ( - $(impl ToJson for $t { - fn to_json(&self) -> Json { Json::I64(*self as i64) } - })+ - ) -} - -to_json_impl_i64! { int, i8, i16, i32, i64 } - -macro_rules! to_json_impl_u64 { - ($($t:ty), +) => ( - $(impl ToJson for $t { - fn to_json(&self) -> Json { Json::U64(*self as u64) } - })+ - ) -} - -to_json_impl_u64! { uint, u8, u16, u32, u64 } - -impl ToJson for Json { - fn to_json(&self) -> Json { self.clone() } -} - -impl ToJson for f32 { - fn to_json(&self) -> Json { (*self as f64).to_json() } -} - -impl ToJson for f64 { - fn to_json(&self) -> Json { - match self.classify() { - Fp::Nan | Fp::Infinite => Json::Null, - _ => Json::F64(*self) - } - } -} - -impl ToJson for () { - fn to_json(&self) -> Json { Json::Null } -} - -impl ToJson for bool { - fn to_json(&self) -> Json { Json::Boolean(*self) } -} - -impl ToJson for str { - fn to_json(&self) -> Json { Json::String(self.to_string()) } -} - -impl ToJson for string::String { - fn to_json(&self) -> Json { Json::String((*self).clone()) } -} - -macro_rules! tuple_impl { - // use variables to indicate the arity of the tuple - ($($tyvar:ident),* ) => { - // the trailing commas are for the 1 tuple - impl< - $( $tyvar : ToJson ),* - > ToJson for ( $( $tyvar ),* , ) { - - #[inline] - #[allow(non_snake_case)] - fn to_json(&self) -> Json { - match *self { - ($(ref $tyvar),*,) => Json::Array(vec![$($tyvar.to_json()),*]) - } - } - } - } -} - -tuple_impl!{A} -tuple_impl!{A, B} -tuple_impl!{A, B, C} -tuple_impl!{A, B, C, D} -tuple_impl!{A, B, C, D, E} -tuple_impl!{A, B, C, D, E, F} -tuple_impl!{A, B, C, D, E, F, G} -tuple_impl!{A, B, C, D, E, F, G, H} -tuple_impl!{A, B, C, D, E, F, G, H, I} -tuple_impl!{A, B, C, D, E, F, G, H, I, J} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K} -tuple_impl!{A, B, C, D, E, F, G, H, I, J, K, L} - -impl ToJson for [A] { - fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) } -} - -impl ToJson for Vec { - fn to_json(&self) -> Json { Json::Array(self.iter().map(|elt| elt.to_json()).collect()) } -} - -impl ToJson for BTreeMap { - fn to_json(&self) -> Json { - let mut d = BTreeMap::new(); - for (key, value) in self.iter() { - d.insert((*key).clone(), value.to_json()); - } - Json::Object(d) - } -} - -impl ToJson for HashMap { - fn to_json(&self) -> Json { - let mut d = BTreeMap::new(); - for (key, value) in self.iter() { - d.insert((*key).clone(), value.to_json()); - } - Json::Object(d) - } -} - -impl ToJson for Option { - fn to_json(&self) -> Json { - match *self { - None => Json::Null, - Some(ref value) => value.to_json() - } - } -} - -struct FormatShim<'a, 'b: 'a> { - inner: &'a mut fmt::Formatter<'b>, -} - -impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> { - fn write_str(&mut self, s: &str) -> fmt::Result { - self.inner.write_str(s) - } -} - -impl fmt::Show for Json { - /// Encodes a json value into a string - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut shim = FormatShim { inner: f }; - let mut encoder = Encoder::new(&mut shim); - self.encode(&mut encoder) - } -} - -impl<'a> fmt::Show for PrettyJson<'a> { - /// Encodes a json value into a string - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut shim = FormatShim { inner: f }; - let mut encoder = PrettyEncoder::new(&mut shim); - self.inner.encode(&mut encoder) - } -} - -impl<'a, T> fmt::Show for AsJson<'a, T> - where T: for<'b> Encodable, fmt::Error> -{ - /// Encodes a json value into a string - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut shim = FormatShim { inner: f }; - let mut encoder = Encoder::new(&mut shim); - self.inner.encode(&mut encoder) - } -} - -impl<'a, T> AsPrettyJson<'a, T> { - /// Set the indentation level for the emitted JSON - pub fn indent(mut self, indent: uint) -> AsPrettyJson<'a, T> { - self.indent = Some(indent); - self - } -} - -impl<'a, T> fmt::Show for AsPrettyJson<'a, T> - where T: for<'b> Encodable, fmt::Error> -{ - /// Encodes a json value into a string - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut shim = FormatShim { inner: f }; - let mut encoder = PrettyEncoder::new(&mut shim); - match self.indent { - Some(n) => encoder.set_indent(n), - None => {} - } - self.inner.encode(&mut encoder) - } -} - -impl FromStr for Json { - fn from_str(s: &str) -> Option { - from_str(s).ok() - } -} - -#[cfg(test)] -mod tests { - extern crate test; - use self::Animal::*; - use self::DecodeEnum::*; - use self::test::Bencher; - use {Encodable, Decodable}; - use super::Json::*; - use super::ErrorCode::*; - use super::ParserError::*; - use super::DecoderError::*; - use super::JsonEvent::*; - use super::StackElement::*; - use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, - StackElement, Stack, Decoder}; - use std::{i64, u64, f32, f64}; - use std::collections::BTreeMap; - use std::num::Float; - use std::string; - - #[derive(RustcDecodable, Eq, PartialEq, Show)] - struct OptionData { - opt: Option, - } - - #[test] - fn test_decode_option_none() { - let s ="{}"; - let obj: OptionData = super::decode(s).unwrap(); - assert_eq!(obj, OptionData { opt: None }); - } - - #[test] - fn test_decode_option_some() { - let s = "{ \"opt\": 10 }"; - let obj: OptionData = super::decode(s).unwrap(); - assert_eq!(obj, OptionData { opt: Some(10u) }); - } - - #[test] - fn test_decode_option_malformed() { - check_err::("{ \"opt\": [] }", - ExpectedError("Number".to_string(), "[]".to_string())); - check_err::("{ \"opt\": false }", - ExpectedError("Number".to_string(), "false".to_string())); - } - - #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)] - enum Animal { - Dog, - Frog(string::String, int) - } - - #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)] - struct Inner { - a: (), - b: uint, - c: Vec, - } - - #[derive(PartialEq, RustcEncodable, RustcDecodable, Show)] - struct Outer { - inner: Vec, - } - - fn mk_object(items: &[(string::String, Json)]) -> Json { - let mut d = BTreeMap::new(); - - for item in items.iter() { - match *item { - (ref key, ref value) => { d.insert((*key).clone(), (*value).clone()); }, - } - }; - - Object(d) - } - - #[test] - fn test_from_str_trait() { - let s = "null"; - assert!(s.parse::().unwrap() == s.parse().unwrap()); - } - - #[test] - fn test_write_null() { - assert_eq!(Null.to_string(), "null"); - assert_eq!(Null.pretty().to_string(), "null"); - } - - #[test] - fn test_write_i64() { - assert_eq!(U64(0).to_string(), "0"); - assert_eq!(U64(0).pretty().to_string(), "0"); - - assert_eq!(U64(1234).to_string(), "1234"); - assert_eq!(U64(1234).pretty().to_string(), "1234"); - - assert_eq!(I64(-5678).to_string(), "-5678"); - assert_eq!(I64(-5678).pretty().to_string(), "-5678"); - - assert_eq!(U64(7650007200025252000).to_string(), "7650007200025252000"); - assert_eq!(U64(7650007200025252000).pretty().to_string(), "7650007200025252000"); - } - - #[test] - fn test_write_f64() { - assert_eq!(F64(3.0).to_string(), "3.0"); - assert_eq!(F64(3.0).pretty().to_string(), "3.0"); - - assert_eq!(F64(3.1).to_string(), "3.1"); - assert_eq!(F64(3.1).pretty().to_string(), "3.1"); - - assert_eq!(F64(-1.5).to_string(), "-1.5"); - assert_eq!(F64(-1.5).pretty().to_string(), "-1.5"); - - assert_eq!(F64(0.5).to_string(), "0.5"); - assert_eq!(F64(0.5).pretty().to_string(), "0.5"); - - assert_eq!(F64(f64::NAN).to_string(), "null"); - assert_eq!(F64(f64::NAN).pretty().to_string(), "null"); - - assert_eq!(F64(f64::INFINITY).to_string(), "null"); - assert_eq!(F64(f64::INFINITY).pretty().to_string(), "null"); - - assert_eq!(F64(f64::NEG_INFINITY).to_string(), "null"); - assert_eq!(F64(f64::NEG_INFINITY).pretty().to_string(), "null"); - } - - #[test] - fn test_write_str() { - assert_eq!(String("".to_string()).to_string(), "\"\""); - assert_eq!(String("".to_string()).pretty().to_string(), "\"\""); - - assert_eq!(String("homura".to_string()).to_string(), "\"homura\""); - assert_eq!(String("madoka".to_string()).pretty().to_string(), "\"madoka\""); - } - - #[test] - fn test_write_bool() { - assert_eq!(Boolean(true).to_string(), "true"); - assert_eq!(Boolean(true).pretty().to_string(), "true"); - - assert_eq!(Boolean(false).to_string(), "false"); - assert_eq!(Boolean(false).pretty().to_string(), "false"); - } - - #[test] - fn test_write_array() { - assert_eq!(Array(vec![]).to_string(), "[]"); - assert_eq!(Array(vec![]).pretty().to_string(), "[]"); - - assert_eq!(Array(vec![Boolean(true)]).to_string(), "[true]"); - assert_eq!( - Array(vec![Boolean(true)]).pretty().to_string(), - "\ - [\n \ - true\n\ - ]" - ); - - let long_test_array = Array(vec![ - Boolean(false), - Null, - Array(vec![String("foo\nbar".to_string()), F64(3.5)])]); - - assert_eq!(long_test_array.to_string(), - "[false,null,[\"foo\\nbar\",3.5]]"); - assert_eq!( - long_test_array.pretty().to_string(), - "\ - [\n \ - false,\n \ - null,\n \ - [\n \ - \"foo\\nbar\",\n \ - 3.5\n \ - ]\n\ - ]" - ); - } - - #[test] - fn test_write_object() { - assert_eq!(mk_object(&[]).to_string(), "{}"); - assert_eq!(mk_object(&[]).pretty().to_string(), "{}"); - - assert_eq!( - mk_object(&[ - ("a".to_string(), Boolean(true)) - ]).to_string(), - "{\"a\":true}" - ); - assert_eq!( - mk_object(&[("a".to_string(), Boolean(true))]).pretty().to_string(), - "\ - {\n \ - \"a\": true\n\ - }" - ); - - let complex_obj = mk_object(&[ - ("b".to_string(), Array(vec![ - mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), - mk_object(&[("d".to_string(), String("".to_string()))]) - ])) - ]); - - assert_eq!( - complex_obj.to_string(), - "{\ - \"b\":[\ - {\"c\":\"\\f\\r\"},\ - {\"d\":\"\"}\ - ]\ - }" - ); - assert_eq!( - complex_obj.pretty().to_string(), - "\ - {\n \ - \"b\": [\n \ - {\n \ - \"c\": \"\\f\\r\"\n \ - },\n \ - {\n \ - \"d\": \"\"\n \ - }\n \ - ]\n\ - }" - ); - - let a = mk_object(&[ - ("a".to_string(), Boolean(true)), - ("b".to_string(), Array(vec![ - mk_object(&[("c".to_string(), String("\x0c\r".to_string()))]), - mk_object(&[("d".to_string(), String("".to_string()))]) - ])) - ]); - - // We can't compare the strings directly because the object fields be - // printed in a different order. - assert_eq!(a.clone(), a.to_string().parse().unwrap()); - assert_eq!(a.clone(), a.pretty().to_string().parse().unwrap()); - } - - #[test] - fn test_write_enum() { - let animal = Dog; - assert_eq!( - format!("{}", super::as_json(&animal)), - "\"Dog\"" - ); - assert_eq!( - format!("{}", super::as_pretty_json(&animal)), - "\"Dog\"" - ); - - let animal = Frog("Henry".to_string(), 349); - assert_eq!( - format!("{}", super::as_json(&animal)), - "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}" - ); - assert_eq!( - format!("{}", super::as_pretty_json(&animal)), - "{\n \ - \"variant\": \"Frog\",\n \ - \"fields\": [\n \ - \"Henry\",\n \ - 349\n \ - ]\n\ - }" - ); - } - - macro_rules! check_encoder_for_simple { - ($value:expr, $expected:expr) => ({ - let s = format!("{}", super::as_json(&$value)); - assert_eq!(s, $expected); - - let s = format!("{}", super::as_pretty_json(&$value)); - assert_eq!(s, $expected); - }) - } - - #[test] - fn test_write_some() { - check_encoder_for_simple!(Some("jodhpurs".to_string()), "\"jodhpurs\""); - } - - #[test] - fn test_write_none() { - check_encoder_for_simple!(None::, "null"); - } - - #[test] - fn test_write_char() { - check_encoder_for_simple!('a', "\"a\""); - check_encoder_for_simple!('\t', "\"\\t\""); - check_encoder_for_simple!('\u{0000}', "\"\\u0000\""); - check_encoder_for_simple!('\u{001b}', "\"\\u001b\""); - check_encoder_for_simple!('\u{007f}', "\"\\u007f\""); - check_encoder_for_simple!('\u{00a0}', "\"\u{00a0}\""); - check_encoder_for_simple!('\u{abcd}', "\"\u{abcd}\""); - check_encoder_for_simple!('\u{10ffff}', "\"\u{10ffff}\""); - } - - #[test] - fn test_trailing_characters() { - assert_eq!(from_str("nulla"), Err(SyntaxError(TrailingCharacters, 1, 5))); - assert_eq!(from_str("truea"), Err(SyntaxError(TrailingCharacters, 1, 5))); - assert_eq!(from_str("falsea"), Err(SyntaxError(TrailingCharacters, 1, 6))); - assert_eq!(from_str("1a"), Err(SyntaxError(TrailingCharacters, 1, 2))); - assert_eq!(from_str("[]a"), Err(SyntaxError(TrailingCharacters, 1, 3))); - assert_eq!(from_str("{}a"), Err(SyntaxError(TrailingCharacters, 1, 3))); - } - - #[test] - fn test_read_identifiers() { - assert_eq!(from_str("n"), Err(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(from_str("nul"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("t"), Err(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(from_str("truz"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("f"), Err(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(from_str("faz"), Err(SyntaxError(InvalidSyntax, 1, 3))); - - 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 v: () = super::decode("null").unwrap(); - assert_eq!(v, ()); - - let v: bool = super::decode("true").unwrap(); - assert_eq!(v, true); - - let v: bool = super::decode("false").unwrap(); - assert_eq!(v, false); - } - - #[test] - fn test_read_number() { - assert_eq!(from_str("+"), Err(SyntaxError(InvalidSyntax, 1, 1))); - assert_eq!(from_str("."), Err(SyntaxError(InvalidSyntax, 1, 1))); - assert_eq!(from_str("NaN"), Err(SyntaxError(InvalidSyntax, 1, 1))); - assert_eq!(from_str("-"), Err(SyntaxError(InvalidNumber, 1, 2))); - assert_eq!(from_str("00"), Err(SyntaxError(InvalidNumber, 1, 2))); - assert_eq!(from_str("1."), Err(SyntaxError(InvalidNumber, 1, 3))); - assert_eq!(from_str("1e"), Err(SyntaxError(InvalidNumber, 1, 3))); - assert_eq!(from_str("1e+"), Err(SyntaxError(InvalidNumber, 1, 4))); - - assert_eq!(from_str("18446744073709551616"), Err(SyntaxError(InvalidNumber, 1, 20))); - assert_eq!(from_str("-9223372036854775809"), Err(SyntaxError(InvalidNumber, 1, 21))); - - assert_eq!(from_str("3"), Ok(U64(3))); - assert_eq!(from_str("3.1"), Ok(F64(3.1))); - assert_eq!(from_str("-1.2"), Ok(F64(-1.2))); - assert_eq!(from_str("0.4"), Ok(F64(0.4))); - assert_eq!(from_str("0.4e5"), Ok(F64(0.4e5))); - assert_eq!(from_str("0.4e+15"), Ok(F64(0.4e15))); - assert_eq!(from_str("0.4e-01"), Ok(F64(0.4e-01))); - assert_eq!(from_str(" 3 "), Ok(U64(3))); - - assert_eq!(from_str("-9223372036854775808"), Ok(I64(i64::MIN))); - assert_eq!(from_str("9223372036854775807"), Ok(U64(i64::MAX as u64))); - assert_eq!(from_str("18446744073709551615"), Ok(U64(u64::MAX))); - } - - #[test] - fn test_decode_numbers() { - let v: f64 = super::decode("3").unwrap(); - assert_eq!(v, 3.0); - - let v: f64 = super::decode("3.1").unwrap(); - assert_eq!(v, 3.1); - - let v: f64 = super::decode("-1.2").unwrap(); - assert_eq!(v, -1.2); - - let v: f64 = super::decode("0.4").unwrap(); - assert_eq!(v, 0.4); - - let v: f64 = super::decode("0.4e5").unwrap(); - assert_eq!(v, 0.4e5); - - let v: f64 = super::decode("0.4e15").unwrap(); - assert_eq!(v, 0.4e15); - - let v: f64 = super::decode("0.4e-01").unwrap(); - assert_eq!(v, 0.4e-01); - - let v: u64 = super::decode("0").unwrap(); - assert_eq!(v, 0); - - let v: u64 = super::decode("18446744073709551615").unwrap(); - assert_eq!(v, u64::MAX); - - let v: i64 = super::decode("-9223372036854775808").unwrap(); - assert_eq!(v, i64::MIN); - - let v: i64 = super::decode("9223372036854775807").unwrap(); - assert_eq!(v, i64::MAX); - - let res: DecodeResult = super::decode("765.25252"); - assert_eq!(res, Err(ExpectedError("Integer".to_string(), "765.25252".to_string()))); - } - - #[test] - fn test_read_str() { - assert_eq!(from_str("\""), Err(SyntaxError(EOFWhileParsingString, 1, 2))); - assert_eq!(from_str("\"lol"), Err(SyntaxError(EOFWhileParsingString, 1, 5))); - - assert_eq!(from_str("\"\""), Ok(String("".to_string()))); - assert_eq!(from_str("\"foo\""), Ok(String("foo".to_string()))); - assert_eq!(from_str("\"\\\"\""), Ok(String("\"".to_string()))); - assert_eq!(from_str("\"\\b\""), Ok(String("\x08".to_string()))); - assert_eq!(from_str("\"\\n\""), Ok(String("\n".to_string()))); - assert_eq!(from_str("\"\\r\""), Ok(String("\r".to_string()))); - assert_eq!(from_str("\"\\t\""), Ok(String("\t".to_string()))); - assert_eq!(from_str(" \"foo\" "), Ok(String("foo".to_string()))); - assert_eq!(from_str("\"\\u12ab\""), Ok(String("\u{12ab}".to_string()))); - assert_eq!(from_str("\"\\uAB12\""), Ok(String("\u{AB12}".to_string()))); - } - - #[test] - fn test_decode_str() { - let s = [("\"\"", ""), - ("\"foo\"", "foo"), - ("\"\\\"\"", "\""), - ("\"\\b\"", "\x08"), - ("\"\\n\"", "\n"), - ("\"\\r\"", "\r"), - ("\"\\t\"", "\t"), - ("\"\\u12ab\"", "\u{12ab}"), - ("\"\\uAB12\"", "\u{AB12}")]; - - for &(i, o) in s.iter() { - let v: string::String = super::decode(i).unwrap(); - assert_eq!(v, o); - } - } - - #[test] - fn test_read_array() { - assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); - assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); - assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); - assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); - - assert_eq!(from_str("[]"), Ok(Array(vec![]))); - assert_eq!(from_str("[ ]"), Ok(Array(vec![]))); - assert_eq!(from_str("[true]"), Ok(Array(vec![Boolean(true)]))); - assert_eq!(from_str("[ false ]"), Ok(Array(vec![Boolean(false)]))); - assert_eq!(from_str("[null]"), Ok(Array(vec![Null]))); - assert_eq!(from_str("[3, 1]"), - Ok(Array(vec![U64(3), U64(1)]))); - assert_eq!(from_str("\n[3, 2]\n"), - Ok(Array(vec![U64(3), U64(2)]))); - assert_eq!(from_str("[2, [4, 1]]"), - Ok(Array(vec![U64(2), Array(vec![U64(4), U64(1)])]))); - } - - #[test] - fn test_decode_array() { - let v: Vec<()> = super::decode("[]").unwrap(); - assert_eq!(v, vec![]); - - let v: Vec<()> = super::decode("[null]").unwrap(); - assert_eq!(v, vec![()]); - - let v: Vec = super::decode("[true]").unwrap(); - assert_eq!(v, vec![true]); - - let v: Vec = super::decode("[3, 1]").unwrap(); - assert_eq!(v, vec![3, 1]); - - let v: Vec> = super::decode("[[3], [1, 2]]").unwrap(); - assert_eq!(v, vec![vec![3], vec![1, 2]]); - } - - #[test] - fn test_decode_tuple() { - let t: (uint, uint, uint) = super::decode("[1, 2, 3]").unwrap(); - assert_eq!(t, (1u, 2, 3)); - - let t: (uint, string::String) = super::decode("[1, \"two\"]").unwrap(); - assert_eq!(t, (1u, "two".to_string())); - } - - #[test] - fn test_decode_tuple_malformed_types() { - assert!(super::decode::<(uint, string::String)>("[1, 2]").is_err()); - } - - #[test] - fn test_decode_tuple_malformed_length() { - assert!(super::decode::<(uint, uint)>("[1, 2, 3]").is_err()); - } - - #[test] - fn test_read_object() { - assert_eq!(from_str("{"), Err(SyntaxError(EOFWhileParsingObject, 1, 2))); - assert_eq!(from_str("{ "), Err(SyntaxError(EOFWhileParsingObject, 1, 3))); - assert_eq!(from_str("{1"), Err(SyntaxError(KeyMustBeAString, 1, 2))); - assert_eq!(from_str("{ \"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 6))); - assert_eq!(from_str("{\"a\""), Err(SyntaxError(EOFWhileParsingObject, 1, 5))); - assert_eq!(from_str("{\"a\" "), Err(SyntaxError(EOFWhileParsingObject, 1, 6))); - - assert_eq!(from_str("{\"a\" 1"), Err(SyntaxError(ExpectedColon, 1, 6))); - assert_eq!(from_str("{\"a\":"), Err(SyntaxError(EOFWhileParsingValue, 1, 6))); - assert_eq!(from_str("{\"a\":1"), Err(SyntaxError(EOFWhileParsingObject, 1, 7))); - assert_eq!(from_str("{\"a\":1 1"), Err(SyntaxError(InvalidSyntax, 1, 8))); - assert_eq!(from_str("{\"a\":1,"), Err(SyntaxError(EOFWhileParsingObject, 1, 8))); - - assert_eq!(from_str("{}").unwrap(), mk_object(&[])); - assert_eq!(from_str("{\"a\": 3}").unwrap(), - mk_object(&[("a".to_string(), U64(3))])); - - assert_eq!(from_str( - "{ \"a\": null, \"b\" : true }").unwrap(), - mk_object(&[ - ("a".to_string(), Null), - ("b".to_string(), Boolean(true))])); - assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(), - mk_object(&[ - ("a".to_string(), Null), - ("b".to_string(), Boolean(true))])); - assert_eq!(from_str( - "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(), - mk_object(&[ - ("a".to_string(), F64(1.0)), - ("b".to_string(), Array(vec![Boolean(true)])) - ])); - assert_eq!(from_str( - "{\ - \"a\": 1.0, \ - \"b\": [\ - true,\ - \"foo\\nbar\", \ - { \"c\": {\"d\": null} } \ - ]\ - }").unwrap(), - mk_object(&[ - ("a".to_string(), F64(1.0)), - ("b".to_string(), Array(vec![ - Boolean(true), - String("foo\nbar".to_string()), - mk_object(&[ - ("c".to_string(), mk_object(&[("d".to_string(), Null)])) - ]) - ])) - ])); - } - - #[test] - fn test_decode_struct() { - let s = "{ - \"inner\": [ - { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] } - ] - }"; - - let v: Outer = super::decode(s).unwrap(); - assert_eq!( - v, - Outer { - inner: vec![ - Inner { a: (), b: 2, c: vec!["abc".to_string(), "xyz".to_string()] } - ] - } - ); - } - - #[derive(RustcDecodable)] - struct FloatStruct { - f: f64, - a: Vec - } - #[test] - fn test_decode_struct_with_nan() { - let s = "{\"f\":null,\"a\":[null,123]}"; - let obj: FloatStruct = super::decode(s).unwrap(); - assert!(obj.f.is_nan()); - assert!(obj.a[0].is_nan()); - assert_eq!(obj.a[1], 123f64); - } - - #[test] - fn test_decode_option() { - let value: Option = super::decode("null").unwrap(); - assert_eq!(value, None); - - let value: Option = super::decode("\"jodhpurs\"").unwrap(); - assert_eq!(value, Some("jodhpurs".to_string())); - } - - #[test] - fn test_decode_enum() { - let value: Animal = super::decode("\"Dog\"").unwrap(); - assert_eq!(value, Dog); - - let s = "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}"; - let value: Animal = super::decode(s).unwrap(); - assert_eq!(value, Frog("Henry".to_string(), 349)); - } - - #[test] - fn test_decode_map() { - let s = "{\"a\": \"Dog\", \"b\": {\"variant\":\"Frog\",\ - \"fields\":[\"Henry\", 349]}}"; - let mut map: BTreeMap = super::decode(s).unwrap(); - - assert_eq!(map.remove(&"a".to_string()), Some(Dog)); - assert_eq!(map.remove(&"b".to_string()), Some(Frog("Henry".to_string(), 349))); - } - - #[test] - fn test_multiline_errors() { - assert_eq!(from_str("{\n \"foo\":\n \"bar\""), - Err(SyntaxError(EOFWhileParsingObject, 3u, 8u))); - } - - #[derive(RustcDecodable)] - #[allow(dead_code)] - struct DecodeStruct { - x: f64, - y: bool, - z: string::String, - w: Vec - } - #[derive(RustcDecodable)] - enum DecodeEnum { - A(f64), - B(string::String) - } - fn check_err>(to_parse: &'static str, - expected: DecoderError) { - let res: DecodeResult = match from_str(to_parse) { - Err(e) => Err(ParseError(e)), - Ok(json) => Decodable::decode(&mut Decoder::new(json)) - }; - match res { - Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`", - to_parse, expected), - Err(ParseError(e)) => panic!("`{}` is not valid json: {}", - to_parse, e), - Err(e) => { - assert_eq!(e, expected); - } - } - } - #[test] - fn test_decode_errors_struct() { - check_err::("[]", ExpectedError("Object".to_string(), "[]".to_string())); - check_err::("{\"x\": true, \"y\": true, \"z\": \"\", \"w\": []}", - ExpectedError("Number".to_string(), "true".to_string())); - check_err::("{\"x\": 1, \"y\": [], \"z\": \"\", \"w\": []}", - ExpectedError("Boolean".to_string(), "[]".to_string())); - check_err::("{\"x\": 1, \"y\": true, \"z\": {}, \"w\": []}", - ExpectedError("String".to_string(), "{}".to_string())); - check_err::("{\"x\": 1, \"y\": true, \"z\": \"\", \"w\": null}", - ExpectedError("Array".to_string(), "null".to_string())); - check_err::("{\"x\": 1, \"y\": true, \"z\": \"\"}", - MissingFieldError("w".to_string())); - } - #[test] - fn test_decode_errors_enum() { - check_err::("{}", - MissingFieldError("variant".to_string())); - check_err::("{\"variant\": 1}", - ExpectedError("String".to_string(), "1".to_string())); - check_err::("{\"variant\": \"A\"}", - MissingFieldError("fields".to_string())); - check_err::("{\"variant\": \"A\", \"fields\": null}", - ExpectedError("Array".to_string(), "null".to_string())); - check_err::("{\"variant\": \"C\", \"fields\": []}", - UnknownVariantError("C".to_string())); - } - - #[test] - fn test_find(){ - let json_value = from_str("{\"dog\" : \"cat\"}").unwrap(); - let found_str = json_value.find("dog"); - assert!(found_str.unwrap().as_string().unwrap() == "cat"); - } - - #[test] - fn test_find_path(){ - let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap(); - let found_str = json_value.find_path(&["dog", "cat", "mouse"]); - assert!(found_str.unwrap().as_string().unwrap() == "cheese"); - } - - #[test] - fn test_search(){ - let json_value = from_str("{\"dog\":{\"cat\": {\"mouse\" : \"cheese\"}}}").unwrap(); - let found_str = json_value.search("mouse").and_then(|j| j.as_string()); - assert!(found_str.unwrap() == "cheese"); - } - - #[test] - fn test_index(){ - let json_value = from_str("{\"animals\":[\"dog\",\"cat\",\"mouse\"]}").unwrap(); - let ref array = json_value["animals"]; - assert_eq!(array[0].as_string().unwrap(), "dog"); - assert_eq!(array[1].as_string().unwrap(), "cat"); - assert_eq!(array[2].as_string().unwrap(), "mouse"); - } - - #[test] - fn test_is_object(){ - let json_value = from_str("{}").unwrap(); - assert!(json_value.is_object()); - } - - #[test] - fn test_as_object(){ - let json_value = from_str("{}").unwrap(); - let json_object = json_value.as_object(); - assert!(json_object.is_some()); - } - - #[test] - fn test_is_array(){ - let json_value = from_str("[1, 2, 3]").unwrap(); - assert!(json_value.is_array()); - } - - #[test] - fn test_as_array(){ - let json_value = from_str("[1, 2, 3]").unwrap(); - let json_array = json_value.as_array(); - let expected_length = 3; - assert!(json_array.is_some() && json_array.unwrap().len() == expected_length); - } - - #[test] - fn test_is_string(){ - let json_value = from_str("\"dog\"").unwrap(); - assert!(json_value.is_string()); - } - - #[test] - fn test_as_string(){ - let json_value = from_str("\"dog\"").unwrap(); - let json_str = json_value.as_string(); - let expected_str = "dog"; - assert_eq!(json_str, Some(expected_str)); - } - - #[test] - fn test_is_number(){ - let json_value = from_str("12").unwrap(); - assert!(json_value.is_number()); - } - - #[test] - fn test_is_i64(){ - let json_value = from_str("-12").unwrap(); - assert!(json_value.is_i64()); - - let json_value = from_str("12").unwrap(); - assert!(!json_value.is_i64()); - - let json_value = from_str("12.0").unwrap(); - assert!(!json_value.is_i64()); - } - - #[test] - fn test_is_u64(){ - let json_value = from_str("12").unwrap(); - assert!(json_value.is_u64()); - - let json_value = from_str("-12").unwrap(); - assert!(!json_value.is_u64()); - - let json_value = from_str("12.0").unwrap(); - assert!(!json_value.is_u64()); - } - - #[test] - fn test_is_f64(){ - let json_value = from_str("12").unwrap(); - assert!(!json_value.is_f64()); - - let json_value = from_str("-12").unwrap(); - assert!(!json_value.is_f64()); - - let json_value = from_str("12.0").unwrap(); - assert!(json_value.is_f64()); - - let json_value = from_str("-12.0").unwrap(); - assert!(json_value.is_f64()); - } - - #[test] - fn test_as_i64(){ - let json_value = from_str("-12").unwrap(); - let json_num = json_value.as_i64(); - assert_eq!(json_num, Some(-12)); - } - - #[test] - fn test_as_u64(){ - let json_value = from_str("12").unwrap(); - let json_num = json_value.as_u64(); - assert_eq!(json_num, Some(12)); - } - - #[test] - fn test_as_f64(){ - let json_value = from_str("12.0").unwrap(); - let json_num = json_value.as_f64(); - assert_eq!(json_num, Some(12f64)); - } - - #[test] - fn test_is_boolean(){ - let json_value = from_str("false").unwrap(); - assert!(json_value.is_boolean()); - } - - #[test] - fn test_as_boolean(){ - let json_value = from_str("false").unwrap(); - let json_bool = json_value.as_boolean(); - let expected_bool = false; - assert!(json_bool.is_some() && json_bool.unwrap() == expected_bool); - } - - #[test] - fn test_is_null(){ - let json_value = from_str("null").unwrap(); - assert!(json_value.is_null()); - } - - #[test] - fn test_as_null(){ - let json_value = from_str("null").unwrap(); - let json_null = json_value.as_null(); - let expected_null = (); - assert!(json_null.is_some() && json_null.unwrap() == expected_null); - } - - #[test] - fn test_encode_hashmap_with_numeric_key() { - use std::str::from_utf8; - use std::io::Writer; - use std::collections::HashMap; - let mut hm: HashMap = HashMap::new(); - hm.insert(1, true); - let mut mem_buf = Vec::new(); - write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap(); - match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), - _ => {} // it parsed and we are good to go - } - } - - #[test] - fn test_prettyencode_hashmap_with_numeric_key() { - use std::str::from_utf8; - use std::io::Writer; - use std::collections::HashMap; - let mut hm: HashMap = HashMap::new(); - hm.insert(1, true); - let mut mem_buf = Vec::new(); - write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap(); - match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), - _ => {} // it parsed and we are good to go - } - } - - #[test] - fn test_prettyencoder_indent_level_param() { - use std::str::from_utf8; - use std::collections::BTreeMap; - - let mut tree = BTreeMap::new(); - - tree.insert("hello".to_string(), String("guten tag".to_string())); - tree.insert("goodbye".to_string(), String("sayonara".to_string())); - - let json = Array( - // The following layout below should look a lot like - // the pretty-printed JSON (indent * x) - vec! - ( // 0x - String("greetings".to_string()), // 1x - Object(tree), // 1x + 2x + 2x + 1x - ) // 0x - // End JSON array (7 lines) - ); - - // Helper function for counting indents - fn indents(source: &str) -> uint { - let trimmed = source.trim_left_matches(' '); - source.len() - trimmed.len() - } - - // Test up to 4 spaces of indents (more?) - for i in range(0, 4u) { - let mut writer = Vec::new(); - write!(&mut writer, "{}", - super::as_pretty_json(&json).indent(i)).unwrap(); - - let printed = from_utf8(&writer.index(&FullRange)).unwrap(); - - // Check for indents at each line - let lines: Vec<&str> = printed.lines().collect(); - assert_eq!(lines.len(), 7); // JSON should be 7 lines - - assert_eq!(indents(lines[0]), 0 * i); // [ - assert_eq!(indents(lines[1]), 1 * i); // "greetings", - assert_eq!(indents(lines[2]), 1 * i); // { - assert_eq!(indents(lines[3]), 2 * i); // "hello": "guten tag", - assert_eq!(indents(lines[4]), 2 * i); // "goodbye": "sayonara" - assert_eq!(indents(lines[5]), 1 * i); // }, - assert_eq!(indents(lines[6]), 0 * i); // ] - - // Finally, test that the pretty-printed JSON is valid - from_str(printed).ok().expect("Pretty-printed JSON is invalid!"); - } - } - - #[test] - fn test_hashmap_with_numeric_key_can_handle_double_quote_delimited_key() { - use std::collections::HashMap; - use Decodable; - let json_str = "{\"1\":true}"; - let json_obj = match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), - Ok(o) => o - }; - let mut decoder = Decoder::new(json_obj); - let _hm: HashMap = Decodable::decode(&mut decoder).unwrap(); - } - - #[test] - fn test_hashmap_with_numeric_key_will_error_with_string_keys() { - use std::collections::HashMap; - use Decodable; - let json_str = "{\"a\":true}"; - let json_obj = match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), - Ok(o) => o - }; - let mut decoder = Decoder::new(json_obj); - let result: Result, DecoderError> = Decodable::decode(&mut decoder); - assert_eq!(result, Err(ExpectedError("Number".to_string(), "a".to_string()))); - } - - fn assert_stream_equal(src: &str, - expected: Vec<(JsonEvent, Vec)>) { - let mut parser = Parser::new(src.chars()); - let mut i = 0; - loop { - let evt = match parser.next() { - Some(e) => e, - None => { break; } - }; - let (ref expected_evt, ref expected_stack) = expected[i]; - if !parser.stack().is_equal_to(expected_stack.as_slice()) { - panic!("Parser stack is not equal to {}", expected_stack); - } - assert_eq!(&evt, expected_evt); - i+=1; - } - } - #[test] - #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) - fn test_streaming_parser() { - assert_stream_equal( - r#"{ "foo":"bar", "array" : [0, 1, 2, 3, 4, 5], "idents":[null,true,false]}"#, - vec![ - (ObjectStart, vec![]), - (StringValue("bar".to_string()), vec![Key("foo")]), - (ArrayStart, vec![Key("array")]), - (U64Value(0), vec![Key("array"), Index(0)]), - (U64Value(1), vec![Key("array"), Index(1)]), - (U64Value(2), vec![Key("array"), Index(2)]), - (U64Value(3), vec![Key("array"), Index(3)]), - (U64Value(4), vec![Key("array"), Index(4)]), - (U64Value(5), vec![Key("array"), Index(5)]), - (ArrayEnd, vec![Key("array")]), - (ArrayStart, vec![Key("idents")]), - (NullValue, vec![Key("idents"), Index(0)]), - (BooleanValue(true), vec![Key("idents"), Index(1)]), - (BooleanValue(false), vec![Key("idents"), Index(2)]), - (ArrayEnd, vec![Key("idents")]), - (ObjectEnd, vec![]), - ] - ); - } - fn last_event(src: &str) -> JsonEvent { - let mut parser = Parser::new(src.chars()); - let mut evt = NullValue; - loop { - evt = match parser.next() { - Some(e) => e, - None => return evt, - } - } - } - - #[test] - #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) - fn test_read_object_streaming() { - assert_eq!(last_event("{ "), Error(SyntaxError(EOFWhileParsingObject, 1, 3))); - assert_eq!(last_event("{1"), Error(SyntaxError(KeyMustBeAString, 1, 2))); - assert_eq!(last_event("{ \"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 6))); - assert_eq!(last_event("{\"a\""), Error(SyntaxError(EOFWhileParsingObject, 1, 5))); - assert_eq!(last_event("{\"a\" "), Error(SyntaxError(EOFWhileParsingObject, 1, 6))); - - assert_eq!(last_event("{\"a\" 1"), Error(SyntaxError(ExpectedColon, 1, 6))); - assert_eq!(last_event("{\"a\":"), Error(SyntaxError(EOFWhileParsingValue, 1, 6))); - assert_eq!(last_event("{\"a\":1"), Error(SyntaxError(EOFWhileParsingObject, 1, 7))); - assert_eq!(last_event("{\"a\":1 1"), Error(SyntaxError(InvalidSyntax, 1, 8))); - assert_eq!(last_event("{\"a\":1,"), Error(SyntaxError(EOFWhileParsingObject, 1, 8))); - assert_eq!(last_event("{\"a\":1,}"), Error(SyntaxError(TrailingComma, 1, 8))); - - assert_stream_equal( - "{}", - vec![(ObjectStart, vec![]), (ObjectEnd, vec![])] - ); - assert_stream_equal( - "{\"a\": 3}", - vec![ - (ObjectStart, vec![]), - (U64Value(3), vec![Key("a")]), - (ObjectEnd, vec![]), - ] - ); - assert_stream_equal( - "{ \"a\": null, \"b\" : true }", - vec![ - (ObjectStart, vec![]), - (NullValue, vec![Key("a")]), - (BooleanValue(true), vec![Key("b")]), - (ObjectEnd, vec![]), - ] - ); - assert_stream_equal( - "{\"a\" : 1.0 ,\"b\": [ true ]}", - vec![ - (ObjectStart, vec![]), - (F64Value(1.0), vec![Key("a")]), - (ArrayStart, vec![Key("b")]), - (BooleanValue(true),vec![Key("b"), Index(0)]), - (ArrayEnd, vec![Key("b")]), - (ObjectEnd, vec![]), - ] - ); - assert_stream_equal( - r#"{ - "a": 1.0, - "b": [ - true, - "foo\nbar", - { "c": {"d": null} } - ] - }"#, - vec![ - (ObjectStart, vec![]), - (F64Value(1.0), vec![Key("a")]), - (ArrayStart, vec![Key("b")]), - (BooleanValue(true), vec![Key("b"), Index(0)]), - (StringValue("foo\nbar".to_string()), vec![Key("b"), Index(1)]), - (ObjectStart, vec![Key("b"), Index(2)]), - (ObjectStart, vec![Key("b"), Index(2), Key("c")]), - (NullValue, vec![Key("b"), Index(2), Key("c"), Key("d")]), - (ObjectEnd, vec![Key("b"), Index(2), Key("c")]), - (ObjectEnd, vec![Key("b"), Index(2)]), - (ArrayEnd, vec![Key("b")]), - (ObjectEnd, vec![]), - ] - ); - } - #[test] - #[cfg_attr(target_word_size = "32", ignore)] // FIXME(#14064) - fn test_read_array_streaming() { - assert_stream_equal( - "[]", - vec![ - (ArrayStart, vec![]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "[ ]", - vec![ - (ArrayStart, vec![]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "[true]", - vec![ - (ArrayStart, vec![]), - (BooleanValue(true), vec![Index(0)]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "[ false ]", - vec![ - (ArrayStart, vec![]), - (BooleanValue(false), vec![Index(0)]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "[null]", - vec![ - (ArrayStart, vec![]), - (NullValue, vec![Index(0)]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "[3, 1]", - vec![ - (ArrayStart, vec![]), - (U64Value(3), vec![Index(0)]), - (U64Value(1), vec![Index(1)]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "\n[3, 2]\n", - vec![ - (ArrayStart, vec![]), - (U64Value(3), vec![Index(0)]), - (U64Value(2), vec![Index(1)]), - (ArrayEnd, vec![]), - ] - ); - assert_stream_equal( - "[2, [4, 1]]", - vec![ - (ArrayStart, vec![]), - (U64Value(2), vec![Index(0)]), - (ArrayStart, vec![Index(1)]), - (U64Value(4), vec![Index(1), Index(0)]), - (U64Value(1), vec![Index(1), Index(1)]), - (ArrayEnd, vec![Index(1)]), - (ArrayEnd, vec![]), - ] - ); - - assert_eq!(last_event("["), Error(SyntaxError(EOFWhileParsingValue, 1, 2))); - - assert_eq!(from_str("["), Err(SyntaxError(EOFWhileParsingValue, 1, 2))); - assert_eq!(from_str("[1"), Err(SyntaxError(EOFWhileParsingArray, 1, 3))); - assert_eq!(from_str("[1,"), Err(SyntaxError(EOFWhileParsingValue, 1, 4))); - assert_eq!(from_str("[1,]"), Err(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(from_str("[6 7]"), Err(SyntaxError(InvalidSyntax, 1, 4))); - - } - #[test] - fn test_trailing_characters_streaming() { - assert_eq!(last_event("nulla"), Error(SyntaxError(TrailingCharacters, 1, 5))); - assert_eq!(last_event("truea"), Error(SyntaxError(TrailingCharacters, 1, 5))); - assert_eq!(last_event("falsea"), Error(SyntaxError(TrailingCharacters, 1, 6))); - assert_eq!(last_event("1a"), Error(SyntaxError(TrailingCharacters, 1, 2))); - assert_eq!(last_event("[]a"), Error(SyntaxError(TrailingCharacters, 1, 3))); - assert_eq!(last_event("{}a"), Error(SyntaxError(TrailingCharacters, 1, 3))); - } - #[test] - fn test_read_identifiers_streaming() { - assert_eq!(Parser::new("null".chars()).next(), Some(NullValue)); - assert_eq!(Parser::new("true".chars()).next(), Some(BooleanValue(true))); - assert_eq!(Parser::new("false".chars()).next(), Some(BooleanValue(false))); - - assert_eq!(last_event("n"), Error(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(last_event("nul"), Error(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(last_event("t"), Error(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(last_event("truz"), Error(SyntaxError(InvalidSyntax, 1, 4))); - assert_eq!(last_event("f"), Error(SyntaxError(InvalidSyntax, 1, 2))); - assert_eq!(last_event("faz"), Error(SyntaxError(InvalidSyntax, 1, 3))); - } - - #[test] - fn test_stack() { - let mut stack = Stack::new(); - - assert!(stack.is_empty()); - assert!(stack.len() == 0); - assert!(!stack.last_is_index()); - - stack.push_index(0); - stack.bump_index(); - - assert!(stack.len() == 1); - assert!(stack.is_equal_to(&[Index(1)])); - assert!(stack.starts_with(&[Index(1)])); - assert!(stack.ends_with(&[Index(1)])); - assert!(stack.last_is_index()); - assert!(stack.get(0) == Index(1)); - - stack.push_key("foo".to_string()); - - assert!(stack.len() == 2); - assert!(stack.is_equal_to(&[Index(1), Key("foo")])); - assert!(stack.starts_with(&[Index(1), Key("foo")])); - assert!(stack.starts_with(&[Index(1)])); - assert!(stack.ends_with(&[Index(1), Key("foo")])); - assert!(stack.ends_with(&[Key("foo")])); - assert!(!stack.last_is_index()); - assert!(stack.get(0) == Index(1)); - assert!(stack.get(1) == Key("foo")); - - stack.push_key("bar".to_string()); - - assert!(stack.len() == 3); - assert!(stack.is_equal_to(&[Index(1), Key("foo"), Key("bar")])); - assert!(stack.starts_with(&[Index(1)])); - assert!(stack.starts_with(&[Index(1), Key("foo")])); - assert!(stack.starts_with(&[Index(1), Key("foo"), Key("bar")])); - assert!(stack.ends_with(&[Key("bar")])); - assert!(stack.ends_with(&[Key("foo"), Key("bar")])); - assert!(stack.ends_with(&[Index(1), Key("foo"), Key("bar")])); - assert!(!stack.last_is_index()); - assert!(stack.get(0) == Index(1)); - assert!(stack.get(1) == Key("foo")); - assert!(stack.get(2) == Key("bar")); - - stack.pop(); - - assert!(stack.len() == 2); - assert!(stack.is_equal_to(&[Index(1), Key("foo")])); - assert!(stack.starts_with(&[Index(1), Key("foo")])); - assert!(stack.starts_with(&[Index(1)])); - assert!(stack.ends_with(&[Index(1), Key("foo")])); - assert!(stack.ends_with(&[Key("foo")])); - assert!(!stack.last_is_index()); - assert!(stack.get(0) == Index(1)); - assert!(stack.get(1) == Key("foo")); - } - - #[test] - fn test_to_json() { - use std::collections::{HashMap,BTreeMap}; - use super::ToJson; - - let array2 = Array(vec!(U64(1), U64(2))); - let array3 = Array(vec!(U64(1), U64(2), U64(3))); - let object = { - let mut tree_map = BTreeMap::new(); - tree_map.insert("a".to_string(), U64(1)); - tree_map.insert("b".to_string(), U64(2)); - Object(tree_map) - }; - - assert_eq!(array2.to_json(), array2); - assert_eq!(object.to_json(), object); - assert_eq!(3_i.to_json(), I64(3)); - assert_eq!(4_i8.to_json(), I64(4)); - assert_eq!(5_i16.to_json(), I64(5)); - assert_eq!(6_i32.to_json(), I64(6)); - assert_eq!(7_i64.to_json(), I64(7)); - assert_eq!(8_u.to_json(), U64(8)); - assert_eq!(9_u8.to_json(), U64(9)); - assert_eq!(10_u16.to_json(), U64(10)); - assert_eq!(11_u32.to_json(), U64(11)); - assert_eq!(12_u64.to_json(), U64(12)); - assert_eq!(13.0_f32.to_json(), F64(13.0_f64)); - assert_eq!(14.0_f64.to_json(), F64(14.0_f64)); - assert_eq!(().to_json(), Null); - assert_eq!(f32::INFINITY.to_json(), Null); - assert_eq!(f64::NAN.to_json(), Null); - assert_eq!(true.to_json(), Boolean(true)); - assert_eq!(false.to_json(), Boolean(false)); - assert_eq!("abc".to_json(), String("abc".to_string())); - assert_eq!("abc".to_string().to_json(), String("abc".to_string())); - assert_eq!((1u, 2u).to_json(), array2); - assert_eq!((1u, 2u, 3u).to_json(), array3); - assert_eq!([1u, 2].to_json(), array2); - assert_eq!((&[1u, 2, 3]).to_json(), array3); - assert_eq!((vec![1u, 2]).to_json(), array2); - assert_eq!(vec!(1u, 2, 3).to_json(), array3); - let mut tree_map = BTreeMap::new(); - tree_map.insert("a".to_string(), 1u); - tree_map.insert("b".to_string(), 2); - assert_eq!(tree_map.to_json(), object); - let mut hash_map = HashMap::new(); - hash_map.insert("a".to_string(), 1u); - hash_map.insert("b".to_string(), 2); - assert_eq!(hash_map.to_json(), object); - assert_eq!(Some(15i).to_json(), I64(15)); - assert_eq!(Some(15u).to_json(), U64(15)); - assert_eq!(None::.to_json(), Null); - } - - #[bench] - fn bench_streaming_small(b: &mut Bencher) { - b.iter( || { - let mut parser = Parser::new( - r#"{ - "a": 1.0, - "b": [ - true, - "foo\nbar", - { "c": {"d": null} } - ] - }"#.chars() - ); - loop { - match parser.next() { - None => return, - _ => {} - } - } - }); - } - #[bench] - fn bench_small(b: &mut Bencher) { - b.iter( || { - let _ = from_str(r#"{ - "a": 1.0, - "b": [ - true, - "foo\nbar", - { "c": {"d": null} } - ] - }"#); - }); - } - - fn big_json() -> string::String { - let mut src = "[\n".to_string(); - for _ in range(0i, 500) { - src.push_str(r#"{ "a": true, "b": null, "c":3.1415, "d": "Hello world", "e": \ - [1,2,3]},"#); - } - src.push_str("{}]"); - return src; - } - - #[bench] - fn bench_streaming_large(b: &mut Bencher) { - let src = big_json(); - b.iter( || { - let mut parser = Parser::new(src.chars()); - loop { - match parser.next() { - None => return, - _ => {} - } - } - }); - } - #[bench] - fn bench_large(b: &mut Bencher) { - let src = big_json(); - b.iter( || { let _ = from_str(src.as_slice()); }); - } -} diff --git a/src/libserialize/lib.rs b/src/libserialize/lib.rs index 8fe15f00ded..3dfed466e60 100644 --- a/src/libserialize/lib.rs +++ b/src/libserialize/lib.rs @@ -23,48 +23,23 @@ Core encoding and decoding interfaces. html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] -#![feature(macro_rules, default_type_params, phase, slicing_syntax, globs)] -#![feature(unboxed_closures)] -#![feature(associated_types)] +#![feature(slicing_syntax)] // test harness access -#[cfg(test)] -extern crate test; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; +#[cfg(test)] extern crate test; +#[macro_use] extern crate log; extern crate unicode; - extern crate collections; pub use self::serialize::{Decoder, Encoder, Decodable, Encodable, DecoderHelpers, EncoderHelpers}; -#[cfg(stage0)] -#[path = "serialize_stage0.rs"] -mod serialize; -#[cfg(not(stage0))] mod serialize; - -#[cfg(stage0)] -#[path = "collection_impls_stage0.rs"] -mod collection_impls; -#[cfg(not(stage0))] mod collection_impls; pub mod base64; pub mod hex; - -#[cfg(stage0)] -#[path = "json_stage0.rs"] -pub mod json; -#[cfg(not(stage0))] pub mod json; mod rustc_serialize { diff --git a/src/libserialize/serialize_stage0.rs b/src/libserialize/serialize_stage0.rs deleted file mode 100644 index 87ff5922c1a..00000000000 --- a/src/libserialize/serialize_stage0.rs +++ /dev/null @@ -1,630 +0,0 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Support code for encoding and decoding types. - -/* -Core encoding and decoding interfaces. -*/ - -use std::ops::FullRange; -use std::path; -use std::rc::Rc; -use std::cell::{Cell, RefCell}; -use std::sync::Arc; - -pub trait Encoder { - // Primitive types: - fn emit_nil(&mut self) -> Result<(), E>; - fn emit_uint(&mut self, v: uint) -> Result<(), E>; - fn emit_u64(&mut self, v: u64) -> Result<(), E>; - fn emit_u32(&mut self, v: u32) -> Result<(), E>; - fn emit_u16(&mut self, v: u16) -> Result<(), E>; - fn emit_u8(&mut self, v: u8) -> Result<(), E>; - fn emit_int(&mut self, v: int) -> Result<(), E>; - fn emit_i64(&mut self, v: i64) -> Result<(), E>; - fn emit_i32(&mut self, v: i32) -> Result<(), E>; - fn emit_i16(&mut self, v: i16) -> Result<(), E>; - fn emit_i8(&mut self, v: i8) -> Result<(), E>; - fn emit_bool(&mut self, v: bool) -> Result<(), E>; - fn emit_f64(&mut self, v: f64) -> Result<(), E>; - fn emit_f32(&mut self, v: f32) -> Result<(), E>; - fn emit_char(&mut self, v: char) -> Result<(), E>; - fn emit_str(&mut self, v: &str) -> Result<(), E>; - - // Compound types: - fn emit_enum(&mut self, name: &str, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - fn emit_enum_variant(&mut self, v_name: &str, - v_id: uint, - len: uint, - f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_enum_variant_arg(&mut self, a_idx: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - fn emit_enum_struct_variant(&mut self, v_name: &str, - v_id: uint, - len: uint, - f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_enum_struct_variant_field(&mut self, - f_name: &str, - f_idx: uint, - f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - fn emit_struct(&mut self, name: &str, len: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_struct_field(&mut self, f_name: &str, f_idx: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - fn emit_tuple(&mut self, len: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_tuple_arg(&mut self, idx: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - fn emit_tuple_struct(&mut self, name: &str, len: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_tuple_struct_arg(&mut self, f_idx: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - // Specialized types: - fn emit_option(&mut self, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_option_none(&mut self) -> Result<(), E>; - fn emit_option_some(&mut self, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - fn emit_seq(&mut self, len: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_seq_elt(&mut self, idx: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - - fn emit_map(&mut self, len: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; - fn emit_map_elt_key(&mut self, idx: uint, f: F) -> Result<(), E> where - F: FnMut(&mut Self) -> Result<(), E>; - fn emit_map_elt_val(&mut self, idx: uint, f: F) -> Result<(), E> where - F: FnOnce(&mut Self) -> Result<(), E>; -} - -pub trait Decoder { - // Primitive types: - fn read_nil(&mut self) -> Result<(), E>; - fn read_uint(&mut self) -> Result; - fn read_u64(&mut self) -> Result; - fn read_u32(&mut self) -> Result; - fn read_u16(&mut self) -> Result; - fn read_u8(&mut self) -> Result; - fn read_int(&mut self) -> Result; - fn read_i64(&mut self) -> Result; - fn read_i32(&mut self) -> Result; - fn read_i16(&mut self) -> Result; - fn read_i8(&mut self) -> Result; - fn read_bool(&mut self) -> Result; - fn read_f64(&mut self) -> Result; - fn read_f32(&mut self) -> Result; - fn read_char(&mut self) -> Result; - fn read_str(&mut self) -> Result; - - // Compound types: - fn read_enum(&mut self, name: &str, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - - fn read_enum_variant(&mut self, names: &[&str], f: F) -> Result where - F: FnMut(&mut Self, uint) -> Result; - fn read_enum_variant_arg(&mut self, a_idx: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - - fn read_enum_struct_variant(&mut self, names: &[&str], f: F) -> Result where - F: FnMut(&mut Self, uint) -> Result; - fn read_enum_struct_variant_field(&mut self, - &f_name: &str, - f_idx: uint, - f: F) - -> Result where - F: FnOnce(&mut Self) -> Result; - - fn read_struct(&mut self, s_name: &str, len: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - fn read_struct_field(&mut self, - f_name: &str, - f_idx: uint, - f: F) - -> Result where - F: FnOnce(&mut Self) -> Result; - - fn read_tuple(&mut self, len: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - fn read_tuple_arg(&mut self, a_idx: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - - fn read_tuple_struct(&mut self, s_name: &str, len: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - fn read_tuple_struct_arg(&mut self, a_idx: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - - // Specialized types: - fn read_option(&mut self, f: F) -> Result where - F: FnMut(&mut Self, bool) -> Result; - - fn read_seq(&mut self, f: F) -> Result where - F: FnOnce(&mut Self, uint) -> Result; - fn read_seq_elt(&mut self, idx: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - - fn read_map(&mut self, f: F) -> Result where - F: FnOnce(&mut Self, uint) -> Result; - fn read_map_elt_key(&mut self, idx: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - fn read_map_elt_val(&mut self, idx: uint, f: F) -> Result where - F: FnOnce(&mut Self) -> Result; - - // Failure - fn error(&mut self, err: &str) -> E; -} - -pub trait Encodable, E> { - fn encode(&self, s: &mut S) -> Result<(), E>; -} - -pub trait Decodable, E> { - fn decode(d: &mut D) -> Result; -} - -impl> Encodable for uint { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_uint(*self) - } -} - -impl> Decodable for uint { - fn decode(d: &mut D) -> Result { - d.read_uint() - } -} - -impl> Encodable for u8 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_u8(*self) - } -} - -impl> Decodable for u8 { - fn decode(d: &mut D) -> Result { - d.read_u8() - } -} - -impl> Encodable for u16 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_u16(*self) - } -} - -impl> Decodable for u16 { - fn decode(d: &mut D) -> Result { - d.read_u16() - } -} - -impl> Encodable for u32 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_u32(*self) - } -} - -impl> Decodable for u32 { - fn decode(d: &mut D) -> Result { - d.read_u32() - } -} - -impl> Encodable for u64 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_u64(*self) - } -} - -impl> Decodable for u64 { - fn decode(d: &mut D) -> Result { - d.read_u64() - } -} - -impl> Encodable for int { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_int(*self) - } -} - -impl> Decodable for int { - fn decode(d: &mut D) -> Result { - d.read_int() - } -} - -impl> Encodable for i8 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_i8(*self) - } -} - -impl> Decodable for i8 { - fn decode(d: &mut D) -> Result { - d.read_i8() - } -} - -impl> Encodable for i16 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_i16(*self) - } -} - -impl> Decodable for i16 { - fn decode(d: &mut D) -> Result { - d.read_i16() - } -} - -impl> Encodable for i32 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_i32(*self) - } -} - -impl> Decodable for i32 { - fn decode(d: &mut D) -> Result { - d.read_i32() - } -} - -impl> Encodable for i64 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_i64(*self) - } -} - -impl> Decodable for i64 { - fn decode(d: &mut D) -> Result { - d.read_i64() - } -} - -impl> Encodable for str { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(self) - } -} - -impl> Encodable for String { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(self.index(&FullRange)) - } -} - -impl> Decodable for String { - fn decode(d: &mut D) -> Result { - d.read_str() - } -} - -impl> Encodable for f32 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_f32(*self) - } -} - -impl> Decodable for f32 { - fn decode(d: &mut D) -> Result { - d.read_f32() - } -} - -impl> Encodable for f64 { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_f64(*self) - } -} - -impl> Decodable for f64 { - fn decode(d: &mut D) -> Result { - d.read_f64() - } -} - -impl> Encodable for bool { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_bool(*self) - } -} - -impl> Decodable for bool { - fn decode(d: &mut D) -> Result { - d.read_bool() - } -} - -impl> Encodable for char { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_char(*self) - } -} - -impl> Decodable for char { - fn decode(d: &mut D) -> Result { - d.read_char() - } -} - -impl> Encodable for () { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_nil() - } -} - -impl> Decodable for () { - fn decode(d: &mut D) -> Result<(), E> { - d.read_nil() - } -} - -impl<'a, E, S: Encoder, T: ?Sized + Encodable> Encodable for &'a T { - fn encode(&self, s: &mut S) -> Result<(), E> { - (**self).encode(s) - } -} - -impl, T: ?Sized + Encodable> Encodable for Box { - fn encode(&self, s: &mut S) -> Result<(), E> { - (**self).encode(s) - } -} - -impl, T: Decodable> Decodable for Box { - fn decode(d: &mut D) -> Result, E> { - Ok(box try!(Decodable::decode(d))) - } -} - -impl, T: Decodable> Decodable for Box<[T]> { - fn decode(d: &mut D) -> Result, E> { - let v: Vec = try!(Decodable::decode(d)); - Ok(v.into_boxed_slice()) - } -} - -impl,T:Encodable> Encodable for Rc { - #[inline] - fn encode(&self, s: &mut S) -> Result<(), E> { - (**self).encode(s) - } -} - -impl,T:Decodable> Decodable for Rc { - #[inline] - fn decode(d: &mut D) -> Result, E> { - Ok(Rc::new(try!(Decodable::decode(d)))) - } -} - -impl,T:Encodable> Encodable for [T] { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_seq(self.len(), |s| { - for (i, e) in self.iter().enumerate() { - try!(s.emit_seq_elt(i, |s| e.encode(s))) - } - Ok(()) - }) - } -} - -impl,T:Encodable> Encodable for Vec { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_seq(self.len(), |s| { - for (i, e) in self.iter().enumerate() { - try!(s.emit_seq_elt(i, |s| e.encode(s))) - } - Ok(()) - }) - } -} - -impl,T:Decodable> Decodable for Vec { - fn decode(d: &mut D) -> Result, E> { - d.read_seq(|d, len| { - let mut v = Vec::with_capacity(len); - for i in range(0, len) { - v.push(try!(d.read_seq_elt(i, |d| Decodable::decode(d)))); - } - Ok(v) - }) - } -} - -impl,T:Encodable> Encodable for Option { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_option(|s| { - match *self { - None => s.emit_option_none(), - Some(ref v) => s.emit_option_some(|s| v.encode(s)), - } - }) - } -} - -impl,T:Decodable> Decodable for Option { - fn decode(d: &mut D) -> Result, E> { - d.read_option(|d, b| { - if b { - Ok(Some(try!(Decodable::decode(d)))) - } else { - Ok(None) - } - }) - } -} - -macro_rules! peel { - ($name:ident, $($other:ident,)*) => (tuple! { $($other,)* }) -} - -/// Evaluates to the number of identifiers passed to it, for example: `count_idents!(a, b, c) == 3 -macro_rules! count_idents { - () => { 0u }; - ($_i:ident $(, $rest:ident)*) => { 1 + count_idents!($($rest),*) } -} - -macro_rules! tuple { - () => (); - ( $($name:ident,)+ ) => ( - impl,$($name:Decodable),*> Decodable for ($($name,)*) { - #[allow(non_snake_case)] - fn decode(d: &mut D) -> Result<($($name,)*), E> { - let len: uint = count_idents!($($name),*); - d.read_tuple(len, |d| { - let mut i = 0; - let ret = ($(try!(d.read_tuple_arg({ i+=1; i-1 }, |d| -> Result<$name,E> { - Decodable::decode(d) - })),)*); - return Ok(ret); - }) - } - } - impl,$($name:Encodable),*> Encodable for ($($name,)*) { - #[allow(non_snake_case)] - fn encode(&self, s: &mut S) -> Result<(), E> { - let ($(ref $name,)*) = *self; - let mut n = 0; - $(let $name = $name; n += 1;)* - s.emit_tuple(n, |s| { - let mut i = 0; - $(try!(s.emit_tuple_arg({ i+=1; i-1 }, |s| $name.encode(s)));)* - Ok(()) - }) - } - } - peel! { $($name,)* } - ) -} - -tuple! { T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, } - -impl> Encodable for path::posix::Path { - fn encode(&self, e: &mut S) -> Result<(), E> { - self.as_vec().encode(e) - } -} - -impl> Decodable for path::posix::Path { - fn decode(d: &mut D) -> Result { - let bytes: Vec = try!(Decodable::decode(d)); - Ok(path::posix::Path::new(bytes)) - } -} - -impl> Encodable for path::windows::Path { - fn encode(&self, e: &mut S) -> Result<(), E> { - self.as_vec().encode(e) - } -} - -impl> Decodable for path::windows::Path { - fn decode(d: &mut D) -> Result { - let bytes: Vec = try!(Decodable::decode(d)); - Ok(path::windows::Path::new(bytes)) - } -} - -impl, T: Encodable + Copy> Encodable for Cell { - fn encode(&self, s: &mut S) -> Result<(), E> { - self.get().encode(s) - } -} - -impl, T: Decodable + Copy> Decodable for Cell { - fn decode(d: &mut D) -> Result, E> { - Ok(Cell::new(try!(Decodable::decode(d)))) - } -} - -// FIXME: #15036 -// Should use `try_borrow`, returning a -// `encoder.error("attempting to Encode borrowed RefCell")` -// from `encode` when `try_borrow` returns `None`. - -impl, T: Encodable> Encodable for RefCell { - fn encode(&self, s: &mut S) -> Result<(), E> { - self.borrow().encode(s) - } -} - -impl, T: Decodable> Decodable for RefCell { - fn decode(d: &mut D) -> Result, E> { - Ok(RefCell::new(try!(Decodable::decode(d)))) - } -} - -impl, T:Encodable> Encodable for Arc { - fn encode(&self, s: &mut S) -> Result<(), E> { - (**self).encode(s) - } -} - -impl,T:Decodable+Send+Sync> Decodable for Arc { - fn decode(d: &mut D) -> Result, E> { - Ok(Arc::new(try!(Decodable::decode(d)))) - } -} - -// ___________________________________________________________________________ -// Helper routines - -pub trait EncoderHelpers { - fn emit_from_vec(&mut self, v: &[T], f: F) -> Result<(), E> where - F: FnMut(&mut Self, &T) -> Result<(), E>; -} - -impl> EncoderHelpers for S { - fn emit_from_vec(&mut self, v: &[T], mut f: F) -> Result<(), E> where - F: FnMut(&mut S, &T) -> Result<(), E>, - { - self.emit_seq(v.len(), |this| { - for (i, e) in v.iter().enumerate() { - try!(this.emit_seq_elt(i, |this| { - f(this, e) - })); - } - Ok(()) - }) - } -} - -pub trait DecoderHelpers { - fn read_to_vec(&mut self, f: F) -> Result, E> where - F: FnMut(&mut Self) -> Result; -} - -impl> DecoderHelpers for D { - fn read_to_vec(&mut self, mut f: F) -> Result, E> where F: - FnMut(&mut D) -> Result, - { - self.read_seq(|this, len| { - let mut v = Vec::with_capacity(len); - for i in range(0, len) { - v.push(try!(this.read_seq_elt(i, |this| f(this)))); - } - Ok(v) - }) - } -} diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index 10e8ca6c622..e598923f11c 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -22,9 +22,6 @@ use iter::{Iterator, IteratorExt, FromIterator, Map, Chain, Extend}; use ops::{BitOr, BitAnd, BitXor, Sub}; use option::Option::{Some, None, self}; -// NOTE: for old macros; remove after the next snapshot -#[cfg(stage0)] use result::Result::{Ok, Err}; - use super::map::{self, HashMap, Keys, INITIAL_CAPACITY}; // Future Optimization (FIXME!) diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index c54a5ffa665..74c503e6f2b 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -23,9 +23,6 @@ use slice::{SliceExt}; use slice; use vec::Vec; -// NOTE: for old macros; remove after the next snapshot -#[cfg(stage0)] use result::Result::Err; - /// Wraps a Reader and buffers input from it /// /// It can be excessively inefficient to work directly with a `Reader`. For diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 010cb814732..5de66c02b53 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -285,8 +285,7 @@ pub mod stdio; pub mod timer; pub mod util; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod test; /// The default buffer size for various I/O operations diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index b9f226c5aca..25cc574bb5d 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -104,42 +104,24 @@ html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] -#![feature(macro_rules, globs, linkage, thread_local, asm)] -#![feature(default_type_params, phase, lang_items, unsafe_destructor)] +#![feature(linkage, thread_local, asm)] +#![feature(phase, lang_items, unsafe_destructor)] #![feature(slicing_syntax, unboxed_closures)] -#![feature(old_orphan_check)] -#![feature(associated_types)] // Don't link to std. We are std. #![no_std] #![deny(missing_docs)] -#![reexport_test_harness_main = "test_main"] - -#[cfg(all(test, stage0))] -#[phase(plugin, link)] -extern crate log; - -#[cfg(all(test, not(stage0)))] +#[cfg(test)] #[macro_use] extern crate log; -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate core; - -#[cfg(not(stage0))] #[macro_use] #[macro_reexport(assert, assert_eq, debug_assert, debug_assert_eq, - unreachable, unimplemented, write, writeln)] + unreachable, unimplemented, write, writeln)] extern crate core; -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate "collections" as core_collections; - -#[cfg(not(stage0))] #[macro_use] #[macro_reexport(vec)] extern crate "collections" as core_collections; @@ -190,18 +172,10 @@ pub use unicode::char; /* Exported macros */ -#[cfg(stage0)] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] -pub mod macros_stage0; - -#[cfg(not(stage0))] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod macros; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod bitflags; mod rtdeps; @@ -214,18 +188,15 @@ pub mod prelude; /* Primitive types */ #[path = "num/float_macros.rs"] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod float_macros; #[path = "num/int_macros.rs"] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod int_macros; #[path = "num/uint_macros.rs"] -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod uint_macros; #[path = "num/int.rs"] pub mod int; @@ -253,8 +224,7 @@ pub mod num; /* Runtime and platform support */ -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod thread_local; pub mod dynamic_lib; diff --git a/src/libstd/macros_stage0.rs b/src/libstd/macros_stage0.rs deleted file mode 100644 index 48d62e73e13..00000000000 --- a/src/libstd/macros_stage0.rs +++ /dev/null @@ -1,648 +0,0 @@ -// Copyright 2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Standard library macros -//! -//! This modules contains a set of macros which are exported from the standard -//! library. Each macro is available for use when linking against the standard -//! library. - -#![experimental] - -/// The entry point for panic of Rust tasks. -/// -/// This macro is used to inject panic into a Rust task, causing the task to -/// unwind and panic entirely. Each task's panic can be reaped as the -/// `Box` type, and the single-argument form of the `panic!` macro will be -/// the value which is transmitted. -/// -/// The multi-argument form of this macro panics with a string and has the -/// `format!` syntax for building a string. -/// -/// # Example -/// -/// ```should_fail -/// # #![allow(unreachable_code)] -/// panic!(); -/// panic!("this is a terrible mistake!"); -/// panic!(4i); // panic with the value of 4 to be collected elsewhere -/// panic!("this is a {} {message}", "fancy", message = "message"); -/// ``` -#[macro_export] -macro_rules! panic { - () => ({ - panic!("explicit panic") - }); - ($msg:expr) => ({ - // static requires less code at runtime, more constant data - static _FILE_LINE: (&'static str, uint) = (file!(), line!()); - ::std::rt::begin_unwind($msg, &_FILE_LINE) - }); - ($fmt:expr, $($arg:tt)*) => ({ - // The leading _'s are to avoid dead code warnings if this is - // used inside a dead function. Just `#[allow(dead_code)]` is - // insufficient, since the user may have - // `#[forbid(dead_code)]` and which cannot be overridden. - static _FILE_LINE: (&'static str, uint) = (file!(), line!()); - ::std::rt::begin_unwind_fmt(format_args!($fmt, $($arg)*), &_FILE_LINE) - - }); -} - -/// Ensure that a boolean expression is `true` at runtime. -/// -/// This will invoke the `panic!` macro if the provided expression cannot be -/// evaluated to `true` at runtime. -/// -/// # Example -/// -/// ``` -/// // the panic message for these assertions is the stringified value of the -/// // expression given. -/// assert!(true); -/// # fn some_computation() -> bool { true } -/// assert!(some_computation()); -/// -/// // assert with a custom message -/// # let x = true; -/// assert!(x, "x wasn't true!"); -/// # let a = 3i; let b = 27i; -/// assert!(a + b == 30, "a = {}, b = {}", a, b); -/// ``` -#[macro_export] -macro_rules! assert { - ($cond:expr) => ( - if !$cond { - panic!(concat!("assertion failed: ", stringify!($cond))) - } - ); - ($cond:expr, $($arg:expr),+) => ( - if !$cond { - panic!($($arg),+) - } - ); -} - -/// Asserts that two expressions are equal to each other, testing equality in -/// both directions. -/// -/// On panic, this macro will print the values of the expressions. -/// -/// # Example -/// -/// ``` -/// let a = 3i; -/// let b = 1i + 2i; -/// assert_eq!(a, b); -/// ``` -#[macro_export] -macro_rules! assert_eq { - ($left:expr , $right:expr) => ({ - match (&($left), &($right)) { - (left_val, right_val) => { - // check both directions of equality.... - if !((*left_val == *right_val) && - (*right_val == *left_val)) { - panic!("assertion failed: `(left == right) && (right == left)` \ - (left: `{}`, right: `{}`)", *left_val, *right_val) - } - } - } - }) -} - -/// Ensure that a boolean expression is `true` at runtime. -/// -/// This will invoke the `panic!` macro if the provided expression cannot be -/// evaluated to `true` at runtime. -/// -/// Unlike `assert!`, `debug_assert!` statements can be disabled by passing -/// `--cfg ndebug` to the compiler. This makes `debug_assert!` useful for -/// checks that are too expensive to be present in a release build but may be -/// helpful during development. -/// -/// # Example -/// -/// ``` -/// // the panic message for these assertions is the stringified value of the -/// // expression given. -/// debug_assert!(true); -/// # fn some_expensive_computation() -> bool { true } -/// debug_assert!(some_expensive_computation()); -/// -/// // assert with a custom message -/// # let x = true; -/// debug_assert!(x, "x wasn't true!"); -/// # let a = 3i; let b = 27i; -/// debug_assert!(a + b == 30, "a = {}, b = {}", a, b); -/// ``` -#[macro_export] -macro_rules! debug_assert { - ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert!($($arg)*); }) -} - -/// Asserts that two expressions are equal to each other, testing equality in -/// both directions. -/// -/// On panic, this macro will print the values of the expressions. -/// -/// Unlike `assert_eq!`, `debug_assert_eq!` statements can be disabled by -/// passing `--cfg ndebug` to the compiler. This makes `debug_assert_eq!` -/// useful for checks that are too expensive to be present in a release build -/// but may be helpful during development. -/// -/// # Example -/// -/// ``` -/// let a = 3i; -/// let b = 1i + 2i; -/// debug_assert_eq!(a, b); -/// ``` -#[macro_export] -macro_rules! debug_assert_eq { - ($($arg:tt)*) => (if cfg!(not(ndebug)) { assert_eq!($($arg)*); }) -} - -/// A utility macro for indicating unreachable code. -/// -/// This is useful any time that the compiler can't determine that some code is unreachable. For -/// example: -/// -/// * Match arms with guard conditions. -/// * Loops that dynamically terminate. -/// * Iterators that dynamically terminate. -/// -/// # Panics -/// -/// This will always panic. -/// -/// # Examples -/// -/// Match arms: -/// -/// ```rust -/// fn foo(x: Option) { -/// match x { -/// Some(n) if n >= 0 => println!("Some(Non-negative)"), -/// Some(n) if n < 0 => println!("Some(Negative)"), -/// Some(_) => unreachable!(), // compile error if commented out -/// None => println!("None") -/// } -/// } -/// ``` -/// -/// Iterators: -/// -/// ```rust -/// fn divide_by_three(x: u32) -> u32 { // one of the poorest implementations of x/3 -/// for i in std::iter::count(0_u32, 1) { -/// if 3*i < i { panic!("u32 overflow"); } -/// if x < 3*i { return i-1; } -/// } -/// unreachable!(); -/// } -/// ``` -#[macro_export] -macro_rules! unreachable { - () => ({ - panic!("internal error: entered unreachable code") - }); - ($msg:expr) => ({ - unreachable!("{}", $msg) - }); - ($fmt:expr, $($arg:tt)*) => ({ - panic!(concat!("internal error: entered unreachable code: ", $fmt), $($arg)*) - }); -} - -/// A standardised placeholder for marking unfinished code. It panics with the -/// message `"not yet implemented"` when executed. -#[macro_export] -macro_rules! unimplemented { - () => (panic!("not yet implemented")) -} - -/// Use the syntax described in `std::fmt` to create a value of type `String`. -/// See `std::fmt` for more information. -/// -/// # Example -/// -/// ``` -/// format!("test"); -/// format!("hello {}", "world!"); -/// format!("x = {}, y = {y}", 10i, y = 30i); -/// ``` -#[macro_export] -#[stable] -macro_rules! format { - ($($arg:tt)*) => (::std::fmt::format(format_args!($($arg)*))) -} - -/// Use the `format!` syntax to write data into a buffer of type `&mut Writer`. -/// See `std::fmt` for more information. -/// -/// # Example -/// -/// ``` -/// # #![allow(unused_must_use)] -/// -/// let mut w = Vec::new(); -/// write!(&mut w, "test"); -/// write!(&mut w, "formatted {}", "arguments"); -/// ``` -#[macro_export] -#[stable] -macro_rules! write { - ($dst:expr, $($arg:tt)*) => ((&mut *$dst).write_fmt(format_args!($($arg)*))) -} - -/// Equivalent to the `write!` macro, except that a newline is appended after -/// the message is written. -#[macro_export] -#[stable] -macro_rules! writeln { - ($dst:expr, $fmt:expr $($arg:tt)*) => ( - write!($dst, concat!($fmt, "\n") $($arg)*) - ) -} - -/// Equivalent to the `println!` macro except that a newline is not printed at -/// the end of the message. -#[macro_export] -#[stable] -macro_rules! print { - ($($arg:tt)*) => (::std::io::stdio::print_args(format_args!($($arg)*))) -} - -/// Macro for printing to a task's stdout handle. -/// -/// Each task can override its stdout handle via `std::io::stdio::set_stdout`. -/// The syntax of this macro is the same as that used for `format!`. For more -/// information, see `std::fmt` and `std::io::stdio`. -/// -/// # Example -/// -/// ``` -/// println!("hello there!"); -/// println!("format {} arguments", "some"); -/// ``` -#[macro_export] -#[stable] -macro_rules! println { - ($($arg:tt)*) => (::std::io::stdio::println_args(format_args!($($arg)*))) -} - -/// Helper macro for unwrapping `Result` values while returning early with an -/// error if the value of the expression is `Err`. For more information, see -/// `std::io`. -#[macro_export] -macro_rules! try { - ($expr:expr) => ({ - match $expr { - Ok(val) => val, - Err(err) => return Err(::std::error::FromError::from_error(err)) - } - }) -} - -/// Create a `std::vec::Vec` containing the arguments. -#[macro_export] -macro_rules! vec { - ($($x:expr),*) => ({ - let xs: ::std::boxed::Box<[_]> = box [$($x),*]; - ::std::slice::SliceExt::into_vec(xs) - }); - ($($x:expr,)*) => (vec![$($x),*]) -} - -/// A macro to select an event from a number of receivers. -/// -/// This macro is used to wait for the first event to occur on a number of -/// receivers. It places no restrictions on the types of receivers given to -/// this macro, this can be viewed as a heterogeneous select. -/// -/// # Example -/// -/// ``` -/// use std::thread::Thread; -/// use std::sync::mpsc::channel; -/// -/// let (tx1, rx1) = channel(); -/// let (tx2, rx2) = channel(); -/// # fn long_running_task() {} -/// # fn calculate_the_answer() -> int { 42i } -/// -/// Thread::spawn(move|| { long_running_task(); tx1.send(()) }).detach(); -/// Thread::spawn(move|| { tx2.send(calculate_the_answer()) }).detach(); -/// -/// select! ( -/// _ = rx1.recv() => println!("the long running task finished first"), -/// answer = rx2.recv() => { -/// println!("the answer was: {}", answer.unwrap()); -/// } -/// ) -/// ``` -/// -/// For more information about select, see the `std::sync::mpsc::Select` structure. -#[macro_export] -#[experimental] -macro_rules! select { - ( - $($name:pat = $rx:ident.$meth:ident() => $code:expr),+ - ) => ({ - use std::sync::mpsc::Select; - let sel = Select::new(); - $( let mut $rx = sel.handle(&$rx); )+ - unsafe { - $( $rx.add(); )+ - } - let ret = sel.wait(); - $( if ret == $rx.id() { let $name = $rx.$meth(); $code } else )+ - { unreachable!() } - }) -} - -// When testing the standard library, we link to the liblog crate to get the -// logging macros. In doing so, the liblog crate was linked against the real -// version of libstd, and uses a different std::fmt module than the test crate -// uses. To get around this difference, we redefine the log!() macro here to be -// just a dumb version of what it should be. -#[cfg(test)] -macro_rules! log { - ($lvl:expr, $($args:tt)*) => ( - if log_enabled!($lvl) { println!($($args)*) } - ) -} - -/// Built-in macros to the compiler itself. -/// -/// These macros do not have any corresponding definition with a `macro_rules!` -/// macro, but are documented here. Their implementations can be found hardcoded -/// into libsyntax itself. -#[cfg(dox)] -pub mod builtin { - /// The core macro for formatted string creation & output. - /// - /// This macro produces a value of type `fmt::Arguments`. This value can be - /// passed to the functions in `std::fmt` for performing useful functions. - /// All other formatting macros (`format!`, `write!`, `println!`, etc) are - /// proxied through this one. - /// - /// For more information, see the documentation in `std::fmt`. - /// - /// # Example - /// - /// ```rust - /// use std::fmt; - /// - /// let s = fmt::format(format_args!("hello {}", "world")); - /// assert_eq!(s, format!("hello {}", "world")); - /// - /// ``` - #[macro_export] - macro_rules! format_args { ($fmt:expr $($args:tt)*) => ({ - /* compiler built-in */ - }) } - - /// Inspect an environment variable at compile time. - /// - /// This macro will expand to the value of the named environment variable at - /// compile time, yielding an expression of type `&'static str`. - /// - /// If the environment variable is not defined, then a compilation error - /// will be emitted. To not emit a compile error, use the `option_env!` - /// macro instead. - /// - /// # Example - /// - /// ```rust - /// let path: &'static str = env!("PATH"); - /// println!("the $PATH variable at the time of compiling was: {}", path); - /// ``` - #[macro_export] - macro_rules! env { ($name:expr) => ({ /* compiler built-in */ }) } - - /// Optionally inspect an environment variable at compile time. - /// - /// If the named environment variable is present at compile time, this will - /// expand into an expression of type `Option<&'static str>` whose value is - /// `Some` of the value of the environment variable. If the environment - /// variable is not present, then this will expand to `None`. - /// - /// A compile time error is never emitted when using this macro regardless - /// of whether the environment variable is present or not. - /// - /// # Example - /// - /// ```rust - /// let key: Option<&'static str> = option_env!("SECRET_KEY"); - /// println!("the secret key might be: {}", key); - /// ``` - #[macro_export] - macro_rules! option_env { ($name:expr) => ({ /* compiler built-in */ }) } - - /// Concatenate literals into a static byte slice. - /// - /// This macro takes any number of comma-separated literal expressions, - /// yielding an expression of type `&'static [u8]` which is the - /// concatenation (left to right) of all the literals in their byte format. - /// - /// This extension currently only supports string literals, character - /// literals, and integers less than 256. The byte slice returned is the - /// utf8-encoding of strings and characters. - /// - /// # Example - /// - /// ``` - /// let rust = bytes!("r", 'u', "st", 255); - /// assert_eq!(rust[1], b'u'); - /// assert_eq!(rust[4], 255); - /// ``` - #[macro_export] - macro_rules! bytes { ($($e:expr),*) => ({ /* compiler built-in */ }) } - - /// Concatenate identifiers into one identifier. - /// - /// This macro takes any number of comma-separated identifiers, and - /// concatenates them all into one, yielding an expression which is a new - /// identifier. Note that hygiene makes it such that this macro cannot - /// capture local variables, and macros are only allowed in item, - /// statement or expression position, meaning this macro may be difficult to - /// use in some situations. - /// - /// # Example - /// - /// ``` - /// #![feature(concat_idents)] - /// - /// # fn main() { - /// fn foobar() -> int { 23 } - /// - /// let f = concat_idents!(foo, bar); - /// println!("{}", f()); - /// # } - /// ``` - #[macro_export] - macro_rules! concat_idents { - ($($e:ident),*) => ({ /* compiler built-in */ }) - } - - /// Concatenates literals into a static string slice. - /// - /// This macro takes any number of comma-separated literals, yielding an - /// expression of type `&'static str` which represents all of the literals - /// concatenated left-to-right. - /// - /// Integer and floating point literals are stringified in order to be - /// concatenated. - /// - /// # Example - /// - /// ``` - /// let s = concat!("test", 10i, 'b', true); - /// assert_eq!(s, "test10btrue"); - /// ``` - #[macro_export] - macro_rules! concat { ($($e:expr),*) => ({ /* compiler built-in */ }) } - - /// A macro which expands to the line number on which it was invoked. - /// - /// The expanded expression has type `uint`, and the returned line is not - /// the invocation of the `line!()` macro itself, but rather the first macro - /// invocation leading up to the invocation of the `line!()` macro. - /// - /// # Example - /// - /// ``` - /// let current_line = line!(); - /// println!("defined on line: {}", current_line); - /// ``` - #[macro_export] - macro_rules! line { () => ({ /* compiler built-in */ }) } - - /// A macro which expands to the column number on which it was invoked. - /// - /// The expanded expression has type `uint`, and the returned column is not - /// the invocation of the `column!()` macro itself, but rather the first macro - /// invocation leading up to the invocation of the `column!()` macro. - /// - /// # Example - /// - /// ``` - /// let current_col = column!(); - /// println!("defined on column: {}", current_col); - /// ``` - #[macro_export] - macro_rules! column { () => ({ /* compiler built-in */ }) } - - /// A macro which expands to the file name from which it was invoked. - /// - /// The expanded expression has type `&'static str`, and the returned file - /// is not the invocation of the `file!()` macro itself, but rather the - /// first macro invocation leading up to the invocation of the `file!()` - /// macro. - /// - /// # Example - /// - /// ``` - /// let this_file = file!(); - /// println!("defined in file: {}", this_file); - /// ``` - #[macro_export] - macro_rules! file { () => ({ /* compiler built-in */ }) } - - /// A macro which stringifies its argument. - /// - /// This macro will yield an expression of type `&'static str` which is the - /// stringification of all the tokens passed to the macro. No restrictions - /// are placed on the syntax of the macro invocation itself. - /// - /// # Example - /// - /// ``` - /// let one_plus_one = stringify!(1 + 1); - /// assert_eq!(one_plus_one, "1 + 1"); - /// ``` - #[macro_export] - macro_rules! stringify { ($t:tt) => ({ /* compiler built-in */ }) } - - /// Includes a utf8-encoded file as a string. - /// - /// This macro will yield an expression of type `&'static str` which is the - /// contents of the filename specified. The file is located relative to the - /// current file (similarly to how modules are found), - /// - /// # Example - /// - /// ```rust,ignore - /// let secret_key = include_str!("secret-key.ascii"); - /// ``` - #[macro_export] - macro_rules! include_str { ($file:expr) => ({ /* compiler built-in */ }) } - - /// Includes a file as a byte slice. - /// - /// This macro will yield an expression of type `&'static [u8]` which is - /// the contents of the filename specified. The file is located relative to - /// the current file (similarly to how modules are found), - /// - /// # Example - /// - /// ```rust,ignore - /// let secret_key = include_bytes!("secret-key.bin"); - /// ``` - #[macro_export] - macro_rules! include_bytes { ($file:expr) => ({ /* compiler built-in */ }) } - - /// Deprecated alias for `include_bytes!()`. - #[macro_export] - macro_rules! include_bin { ($file:expr) => ({ /* compiler built-in */}) } - - /// Expands to a string that represents the current module path. - /// - /// The current module path can be thought of as the hierarchy of modules - /// leading back up to the crate root. The first component of the path - /// returned is the name of the crate currently being compiled. - /// - /// # Example - /// - /// ```rust - /// mod test { - /// pub fn foo() { - /// assert!(module_path!().ends_with("test")); - /// } - /// } - /// - /// test::foo(); - /// ``` - #[macro_export] - macro_rules! module_path { () => ({ /* compiler built-in */ }) } - - /// Boolean evaluation of configuration flags. - /// - /// In addition to the `#[cfg]` attribute, this macro is provided to allow - /// boolean expression evaluation of configuration flags. This frequently - /// leads to less duplicated code. - /// - /// The syntax given to this macro is the same syntax as the `cfg` - /// attribute. - /// - /// # Example - /// - /// ```rust - /// let my_directory = if cfg!(windows) { - /// "windows-specific-directory" - /// } else { - /// "unix-directory" - /// }; - /// ``` - #[macro_export] - macro_rules! cfg { ($cfg:tt) => ({ /* compiler built-in */ }) } -} diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs index a79a6e35ebc..b64da403c8b 100644 --- a/src/libstd/rand/os.rs +++ b/src/libstd/rand/os.rs @@ -28,9 +28,6 @@ mod imp { use mem; use os::errno; - // NOTE: for old macros; remove after the next snapshot - #[cfg(stage0)] use result::Result::Err; - #[cfg(all(target_os = "linux", any(target_arch = "x86_64", target_arch = "x86", diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index e556888a470..2d54fc36ca8 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -39,8 +39,7 @@ pub use alloc::heap; pub mod backtrace; // Internals -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] mod macros; // These should be refactored/moved/made private over time diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index e0cbaa8ca50..c11162c09bc 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -40,8 +40,7 @@ use prelude::v1::*; use cell::UnsafeCell; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod scoped; // Sure wish we had macro hygiene, no? diff --git a/src/libstd/time/duration.rs b/src/libstd/time/duration.rs index 9bd6f78300e..a651d927c14 100644 --- a/src/libstd/time/duration.rs +++ b/src/libstd/time/duration.rs @@ -19,9 +19,6 @@ use option::Option::{Some, None}; use num::Int; use result::Result::Ok; -// NOTE: for old macros; remove after the next snapshot -#[cfg(stage0)] use result::Result::Err; - /// The number of nanoseconds in a microsecond. const NANOS_PER_MICRO: i32 = 1000; /// The number of nanoseconds in a millisecond. diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 10cdea791b8..45233dd5225 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -195,28 +195,12 @@ impl Name { /// A mark represents a unique id associated with a macro expansion pub type Mrk = u32; -#[cfg(stage0)] -impl, E> Encodable for Ident { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(token::get_ident(*self).get()) - } -} - -#[cfg(not(stage0))] impl Encodable for Ident { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_str(token::get_ident(*self).get()) } } -#[cfg(stage0)] -impl, E> Decodable for Ident { - fn decode(d: &mut D) -> Result { - Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) - } -} - -#[cfg(not(stage0))] impl Decodable for Ident { fn decode(d: &mut D) -> Result { Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 04753bdf652..31fe23847d9 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -120,15 +120,6 @@ impl PartialEq for Span { impl Eq for Span {} -#[cfg(stage0)] -impl, E> Encodable for Span { - /* Note #1972 -- spans are encoded but not decoded */ - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_nil() - } -} - -#[cfg(not(stage0))] impl Encodable for Span { /* Note #1972 -- spans are encoded but not decoded */ fn encode(&self, s: &mut S) -> Result<(), S::Error> { @@ -136,14 +127,6 @@ impl Encodable for Span { } } -#[cfg(stage0)] -impl, E> Decodable for Span { - fn decode(_d: &mut D) -> Result { - Ok(DUMMY_SP) - } -} - -#[cfg(not(stage0))] impl Decodable for Span { fn decode(_d: &mut D) -> Result { Ok(DUMMY_SP) diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 8f13a4475b7..50b3559f369 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -602,7 +602,7 @@ impl<'a> MethodDef<'a> { }; let mut f = self.combine_substructure.borrow_mut(); let f: &mut CombineSubstructureFunc = &mut *f; - f.call_mut((cx, trait_.span, &substructure)) + f(cx, trait_.span, &substructure) } fn get_ret_ty(&self, @@ -1365,8 +1365,8 @@ pub fn cs_fold(use_foldl: bool, } }, EnumNonMatchingCollapsed(ref all_args, _, tuple) => - enum_nonmatch_f.call_mut((cx, trait_span, (all_args.index(&FullRange), tuple), - substructure.nonself_args)), + enum_nonmatch_f(cx, trait_span, (all_args.index(&FullRange), tuple), + substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") } @@ -1405,8 +1405,8 @@ pub fn cs_same_method(f: F, f(cx, trait_span, called) }, EnumNonMatchingCollapsed(ref all_self_args, _, tuple) => - enum_nonmatch_f.call_mut((cx, trait_span, (all_self_args.index(&FullRange), tuple), - substructure.nonself_args)), + enum_nonmatch_f(cx, trait_span, (all_self_args.index(&FullRange), tuple), + substructure.nonself_args), StaticEnum(..) | StaticStruct(..) => { cx.span_bug(trait_span, "static function in `derive`") } diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index b44aa9dbd9f..43a0e0606f8 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -73,7 +73,7 @@ pub fn expand_meta_derive(cx: &mut ExtCtxt, MetaWord(ref tname) => { macro_rules! expand { ($func:path) => ($func(cx, titem.span, &**titem, item, - |i| push.call_mut((i,)))) + |i| push(i))) } match tname.get() { diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 2c36a02d44f..38a369bdb57 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -44,7 +44,7 @@ static KNOWN_FEATURES: &'static [(&'static str, Status)] = &[ ("non_ascii_idents", Active), ("thread_local", Active), ("link_args", Active), - ("phase", Active), // NOTE(stage0): switch to Removed after next snapshot + ("phase", Removed), ("plugin_registrar", Active), ("log_syntax", Active), ("trace_macros", Active), diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index b7bfd346d50..9e14f9dd1ea 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -23,25 +23,15 @@ html_root_url = "http://doc.rust-lang.org/nightly/")] #![allow(unknown_features)] -#![feature(macro_rules, globs, default_type_params, phase, slicing_syntax)] +#![feature(slicing_syntax)] #![feature(quote, unsafe_destructor)] -#![feature(unboxed_closures)] -#![feature(old_orphan_check)] -#![feature(associated_types)] extern crate arena; extern crate fmt_macros; extern crate serialize; extern crate term; extern crate libc; - -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; +#[macro_use] extern crate log; extern crate "serialize" as rustc_serialize; // used by deriving diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 2a27431a086..707e540a17b 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -82,31 +82,12 @@ impl FromIterator for OwnedSlice { } } -#[cfg(stage0)] -impl, T: Encodable, E> Encodable for OwnedSlice { - fn encode(&self, s: &mut S) -> Result<(), E> { - self.as_slice().encode(s) - } -} - -#[cfg(not(stage0))] impl Encodable for OwnedSlice { fn encode(&self, s: &mut S) -> Result<(), S::Error> { self.as_slice().encode(s) } } -#[cfg(stage0)] -impl, T: Decodable, E> Decodable for OwnedSlice { - fn decode(d: &mut D) -> Result, E> { - Ok(OwnedSlice::from_vec(match Decodable::decode(d) { - Ok(t) => t, - Err(e) => return Err(e) - })) - } -} - -#[cfg(not(stage0))] impl Decodable for OwnedSlice { fn decode(d: &mut D) -> Result, D::Error> { Ok(OwnedSlice::from_vec(match Decodable::decode(d) { diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 82e2c8136a4..3335566801a 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -24,8 +24,7 @@ use std::num::Int; use std::str; use std::iter; -#[cfg_attr(stage0, macro_escape)] -#[cfg_attr(not(stage0), macro_use)] +#[macro_use] pub mod parser; pub mod lexer; diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 306ab303411..bdf96104697 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -684,29 +684,12 @@ impl<'a> PartialEq for &'a str { } } -#[cfg(stage0)] -impl, E> Decodable for InternedString { - fn decode(d: &mut D) -> Result { - Ok(get_name(get_ident_interner().intern( - try!(d.read_str()).index(&FullRange)))) - } -} - -#[cfg(not(stage0))] impl Decodable for InternedString { fn decode(d: &mut D) -> Result { Ok(get_name(get_ident_interner().intern(try!(d.read_str()).index(&FullRange)))) } } -#[cfg(stage0)] -impl, E> Encodable for InternedString { - fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(self.string.index(&FullRange)) - } -} - -#[cfg(not(stage0))] impl Encodable for InternedString { fn encode(&self, s: &mut S) -> Result<(), S::Error> { s.emit_str(self.string.index(&FullRange)) diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 13eda7bb88f..8abb46011e6 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -111,28 +111,12 @@ impl> Hash for P { } } -#[cfg(stage0)] -impl, T: 'static + Decodable> Decodable for P { - fn decode(d: &mut D) -> Result, E> { - Decodable::decode(d).map(P) - } -} - -#[cfg(not(stage0))] impl Decodable for P { fn decode(d: &mut D) -> Result, D::Error> { Decodable::decode(d).map(P) } } -#[cfg(stage0)] -impl, T: Encodable> Encodable for P { - fn encode(&self, s: &mut S) -> Result<(), E> { - (**self).encode(s) - } -} - -#[cfg(not(stage0))] impl Encodable for P { fn encode(&self, s: &mut S) -> Result<(), S::Error> { (**self).encode(s) diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index dd42bede13a..c953f591d80 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -48,17 +48,10 @@ html_playground_url = "http://play.rust-lang.org/")] #![allow(unknown_features)] -#![feature(macro_rules, phase, slicing_syntax, globs)] - +#![feature(slicing_syntax)] #![deny(missing_docs)] -#[cfg(stage0)] -#[phase(plugin, link)] -extern crate log; - -#[cfg(not(stage0))] -#[macro_use] -extern crate log; +#[macro_use] extern crate log; pub use terminfo::TerminfoTerminal; #[cfg(windows)] diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 3ee2b1b2224..a7912216630 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -30,11 +30,7 @@ #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/nightly/")] - -#![allow(unknown_features)] -#![feature(asm, globs, slicing_syntax)] -#![feature(unboxed_closures, default_type_params)] -#![feature(old_orphan_check)] +#![feature(asm, slicing_syntax)] extern crate getopts; extern crate regex; diff --git a/src/libunicode/lib.rs b/src/libunicode/lib.rs index a3884d0c86e..db98b429e40 100644 --- a/src/libunicode/lib.rs +++ b/src/libunicode/lib.rs @@ -28,8 +28,7 @@ html_root_url = "http://doc.rust-lang.org/nightly/", html_playground_url = "http://play.rust-lang.org/")] #![no_std] -#![feature(globs, macro_rules, slicing_syntax, unboxed_closures)] -#![feature(associated_types)] +#![feature(slicing_syntax)] extern crate core; diff --git a/src/snapshots.txt b/src/snapshots.txt index 5c21a8a8abf..d6134898cbd 100644 --- a/src/snapshots.txt +++ b/src/snapshots.txt @@ -1,3 +1,12 @@ +S 2015-01-06 340ac04 + freebsd-x86_64 5413b8931d7076e90c873e0cc7a43e0793c2b17a + linux-i386 cacb8e3ad15937916e455d8f63e740c30a807b10 + linux-x86_64 e4a7f73959130671a5eb9107d593d37b43e571b0 + macos-i386 da6b0b7d12964e815175eb1fe5fc495098ca3125 + macos-x86_64 edf8a109e175be6e5bc44484261d2248946f1dd1 + winnt-i386 34fc7d9905d5845cdc7901f661d43a463534a20d + winnt-x86_64 99580840f5763f517f47cd55ff373e4d116b018d + S 2015-01-04 b2085d9 freebsd-x86_64 50ccb6bf9c0645d0746a5167493a39b2be40c2d4 linux-i386 b880b98d832c9a049b8ef6a50df50061e363de5a -- cgit 1.4.1-3-g733a5