From 090a968fe7680cce0d3aa8fde25a5dc48948e43e Mon Sep 17 00:00:00 2001 From: Ryan Cumming Date: Wed, 10 Jan 2018 20:13:03 +1100 Subject: Only link res_init() on GNU/*nix To workaround a bug in glibc <= 2.26 lookup_host() calls res_init() based on the glibc version detected at runtime. While this avoids calling res_init() on platforms where it's not required we will still end up linking against the symbol. This causes an issue on macOS where res_init() is implemented in a separate library (libresolv.9.dylib) from the main libc. While this is harmless for standalone programs it becomes a problem if Rust code is statically linked against another program. If the linked program doesn't already specify -lresolv it will cause the link to fail. This is captured in issue #46797 Fix this by hooking in to the glibc workaround in `cvt_gai` and only activating it for the "gnu" environment on Unix This should include all glibc platforms while excluding musl, windows-gnu, macOS, FreeBSD, etc. This has the side benefit of removing the #[cfg] in sys_common; only unix.rs has code related to the workaround now. --- src/libstd/sys_common/net.rs | 24 +++--------------------- 1 file changed, 3 insertions(+), 21 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys_common/net.rs b/src/libstd/sys_common/net.rs index c70b39995eb..b841afe1a51 100644 --- a/src/libstd/sys_common/net.rs +++ b/src/libstd/sys_common/net.rs @@ -166,27 +166,9 @@ pub fn lookup_host(host: &str) -> io::Result { hints.ai_socktype = c::SOCK_STREAM; let mut res = ptr::null_mut(); unsafe { - match cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)) { - Ok(_) => { - Ok(LookupHost { original: res, cur: res }) - }, - #[cfg(unix)] - Err(e) => { - // If we're running glibc prior to version 2.26, the lookup - // failure could be caused by caching a stale /etc/resolv.conf. - // We need to call libc::res_init() to clear the cache. But we - // shouldn't call it in on any other platform, because other - // res_init implementations aren't thread-safe. See - // https://github.com/rust-lang/rust/issues/41570 and - // https://github.com/rust-lang/rust/issues/43592. - use sys::net::res_init_if_glibc_before_2_26; - let _ = res_init_if_glibc_before_2_26(); - Err(e) - }, - // the cfg is needed here to avoid an "unreachable pattern" warning - #[cfg(not(unix))] - Err(e) => Err(e), - } + cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)).map(|_| { + LookupHost { original: res, cur: res } + }) } } -- cgit 1.4.1-3-g733a5 From 634f8cc06a88eb978c5e52390014740c4bab1e33 Mon Sep 17 00:00:00 2001 From: John Kåre Alsaker Date: Wed, 15 Nov 2017 18:01:09 +0100 Subject: Print inlined functions on Windows --- src/libstd/sys/cloudabi/backtrace.rs | 1 + src/libstd/sys/redox/backtrace/tracing.rs | 1 + .../sys/unix/backtrace/tracing/backtrace_fn.rs | 1 + src/libstd/sys/unix/backtrace/tracing/gcc_s.rs | 1 + src/libstd/sys/windows/backtrace/mod.rs | 31 ++++++------- src/libstd/sys/windows/backtrace/printing/msvc.rs | 54 ++++++++++++++-------- src/libstd/sys/windows/c.rs | 4 +- src/libstd/sys_common/backtrace.rs | 3 ++ src/test/run-pass/backtrace-debuginfo-aux.rs | 4 +- src/test/run-pass/backtrace-debuginfo.rs | 12 +---- 10 files changed, 62 insertions(+), 50 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys/cloudabi/backtrace.rs b/src/libstd/sys/cloudabi/backtrace.rs index 33d93179237..1b970187558 100644 --- a/src/libstd/sys/cloudabi/backtrace.rs +++ b/src/libstd/sys/cloudabi/backtrace.rs @@ -77,6 +77,7 @@ extern "C" fn trace_fn( cx.frames[cx.idx] = Frame { symbol_addr: symaddr as *mut u8, exact_position: ip as *mut u8, + inline_context: 0, }; cx.idx += 1; } diff --git a/src/libstd/sys/redox/backtrace/tracing.rs b/src/libstd/sys/redox/backtrace/tracing.rs index 0a174b3c3f5..bb70ca36037 100644 --- a/src/libstd/sys/redox/backtrace/tracing.rs +++ b/src/libstd/sys/redox/backtrace/tracing.rs @@ -98,6 +98,7 @@ extern fn trace_fn(ctx: *mut uw::_Unwind_Context, cx.frames[cx.idx] = Frame { symbol_addr: symaddr as *mut u8, exact_position: ip as *mut u8, + inline_context: 0, }; cx.idx += 1; } diff --git a/src/libstd/sys/unix/backtrace/tracing/backtrace_fn.rs b/src/libstd/sys/unix/backtrace/tracing/backtrace_fn.rs index 400d39cd4bd..6293eeb4ed6 100644 --- a/src/libstd/sys/unix/backtrace/tracing/backtrace_fn.rs +++ b/src/libstd/sys/unix/backtrace/tracing/backtrace_fn.rs @@ -38,6 +38,7 @@ pub fn unwind_backtrace(frames: &mut [Frame]) *to = Frame { exact_position: *from as *mut u8, symbol_addr: *from as *mut u8, + inline_context: 0, }; } Ok((nb_frames as usize, BacktraceContext)) diff --git a/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs b/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs index 000c08d2e0d..1b92fc0e6ad 100644 --- a/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs +++ b/src/libstd/sys/unix/backtrace/tracing/gcc_s.rs @@ -98,6 +98,7 @@ extern fn trace_fn(ctx: *mut uw::_Unwind_Context, cx.frames[cx.idx] = Frame { symbol_addr: symaddr as *mut u8, exact_position: ip as *mut u8, + inline_context: 0, }; cx.idx += 1; } diff --git a/src/libstd/sys/windows/backtrace/mod.rs b/src/libstd/sys/windows/backtrace/mod.rs index 176891fff23..82498ad4d58 100644 --- a/src/libstd/sys/windows/backtrace/mod.rs +++ b/src/libstd/sys/windows/backtrace/mod.rs @@ -56,14 +56,15 @@ pub fn unwind_backtrace(frames: &mut [Frame]) // Fetch the symbols necessary from dbghelp.dll let SymInitialize = sym!(dbghelp, "SymInitialize", SymInitializeFn)?; let SymCleanup = sym!(dbghelp, "SymCleanup", SymCleanupFn)?; - let StackWalk64 = sym!(dbghelp, "StackWalk64", StackWalk64Fn)?; + let StackWalkEx = sym!(dbghelp, "StackWalkEx", StackWalkExFn)?; // Allocate necessary structures for doing the stack walk let process = unsafe { c::GetCurrentProcess() }; let thread = unsafe { c::GetCurrentThread() }; let mut context: c::CONTEXT = unsafe { mem::zeroed() }; unsafe { c::RtlCaptureContext(&mut context) }; - let mut frame: c::STACKFRAME64 = unsafe { mem::zeroed() }; + let mut frame: c::STACKFRAME_EX = unsafe { mem::zeroed() }; + frame.StackFrameSize = mem::size_of_val(&frame) as c::DWORD; let image = init_frame(&mut frame, &context); let backtrace_context = BacktraceContext { @@ -79,24 +80,22 @@ pub fn unwind_backtrace(frames: &mut [Frame]) } // And now that we're done with all the setup, do the stack walking! - // Start from -1 to avoid printing this stack frame, which will - // always be exactly the same. let mut i = 0; unsafe { while i < frames.len() && - StackWalk64(image, process, thread, &mut frame, &mut context, + StackWalkEx(image, process, thread, &mut frame, &mut context, ptr::null_mut(), ptr::null_mut(), ptr::null_mut(), - ptr::null_mut()) == c::TRUE + ptr::null_mut(), + 0) == c::TRUE { - let addr = frame.AddrPC.Offset; - if addr == frame.AddrReturn.Offset || addr == 0 || - frame.AddrReturn.Offset == 0 { break } + let addr = (frame.AddrPC.Offset - 1) as *const u8; frames[i] = Frame { - symbol_addr: (addr - 1) as *const u8, - exact_position: (addr - 1) as *const u8, + symbol_addr: addr, + exact_position: addr, + inline_context: frame.InlineFrameContext, }; i += 1; } @@ -111,14 +110,14 @@ type SymInitializeFn = type SymCleanupFn = unsafe extern "system" fn(c::HANDLE) -> c::BOOL; -type StackWalk64Fn = +type StackWalkExFn = unsafe extern "system" fn(c::DWORD, c::HANDLE, c::HANDLE, - *mut c::STACKFRAME64, *mut c::CONTEXT, + *mut c::STACKFRAME_EX, *mut c::CONTEXT, *mut c_void, *mut c_void, - *mut c_void, *mut c_void) -> c::BOOL; + *mut c_void, *mut c_void, c::DWORD) -> c::BOOL; #[cfg(target_arch = "x86")] -fn init_frame(frame: &mut c::STACKFRAME64, +fn init_frame(frame: &mut c::STACKFRAME_EX, ctx: &c::CONTEXT) -> c::DWORD { frame.AddrPC.Offset = ctx.Eip as u64; frame.AddrPC.Mode = c::ADDRESS_MODE::AddrModeFlat; @@ -130,7 +129,7 @@ fn init_frame(frame: &mut c::STACKFRAME64, } #[cfg(target_arch = "x86_64")] -fn init_frame(frame: &mut c::STACKFRAME64, +fn init_frame(frame: &mut c::STACKFRAME_EX, ctx: &c::CONTEXT) -> c::DWORD { frame.AddrPC.Offset = ctx.Rip as u64; frame.AddrPC.Mode = c::ADDRESS_MODE::AddrModeFlat; diff --git a/src/libstd/sys/windows/backtrace/printing/msvc.rs b/src/libstd/sys/windows/backtrace/printing/msvc.rs index 5a49b77af8e..967df1c8a2d 100644 --- a/src/libstd/sys/windows/backtrace/printing/msvc.rs +++ b/src/libstd/sys/windows/backtrace/printing/msvc.rs @@ -16,12 +16,12 @@ use sys::c; use sys::backtrace::BacktraceContext; use sys_common::backtrace::Frame; -type SymFromAddrFn = - unsafe extern "system" fn(c::HANDLE, u64, *mut u64, - *mut c::SYMBOL_INFO) -> c::BOOL; -type SymGetLineFromAddr64Fn = - unsafe extern "system" fn(c::HANDLE, u64, *mut u32, - *mut c::IMAGEHLP_LINE64) -> c::BOOL; +type SymFromInlineContextFn = + unsafe extern "system" fn(c::HANDLE, u64, c::ULONG, + *mut u64, *mut c::SYMBOL_INFO) -> c::BOOL; +type SymGetLineFromInlineContextFn = + unsafe extern "system" fn(c::HANDLE, u64, c::ULONG, + u64, *mut c::DWORD, *mut c::IMAGEHLP_LINE64) -> c::BOOL; /// Converts a pointer to symbol to its string value. pub fn resolve_symname(frame: Frame, @@ -29,7 +29,9 @@ pub fn resolve_symname(frame: Frame, context: &BacktraceContext) -> io::Result<()> where F: FnOnce(Option<&str>) -> io::Result<()> { - let SymFromAddr = sym!(&context.dbghelp, "SymFromAddr", SymFromAddrFn)?; + let SymFromInlineContext = sym!(&context.dbghelp, + "SymFromInlineContext", + SymFromInlineContextFn)?; unsafe { let mut info: c::SYMBOL_INFO = mem::zeroed(); @@ -40,12 +42,22 @@ pub fn resolve_symname(frame: Frame, info.SizeOfStruct = 88; let mut displacement = 0u64; - let ret = SymFromAddr(context.handle, - frame.symbol_addr as u64, - &mut displacement, - &mut info); - - let symname = if ret == c::TRUE { + let ret = SymFromInlineContext(context.handle, + frame.symbol_addr as u64, + frame.inline_context, + &mut displacement, + &mut info); + let valid_range = if ret == c::TRUE && + frame.symbol_addr as usize >= info.Address as usize { + if info.Size != 0 { + (frame.symbol_addr as usize) < info.Address as usize + info.Size as usize + } else { + true + } + } else { + false + }; + let symname = if valid_range { let ptr = info.Name.as_ptr() as *const c_char; CStr::from_ptr(ptr).to_str().ok() } else { @@ -61,19 +73,21 @@ pub fn foreach_symbol_fileline(frame: Frame, -> io::Result where F: FnMut(&[u8], u32) -> io::Result<()> { - let SymGetLineFromAddr64 = sym!(&context.dbghelp, - "SymGetLineFromAddr64", - SymGetLineFromAddr64Fn)?; + let SymGetLineFromInlineContext = sym!(&context.dbghelp, + "SymGetLineFromInlineContext", + SymGetLineFromInlineContextFn)?; unsafe { let mut line: c::IMAGEHLP_LINE64 = mem::zeroed(); line.SizeOfStruct = ::mem::size_of::() as u32; let mut displacement = 0u32; - let ret = SymGetLineFromAddr64(context.handle, - frame.exact_position as u64, - &mut displacement, - &mut line); + let ret = SymGetLineFromInlineContext(context.handle, + frame.exact_position as u64, + frame.inline_context, + 0, + &mut displacement, + &mut line); if ret == c::TRUE { let name = CStr::from_ptr(line.Filename).to_bytes(); f(name, line.LineNumber as u32)?; diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index 66b44f1402f..6d929f21365 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -619,7 +619,7 @@ pub struct ADDRESS64 { #[repr(C)] #[cfg(feature = "backtrace")] -pub struct STACKFRAME64 { +pub struct STACKFRAME_EX { pub AddrPC: ADDRESS64, pub AddrReturn: ADDRESS64, pub AddrFrame: ADDRESS64, @@ -631,6 +631,8 @@ pub struct STACKFRAME64 { pub Virtual: BOOL, pub Reserved: [u64; 3], pub KdHelp: KDHELP64, + pub StackFrameSize: DWORD, + pub InlineFrameContext: DWORD, } #[repr(C)] diff --git a/src/libstd/sys_common/backtrace.rs b/src/libstd/sys_common/backtrace.rs index 36cbce2df75..a364a0392b3 100644 --- a/src/libstd/sys_common/backtrace.rs +++ b/src/libstd/sys_common/backtrace.rs @@ -41,6 +41,8 @@ pub struct Frame { pub exact_position: *const u8, /// Address of the enclosing function. pub symbol_addr: *const u8, + /// Which inlined function is this frame referring to + pub inline_context: u32, } /// Max number of frames to print. @@ -64,6 +66,7 @@ fn _print(w: &mut Write, format: PrintFormat) -> io::Result<()> { let mut frames = [Frame { exact_position: ptr::null(), symbol_addr: ptr::null(), + inline_context: 0, }; MAX_NB_FRAMES]; let (nb_frames, context) = unwind_backtrace(&mut frames)?; let (skipped_before, skipped_after) = diff --git a/src/test/run-pass/backtrace-debuginfo-aux.rs b/src/test/run-pass/backtrace-debuginfo-aux.rs index 1236acf3511..cb7ef7e3006 100644 --- a/src/test/run-pass/backtrace-debuginfo-aux.rs +++ b/src/test/run-pass/backtrace-debuginfo-aux.rs @@ -15,9 +15,7 @@ pub fn callback(f: F) where F: FnOnce((&'static str, u32)) { f((file!(), line!())) } -// LLVM does not yet output the required debug info to support showing inlined -// function calls in backtraces when targeting MSVC, so disable inlining in -// this case. +// We emit the wrong location for the caller here when inlined on MSVC #[cfg_attr(not(target_env = "msvc"), inline(always))] #[cfg_attr(target_env = "msvc", inline(never))] pub fn callback_inlined(f: F) where F: FnOnce((&'static str, u32)) { diff --git a/src/test/run-pass/backtrace-debuginfo.rs b/src/test/run-pass/backtrace-debuginfo.rs index 2f1c5c0574a..e8b5f3490e5 100644 --- a/src/test/run-pass/backtrace-debuginfo.rs +++ b/src/test/run-pass/backtrace-debuginfo.rs @@ -62,10 +62,7 @@ type Pos = (&'static str, u32); // this goes to stdout and each line has to be occurred // in the following backtrace to stderr with a correct order. fn dump_filelines(filelines: &[Pos]) { - // Skip top frame for MSVC, because it sees the macro rather than - // the containing function. - let skip = if cfg!(target_env = "msvc") {1} else {0}; - for &(file, line) in filelines.iter().rev().skip(skip) { + for &(file, line) in filelines.iter().rev() { // extract a basename let basename = file.split(&['/', '\\'][..]).last().unwrap(); println!("{}:{}", basename, line); @@ -84,9 +81,7 @@ fn inner(counter: &mut i32, main_pos: Pos, outer_pos: Pos) { }); } -// LLVM does not yet output the required debug info to support showing inlined -// function calls in backtraces when targeting MSVC, so disable inlining in -// this case. +// We emit the wrong location for the caller here when inlined on MSVC #[cfg_attr(not(target_env = "msvc"), inline(always))] #[cfg_attr(target_env = "msvc", inline(never))] fn inner_inlined(counter: &mut i32, main_pos: Pos, outer_pos: Pos) { @@ -137,9 +132,6 @@ fn run_test(me: &str) { use std::str; use std::process::Command; - let mut template = Command::new(me); - template.env("RUST_BACKTRACE", "full"); - let mut i = 0; loop { let out = Command::new(me) -- cgit 1.4.1-3-g733a5 From 55b54a999bcdb0b1c1f42b6e1ae670beb0717086 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 31 Jan 2018 11:41:29 -0800 Subject: Use a range to identify SIGSEGV in stack guards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously, the `guard::init()` and `guard::current()` functions were returning a `usize` address representing the top of the stack guard, respectively for the main thread and for spawned threads. The `SIGSEGV` handler on `unix` targets checked if a fault was within one page below that address, if so reporting it as a stack overflow. Now `unix` targets report a `Range` representing the guard memory, so it can cover arbitrary guard sizes. Non-`unix` targets which always return `None` for guards now do so with `Option`, so they don't pay any overhead. For `linux-gnu` in particular, the previous guard upper-bound was `stackaddr + guardsize`, as the protected memory was *inside* the stack. This was a glibc bug, and starting from 2.27 they are moving the guard *past* the end of the stack. However, there's no simple way for us to know where the guard page actually lies, so now we declare it as the whole range of `stackaddr ± guardsize`, and any fault therein will be called a stack overflow. This fixes #47863. --- src/libstd/sys/cloudabi/thread.rs | 5 +- src/libstd/sys/redox/thread.rs | 5 +- src/libstd/sys/unix/stack_overflow.rs | 9 +-- src/libstd/sys/unix/thread.rs | 115 +++++++++++++++++++++------------- src/libstd/sys/wasm/thread.rs | 5 +- src/libstd/sys/windows/thread.rs | 5 +- src/libstd/sys_common/thread_info.rs | 9 +-- 7 files changed, 89 insertions(+), 64 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs index c980ae75261..78a3b82546e 100644 --- a/src/libstd/sys/cloudabi/thread.rs +++ b/src/libstd/sys/cloudabi/thread.rs @@ -111,10 +111,11 @@ impl Drop for Thread { #[cfg_attr(test, allow(dead_code))] pub mod guard { - pub unsafe fn current() -> Option { + pub type Guard = !; + pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { + pub unsafe fn init() -> Option { None } } diff --git a/src/libstd/sys/redox/thread.rs b/src/libstd/sys/redox/thread.rs index c4aad8d86f8..c4719a94c7e 100644 --- a/src/libstd/sys/redox/thread.rs +++ b/src/libstd/sys/redox/thread.rs @@ -88,6 +88,7 @@ impl Thread { } pub mod guard { - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub type Guard = !; + pub unsafe fn current() -> Option { None } + pub unsafe fn init() -> Option { None } } diff --git a/src/libstd/sys/unix/stack_overflow.rs b/src/libstd/sys/unix/stack_overflow.rs index 51adbc24ae0..40453f9b8a1 100644 --- a/src/libstd/sys/unix/stack_overflow.rs +++ b/src/libstd/sys/unix/stack_overflow.rs @@ -57,9 +57,6 @@ mod imp { use sys_common::thread_info; - // This is initialized in init() and only read from after - static mut PAGE_SIZE: usize = 0; - #[cfg(any(target_os = "linux", target_os = "android"))] unsafe fn siginfo_si_addr(info: *mut libc::siginfo_t) -> usize { #[repr(C)] @@ -102,12 +99,12 @@ mod imp { _data: *mut libc::c_void) { use sys_common::util::report_overflow; - let guard = thread_info::stack_guard().unwrap_or(0); + let guard = thread_info::stack_guard().unwrap_or(0..0); let addr = siginfo_si_addr(info); // If the faulting address is within the guard page, then we print a // message saying so and abort. - if guard != 0 && guard - PAGE_SIZE <= addr && addr < guard { + if guard.start <= addr && addr < guard.end { report_overflow(); rtabort!("stack overflow"); } else { @@ -123,8 +120,6 @@ mod imp { static mut MAIN_ALTSTACK: *mut libc::c_void = ptr::null_mut(); pub unsafe fn init() { - PAGE_SIZE = ::sys::os::page_size(); - let mut action: sigaction = mem::zeroed(); action.sa_flags = SA_SIGINFO | SA_ONSTACK; action.sa_sigaction = signal_handler as sighandler_t; diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index 525882c1e1e..72cdb9440b8 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -205,8 +205,10 @@ impl Drop for Thread { not(target_os = "solaris")))] #[cfg_attr(test, allow(dead_code))] pub mod guard { - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + use ops::Range; + pub type Guard = Range; + pub unsafe fn current() -> Option { None } + pub unsafe fn init() -> Option { None } } @@ -222,14 +224,43 @@ pub mod guard { use libc; use libc::mmap; use libc::{PROT_NONE, MAP_PRIVATE, MAP_ANON, MAP_FAILED, MAP_FIXED}; + use ops::Range; use sys::os; - #[cfg(any(target_os = "macos", - target_os = "bitrig", - target_os = "openbsd", - target_os = "solaris"))] + // This is initialized in init() and only read from after + static mut PAGE_SIZE: usize = 0; + + pub type Guard = Range; + + #[cfg(target_os = "solaris")] + unsafe fn get_stack_start() -> Option<*mut libc::c_void> { + let mut current_stack: libc::stack_t = ::mem::zeroed(); + assert_eq!(libc::stack_getbounds(&mut current_stack), 0); + Some(current_stack.ss_sp) + } + + #[cfg(target_os = "macos")] unsafe fn get_stack_start() -> Option<*mut libc::c_void> { - current().map(|s| s as *mut libc::c_void) + let stackaddr = libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize - + libc::pthread_get_stacksize_np(libc::pthread_self()); + Some(stackaddr as *mut libc::c_void) + } + + #[cfg(any(target_os = "openbsd", target_os = "bitrig"))] + unsafe fn get_stack_start() -> Option<*mut libc::c_void> { + let mut current_stack: libc::stack_t = ::mem::zeroed(); + assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), + &mut current_stack), 0); + + let extra = if cfg!(target_os = "bitrig") {3} else {1} * PAGE_SIZE; + let stackaddr = if libc::pthread_main_np() == 1 { + // main thread + current_stack.ss_sp as usize - current_stack.ss_size + extra + } else { + // new thread + current_stack.ss_sp as usize - current_stack.ss_size + }; + Some(stackaddr as *mut libc::c_void) } #[cfg(any(target_os = "android", target_os = "freebsd", @@ -253,8 +284,9 @@ pub mod guard { ret } - pub unsafe fn init() -> Option { - let psize = os::page_size(); + pub unsafe fn init() -> Option { + PAGE_SIZE = os::page_size(); + let mut stackaddr = get_stack_start()?; // Ensure stackaddr is page aligned! A parent process might @@ -263,9 +295,9 @@ pub mod guard { // stackaddr < stackaddr + stacksize, so if stackaddr is not // page-aligned, calculate the fix such that stackaddr < // new_page_aligned_stackaddr < stackaddr + stacksize - let remainder = (stackaddr as usize) % psize; + let remainder = (stackaddr as usize) % PAGE_SIZE; if remainder != 0 { - stackaddr = ((stackaddr as usize) + psize - remainder) + stackaddr = ((stackaddr as usize) + PAGE_SIZE - remainder) as *mut libc::c_void; } @@ -280,60 +312,42 @@ pub mod guard { // Instead, we'll just note where we expect rlimit to start // faulting, so our handler can report "stack overflow", and // trust that the kernel's own stack guard will work. - Some(stackaddr as usize) + let stackaddr = stackaddr as usize; + Some(stackaddr - PAGE_SIZE..stackaddr) } else { // Reallocate the last page of the stack. // This ensures SIGBUS will be raised on // stack overflow. - let result = mmap(stackaddr, psize, PROT_NONE, + let result = mmap(stackaddr, PAGE_SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_FIXED, -1, 0); if result != stackaddr || result == MAP_FAILED { panic!("failed to allocate a guard page"); } + let guardaddr = stackaddr as usize; let offset = if cfg!(target_os = "freebsd") { 2 } else { 1 }; - Some(stackaddr as usize + offset * psize) + Some(guardaddr..guardaddr + offset * PAGE_SIZE) } } - #[cfg(target_os = "solaris")] - pub unsafe fn current() -> Option { - let mut current_stack: libc::stack_t = ::mem::zeroed(); - assert_eq!(libc::stack_getbounds(&mut current_stack), 0); - Some(current_stack.ss_sp as usize) - } - - #[cfg(target_os = "macos")] - pub unsafe fn current() -> Option { - Some(libc::pthread_get_stackaddr_np(libc::pthread_self()) as usize - - libc::pthread_get_stacksize_np(libc::pthread_self())) - } - - #[cfg(any(target_os = "openbsd", target_os = "bitrig"))] - pub unsafe fn current() -> Option { - let mut current_stack: libc::stack_t = ::mem::zeroed(); - assert_eq!(libc::pthread_stackseg_np(libc::pthread_self(), - &mut current_stack), 0); - - let extra = if cfg!(target_os = "bitrig") {3} else {1} * os::page_size(); - Some(if libc::pthread_main_np() == 1 { - // main thread - current_stack.ss_sp as usize - current_stack.ss_size + extra - } else { - // new thread - current_stack.ss_sp as usize - current_stack.ss_size - }) + #[cfg(any(target_os = "macos", + target_os = "bitrig", + target_os = "openbsd", + target_os = "solaris"))] + pub unsafe fn current() -> Option { + let stackaddr = get_stack_start()? as usize; + Some(stackaddr - PAGE_SIZE..stackaddr) } #[cfg(any(target_os = "android", target_os = "freebsd", target_os = "linux", target_os = "netbsd", target_os = "l4re"))] - pub unsafe fn current() -> Option { + pub unsafe fn current() -> Option { let mut ret = None; let mut attr: libc::pthread_attr_t = ::mem::zeroed(); assert_eq!(libc::pthread_attr_init(&mut attr), 0); @@ -352,12 +366,23 @@ pub mod guard { assert_eq!(libc::pthread_attr_getstack(&attr, &mut stackaddr, &mut size), 0); + let stackaddr = stackaddr as usize; ret = if cfg!(target_os = "freebsd") { - Some(stackaddr as usize - guardsize) + // FIXME does freebsd really fault *below* the guard addr? + let guardaddr = stackaddr - guardsize; + Some(guardaddr - PAGE_SIZE..guardaddr) } else if cfg!(target_os = "netbsd") { - Some(stackaddr as usize) + Some(stackaddr - guardsize..stackaddr) + } else if cfg!(all(target_os = "linux", target_env = "gnu")) { + // glibc used to include the guard area within the stack, as noted in the BUGS + // section of `man pthread_attr_getguardsize`. This has been corrected starting + // with glibc 2.27, and in some distro backports, so the guard is now placed at the + // end (below) the stack. There's no easy way for us to know which we have at + // runtime, so we'll just match any fault in the range right above or below the + // stack base to call that fault a stack overflow. + Some(stackaddr - guardsize..stackaddr + guardsize) } else { - Some(stackaddr as usize + guardsize) + Some(stackaddr..stackaddr + guardsize) }; } assert_eq!(libc::pthread_attr_destroy(&mut attr), 0); diff --git a/src/libstd/sys/wasm/thread.rs b/src/libstd/sys/wasm/thread.rs index 13980e0cc19..6a066509b49 100644 --- a/src/libstd/sys/wasm/thread.rs +++ b/src/libstd/sys/wasm/thread.rs @@ -43,6 +43,7 @@ impl Thread { } pub mod guard { - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub type Guard = !; + pub unsafe fn current() -> Option { None } + pub unsafe fn init() -> Option { None } } diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index 74786d09285..43abfbb1f64 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -93,6 +93,7 @@ impl Thread { #[cfg_attr(test, allow(dead_code))] pub mod guard { - pub unsafe fn current() -> Option { None } - pub unsafe fn init() -> Option { None } + pub type Guard = !; + pub unsafe fn current() -> Option { None } + pub unsafe fn init() -> Option { None } } diff --git a/src/libstd/sys_common/thread_info.rs b/src/libstd/sys_common/thread_info.rs index 7970042b1d6..6a2b6742367 100644 --- a/src/libstd/sys_common/thread_info.rs +++ b/src/libstd/sys_common/thread_info.rs @@ -11,10 +11,11 @@ #![allow(dead_code)] // stack_guard isn't used right now on all platforms use cell::RefCell; +use sys::thread::guard::Guard; use thread::Thread; struct ThreadInfo { - stack_guard: Option, + stack_guard: Option, thread: Thread, } @@ -38,11 +39,11 @@ pub fn current_thread() -> Option { ThreadInfo::with(|info| info.thread.clone()) } -pub fn stack_guard() -> Option { - ThreadInfo::with(|info| info.stack_guard).and_then(|o| o) +pub fn stack_guard() -> Option { + ThreadInfo::with(|info| info.stack_guard.clone()).and_then(|o| o) } -pub fn set(stack_guard: Option, thread: Thread) { +pub fn set(stack_guard: Option, thread: Thread) { THREAD_INFO.with(|c| assert!(c.borrow().is_none())); THREAD_INFO.with(move |c| *c.borrow_mut() = Some(ThreadInfo{ stack_guard, -- cgit 1.4.1-3-g733a5 From 4452446292086d9c92ea709eea61a31cedb55e22 Mon Sep 17 00:00:00 2001 From: Matthias Krüger Date: Fri, 16 Feb 2018 15:56:50 +0100 Subject: fix more typos found by codespell. --- RELEASES.md | 2 +- config.toml.example | 4 ++-- src/bootstrap/test.rs | 2 +- src/librustc/diagnostics.rs | 2 +- src/librustc/hir/mod.rs | 2 +- src/librustc/infer/error_reporting/mod.rs | 4 ++-- src/librustc/infer/outlives/obligations.rs | 2 +- src/librustc/infer/region_constraints/README.md | 2 +- src/librustc/middle/region.rs | 2 +- src/librustc/mir/interpret/mod.rs | 2 +- src/librustc/mir/mod.rs | 2 +- src/librustc/traits/coherence.rs | 2 +- src/librustc/traits/mod.rs | 2 +- src/librustc/ty/layout.rs | 4 ++-- src/librustc_apfloat/tests/ieee.rs | 4 ++-- src/librustc_borrowck/borrowck/mod.rs | 2 +- src/librustc_const_eval/_match.rs | 2 +- src/librustc_data_structures/indexed_vec.rs | 2 +- src/librustc_mir/borrow_check/mod.rs | 8 ++++---- src/librustc_mir/borrow_check/nll/mod.rs | 2 +- src/librustc_mir/borrow_check/nll/region_infer/mod.rs | 2 +- .../borrow_check/nll/region_infer/values.rs | 2 +- src/librustc_mir/build/matches/mod.rs | 2 +- src/librustc_mir/dataflow/impls/borrows.rs | 4 ++-- src/librustc_mir/diagnostics.rs | 2 +- src/librustc_mir/interpret/eval_context.rs | 2 +- src/librustc_mir/monomorphize/item.rs | 2 +- src/librustc_privacy/lib.rs | 2 +- src/librustc_resolve/check_unused.rs | 2 +- src/librustc_resolve/lib.rs | 2 +- src/librustc_resolve/resolve_imports.rs | 2 +- src/librustc_trans/back/lto.rs | 4 ++-- src/librustc_trans/builder.rs | 2 +- src/librustc_trans/mir/rvalue.rs | 2 +- src/librustc_trans_utils/trans_crate.rs | 2 +- src/libstd/io/buffered.rs | 2 +- src/libstd/sync/rwlock.rs | 4 ++-- src/libstd/sys_common/backtrace.rs | 2 +- src/libstd/sys_common/poison.rs | 2 +- src/libsyntax/ast.rs | 2 +- src/libsyntax/config.rs | 2 +- src/libsyntax/parse/parser.rs | 4 ++-- src/test/compile-fail/coerce-to-bang.rs | 2 +- .../macro_expanded_mod_helper/foo/bar.rs | 2 +- .../macro_expanded_mod_helper/foo/mod.rs | 2 +- src/test/compile-fail/hr-subtype.rs | 4 ++-- src/test/compile-fail/issue-20616-1.rs | 2 +- src/test/compile-fail/issue-20616-2.rs | 2 +- src/test/compile-fail/issue-20616-3.rs | 2 +- src/test/compile-fail/issue-20616-4.rs | 2 +- src/test/compile-fail/issue-20616-5.rs | 2 +- src/test/compile-fail/issue-20616-6.rs | 2 +- src/test/compile-fail/issue-20616-7.rs | 2 +- src/test/compile-fail/issue-20616-8.rs | 2 +- src/test/compile-fail/issue-20616-9.rs | 2 +- src/test/compile-fail/no_crate_type.rs | 2 +- src/test/mir-opt/README.md | 2 +- src/test/pretty/stmt_expr_attributes.rs | 2 +- src/test/run-make/hotplug_codegen_backend/Makefile | 2 +- .../run-make/hotplug_codegen_backend/the_backend.rs | 2 +- .../proc-macro/auxiliary/derive-reexport.rs | 2 +- src/test/run-pass/issue-29746.rs | 2 +- src/test/run-pass/issue-32008.rs | 2 +- src/test/run-pass/rfc1857-drop-order.rs | 18 +++++++++--------- src/test/run-pass/simd-target-feature-mixup.rs | 2 +- src/test/rustdoc/impl-parts-crosscrate.rs | 2 +- src/test/ui/explain.stdout | 2 +- .../issue-43106-gating-of-builtin-attrs.rs | 2 +- .../lifetime-errors/liveness-assign-imm-local-notes.rs | 2 +- 69 files changed, 89 insertions(+), 89 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/RELEASES.md b/RELEASES.md index 7a9d256be28..64e2145e0f3 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -29,7 +29,7 @@ Libraries - [Copied `AsciiExt` methods onto `char`][46077] - [Remove `T: Sized` requirement on `ptr::is_null()`][46094] - [impl `From` for `{TryRecvError, RecvTimeoutError}`][45506] -- [Optimised `f32::{min, max}` to generate more efficent x86 assembly][47080] +- [Optimised `f32::{min, max}` to generate more efficient x86 assembly][47080] - [`[u8]::contains` now uses memchr which provides a 3x speed improvement][46713] Stabilized APIs diff --git a/config.toml.example b/config.toml.example index f153562a538..8d1fa3eec5c 100644 --- a/config.toml.example +++ b/config.toml.example @@ -151,8 +151,8 @@ # default. #extended = false -# Installs choosen set of extended tools if enables. By default builds all. -# If choosen tool failed to build the installation fails. +# Installs chosen set of extended tools if enables. By default builds all. +# If chosen tool failed to build the installation fails. #tools = ["cargo", "rls", "rustfmt", "analysis", "src"] # Verbosity level: 0 == not verbose, 1 == verbose, 2 == very verbose diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 64ede4f4ecc..7b485662760 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -935,7 +935,7 @@ impl Step for Compiletest { } } if suite == "run-make" && !build.config.llvm_enabled { - println!("Ignoring run-make test suite as they generally dont work without LLVM"); + println!("Ignoring run-make test suite as they generally don't work without LLVM"); return; } diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs index 4c256556191..287516474d4 100644 --- a/src/librustc/diagnostics.rs +++ b/src/librustc/diagnostics.rs @@ -1891,7 +1891,7 @@ is a function pointer, which is not zero-sized. This pattern should be rewritten. There are a few possible ways to do this: - change the original fn declaration to match the expected signature, - and do the cast in the fn body (the prefered option) + and do the cast in the fn body (the preferred option) - cast the fn item fo a fn pointer before calling transmute, as shown here: ``` diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 2854b9da147..bc03f7ead81 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -543,7 +543,7 @@ impl Generics { } /// Synthetic Type Parameters are converted to an other form during lowering, this allows -/// to track the original form they had. Usefull for error messages. +/// to track the original form they had. Useful for error messages. #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] pub enum SyntheticTyParamKind { ImplTrait diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs index 03fc40b2e39..700d06acf11 100644 --- a/src/librustc/infer/error_reporting/mod.rs +++ b/src/librustc/infer/error_reporting/mod.rs @@ -734,7 +734,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { } } - // When finding T != &T, hightlight only the borrow + // When finding T != &T, highlight only the borrow (&ty::TyRef(r1, ref tnm1), _) if equals(&tnm1.ty, &t2) => { let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new()); push_ty_ref(&r1, tnm1, &mut values.0); @@ -946,7 +946,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { let type_param = generics.type_param(param, self.tcx); let hir = &self.tcx.hir; hir.as_local_node_id(type_param.def_id).map(|id| { - // Get the `hir::TyParam` to verify wether it already has any bounds. + // Get the `hir::TyParam` to verify whether it already has any bounds. // We do this to avoid suggesting code that ends up as `T: 'a'b`, // instead we suggest `T: 'a + 'b` in that case. let has_lifetimes = if let hir_map::NodeTyParam(ref p) = hir.get(id) { diff --git a/src/librustc/infer/outlives/obligations.rs b/src/librustc/infer/outlives/obligations.rs index eda2e1f7b4e..36e657f78b4 100644 --- a/src/librustc/infer/outlives/obligations.rs +++ b/src/librustc/infer/outlives/obligations.rs @@ -106,7 +106,7 @@ impl<'cx, 'gcx, 'tcx> InferCtxt<'cx, 'gcx, 'tcx> { /// done (or else an assert will fire). /// /// See the `region_obligations` field of `InferCtxt` for some - /// comments about how this funtion fits into the overall expected + /// comments about how this function fits into the overall expected /// flow of the the inferencer. The key point is that it is /// invoked after all type-inference variables have been bound -- /// towards the end of regionck. This also ensures that the diff --git a/src/librustc/infer/region_constraints/README.md b/src/librustc/infer/region_constraints/README.md index 67ad08c7530..95f9c8c8353 100644 --- a/src/librustc/infer/region_constraints/README.md +++ b/src/librustc/infer/region_constraints/README.md @@ -19,7 +19,7 @@ The constraints are always of one of three possible forms: a subregion of Rj - `ConstrainRegSubVar(R, Ri)` states that the concrete region R (which must not be a variable) must be a subregion of the variable Ri -- `ConstrainVarSubReg(Ri, R)` states the variable Ri shoudl be less +- `ConstrainVarSubReg(Ri, R)` states the variable Ri should be less than the concrete region R. This is kind of deprecated and ought to be replaced with a verify (they essentially play the same role). diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index e5619f469e7..3ce4ab04777 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -886,7 +886,7 @@ fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: // // Each of the statements within the block is a terminating // scope, and thus a temporary (e.g. the result of calling - // `bar()` in the initalizer expression for `let inner = ...;`) + // `bar()` in the initializer expression for `let inner = ...;`) // will be cleaned up immediately after its corresponding // statement (i.e. `let inner = ...;`) executes. // diff --git a/src/librustc/mir/interpret/mod.rs b/src/librustc/mir/interpret/mod.rs index 8ffea62f6be..a80695ec9b9 100644 --- a/src/librustc/mir/interpret/mod.rs +++ b/src/librustc/mir/interpret/mod.rs @@ -56,7 +56,7 @@ pub struct GlobalId<'tcx> { //////////////////////////////////////////////////////////////////////////////// pub trait PointerArithmetic: layout::HasDataLayout { - // These are not supposed to be overriden. + // These are not supposed to be overridden. //// Trunace the given value to the pointer size; also return whether there was an overflow fn truncate_to_ptr(self, val: u128) -> (u64, bool) { diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index 439be667861..b88dea871ce 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -1950,7 +1950,7 @@ pub struct GeneratorLayout<'tcx> { /// ``` /// /// here, there is one unique free region (`'a`) but it appears -/// twice. We would "renumber" each occurence to a unique vid, as follows: +/// twice. We would "renumber" each occurrence to a unique vid, as follows: /// /// ```text /// ClosureSubsts = [ diff --git a/src/librustc/traits/coherence.rs b/src/librustc/traits/coherence.rs index 9de18612d81..7311b47974a 100644 --- a/src/librustc/traits/coherence.rs +++ b/src/librustc/traits/coherence.rs @@ -277,7 +277,7 @@ pub fn orphan_check<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, /// is bad, because the only local type with `T` as a subtree is /// `LocalType`, and `Vec<->` is between it and the type parameter. /// - similarly, `FundamentalPair, T>` is bad, because -/// the second occurence of `T` is not a subtree of *any* local type. +/// the second occurrence of `T` is not a subtree of *any* local type. /// - however, `LocalType>` is OK, because `T` is a subtree of /// `LocalType>`, which is local and has no types between it and /// the type parameter. diff --git a/src/librustc/traits/mod.rs b/src/librustc/traits/mod.rs index 80819a86b7c..41cc8ca601a 100644 --- a/src/librustc/traits/mod.rs +++ b/src/librustc/traits/mod.rs @@ -621,7 +621,7 @@ pub fn fully_normalize<'a, 'gcx, 'tcx, T>(infcx: &InferCtxt<'a, 'gcx, 'tcx>, // FIXME (@jroesch) ISSUE 26721 // I'm not sure if this is a bug or not, needs further investigation. // It appears that by reusing the fulfillment_cx here we incur more - // obligations and later trip an asssertion on regionck.rs line 337. + // obligations and later trip an assertion on regionck.rs line 337. // // The two possibilities I see is: // - normalization is not actually fully happening and we diff --git a/src/librustc/ty/layout.rs b/src/librustc/ty/layout.rs index 63b91ff1101..c3cd65230bd 100644 --- a/src/librustc/ty/layout.rs +++ b/src/librustc/ty/layout.rs @@ -2059,7 +2059,7 @@ impl<'a, 'tcx> LayoutOf> for LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> { // can however trigger recursive invocations of `layout_of`. // Therefore, we execute it *after* the main query has // completed, to avoid problems around recursive structures - // and the like. (Admitedly, I wasn't able to reproduce a problem + // and the like. (Admittedly, I wasn't able to reproduce a problem // here, but it seems like the right thing to do. -nmatsakis) self.record_layout_for_printing(layout); @@ -2085,7 +2085,7 @@ impl<'a, 'tcx> LayoutOf> for LayoutCx<'tcx, ty::maps::TyCtxtAt<'a, 'tcx // can however trigger recursive invocations of `layout_of`. // Therefore, we execute it *after* the main query has // completed, to avoid problems around recursive structures - // and the like. (Admitedly, I wasn't able to reproduce a problem + // and the like. (Admittedly, I wasn't able to reproduce a problem // here, but it seems like the right thing to do. -nmatsakis) let cx = LayoutCx { tcx: *self.tcx, diff --git a/src/librustc_apfloat/tests/ieee.rs b/src/librustc_apfloat/tests/ieee.rs index aff2076e038..ff46ee79c31 100644 --- a/src/librustc_apfloat/tests/ieee.rs +++ b/src/librustc_apfloat/tests/ieee.rs @@ -2201,12 +2201,12 @@ fn is_finite_non_zero() { assert!(!Single::ZERO.is_finite_non_zero()); assert!(!(-Single::ZERO).is_finite_non_zero()); - // Test +/- qNaN. +/- dont mean anything with qNaN but paranoia can't hurt in + // Test +/- qNaN. +/- don't mean anything with qNaN but paranoia can't hurt in // this instance. assert!(!Single::NAN.is_finite_non_zero()); assert!(!(-Single::NAN).is_finite_non_zero()); - // Test +/- sNaN. +/- dont mean anything with sNaN but paranoia can't hurt in + // Test +/- sNaN. +/- don't mean anything with sNaN but paranoia can't hurt in // this instance. assert!(!Single::snan(None).is_finite_non_zero()); assert!(!(-Single::snan(None)).is_finite_non_zero()); diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 738c0d82ee1..58818d0ce80 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -1111,7 +1111,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { /// Given a type, if it is an immutable reference, return a suggestion to make it mutable fn suggest_mut_for_immutable(&self, pty: &hir::Ty, is_implicit_self: bool) -> Option { - // Check wether the argument is an immutable reference + // Check whether the argument is an immutable reference debug!("suggest_mut_for_immutable({:?}, {:?})", pty, is_implicit_self); if let hir::TyRptr(lifetime, hir::MutTy { mutbl: hir::Mutability::MutImmutable, diff --git a/src/librustc_const_eval/_match.rs b/src/librustc_const_eval/_match.rs index a7c382eba50..e30f5cb4f12 100644 --- a/src/librustc_const_eval/_match.rs +++ b/src/librustc_const_eval/_match.rs @@ -607,7 +607,7 @@ pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, // be able to observe whether the types of the struct's fields are // inhabited. // - // If the field is truely inaccessible, then all the patterns + // If the field is truly inaccessible, then all the patterns // matching against it must be wildcard patterns, so its type // does not matter. // diff --git a/src/librustc_data_structures/indexed_vec.rs b/src/librustc_data_structures/indexed_vec.rs index 753f12f400b..b11ca107af7 100644 --- a/src/librustc_data_structures/indexed_vec.rs +++ b/src/librustc_data_structures/indexed_vec.rs @@ -204,7 +204,7 @@ macro_rules! newtype_index { $($tokens)*); ); - // The case where no derives are added, but encodable is overriden. Don't + // The case where no derives are added, but encodable is overridden. Don't // derive serialization traits (@pub [$($pub:tt)*] @type [$type:ident] diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs index 650f99828ae..c6ed971f767 100644 --- a/src/librustc_mir/borrow_check/mod.rs +++ b/src/librustc_mir/borrow_check/mod.rs @@ -117,7 +117,7 @@ fn do_mir_borrowck<'a, 'gcx, 'tcx>( for move_error in move_errors { let (span, kind): (Span, IllegalMoveOriginKind) = match move_error { MoveError::UnionMove { .. } => { - unimplemented!("dont know how to report union move errors yet.") + unimplemented!("don't know how to report union move errors yet.") } MoveError::IllegalMove { cannot_move_out_of: o, @@ -1424,7 +1424,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { /// tracked in the MoveData. /// /// An Err result includes a tag indicated why the search failed. - /// Currenly this can only occur if the place is built off of a + /// Currently this can only occur if the place is built off of a /// static variable, as we do not track those in the MoveData. fn move_path_closest_to( &mut self, @@ -1439,7 +1439,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { } match *last_prefix { Place::Local(_) => panic!("should have move path for every Local"), - Place::Projection(_) => panic!("PrefixSet::All meant dont stop for Projection"), + Place::Projection(_) => panic!("PrefixSet::All meant don't stop for Projection"), Place::Static(_) => return Err(NoMovePathFound::ReachedStatic), } } @@ -1484,7 +1484,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { { } ProjectionElem::Subslice { .. } => { - panic!("we dont allow assignments to subslices, context: {:?}", + panic!("we don't allow assignments to subslices, context: {:?}", context); } diff --git a/src/librustc_mir/borrow_check/nll/mod.rs b/src/librustc_mir/borrow_check/nll/mod.rs index 66ca74b0139..07e5091da9c 100644 --- a/src/librustc_mir/borrow_check/nll/mod.rs +++ b/src/librustc_mir/borrow_check/nll/mod.rs @@ -278,7 +278,7 @@ fn for_each_region_constraint( /// Right now, we piggy back on the `ReVar` to store our NLL inference /// regions. These are indexed with `RegionVid`. This method will -/// assert that the region is a `ReVar` and extract its interal index. +/// assert that the region is a `ReVar` and extract its internal index. /// This is reasonable because in our MIR we replace all universal regions /// with inference variables. pub trait ToRegionVid { diff --git a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs index 9a338947f47..33c012dfad8 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs @@ -964,7 +964,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { debug!("check_universal_region: fr_minus={:?}", fr_minus); // Grow `shorter_fr` until we find a non-local - // regon. (We always will.) We'll call that + // region. (We always will.) We'll call that // `shorter_fr+` -- it's ever so slightly larger than // `fr`. let shorter_fr_plus = self.universal_regions.non_local_upper_bound(shorter_fr); diff --git a/src/librustc_mir/borrow_check/nll/region_infer/values.rs b/src/librustc_mir/borrow_check/nll/region_infer/values.rs index b2b2ca1182d..45236bbc4aa 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/values.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/values.rs @@ -150,7 +150,7 @@ pub(super) enum RegionElement { /// A point in the control-flow graph. Location(Location), - /// An in-scope, universally quantified region (e.g., a liftime parameter). + /// An in-scope, universally quantified region (e.g., a lifetime parameter). UniversalRegion(RegionVid), } diff --git a/src/librustc_mir/build/matches/mod.rs b/src/librustc_mir/build/matches/mod.rs index 8053a0a6948..58ce572ae8d 100644 --- a/src/librustc_mir/build/matches/mod.rs +++ b/src/librustc_mir/build/matches/mod.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Code related to match expresions. These are sufficiently complex +//! Code related to match expressions. These are sufficiently complex //! to warrant their own module and submodules. :) This main module //! includes the high-level algorithm, the submodules contain the //! details. diff --git a/src/librustc_mir/dataflow/impls/borrows.rs b/src/librustc_mir/dataflow/impls/borrows.rs index e798cc93cb0..8ab4035cf4a 100644 --- a/src/librustc_mir/dataflow/impls/borrows.rs +++ b/src/librustc_mir/dataflow/impls/borrows.rs @@ -80,14 +80,14 @@ pub struct Borrows<'a, 'gcx: 'tcx, 'tcx: 'a> { /// tracking (phased) borrows. It computes where a borrow is reserved; /// i.e. where it can reach in the control flow starting from its /// initial `assigned = &'rgn borrowed` statement, and ending -/// whereever `'rgn` itself ends. +/// wherever `'rgn` itself ends. pub(crate) struct Reservations<'a, 'gcx: 'tcx, 'tcx: 'a>(pub(crate) Borrows<'a, 'gcx, 'tcx>); /// The `ActiveBorrows` analysis is the second of the two flow /// analyses tracking (phased) borrows. It computes where any given /// borrow `&assigned = &'rgn borrowed` is *active*, which starts at /// the first use of `assigned` after the reservation has started, and -/// ends whereever `'rgn` itself ends. +/// ends wherever `'rgn` itself ends. pub(crate) struct ActiveBorrows<'a, 'gcx: 'tcx, 'tcx: 'a>(pub(crate) Borrows<'a, 'gcx, 'tcx>); impl<'a, 'gcx, 'tcx> Reservations<'a, 'gcx, 'tcx> { diff --git a/src/librustc_mir/diagnostics.rs b/src/librustc_mir/diagnostics.rs index 619c0dc847e..3491faf9cda 100644 --- a/src/librustc_mir/diagnostics.rs +++ b/src/librustc_mir/diagnostics.rs @@ -365,7 +365,7 @@ with `#[derive(Clone)]`. Some types have no ownership semantics at all and are trivial to duplicate. An example is `i32` and the other number types. We don't have to call `.clone()` to clone them, because they are marked `Copy` in addition to `Clone`. Implicit -cloning is more convienient in this case. We can mark our own types `Copy` if +cloning is more convenient in this case. We can mark our own types `Copy` if all their members also are marked `Copy`. In the example below, we implement a `Point` type. Because it only stores two diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 52b87282180..3578164feb7 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -84,7 +84,7 @@ pub struct Frame<'tcx> { /// return). pub block: mir::BasicBlock, - /// The index of the currently evaluated statment. + /// The index of the currently evaluated statement. pub stmt: usize, } diff --git a/src/librustc_mir/monomorphize/item.rs b/src/librustc_mir/monomorphize/item.rs index 86a4dd4a31f..a5078187a57 100644 --- a/src/librustc_mir/monomorphize/item.rs +++ b/src/librustc_mir/monomorphize/item.rs @@ -68,7 +68,7 @@ pub enum InstantiationMode { /// however, our local copy may conflict with other crates also /// inlining the same function. /// - /// This flag indicates that this situation is occuring, and informs + /// This flag indicates that this situation is occurring, and informs /// symbol name calculation that some extra mangling is needed to /// avoid conflicts. Note that this may eventually go away entirely if /// ThinLTO enables us to *always* have a globally shared instance of a diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index b46882f054d..6ae04760953 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -781,7 +781,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { // Additionally, until better reachability analysis for macros 2.0 is available, // we prohibit access to private statics from other crates, this allows to give // more code internal visibility at link time. (Access to private functions - // is already prohibited by type privacy for funciton types.) + // is already prohibited by type privacy for function types.) fn visit_qpath(&mut self, qpath: &'tcx hir::QPath, id: ast::NodeId, span: Span) { let def = match *qpath { hir::QPath::Resolved(_, ref path) => match path.def { diff --git a/src/librustc_resolve/check_unused.rs b/src/librustc_resolve/check_unused.rs index 5a321053b7a..a757ac92df5 100644 --- a/src/librustc_resolve/check_unused.rs +++ b/src/librustc_resolve/check_unused.rs @@ -17,7 +17,7 @@ // `use` directives. // // Unused trait imports can't be checked until the method resolution. We save -// candidates here, and do the acutal check in librustc_typeck/check_unused.rs. +// candidates here, and do the actual check in librustc_typeck/check_unused.rs. use std::ops::{Deref, DerefMut}; diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 2da4bfedd3a..d8e03552a6a 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1440,7 +1440,7 @@ impl<'a> Resolver<'a> { /// Rustdoc uses this to resolve things in a recoverable way. ResolutionError<'a> /// isn't something that can be returned because it can't be made to live that long, /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, - /// just that an error occured. + /// just that an error occurred. pub fn resolve_str_path_error(&mut self, span: Span, path_str: &str, is_value: bool) -> Result { use std::iter; diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index a8070c553bd..438ab3a3513 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -186,7 +186,7 @@ impl<'a> Resolver<'a> { } let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| { - // `extern crate` are always usable for backwards compatability, see issue #37020. + // `extern crate` are always usable for backwards compatibility, see issue #37020. let usable = this.is_accessible(binding.vis) || binding.is_extern_crate(); if usable { Ok(binding) } else { Err(Determined) } }; diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index a3327038019..ab354a30d41 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -84,7 +84,7 @@ impl LtoModuleTranslation { } } - /// A "guage" of how costly it is to optimize this module, used to sort + /// A "gauge" of how costly it is to optimize this module, used to sort /// biggest modules first. pub fn cost(&self) -> u64 { match *self { @@ -726,7 +726,7 @@ impl ThinModule { // which was basically a resurgence of #45511 after LLVM's bug 35212 was // fixed. // - // This function below is a huge hack around tihs problem. The function + // This function below is a huge hack around this problem. The function // below is defined in `PassWrapper.cpp` and will basically "merge" // all `DICompileUnit` instances in a module. Basically it'll take all // the objects, rewrite all pointers of `DISubprogram` to point to the diff --git a/src/librustc_trans/builder.rs b/src/librustc_trans/builder.rs index 5ab8d03b8c7..d4e05a18e3a 100644 --- a/src/librustc_trans/builder.rs +++ b/src/librustc_trans/builder.rs @@ -1240,7 +1240,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { /// on), and `ptr` is nonzero-sized, then extracts the size of `ptr` /// and the intrinsic for `lt` and passes them to `emit`, which is in /// charge of generating code to call the passed intrinsic on whatever - /// block of generated code is targetted for the intrinsic. + /// block of generated code is targeted for the intrinsic. /// /// If LLVM lifetime intrinsic support is disabled (i.e. optimizations /// off) or `ptr` is zero-sized, then no-op (does not call `emit`). diff --git a/src/librustc_trans/mir/rvalue.rs b/src/librustc_trans/mir/rvalue.rs index 2e876ec118d..34ac44cec02 100644 --- a/src/librustc_trans/mir/rvalue.rs +++ b/src/librustc_trans/mir/rvalue.rs @@ -844,7 +844,7 @@ fn cast_float_to_int(bx: &Builder, // They are exactly equal to int_ty::{MIN,MAX} if float_ty has enough significand bits. // Otherwise, int_ty::MAX must be rounded towards zero, as it is one less than a power of two. // int_ty::MIN, however, is either zero or a negative power of two and is thus exactly - // representable. Note that this only works if float_ty's exponent range is sufficently large. + // representable. Note that this only works if float_ty's exponent range is sufficiently large. // f16 or 256 bit integers would break this property. Right now the smallest float type is f32 // with exponents ranging up to 127, which is barely enough for i128::MIN = -2^127. // On the other hand, f_max works even if int_ty::MAX is greater than float_ty::MAX. Because diff --git a/src/librustc_trans_utils/trans_crate.rs b/src/librustc_trans_utils/trans_crate.rs index e14abdff339..9943a9bd398 100644 --- a/src/librustc_trans_utils/trans_crate.rs +++ b/src/librustc_trans_utils/trans_crate.rs @@ -151,7 +151,7 @@ impl MetadataLoader for NoLlvmMetadataLoader { } } - Err("Couldnt find metadata section".to_string()) + Err("Couldn't find metadata section".to_string()) } fn get_dylib_metadata( diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 4e7db5f0826..9250c1c437b 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -293,7 +293,7 @@ impl Seek for BufReader { /// where `n` minus the internal buffer length overflows an `i64`, two /// seeks will be performed instead of one. If the second seek returns /// `Err`, the underlying reader will be left at the same position it would - /// have if you seeked to `SeekFrom::Current(0)`. + /// have if you called `seek` with `SeekFrom::Current(0)`. /// /// [`seek_relative`]: #method.seek_relative fn seek(&mut self, pos: SeekFrom) -> io::Result { diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 2edf02efc47..f7fdedc0d21 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -24,8 +24,8 @@ use sys_common::rwlock as sys; /// typically allows for read-only access (shared access). /// /// In comparison, a [`Mutex`] does not distinguish between readers or writers -/// that aquire the lock, therefore blocking any threads waiting for the lock to -/// become available. An `RwLock` will allow any number of readers to aquire the +/// that acquire the lock, therefore blocking any threads waiting for the lock to +/// become available. An `RwLock` will allow any number of readers to acquire the /// lock as long as a writer is not holding the lock. /// /// The priority policy of the lock is dependent on the underlying operating diff --git a/src/libstd/sys_common/backtrace.rs b/src/libstd/sys_common/backtrace.rs index a364a0392b3..1955f3ec9a2 100644 --- a/src/libstd/sys_common/backtrace.rs +++ b/src/libstd/sys_common/backtrace.rs @@ -136,7 +136,7 @@ pub fn __rust_begin_short_backtrace(f: F) -> T f() } -/// Controls how the backtrace should be formated. +/// Controls how the backtrace should be formatted. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum PrintFormat { /// Show all the frames with absolute path for files. diff --git a/src/libstd/sys_common/poison.rs b/src/libstd/sys_common/poison.rs index 934ac3edbf1..e74c40ae04b 100644 --- a/src/libstd/sys_common/poison.rs +++ b/src/libstd/sys_common/poison.rs @@ -98,7 +98,7 @@ pub struct PoisonError { } /// An enumeration of possible errors associated with a [`TryLockResult`] which -/// can occur while trying to aquire a lock, from the [`try_lock`] method on a +/// can occur while trying to acquire a lock, from the [`try_lock`] method on a /// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`]. /// /// [`Mutex`]: struct.Mutex.html diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index c7ab6158256..8c1e5cf7586 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -918,7 +918,7 @@ pub struct Expr { } impl Expr { - /// Wether this expression would be valid somewhere that expects a value, for example, an `if` + /// Whether this expression would be valid somewhere that expects a value, for example, an `if` /// condition. pub fn returns(&self) -> bool { if let ExprKind::Block(ref block) = self.node { diff --git a/src/libsyntax/config.rs b/src/libsyntax/config.rs index fc82357455b..aa360ed1bf5 100644 --- a/src/libsyntax/config.rs +++ b/src/libsyntax/config.rs @@ -114,7 +114,7 @@ impl<'a> StripUnconfigured<'a> { } } - // Determine if a node with the given attributes should be included in this configuation. + // Determine if a node with the given attributes should be included in this configuration. pub fn in_cfg(&mut self, attrs: &[ast::Attribute]) -> bool { attrs.iter().all(|attr| { // When not compiling with --test we should not compile the #[test] functions diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index ac582627f88..7915109ce3a 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -3912,7 +3912,7 @@ impl<'a> Parser<'a> { "use `=` if you meant to assign", "=".to_string()); err.emit(); - // As this was parsed successfuly, continue as if the code has been fixed for the + // As this was parsed successfully, continue as if the code has been fixed for the // rest of the file. It will still fail due to the emitted error, but we avoid // extra noise. init @@ -6571,7 +6571,7 @@ impl<'a> Parser<'a> { return Ok(Some(macro_def)); } - // Verify wether we have encountered a struct or method definition where the user forgot to + // Verify whether we have encountered a struct or method definition where the user forgot to // add the `struct` or `fn` keyword after writing `pub`: `pub S {}` if visibility == Visibility::Public && self.check_ident() && diff --git a/src/test/compile-fail/coerce-to-bang.rs b/src/test/compile-fail/coerce-to-bang.rs index 2cf568777d4..b804bb2981b 100644 --- a/src/test/compile-fail/coerce-to-bang.rs +++ b/src/test/compile-fail/coerce-to-bang.rs @@ -14,7 +14,7 @@ fn foo(x: usize, y: !, z: usize) { } fn call_foo_a() { - // FIXME(#40800) -- accepted beacuse divergence happens **before** + // FIXME(#40800) -- accepted because divergence happens **before** // the coercion to `!`, but within same expression. Not clear that // these are the rules we want. foo(return, 22, 44); diff --git a/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/bar.rs b/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/bar.rs index 9177dcba0d7..4ef92981314 100644 --- a/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/bar.rs +++ b/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/bar.rs @@ -8,4 +8,4 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-test not a test, auxillary +// ignore-test not a test, auxiliary diff --git a/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/mod.rs b/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/mod.rs index e29c985b983..41a8c288e7c 100644 --- a/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/mod.rs +++ b/src/test/compile-fail/directory_ownership/macro_expanded_mod_helper/foo/mod.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-test not a test, auxillary +// ignore-test not a test, auxiliary mod_decl!(bar); diff --git a/src/test/compile-fail/hr-subtype.rs b/src/test/compile-fail/hr-subtype.rs index c88d74d53ce..86df2382732 100644 --- a/src/test/compile-fail/hr-subtype.rs +++ b/src/test/compile-fail/hr-subtype.rs @@ -84,7 +84,7 @@ check! { free_inv_x_vs_free_inv_y: (fn(Inv<'x>), fn(Inv<'y>)) } // Somewhat surprisingly, a fn taking two distinct bound lifetimes and -// a fn taking one bound lifetime can be interchangable, but only if +// a fn taking one bound lifetime can be interchangeable, but only if // we are co- or contra-variant with respect to both lifetimes. // // The reason is: @@ -100,7 +100,7 @@ check! { bound_contra_a_contra_b_ret_co_a: (for<'a,'b> fn(Contra<'a>, Contra<'b> check! { bound_co_a_co_b_ret_contra_a: (for<'a,'b> fn(Co<'a>, Co<'b>) -> Contra<'a>, for<'a> fn(Co<'a>, Co<'a>) -> Contra<'a>) } -// If we make those lifetimes invariant, then the two types are not interchangable. +// If we make those lifetimes invariant, then the two types are not interchangeable. check! { bound_inv_a_b_vs_bound_inv_a: (for<'a,'b> fn(Inv<'a>, Inv<'b>), for<'a> fn(Inv<'a>, Inv<'a>)) } check! { bound_a_b_ret_a_vs_bound_a_ret_a: (for<'a,'b> fn(&'a u32, &'b u32) -> &'a u32, diff --git a/src/test/compile-fail/issue-20616-1.rs b/src/test/compile-fail/issue-20616-1.rs index a1949df661a..3e29383d62c 100644 --- a/src/test/compile-fail/issue-20616-1.rs +++ b/src/test/compile-fail/issue-20616-1.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-2.rs b/src/test/compile-fail/issue-20616-2.rs index 87b836d6872..1ec7a74559a 100644 --- a/src/test/compile-fail/issue-20616-2.rs +++ b/src/test/compile-fail/issue-20616-2.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-3.rs b/src/test/compile-fail/issue-20616-3.rs index e5ed46d2cb3..885fd246547 100644 --- a/src/test/compile-fail/issue-20616-3.rs +++ b/src/test/compile-fail/issue-20616-3.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-4.rs b/src/test/compile-fail/issue-20616-4.rs index 9b731289e13..0dbe92fc1bc 100644 --- a/src/test/compile-fail/issue-20616-4.rs +++ b/src/test/compile-fail/issue-20616-4.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-5.rs b/src/test/compile-fail/issue-20616-5.rs index 5e3b024da9a..794e5178f4b 100644 --- a/src/test/compile-fail/issue-20616-5.rs +++ b/src/test/compile-fail/issue-20616-5.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-6.rs b/src/test/compile-fail/issue-20616-6.rs index b6ee26f9f62..fe91751a4a0 100644 --- a/src/test/compile-fail/issue-20616-6.rs +++ b/src/test/compile-fail/issue-20616-6.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-7.rs b/src/test/compile-fail/issue-20616-7.rs index fef3dd4e31d..184ad027102 100644 --- a/src/test/compile-fail/issue-20616-7.rs +++ b/src/test/compile-fail/issue-20616-7.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-8.rs b/src/test/compile-fail/issue-20616-8.rs index b7bef47c4f4..5cdec33e94b 100644 --- a/src/test/compile-fail/issue-20616-8.rs +++ b/src/test/compile-fail/issue-20616-8.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/issue-20616-9.rs b/src/test/compile-fail/issue-20616-9.rs index 5c16d24cef8..7995addb692 100644 --- a/src/test/compile-fail/issue-20616-9.rs +++ b/src/test/compile-fail/issue-20616-9.rs @@ -9,7 +9,7 @@ // except according to those terms. // We need all these 9 issue-20616-N.rs files -// becase we can only catch one parsing error at a time +// because we can only catch one parsing error at a time diff --git a/src/test/compile-fail/no_crate_type.rs b/src/test/compile-fail/no_crate_type.rs index bef909917d2..b2cc5cae697 100644 --- a/src/test/compile-fail/no_crate_type.rs +++ b/src/test/compile-fail/no_crate_type.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// regresion test for issue 11256 +// regression test for issue 11256 #![crate_type] //~ ERROR `crate_type` requires a value fn main() { diff --git a/src/test/mir-opt/README.md b/src/test/mir-opt/README.md index b00b35aa29f..ad4932b9fb9 100644 --- a/src/test/mir-opt/README.md +++ b/src/test/mir-opt/README.md @@ -26,7 +26,7 @@ other non-matched lines before and after, but not between $expected_lines, should you want to skip lines, you must include an elision comment, of the form (as a regex) `//\s*...\s*`. The lines will be skipped lazily, that is, if there are two identical lines in the output that match the line after the elision -comment, the first one wil be matched. +comment, the first one will be matched. Examples: diff --git a/src/test/pretty/stmt_expr_attributes.rs b/src/test/pretty/stmt_expr_attributes.rs index 1c443020d2e..17e6119f968 100644 --- a/src/test/pretty/stmt_expr_attributes.rs +++ b/src/test/pretty/stmt_expr_attributes.rs @@ -255,7 +255,7 @@ fn _11() { while true { let _ = #[attr] break ; } || #[attr] return; let _ = #[attr] expr_mac!(); - /* FIXME: pp bug, loosing delimiter styles + /* FIXME: pp bug, losing delimiter styles let _ = #[attr] expr_mac![]; let _ = #[attr] expr_mac!{}; */ diff --git a/src/test/run-make/hotplug_codegen_backend/Makefile b/src/test/run-make/hotplug_codegen_backend/Makefile index 9a216d1d81f..2ddf3aa5439 100644 --- a/src/test/run-make/hotplug_codegen_backend/Makefile +++ b/src/test/run-make/hotplug_codegen_backend/Makefile @@ -6,4 +6,4 @@ all: -o $(TMPDIR)/the_backend.dylib $(RUSTC) some_crate.rs --crate-name some_crate --crate-type bin -o $(TMPDIR)/some_crate \ -Z codegen-backend=$(TMPDIR)/the_backend.dylib -Z unstable-options - grep -x "This has been \"compiled\" succesfully." $(TMPDIR)/some_crate + grep -x "This has been \"compiled\" successfully." $(TMPDIR)/some_crate diff --git a/src/test/run-make/hotplug_codegen_backend/the_backend.rs b/src/test/run-make/hotplug_codegen_backend/the_backend.rs index 5972149590c..9e87268e699 100644 --- a/src/test/run-make/hotplug_codegen_backend/the_backend.rs +++ b/src/test/run-make/hotplug_codegen_backend/the_backend.rs @@ -69,7 +69,7 @@ impl TransCrate for TheBackend { let output_name = out_filename(sess, crate_type, &outputs, &*crate_name.as_str()); let mut out_file = ::std::fs::File::create(output_name).unwrap(); - write!(out_file, "This has been \"compiled\" succesfully.").unwrap(); + write!(out_file, "This has been \"compiled\" successfully.").unwrap(); } Ok(()) } diff --git a/src/test/run-pass-fulldeps/proc-macro/auxiliary/derive-reexport.rs b/src/test/run-pass-fulldeps/proc-macro/auxiliary/derive-reexport.rs index 24865ea2709..cfaf913216a 100644 --- a/src/test/run-pass-fulldeps/proc-macro/auxiliary/derive-reexport.rs +++ b/src/test/run-pass-fulldeps/proc-macro/auxiliary/derive-reexport.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// ignore-test not a test, auxillary +// ignore-test not a test, auxiliary #![feature(macro_reexport)] diff --git a/src/test/run-pass/issue-29746.rs b/src/test/run-pass/issue-29746.rs index 61c601ac6a9..d4463fed1a6 100644 --- a/src/test/run-pass/issue-29746.rs +++ b/src/test/run-pass/issue-29746.rs @@ -17,7 +17,7 @@ macro_rules! zip { }; // Intermediate steps to build the zipped expression, the match pattern, and - // and the output tuple of the closure, using macro hygene to repeatedly + // and the output tuple of the closure, using macro hygiene to repeatedly // introduce new variables named 'x'. ([$a:expr, $($rest:expr),*], $zip:expr, $pat:pat, [$($flat:expr),*]) => { zip!([$($rest),*], $zip.zip($a), ($pat,x), [$($flat),*, x]) diff --git a/src/test/run-pass/issue-32008.rs b/src/test/run-pass/issue-32008.rs index cb489acf1d9..95890d2e1b4 100644 --- a/src/test/run-pass/issue-32008.rs +++ b/src/test/run-pass/issue-32008.rs @@ -9,7 +9,7 @@ // except according to those terms. // Tests that binary operators allow subtyping on both the LHS and RHS, -// and as such do not introduce unnecesarily strict lifetime constraints. +// and as such do not introduce unnecessarily strict lifetime constraints. use std::ops::Add; diff --git a/src/test/run-pass/rfc1857-drop-order.rs b/src/test/run-pass/rfc1857-drop-order.rs index b2e5ff62eb8..94b2a586ddf 100644 --- a/src/test/run-pass/rfc1857-drop-order.rs +++ b/src/test/run-pass/rfc1857-drop-order.rs @@ -67,7 +67,7 @@ fn test_drop_tuple() { panic::catch_unwind(|| { (PushOnDrop::new(2, cloned.clone()), PushOnDrop::new(1, cloned.clone()), - panic!("this panic is catched :D")); + panic!("this panic is caught :D")); }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); } @@ -99,7 +99,7 @@ fn test_drop_struct() { TestStruct { x: PushOnDrop::new(2, cloned.clone()), y: PushOnDrop::new(1, cloned.clone()), - z: panic!("this panic is catched :D") + z: panic!("this panic is caught :D") }; }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); @@ -111,7 +111,7 @@ fn test_drop_struct() { TestStruct { y: PushOnDrop::new(2, cloned.clone()), x: PushOnDrop::new(1, cloned.clone()), - z: panic!("this panic is catched :D") + z: panic!("this panic is caught :D") }; }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); @@ -122,7 +122,7 @@ fn test_drop_struct() { panic::catch_unwind(|| { TestTupleStruct(PushOnDrop::new(2, cloned.clone()), PushOnDrop::new(1, cloned.clone()), - panic!("this panic is catched :D")); + panic!("this panic is caught :D")); }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); } @@ -154,7 +154,7 @@ fn test_drop_enum() { TestEnum::Struct { x: PushOnDrop::new(2, cloned.clone()), y: PushOnDrop::new(1, cloned.clone()), - z: panic!("this panic is catched :D") + z: panic!("this panic is caught :D") }; }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); @@ -166,7 +166,7 @@ fn test_drop_enum() { TestEnum::Struct { y: PushOnDrop::new(2, cloned.clone()), x: PushOnDrop::new(1, cloned.clone()), - z: panic!("this panic is catched :D") + z: panic!("this panic is caught :D") }; }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); @@ -177,7 +177,7 @@ fn test_drop_enum() { panic::catch_unwind(|| { TestEnum::Tuple(PushOnDrop::new(2, cloned.clone()), PushOnDrop::new(1, cloned.clone()), - panic!("this panic is catched :D")); + panic!("this panic is caught :D")); }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); } @@ -207,7 +207,7 @@ fn test_drop_list() { vec![ PushOnDrop::new(2, cloned.clone()), PushOnDrop::new(1, cloned.clone()), - panic!("this panic is catched :D") + panic!("this panic is caught :D") ]; }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); @@ -219,7 +219,7 @@ fn test_drop_list() { [ PushOnDrop::new(2, cloned.clone()), PushOnDrop::new(1, cloned.clone()), - panic!("this panic is catched :D") + panic!("this panic is caught :D") ]; }).err().unwrap(); assert_eq!(*dropped_fields.borrow(), &[1, 2]); diff --git a/src/test/run-pass/simd-target-feature-mixup.rs b/src/test/run-pass/simd-target-feature-mixup.rs index 2c9ef59709d..3c54921ac6e 100644 --- a/src/test/run-pass/simd-target-feature-mixup.rs +++ b/src/test/run-pass/simd-target-feature-mixup.rs @@ -30,7 +30,7 @@ fn main() { // We don't actually know if our computer has the requisite target features // for the test below. Testing for that will get added to libstd later so - // for now just asume sigill means this is a machine that can't run this test. + // for now just assume sigill means this is a machine that can't run this test. if is_sigill(status) { println!("sigill with {}, assuming spurious", level); continue diff --git a/src/test/rustdoc/impl-parts-crosscrate.rs b/src/test/rustdoc/impl-parts-crosscrate.rs index 5fa2e03e0a8..1d055ccbead 100644 --- a/src/test/rustdoc/impl-parts-crosscrate.rs +++ b/src/test/rustdoc/impl-parts-crosscrate.rs @@ -17,7 +17,7 @@ extern crate rustdoc_impl_parts_crosscrate; pub struct Bar { t: T } -// The output file is html embeded in javascript, so the html tags +// The output file is html embedded in javascript, so the html tags // aren't stripped by the processing script and we can't check for the // full impl string. Instead, just make sure something from each part // is mentioned. diff --git a/src/test/ui/explain.stdout b/src/test/ui/explain.stdout index 0bbbd95320a..411cdfb335b 100644 --- a/src/test/ui/explain.stdout +++ b/src/test/ui/explain.stdout @@ -45,7 +45,7 @@ is a function pointer, which is not zero-sized. This pattern should be rewritten. There are a few possible ways to do this: - change the original fn declaration to match the expected signature, - and do the cast in the fn body (the prefered option) + and do the cast in the fn body (the preferred option) - cast the fn item fo a fn pointer before calling transmute, as shown here: ``` diff --git a/src/test/ui/feature-gate/issue-43106-gating-of-builtin-attrs.rs b/src/test/ui/feature-gate/issue-43106-gating-of-builtin-attrs.rs index 029949b2604..21950402c8c 100644 --- a/src/test/ui/feature-gate/issue-43106-gating-of-builtin-attrs.rs +++ b/src/test/ui/feature-gate/issue-43106-gating-of-builtin-attrs.rs @@ -509,7 +509,7 @@ mod reexport_test_harness_main { //~^ WARN unused attribute } -// Cannnot feed "2700" to `#[macro_escape]` without signaling an error. +// Cannot feed "2700" to `#[macro_escape]` without signaling an error. #[macro_escape] //~^ WARN macro_escape is a deprecated synonym for macro_use mod macro_escape { diff --git a/src/test/ui/lifetime-errors/liveness-assign-imm-local-notes.rs b/src/test/ui/lifetime-errors/liveness-assign-imm-local-notes.rs index d4ef87cdd76..20a2cbfd3aa 100644 --- a/src/test/ui/lifetime-errors/liveness-assign-imm-local-notes.rs +++ b/src/test/ui/lifetime-errors/liveness-assign-imm-local-notes.rs @@ -9,7 +9,7 @@ // except according to those terms. // FIXME: Change to UI Test -// Check notes are placed on an assignment that can actually preceed the current assigmnent +// Check notes are placed on an assignment that can actually precede the current assigmnent // Don't emmit a first assignment for assignment in a loop. // compile-flags: -Zborrowck=compare -- cgit 1.4.1-3-g733a5 From 2e7e68b76223b9f14b54852584a5334f33a8798d Mon Sep 17 00:00:00 2001 From: "leonardo.yvens" Date: Mon, 5 Mar 2018 15:58:54 -0300 Subject: while let all the things --- src/librustc/hir/print.rs | 9 ++------- src/librustc/middle/reachable.rs | 6 +----- .../obligation_forest/mod.rs | 8 +------- src/libstd/sys_common/wtf8.rs | 23 +++++++++------------- src/libsyntax_ext/format.rs | 17 ++++++---------- src/libsyntax_pos/lib.rs | 7 +------ 6 files changed, 20 insertions(+), 50 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index ed8cea3eb65..d91aa3a3851 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -2208,13 +2208,8 @@ impl<'a> State<'a> { if self.next_comment().is_none() { self.s.hardbreak()?; } - loop { - match self.next_comment() { - Some(ref cmnt) => { - self.print_comment(cmnt)?; - } - _ => break, - } + while let Some(ref cmnt) = self.next_comment() { + self.print_comment(cmnt)? } Ok(()) } diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 749685182a8..5658b5b6832 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -206,11 +206,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { // Step 2: Mark all symbols that the symbols on the worklist touch. fn propagate(&mut self) { let mut scanned = FxHashSet(); - loop { - let search_item = match self.worklist.pop() { - Some(item) => item, - None => break, - }; + while let Some(search_item) = self.worklist.pop() { if !scanned.insert(search_item) { continue } diff --git a/src/librustc_data_structures/obligation_forest/mod.rs b/src/librustc_data_structures/obligation_forest/mod.rs index 02cae52166a..42a17d33fa6 100644 --- a/src/librustc_data_structures/obligation_forest/mod.rs +++ b/src/librustc_data_structures/obligation_forest/mod.rs @@ -415,13 +415,7 @@ impl ObligationForest { } } - loop { - // non-standard `while let` to bypass #6393 - let i = match error_stack.pop() { - Some(i) => i, - None => break - }; - + while let Some(i) = error_stack.pop() { let node = &self.nodes[i]; match node.state.get() { diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index 46d554d6411..9fff8b91f96 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -428,20 +428,15 @@ impl fmt::Debug for Wtf8 { formatter.write_str("\"")?; let mut pos = 0; - loop { - match self.next_surrogate(pos) { - None => break, - Some((surrogate_pos, surrogate)) => { - write_str_escaped( - formatter, - unsafe { str::from_utf8_unchecked( - &self.bytes[pos .. surrogate_pos] - )}, - )?; - write!(formatter, "\\u{{{:x}}}", surrogate)?; - pos = surrogate_pos + 3; - } - } + while let Some((surrogate_pos, surrogate)) = self.next_surrogate(pos) { + write_str_escaped( + formatter, + unsafe { str::from_utf8_unchecked( + &self.bytes[pos .. surrogate_pos] + )}, + )?; + write!(formatter, "\\u{{{:x}}}", surrogate)?; + pos = surrogate_pos + 3; } write_str_escaped( formatter, diff --git a/src/libsyntax_ext/format.rs b/src/libsyntax_ext/format.rs index a7822414c69..8fd95aa1ca8 100644 --- a/src/libsyntax_ext/format.rs +++ b/src/libsyntax_ext/format.rs @@ -732,18 +732,13 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, let mut parser = parse::Parser::new(fmt_str); let mut pieces = vec![]; - loop { - match parser.next() { - Some(mut piece) => { - if !parser.errors.is_empty() { - break; - } - cx.verify_piece(&piece); - cx.resolve_name_inplace(&mut piece); - pieces.push(piece); - } - None => break, + while let Some(mut piece) = parser.next() { + if !parser.errors.is_empty() { + break; } + cx.verify_piece(&piece); + cx.resolve_name_inplace(&mut piece); + pieces.push(piece); } let numbered_position_args = pieces.iter().any(|arg: &parse::Piece| { diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 9f746adbe65..ed9eb5d5c92 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -322,12 +322,7 @@ impl Span { pub fn macro_backtrace(mut self) -> Vec { let mut prev_span = DUMMY_SP; let mut result = vec![]; - loop { - let info = match self.ctxt().outer().expn_info() { - Some(info) => info, - None => break, - }; - + while let Some(info) = self.ctxt().outer().expn_info() { let (pre, post) = match info.callee.format { ExpnFormat::MacroAttribute(..) => ("#[", "]"), ExpnFormat::MacroBang(..) => ("", "!"), -- cgit 1.4.1-3-g733a5 From e85c9227c2e913b71f0d7b6cc2322d7897f28554 Mon Sep 17 00:00:00 2001 From: Tatsuyuki Ishi Date: Tue, 27 Feb 2018 16:51:12 +0900 Subject: rustc_driver: get rid of extra thread on Unix --- src/librustc_driver/lib.rs | 51 ++++++++++++++++++++++++++++++------ src/libstd/sys_common/thread_info.rs | 4 +++ src/libstd/thread/mod.rs | 8 ++++++ 3 files changed, 55 insertions(+), 8 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index f1f3a0519bb..8605764497a 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -24,6 +24,7 @@ #![feature(quote)] #![feature(rustc_diagnostic_macros)] #![feature(set_stdio)] +#![feature(rustc_stack_internals)] extern crate arena; extern crate getopts; @@ -1461,16 +1462,50 @@ pub fn in_rustc_thread(f: F) -> Result> // Temporarily have stack size set to 16MB to deal with nom-using crates failing const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB - let mut cfg = thread::Builder::new().name("rustc".to_string()); + #[cfg(unix)] + let spawn_thread = unsafe { + // Fetch the current resource limits + let mut rlim = libc::rlimit { + rlim_cur: 0, + rlim_max: 0, + }; + if libc::getrlimit(libc::RLIMIT_STACK, &mut rlim) != 0 { + let err = io::Error::last_os_error(); + error!("in_rustc_thread: error calling getrlimit: {}", err); + true + } else if rlim.rlim_max < STACK_SIZE as libc::rlim_t { + true + } else { + rlim.rlim_cur = STACK_SIZE as libc::rlim_t; + if libc::setrlimit(libc::RLIMIT_STACK, &mut rlim) != 0 { + let err = io::Error::last_os_error(); + error!("in_rustc_thread: error calling setrlimit: {}", err); + true + } else { + std::thread::update_stack_guard(); + false + } + } + }; - // FIXME: Hacks on hacks. If the env is trying to override the stack size - // then *don't* set it explicitly. - if env::var_os("RUST_MIN_STACK").is_none() { - cfg = cfg.stack_size(STACK_SIZE); - } + #[cfg(not(unix))] + let spawn_thread = true; + + // The or condition is added from backward compatibility. + if spawn_thread || env::var_os("RUST_MIN_STACK").is_some() { + let mut cfg = thread::Builder::new().name("rustc".to_string()); + + // FIXME: Hacks on hacks. If the env is trying to override the stack size + // then *don't* set it explicitly. + if env::var_os("RUST_MIN_STACK").is_none() { + cfg = cfg.stack_size(STACK_SIZE); + } - let thread = cfg.spawn(f); - thread.unwrap().join() + let thread = cfg.spawn(f); + thread.unwrap().join() + } else { + Ok(f()) + } } /// Get a list of extra command-line flags provided by the user, as strings. diff --git a/src/libstd/sys_common/thread_info.rs b/src/libstd/sys_common/thread_info.rs index 6a2b6742367..d75cbded734 100644 --- a/src/libstd/sys_common/thread_info.rs +++ b/src/libstd/sys_common/thread_info.rs @@ -50,3 +50,7 @@ pub fn set(stack_guard: Option, thread: Thread) { thread, })); } + +pub fn reset_guard(stack_guard: Option) { + THREAD_INFO.with(move |c| c.borrow_mut().as_mut().unwrap().stack_guard = stack_guard); +} diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 71aee673cfe..b686ddc205e 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -208,6 +208,14 @@ pub use self::local::{LocalKey, AccessError}; #[unstable(feature = "libstd_thread_internals", issue = "0")] #[doc(hidden)] pub use self::local::os::Key as __OsLocalKeyInner; +/// Function used for resetting the main stack guard address after setrlimit(). +/// This is POSIX specific and unlikely to be directly stabilized. +#[unstable(feature = "rustc_stack_internals", issue = "0")] +pub unsafe fn update_stack_guard() { + let main_guard = imp::guard::init(); + thread_info::reset_guard(main_guard); +} + //////////////////////////////////////////////////////////////////////////////// // Builder //////////////////////////////////////////////////////////////////////////////// -- cgit 1.4.1-3-g733a5 From 6212904dd800864ca20ede8690fc827a1169fa26 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Mon, 19 Mar 2018 15:40:09 -0700 Subject: Don't use posix_spawn() if PATH was modified in the environment. The expected behavior is that the environment's PATH should be used to find the process. posix_spawn() could be used if we iterated PATH to search for the binary to execute. For now just skip posix_spawn() if PATH is modified. --- src/libstd/sys/unix/process/process_common.rs | 3 +++ src/libstd/sys/unix/process/process_unix.rs | 1 + src/libstd/sys_common/process.rs | 12 ++++++++++++ 3 files changed, 16 insertions(+) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys/unix/process/process_common.rs b/src/libstd/sys/unix/process/process_common.rs index d0486f06a14..48255489dd9 100644 --- a/src/libstd/sys/unix/process/process_common.rs +++ b/src/libstd/sys/unix/process/process_common.rs @@ -184,6 +184,9 @@ impl Command { let maybe_env = self.env.capture_if_changed(); maybe_env.map(|env| construct_envp(env, &mut self.saw_nul)) } + pub fn env_saw_path(&self) -> bool { + self.env.have_changed_path() + } pub fn setup_io(&self, default: Stdio, needs_stdin: bool) -> io::Result<(StdioPipes, ChildPipes)> { diff --git a/src/libstd/sys/unix/process/process_unix.rs b/src/libstd/sys/unix/process/process_unix.rs index 29e33ee822e..9d6d607e3f3 100644 --- a/src/libstd/sys/unix/process/process_unix.rs +++ b/src/libstd/sys/unix/process/process_unix.rs @@ -256,6 +256,7 @@ impl Command { if self.get_cwd().is_some() || self.get_gid().is_some() || self.get_uid().is_some() || + self.env_saw_path() || self.get_closures().len() != 0 { return Ok(None) } diff --git a/src/libstd/sys_common/process.rs b/src/libstd/sys_common/process.rs index fd1a5fdb410..775491d762c 100644 --- a/src/libstd/sys_common/process.rs +++ b/src/libstd/sys_common/process.rs @@ -47,6 +47,7 @@ impl EnvKey for DefaultEnvKey {} #[derive(Clone, Debug)] pub struct CommandEnv { clear: bool, + saw_path: bool, vars: BTreeMap> } @@ -54,6 +55,7 @@ impl Default for CommandEnv { fn default() -> Self { CommandEnv { clear: false, + saw_path: false, vars: Default::default() } } @@ -108,9 +110,11 @@ impl CommandEnv { // The following functions build up changes pub fn set(&mut self, key: &OsStr, value: &OsStr) { + self.maybe_saw_path(&key); self.vars.insert(key.to_owned().into(), Some(value.to_owned())); } pub fn remove(&mut self, key: &OsStr) { + self.maybe_saw_path(&key); if self.clear { self.vars.remove(key); } else { @@ -121,4 +125,12 @@ impl CommandEnv { self.clear = true; self.vars.clear(); } + pub fn have_changed_path(&self) -> bool { + self.saw_path || self.clear + } + fn maybe_saw_path(&mut self, key: &OsStr) { + if !self.saw_path && key.to_os_string() == OsString::from("PATH") { + self.saw_path = true; + } + } } -- cgit 1.4.1-3-g733a5 From 8e0faf79c0859f22d4e11268f272247a6ef73709 Mon Sep 17 00:00:00 2001 From: Bryan Drewery Date: Mon, 19 Mar 2018 16:15:26 -0700 Subject: Simplify PATH key comparison --- src/libstd/sys_common/process.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys_common/process.rs b/src/libstd/sys_common/process.rs index 775491d762c..d0c5951bd6c 100644 --- a/src/libstd/sys_common/process.rs +++ b/src/libstd/sys_common/process.rs @@ -129,7 +129,7 @@ impl CommandEnv { self.saw_path || self.clear } fn maybe_saw_path(&mut self, key: &OsStr) { - if !self.saw_path && key.to_os_string() == OsString::from("PATH") { + if !self.saw_path && key == "PATH" { self.saw_path = true; } } -- cgit 1.4.1-3-g733a5 From c09b9f937250db0f51b705a3110f8cffdad083bb Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Sat, 17 Mar 2018 12:15:24 +0100 Subject: Deprecate the AsciiExt trait in favor of inherent methods The trait and some of its methods are stable and will remain. Some of the newer methods are unstable and can be removed later. Fixes https://github.com/rust-lang/rust/issues/39658 --- src/libcore/tests/ascii.rs | 3 --- src/libstd/ascii.rs | 17 +++++++++++++++++ src/libstd/sys/windows/process.rs | 1 - src/libstd/sys_common/wtf8.rs | 17 +++++++---------- src/test/run-pass/issue-10683.rs | 2 -- 5 files changed, 24 insertions(+), 16 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libcore/tests/ascii.rs b/src/libcore/tests/ascii.rs index 4d43067ad2c..950222dbcfa 100644 --- a/src/libcore/tests/ascii.rs +++ b/src/libcore/tests/ascii.rs @@ -9,7 +9,6 @@ // except according to those terms. use core::char::from_u32; -use std::ascii::AsciiExt; #[test] fn test_is_ascii() { @@ -143,8 +142,6 @@ macro_rules! assert_all { stringify!($what), b); } } - assert!($str.$what()); - assert!($str.as_bytes().$what()); )+ }}; ($what:ident, $($str:tt),+,) => (assert_all!($what,$($str),+)) diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 0837ff91c14..6472edb0aa7 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -52,6 +52,7 @@ pub use core::ascii::{EscapeDefault, escape_default}; /// /// [combining character]: https://en.wikipedia.org/wiki/Combining_character #[stable(feature = "rust1", since = "1.0.0")] +#[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] pub trait AsciiExt { /// Container type for copied ASCII characters. #[stable(feature = "rust1", since = "1.0.0")] @@ -84,6 +85,7 @@ pub trait AsciiExt { /// [`make_ascii_uppercase`]: #tymethod.make_ascii_uppercase /// [`str::to_uppercase`]: ../primitive.str.html#method.to_uppercase #[stable(feature = "rust1", since = "1.0.0")] + #[allow(deprecated)] fn to_ascii_uppercase(&self) -> Self::Owned; /// Makes a copy of the value in its ASCII lower case equivalent. @@ -104,6 +106,7 @@ pub trait AsciiExt { /// [`make_ascii_lowercase`]: #tymethod.make_ascii_lowercase /// [`str::to_lowercase`]: ../primitive.str.html#method.to_lowercase #[stable(feature = "rust1", since = "1.0.0")] + #[allow(deprecated)] fn to_ascii_lowercase(&self) -> Self::Owned; /// Checks that two values are an ASCII case-insensitive match. @@ -162,6 +165,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_alphabetic(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII uppercase character: @@ -174,6 +178,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_uppercase(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII lowercase character: @@ -186,6 +191,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_lowercase(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII alphanumeric character: @@ -199,6 +205,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_alphanumeric(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII decimal digit: @@ -211,6 +218,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_digit(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII hexadecimal digit: @@ -224,6 +232,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_hexdigit(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII punctuation character: @@ -241,6 +250,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_punctuation(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII graphic character: @@ -253,6 +263,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_graphic(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII whitespace character: @@ -282,6 +293,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_whitespace(&self) -> bool { unimplemented!(); } /// Checks if the value is an ASCII control character: @@ -294,6 +306,7 @@ pub trait AsciiExt { /// This method will be deprecated in favor of the identically-named /// inherent methods on `u8`, `char`, `[u8]` and `str`. #[unstable(feature = "ascii_ctype", issue = "39658")] + #[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")] fn is_ascii_control(&self) -> bool { unimplemented!(); } } @@ -354,6 +367,7 @@ macro_rules! delegating_ascii_ctype_methods { } #[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated)] impl AsciiExt for u8 { type Owned = u8; @@ -362,6 +376,7 @@ impl AsciiExt for u8 { } #[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated)] impl AsciiExt for char { type Owned = char; @@ -370,6 +385,7 @@ impl AsciiExt for char { } #[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated)] impl AsciiExt for [u8] { type Owned = Vec; @@ -427,6 +443,7 @@ impl AsciiExt for [u8] { } #[stable(feature = "rust1", since = "1.0.0")] +#[allow(deprecated)] impl AsciiExt for str { type Owned = String; diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index f1ab9c47609..afa8e3e1369 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -10,7 +10,6 @@ #![unstable(feature = "process_internals", issue = "0")] -use ascii::AsciiExt; use collections::BTreeMap; use env::split_paths; use env; diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index 9fff8b91f96..78b2bb5fe6e 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -27,7 +27,6 @@ use core::str::next_code_point; -use ascii::*; use borrow::Cow; use char; use fmt; @@ -871,24 +870,22 @@ impl Hash for Wtf8 { } } -impl AsciiExt for Wtf8 { - type Owned = Wtf8Buf; - - fn is_ascii(&self) -> bool { +impl Wtf8 { + pub fn is_ascii(&self) -> bool { self.bytes.is_ascii() } - fn to_ascii_uppercase(&self) -> Wtf8Buf { + pub fn to_ascii_uppercase(&self) -> Wtf8Buf { Wtf8Buf { bytes: self.bytes.to_ascii_uppercase() } } - fn to_ascii_lowercase(&self) -> Wtf8Buf { + pub fn to_ascii_lowercase(&self) -> Wtf8Buf { Wtf8Buf { bytes: self.bytes.to_ascii_lowercase() } } - fn eq_ignore_ascii_case(&self, other: &Wtf8) -> bool { + pub fn eq_ignore_ascii_case(&self, other: &Wtf8) -> bool { self.bytes.eq_ignore_ascii_case(&other.bytes) } - fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() } - fn make_ascii_lowercase(&mut self) { self.bytes.make_ascii_lowercase() } + pub fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() } + pub fn make_ascii_lowercase(&mut self) { self.bytes.make_ascii_lowercase() } } #[cfg(test)] diff --git a/src/test/run-pass/issue-10683.rs b/src/test/run-pass/issue-10683.rs index eb2177202a2..d3ba477fa57 100644 --- a/src/test/run-pass/issue-10683.rs +++ b/src/test/run-pass/issue-10683.rs @@ -10,8 +10,6 @@ // pretty-expanded FIXME #23616 -use std::ascii::AsciiExt; - static NAME: &'static str = "hello world"; fn main() { -- cgit 1.4.1-3-g733a5 From 04f6692aaf78809c041ba6145bde2dcbeec9725e Mon Sep 17 00:00:00 2001 From: Diggory Blake Date: Mon, 26 Mar 2018 23:24:31 +0100 Subject: Implement `shrink_to` method on collections --- src/liballoc/binary_heap.rs | 25 ++++++++++++++++++++++++ src/liballoc/string.rs | 28 ++++++++++++++++++++++++++ src/liballoc/vec.rs | 27 ++++++++++++++++++++++++- src/liballoc/vec_deque.rs | 35 ++++++++++++++++++++++++++++++++- src/libstd/collections/hash/map.rs | 40 ++++++++++++++++++++++++++++++++++++++ src/libstd/collections/hash/set.rs | 28 ++++++++++++++++++++++++++ src/libstd/ffi/os_str.rs | 30 ++++++++++++++++++++++++++++ src/libstd/lib.rs | 1 + src/libstd/sys/redox/os_str.rs | 5 +++++ src/libstd/sys/unix/os_str.rs | 5 +++++ src/libstd/sys/wasm/os_str.rs | 5 +++++ src/libstd/sys/windows/os_str.rs | 5 +++++ src/libstd/sys_common/wtf8.rs | 5 +++++ 13 files changed, 237 insertions(+), 2 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/liballoc/binary_heap.rs b/src/liballoc/binary_heap.rs index 8aaac5d6e08..f6a666b599b 100644 --- a/src/liballoc/binary_heap.rs +++ b/src/liballoc/binary_heap.rs @@ -509,6 +509,31 @@ impl BinaryHeap { self.data.shrink_to_fit(); } + /// Discards capacity with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// use std::collections::BinaryHeap; + /// let mut heap: BinaryHeap = BinaryHeap::with_capacity(100); + /// + /// assert!(heap.capacity() >= 100); + /// heap.shrink_to(10); + /// assert!(heap.capacity() >= 10); + /// ``` + #[inline] + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.data.shrink_to(min_capacity) + } + /// Removes the greatest item from the binary heap and returns it, or `None` if it /// is empty. /// diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs index e253122ffd6..2bb60a50679 100644 --- a/src/liballoc/string.rs +++ b/src/liballoc/string.rs @@ -1015,6 +1015,34 @@ impl String { self.vec.shrink_to_fit() } + /// Shrinks the capacity of this `String` with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// let mut s = String::from("foo"); + /// + /// s.reserve(100); + /// assert!(s.capacity() >= 100); + /// + /// s.shrink_to(10); + /// assert!(s.capacity() >= 10); + /// s.shrink_to(0); + /// assert!(s.capacity() >= 3); + /// ``` + #[inline] + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.vec.shrink_to(min_capacity) + } + /// Appends the given [`char`] to the end of this `String`. /// /// [`char`]: ../../std/primitive.char.html diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs index 953f95876be..c9c6cf1cb66 100644 --- a/src/liballoc/vec.rs +++ b/src/liballoc/vec.rs @@ -66,7 +66,7 @@ #![stable(feature = "rust1", since = "1.0.0")] -use core::cmp::Ordering; +use core::cmp::{self, Ordering}; use core::fmt; use core::hash::{self, Hash}; use core::intrinsics::{arith_offset, assume}; @@ -586,6 +586,31 @@ impl Vec { self.buf.shrink_to_fit(self.len); } + /// Shrinks the capacity of the vector with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// let mut vec = Vec::with_capacity(10); + /// vec.extend([1, 2, 3].iter().cloned()); + /// assert_eq!(vec.capacity(), 10); + /// vec.shrink_to(4); + /// assert!(vec.capacity() >= 4); + /// vec.shrink_to(0); + /// assert!(vec.capacity() >= 3); + /// ``` + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.buf.shrink_to_fit(cmp::max(self.len, min_capacity)); + } + /// Converts the vector into [`Box<[T]>`][owned slice]. /// /// Note that this will drop any excess capacity. diff --git a/src/liballoc/vec_deque.rs b/src/liballoc/vec_deque.rs index 0658777f0a0..be6e8d0f22f 100644 --- a/src/liballoc/vec_deque.rs +++ b/src/liballoc/vec_deque.rs @@ -676,9 +676,42 @@ impl VecDeque { /// ``` #[stable(feature = "deque_extras_15", since = "1.5.0")] pub fn shrink_to_fit(&mut self) { + self.shrink_to(0); + } + + /// Shrinks the capacity of the `VecDeque` with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// use std::collections::VecDeque; + /// + /// let mut buf = VecDeque::with_capacity(15); + /// buf.extend(0..4); + /// assert_eq!(buf.capacity(), 15); + /// buf.shrink_to(6); + /// assert!(buf.capacity() >= 6); + /// buf.shrink_to(0); + /// assert!(buf.capacity() >= 4); + /// ``` + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity"); + // +1 since the ringbuffer always leaves one space empty // len + 1 can't overflow for an existing, well-formed ringbuffer. - let target_cap = cmp::max(self.len() + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); + let target_cap = cmp::max( + cmp::max(min_capacity, self.len()) + 1, + MINIMUM_CAPACITY + 1 + ).next_power_of_two(); + if target_cap < self.cap() { // There are three cases of interest: // All elements are out of desired bounds diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index b18b38ec302..169d365c0ac 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -910,6 +910,46 @@ impl HashMap } } + /// Shrinks the capacity of the map with a lower limit. It will drop + /// down no lower than the supplied limit while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// use std::collections::HashMap; + /// + /// let mut map: HashMap = HashMap::with_capacity(100); + /// map.insert(1, 2); + /// map.insert(3, 4); + /// assert!(map.capacity() >= 100); + /// map.shrink_to(10); + /// assert!(map.capacity() >= 10); + /// map.shrink_to(0); + /// assert!(map.capacity() >= 2); + /// ``` + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + assert!(self.capacity() >= min_capacity, "Tried to shrink to a larger capacity"); + + let new_raw_cap = self.resize_policy.raw_capacity(max(self.len(), min_capacity)); + if self.raw_capacity() != new_raw_cap { + let old_table = replace(&mut self.table, RawTable::new(new_raw_cap)); + let old_size = old_table.size(); + + // Shrink the table. Naive algorithm for resizing: + for (h, k, v) in old_table.into_iter() { + self.insert_hashed_nocheck(h, k, v); + } + + debug_assert_eq!(self.table.size(), old_size); + } + } + /// Insert a pre-hashed key-value pair, without first checking /// that there's enough room in the buckets. Returns a reference to the /// newly insert value. diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index 9e63ba2717a..855563a5cb8 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -292,6 +292,34 @@ impl HashSet self.map.shrink_to_fit() } + /// Shrinks the capacity of the set with a lower limit. It will drop + /// down no lower than the supplied limit while maintaining the internal rules + /// and possibly leaving some space in accordance with the resize policy. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// use std::collections::HashSet; + /// + /// let mut set = HashSet::with_capacity(100); + /// set.insert(1); + /// set.insert(2); + /// assert!(set.capacity() >= 100); + /// set.shrink_to(10); + /// assert!(set.capacity() >= 10); + /// set.shrink_to(0); + /// assert!(set.capacity() >= 2); + /// ``` + #[inline] + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.map.shrink_to(min_capacity) + } + /// An iterator visiting all elements in arbitrary order. /// The iterator element type is `&'a T`. /// diff --git a/src/libstd/ffi/os_str.rs b/src/libstd/ffi/os_str.rs index 3959e8533be..7520121a8c2 100644 --- a/src/libstd/ffi/os_str.rs +++ b/src/libstd/ffi/os_str.rs @@ -295,6 +295,36 @@ impl OsString { self.inner.shrink_to_fit() } + /// Shrinks the capacity of the `OsString` with a lower bound. + /// + /// The capacity will remain at least as large as both the length + /// and the supplied value. + /// + /// Panics if the current capacity is smaller than the supplied + /// minimum capacity. + /// + /// # Examples + /// + /// ``` + /// #![feature(shrink_to)] + /// use std::ffi::OsString; + /// + /// let mut s = OsString::from("foo"); + /// + /// s.reserve(100); + /// assert!(s.capacity() >= 100); + /// + /// s.shrink_to(10); + /// assert!(s.capacity() >= 10); + /// s.shrink_to(0); + /// assert!(s.capacity() >= 3); + /// ``` + #[inline] + #[unstable(feature = "shrink_to", reason = "new API", issue="0")] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.inner.shrink_to(min_capacity) + } + /// Converts this `OsString` into a boxed [`OsStr`]. /// /// [`OsStr`]: struct.OsStr.html diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 0b06c5d4d65..edecf309d16 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -299,6 +299,7 @@ #![feature(raw)] #![feature(rustc_attrs)] #![feature(stdsimd)] +#![feature(shrink_to)] #![feature(slice_bytes)] #![feature(slice_concat_ext)] #![feature(slice_internals)] diff --git a/src/libstd/sys/redox/os_str.rs b/src/libstd/sys/redox/os_str.rs index 655bfdb9167..da27787babb 100644 --- a/src/libstd/sys/redox/os_str.rs +++ b/src/libstd/sys/redox/os_str.rs @@ -104,6 +104,11 @@ impl Buf { self.inner.shrink_to_fit() } + #[inline] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.inner.shrink_to(min_capacity) + } + pub fn as_slice(&self) -> &Slice { unsafe { mem::transmute(&*self.inner) } } diff --git a/src/libstd/sys/unix/os_str.rs b/src/libstd/sys/unix/os_str.rs index e0349387998..e43bc6da5f1 100644 --- a/src/libstd/sys/unix/os_str.rs +++ b/src/libstd/sys/unix/os_str.rs @@ -104,6 +104,11 @@ impl Buf { self.inner.shrink_to_fit() } + #[inline] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.inner.shrink_to(min_capacity) + } + pub fn as_slice(&self) -> &Slice { unsafe { mem::transmute(&*self.inner) } } diff --git a/src/libstd/sys/wasm/os_str.rs b/src/libstd/sys/wasm/os_str.rs index 543c22ebe18..84f560af69b 100644 --- a/src/libstd/sys/wasm/os_str.rs +++ b/src/libstd/sys/wasm/os_str.rs @@ -104,6 +104,11 @@ impl Buf { self.inner.shrink_to_fit() } + #[inline] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.inner.shrink_to(min_capacity) + } + pub fn as_slice(&self) -> &Slice { unsafe { mem::transmute(&*self.inner) } } diff --git a/src/libstd/sys/windows/os_str.rs b/src/libstd/sys/windows/os_str.rs index 414c9c5418e..bcc66b9954b 100644 --- a/src/libstd/sys/windows/os_str.rs +++ b/src/libstd/sys/windows/os_str.rs @@ -113,6 +113,11 @@ impl Buf { self.inner.shrink_to_fit() } + #[inline] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.inner.shrink_to(min_capacity) + } + #[inline] pub fn into_box(self) -> Box { unsafe { mem::transmute(self.inner.into_box()) } diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index 78b2bb5fe6e..dda4e1bab3b 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -253,6 +253,11 @@ impl Wtf8Buf { self.bytes.shrink_to_fit() } + #[inline] + pub fn shrink_to(&mut self, min_capacity: usize) { + self.bytes.shrink_to(min_capacity) + } + /// Returns the number of bytes that this string buffer can hold without reallocating. #[inline] pub fn capacity(&self) -> usize { -- cgit 1.4.1-3-g733a5 From f87d4a15a82a76e7510629173c366d084f2c02ca Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Thu, 5 Apr 2018 15:55:28 +0200 Subject: Move Utf8Lossy decoder to libcore --- src/liballoc/string.rs | 2 +- src/libcore/str/lossy.rs | 212 +++++++++++++++++++++++++++++++++++ src/libcore/str/mod.rs | 4 + src/libcore/tests/lib.rs | 2 + src/libcore/tests/str_lossy.rs | 91 +++++++++++++++ src/libstd/sys/redox/os_str.rs | 2 +- src/libstd/sys/unix/os_str.rs | 2 +- src/libstd/sys/wasm/os_str.rs | 2 +- src/libstd/sys_common/bytestring.rs | 2 +- src/libstd_unicode/Cargo.toml | 4 - src/libstd_unicode/lib.rs | 1 - src/libstd_unicode/lossy.rs | 213 ------------------------------------ src/libstd_unicode/tests/lib.rs | 15 --- src/libstd_unicode/tests/lossy.rs | 91 --------------- 14 files changed, 314 insertions(+), 329 deletions(-) create mode 100644 src/libcore/str/lossy.rs create mode 100644 src/libcore/tests/str_lossy.rs delete mode 100644 src/libstd_unicode/lossy.rs delete mode 100644 src/libstd_unicode/tests/lib.rs delete mode 100644 src/libstd_unicode/tests/lossy.rs (limited to 'src/libstd/sys_common') diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs index b95aae02894..5f90e28cb3c 100644 --- a/src/liballoc/string.rs +++ b/src/liballoc/string.rs @@ -63,7 +63,7 @@ use core::ops::Bound::{Excluded, Included, Unbounded}; use core::ops::{self, Add, AddAssign, Index, IndexMut, RangeBounds}; use core::ptr; use core::str::pattern::Pattern; -use std_unicode::lossy; +use core::str::lossy; use std_unicode::char::{decode_utf16, REPLACEMENT_CHARACTER}; use borrow::{Cow, ToOwned}; diff --git a/src/libcore/str/lossy.rs b/src/libcore/str/lossy.rs new file mode 100644 index 00000000000..30b7267da7c --- /dev/null +++ b/src/libcore/str/lossy.rs @@ -0,0 +1,212 @@ +// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use char; +use str as core_str; +use fmt; +use fmt::Write; +use mem; + +/// Lossy UTF-8 string. +#[unstable(feature = "str_internals", issue = "0")] +pub struct Utf8Lossy { + bytes: [u8] +} + +impl Utf8Lossy { + pub fn from_str(s: &str) -> &Utf8Lossy { + Utf8Lossy::from_bytes(s.as_bytes()) + } + + pub fn from_bytes(bytes: &[u8]) -> &Utf8Lossy { + unsafe { mem::transmute(bytes) } + } + + pub fn chunks(&self) -> Utf8LossyChunksIter { + Utf8LossyChunksIter { source: &self.bytes } + } +} + + +/// Iterator over lossy UTF-8 string +#[unstable(feature = "str_internals", issue = "0")] +#[allow(missing_debug_implementations)] +pub struct Utf8LossyChunksIter<'a> { + source: &'a [u8], +} + +#[unstable(feature = "str_internals", issue = "0")] +#[derive(PartialEq, Eq, Debug)] +pub struct Utf8LossyChunk<'a> { + /// Sequence of valid chars. + /// Can be empty between broken UTF-8 chars. + pub valid: &'a str, + /// Single broken char, empty if none. + /// Empty iff iterator item is last. + pub broken: &'a [u8], +} + +impl<'a> Iterator for Utf8LossyChunksIter<'a> { + type Item = Utf8LossyChunk<'a>; + + fn next(&mut self) -> Option> { + if self.source.len() == 0 { + return None; + } + + const TAG_CONT_U8: u8 = 128; + fn unsafe_get(xs: &[u8], i: usize) -> u8 { + unsafe { *xs.get_unchecked(i) } + } + fn safe_get(xs: &[u8], i: usize) -> u8 { + if i >= xs.len() { 0 } else { unsafe_get(xs, i) } + } + + let mut i = 0; + while i < self.source.len() { + let i_ = i; + + let byte = unsafe_get(self.source, i); + i += 1; + + if byte < 128 { + + } else { + let w = core_str::utf8_char_width(byte); + + macro_rules! error { () => ({ + unsafe { + let r = Utf8LossyChunk { + valid: core_str::from_utf8_unchecked(&self.source[0..i_]), + broken: &self.source[i_..i], + }; + self.source = &self.source[i..]; + return Some(r); + } + })} + + match w { + 2 => { + if safe_get(self.source, i) & 192 != TAG_CONT_U8 { + error!(); + } + i += 1; + } + 3 => { + match (byte, safe_get(self.source, i)) { + (0xE0, 0xA0 ... 0xBF) => (), + (0xE1 ... 0xEC, 0x80 ... 0xBF) => (), + (0xED, 0x80 ... 0x9F) => (), + (0xEE ... 0xEF, 0x80 ... 0xBF) => (), + _ => { + error!(); + } + } + i += 1; + if safe_get(self.source, i) & 192 != TAG_CONT_U8 { + error!(); + } + i += 1; + } + 4 => { + match (byte, safe_get(self.source, i)) { + (0xF0, 0x90 ... 0xBF) => (), + (0xF1 ... 0xF3, 0x80 ... 0xBF) => (), + (0xF4, 0x80 ... 0x8F) => (), + _ => { + error!(); + } + } + i += 1; + if safe_get(self.source, i) & 192 != TAG_CONT_U8 { + error!(); + } + i += 1; + if safe_get(self.source, i) & 192 != TAG_CONT_U8 { + error!(); + } + i += 1; + } + _ => { + error!(); + } + } + } + } + + let r = Utf8LossyChunk { + valid: unsafe { core_str::from_utf8_unchecked(self.source) }, + broken: &[], + }; + self.source = &[]; + return Some(r); + } +} + + +impl fmt::Display for Utf8Lossy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + // If we're the empty string then our iterator won't actually yield + // anything, so perform the formatting manually + if self.bytes.len() == 0 { + return "".fmt(f) + } + + for Utf8LossyChunk { valid, broken } in self.chunks() { + // If we successfully decoded the whole chunk as a valid string then + // we can return a direct formatting of the string which will also + // respect various formatting flags if possible. + if valid.len() == self.bytes.len() { + assert!(broken.is_empty()); + return valid.fmt(f) + } + + f.write_str(valid)?; + if !broken.is_empty() { + f.write_char(char::REPLACEMENT_CHARACTER)?; + } + } + Ok(()) + } +} + +impl fmt::Debug for Utf8Lossy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_char('"')?; + + for Utf8LossyChunk { valid, broken } in self.chunks() { + + // Valid part. + // Here we partially parse UTF-8 again which is suboptimal. + { + let mut from = 0; + for (i, c) in valid.char_indices() { + let esc = c.escape_debug(); + // If char needs escaping, flush backlog so far and write, else skip + if esc.len() != 1 { + f.write_str(&valid[from..i])?; + for c in esc { + f.write_char(c)?; + } + from = i + c.len_utf8(); + } + } + f.write_str(&valid[from..])?; + } + + // Broken parts of string as hex escape. + for &b in broken { + write!(f, "\\x{:02x}", b)?; + } + } + + f.write_char('"') + } +} diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 1185b7acaae..7a97d89dcf9 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -26,6 +26,10 @@ use mem; pub mod pattern; +#[unstable(feature = "str_internals", issue = "0")] +#[allow(missing_docs)] +pub mod lossy; + /// A trait to abstract the idea of creating a new instance of a type from a /// string. /// diff --git a/src/libcore/tests/lib.rs b/src/libcore/tests/lib.rs index c3162899bbd..149269263dc 100644 --- a/src/libcore/tests/lib.rs +++ b/src/libcore/tests/lib.rs @@ -33,6 +33,7 @@ #![feature(sort_internals)] #![feature(specialization)] #![feature(step_trait)] +#![feature(str_internals)] #![feature(test)] #![feature(trusted_len)] #![feature(try_trait)] @@ -68,4 +69,5 @@ mod ptr; mod result; mod slice; mod str; +mod str_lossy; mod tuple; diff --git a/src/libcore/tests/str_lossy.rs b/src/libcore/tests/str_lossy.rs new file mode 100644 index 00000000000..69e28256da9 --- /dev/null +++ b/src/libcore/tests/str_lossy.rs @@ -0,0 +1,91 @@ +// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::str::lossy::*; + +#[test] +fn chunks() { + let mut iter = Utf8Lossy::from_bytes(b"hello").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "hello", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + let mut iter = Utf8Lossy::from_bytes("ศไทย中华Việt Nam".as_bytes()).chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "ศไทย中华Việt Nam", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + let mut iter = Utf8Lossy::from_bytes(b"Hello\xC2 There\xFF Goodbye").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC2", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xFF", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + let mut iter = Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC0", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xE6\x83", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + let mut iter = Utf8Lossy::from_bytes(b"\xF5foo\xF5\x80bar").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF5", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF5", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + let mut iter = Utf8Lossy::from_bytes(b"\xF1foo\xF1\x80bar\xF1\x80\x80baz").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF1", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF1\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF1\x80\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + let mut iter = Utf8Lossy::from_bytes(b"\xF4foo\xF4\x80bar\xF4\xBFbaz").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF4", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF4\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF4", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + let mut iter = Utf8Lossy::from_bytes(b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF0", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo\u{10000}bar", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); + + // surrogates + let mut iter = Utf8Lossy::from_bytes(b"\xED\xA0\x80foo\xED\xBF\xBFbar").chunks(); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xED", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xA0", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xED", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); + assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"", }), iter.next()); + assert_eq!(None, iter.next()); +} + +#[test] +fn display() { + assert_eq!( + "Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye", + &format!("{}", Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye"))); +} + +#[test] +fn debug() { + assert_eq!( + "\"Hello\\xc0\\x80 There\\xe6\\x83 Goodbye\\u{10d4ea}\"", + &format!("{:?}", Utf8Lossy::from_bytes( + b"Hello\xC0\x80 There\xE6\x83 Goodbye\xf4\x8d\x93\xaa"))); +} diff --git a/src/libstd/sys/redox/os_str.rs b/src/libstd/sys/redox/os_str.rs index da27787babb..eb3a1ead58c 100644 --- a/src/libstd/sys/redox/os_str.rs +++ b/src/libstd/sys/redox/os_str.rs @@ -19,7 +19,7 @@ use rc::Rc; use sync::Arc; use sys_common::{AsInner, IntoInner}; use sys_common::bytestring::debug_fmt_bytestring; -use std_unicode::lossy::Utf8Lossy; +use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub struct Buf { diff --git a/src/libstd/sys/unix/os_str.rs b/src/libstd/sys/unix/os_str.rs index e43bc6da5f1..01c0fb830aa 100644 --- a/src/libstd/sys/unix/os_str.rs +++ b/src/libstd/sys/unix/os_str.rs @@ -19,7 +19,7 @@ use rc::Rc; use sync::Arc; use sys_common::{AsInner, IntoInner}; use sys_common::bytestring::debug_fmt_bytestring; -use std_unicode::lossy::Utf8Lossy; +use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub struct Buf { diff --git a/src/libstd/sys/wasm/os_str.rs b/src/libstd/sys/wasm/os_str.rs index 84f560af69b..e0da5bdf36c 100644 --- a/src/libstd/sys/wasm/os_str.rs +++ b/src/libstd/sys/wasm/os_str.rs @@ -19,7 +19,7 @@ use rc::Rc; use sync::Arc; use sys_common::{AsInner, IntoInner}; use sys_common::bytestring::debug_fmt_bytestring; -use std_unicode::lossy::Utf8Lossy; +use core::str::lossy::Utf8Lossy; #[derive(Clone, Hash)] pub struct Buf { diff --git a/src/libstd/sys_common/bytestring.rs b/src/libstd/sys_common/bytestring.rs index eb9cad09915..971b83938c1 100644 --- a/src/libstd/sys_common/bytestring.rs +++ b/src/libstd/sys_common/bytestring.rs @@ -11,7 +11,7 @@ #![allow(dead_code)] use fmt::{Formatter, Result, Write}; -use std_unicode::lossy::{Utf8Lossy, Utf8LossyChunk}; +use core::str::lossy::{Utf8Lossy, Utf8LossyChunk}; pub fn debug_fmt_bytestring(slice: &[u8], f: &mut Formatter) -> Result { // Writes out a valid unicode string with the correct escape sequences diff --git a/src/libstd_unicode/Cargo.toml b/src/libstd_unicode/Cargo.toml index 283070a0e2c..b1c55c2e4b6 100644 --- a/src/libstd_unicode/Cargo.toml +++ b/src/libstd_unicode/Cargo.toml @@ -9,10 +9,6 @@ path = "lib.rs" test = false bench = false -[[test]] -name = "std_unicode_tests" -path = "tests/lib.rs" - [dependencies] core = { path = "../libcore" } compiler_builtins = { path = "../rustc/compiler_builtins_shim" } diff --git a/src/libstd_unicode/lib.rs b/src/libstd_unicode/lib.rs index cf8c101a2f9..106a2c0f0c5 100644 --- a/src/libstd_unicode/lib.rs +++ b/src/libstd_unicode/lib.rs @@ -45,7 +45,6 @@ mod tables; mod u_str; mod version; pub mod char; -pub mod lossy; #[allow(deprecated)] pub mod str { diff --git a/src/libstd_unicode/lossy.rs b/src/libstd_unicode/lossy.rs deleted file mode 100644 index cc8e93308a5..00000000000 --- a/src/libstd_unicode/lossy.rs +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use core::str as core_str; -use core::fmt; -use core::fmt::Write; -use char; -use core::mem; - - -/// Lossy UTF-8 string. -#[unstable(feature = "str_internals", issue = "0")] -pub struct Utf8Lossy { - bytes: [u8] -} - -impl Utf8Lossy { - pub fn from_str(s: &str) -> &Utf8Lossy { - Utf8Lossy::from_bytes(s.as_bytes()) - } - - pub fn from_bytes(bytes: &[u8]) -> &Utf8Lossy { - unsafe { mem::transmute(bytes) } - } - - pub fn chunks(&self) -> Utf8LossyChunksIter { - Utf8LossyChunksIter { source: &self.bytes } - } -} - - -/// Iterator over lossy UTF-8 string -#[unstable(feature = "str_internals", issue = "0")] -#[allow(missing_debug_implementations)] -pub struct Utf8LossyChunksIter<'a> { - source: &'a [u8], -} - -#[unstable(feature = "str_internals", issue = "0")] -#[derive(PartialEq, Eq, Debug)] -pub struct Utf8LossyChunk<'a> { - /// Sequence of valid chars. - /// Can be empty between broken UTF-8 chars. - pub valid: &'a str, - /// Single broken char, empty if none. - /// Empty iff iterator item is last. - pub broken: &'a [u8], -} - -impl<'a> Iterator for Utf8LossyChunksIter<'a> { - type Item = Utf8LossyChunk<'a>; - - fn next(&mut self) -> Option> { - if self.source.len() == 0 { - return None; - } - - const TAG_CONT_U8: u8 = 128; - fn unsafe_get(xs: &[u8], i: usize) -> u8 { - unsafe { *xs.get_unchecked(i) } - } - fn safe_get(xs: &[u8], i: usize) -> u8 { - if i >= xs.len() { 0 } else { unsafe_get(xs, i) } - } - - let mut i = 0; - while i < self.source.len() { - let i_ = i; - - let byte = unsafe_get(self.source, i); - i += 1; - - if byte < 128 { - - } else { - let w = core_str::utf8_char_width(byte); - - macro_rules! error { () => ({ - unsafe { - let r = Utf8LossyChunk { - valid: core_str::from_utf8_unchecked(&self.source[0..i_]), - broken: &self.source[i_..i], - }; - self.source = &self.source[i..]; - return Some(r); - } - })} - - match w { - 2 => { - if safe_get(self.source, i) & 192 != TAG_CONT_U8 { - error!(); - } - i += 1; - } - 3 => { - match (byte, safe_get(self.source, i)) { - (0xE0, 0xA0 ... 0xBF) => (), - (0xE1 ... 0xEC, 0x80 ... 0xBF) => (), - (0xED, 0x80 ... 0x9F) => (), - (0xEE ... 0xEF, 0x80 ... 0xBF) => (), - _ => { - error!(); - } - } - i += 1; - if safe_get(self.source, i) & 192 != TAG_CONT_U8 { - error!(); - } - i += 1; - } - 4 => { - match (byte, safe_get(self.source, i)) { - (0xF0, 0x90 ... 0xBF) => (), - (0xF1 ... 0xF3, 0x80 ... 0xBF) => (), - (0xF4, 0x80 ... 0x8F) => (), - _ => { - error!(); - } - } - i += 1; - if safe_get(self.source, i) & 192 != TAG_CONT_U8 { - error!(); - } - i += 1; - if safe_get(self.source, i) & 192 != TAG_CONT_U8 { - error!(); - } - i += 1; - } - _ => { - error!(); - } - } - } - } - - let r = Utf8LossyChunk { - valid: unsafe { core_str::from_utf8_unchecked(self.source) }, - broken: &[], - }; - self.source = &[]; - return Some(r); - } -} - - -impl fmt::Display for Utf8Lossy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // If we're the empty string then our iterator won't actually yield - // anything, so perform the formatting manually - if self.bytes.len() == 0 { - return "".fmt(f) - } - - for Utf8LossyChunk { valid, broken } in self.chunks() { - // If we successfully decoded the whole chunk as a valid string then - // we can return a direct formatting of the string which will also - // respect various formatting flags if possible. - if valid.len() == self.bytes.len() { - assert!(broken.is_empty()); - return valid.fmt(f) - } - - f.write_str(valid)?; - if !broken.is_empty() { - f.write_char(char::REPLACEMENT_CHARACTER)?; - } - } - Ok(()) - } -} - -impl fmt::Debug for Utf8Lossy { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_char('"')?; - - for Utf8LossyChunk { valid, broken } in self.chunks() { - - // Valid part. - // Here we partially parse UTF-8 again which is suboptimal. - { - let mut from = 0; - for (i, c) in valid.char_indices() { - let esc = c.escape_debug(); - // If char needs escaping, flush backlog so far and write, else skip - if esc.len() != 1 { - f.write_str(&valid[from..i])?; - for c in esc { - f.write_char(c)?; - } - from = i + c.len_utf8(); - } - } - f.write_str(&valid[from..])?; - } - - // Broken parts of string as hex escape. - for &b in broken { - write!(f, "\\x{:02x}", b)?; - } - } - - f.write_char('"') - } -} diff --git a/src/libstd_unicode/tests/lib.rs b/src/libstd_unicode/tests/lib.rs deleted file mode 100644 index 9535ec18763..00000000000 --- a/src/libstd_unicode/tests/lib.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2012-2017 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. - -#![feature(str_internals, unicode)] - -extern crate std_unicode; - -mod lossy; diff --git a/src/libstd_unicode/tests/lossy.rs b/src/libstd_unicode/tests/lossy.rs deleted file mode 100644 index e05d0668556..00000000000 --- a/src/libstd_unicode/tests/lossy.rs +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2012-2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std_unicode::lossy::*; - -#[test] -fn chunks() { - let mut iter = Utf8Lossy::from_bytes(b"hello").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "hello", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - let mut iter = Utf8Lossy::from_bytes("ศไทย中华Việt Nam".as_bytes()).chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "ศไทย中华Việt Nam", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - let mut iter = Utf8Lossy::from_bytes(b"Hello\xC2 There\xFF Goodbye").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC2", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xFF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - let mut iter = Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "Hello", broken: b"\xC0", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " There", broken: b"\xE6\x83", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: " Goodbye", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - let mut iter = Utf8Lossy::from_bytes(b"\xF5foo\xF5\x80bar").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF5", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF5", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - let mut iter = Utf8Lossy::from_bytes(b"\xF1foo\xF1\x80bar\xF1\x80\x80baz").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF1", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF1\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF1\x80\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - let mut iter = Utf8Lossy::from_bytes(b"\xF4foo\xF4\x80bar\xF4\xBFbaz").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF4", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xF4\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"\xF4", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "baz", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - let mut iter = Utf8Lossy::from_bytes(b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xF0", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo\u{10000}bar", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); - - // surrogates - let mut iter = Utf8Lossy::from_bytes(b"\xED\xA0\x80foo\xED\xBF\xBFbar").chunks(); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xED", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xA0", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\x80", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "foo", broken: b"\xED", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "", broken: b"\xBF", }), iter.next()); - assert_eq!(Some(Utf8LossyChunk { valid: "bar", broken: b"", }), iter.next()); - assert_eq!(None, iter.next()); -} - -#[test] -fn display() { - assert_eq!( - "Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye", - &format!("{}", Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye"))); -} - -#[test] -fn debug() { - assert_eq!( - "\"Hello\\xc0\\x80 There\\xe6\\x83 Goodbye\\u{10d4ea}\"", - &format!("{:?}", Utf8Lossy::from_bytes( - b"Hello\xC0\x80 There\xE6\x83 Goodbye\xf4\x8d\x93\xaa"))); -} -- cgit 1.4.1-3-g733a5 From 1b895d8b88413f72230fbc0f00c67328870a2e9a Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Tue, 3 Apr 2018 14:36:57 +0200 Subject: Import the `alloc` crate as `alloc_crate` in std MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit … to make the name `alloc` available. --- src/libstd/collections/hash/map.rs | 4 +--- src/libstd/collections/hash/table.rs | 5 +---- src/libstd/collections/mod.rs | 10 +++++----- src/libstd/error.rs | 10 +++++----- src/libstd/heap.rs | 2 +- src/libstd/lib.rs | 18 +++++++++--------- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/mpsc/mpsc_queue.rs | 3 +-- src/libstd/sync/mpsc/spsc_queue.rs | 2 +- src/libstd/sys/cloudabi/thread.rs | 2 +- src/libstd/sys/redox/thread.rs | 2 +- src/libstd/sys/unix/thread.rs | 2 +- src/libstd/sys/wasm/thread.rs | 2 +- src/libstd/sys/windows/process.rs | 2 +- src/libstd/sys/windows/thread.rs | 2 +- src/libstd/sys_common/at_exit_imp.rs | 2 +- src/libstd/sys_common/process.rs | 2 +- src/libstd/sys_common/thread.rs | 2 +- 18 files changed, 34 insertions(+), 40 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index e0b48e565d0..73a5df8dc28 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -11,15 +11,13 @@ use self::Entry::*; use self::VacantEntryState::*; -use alloc::heap::Heap; -use alloc::allocator::CollectionAllocErr; use cell::Cell; -use core::heap::Alloc; use borrow::Borrow; use cmp::max; use fmt::{self, Debug}; #[allow(deprecated)] use hash::{Hash, Hasher, BuildHasher, SipHasher13}; +use heap::{Heap, Alloc, CollectionAllocErr}; use iter::{FromIterator, FusedIterator}; use mem::{self, replace}; use ops::{Deref, Index}; diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index fa6053d3f6d..878cd82a258 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -8,17 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::heap::Heap; -use core::heap::{Alloc, Layout}; - use cmp; use hash::{BuildHasher, Hash, Hasher}; +use heap::{Heap, Alloc, Layout, CollectionAllocErr}; use marker; use mem::{align_of, size_of, needs_drop}; use mem; use ops::{Deref, DerefMut}; use ptr::{self, Unique, NonNull}; -use alloc::allocator::CollectionAllocErr; use self::BucketState::*; diff --git a/src/libstd/collections/mod.rs b/src/libstd/collections/mod.rs index c7ad27d8d26..9cf73824dea 100644 --- a/src/libstd/collections/mod.rs +++ b/src/libstd/collections/mod.rs @@ -424,13 +424,13 @@ #[doc(hidden)] pub use ops::Bound; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::{BinaryHeap, BTreeMap, BTreeSet}; +pub use alloc_crate::{BinaryHeap, BTreeMap, BTreeSet}; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::{LinkedList, VecDeque}; +pub use alloc_crate::{LinkedList, VecDeque}; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::{binary_heap, btree_map, btree_set}; +pub use alloc_crate::{binary_heap, btree_map, btree_set}; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::{linked_list, vec_deque}; +pub use alloc_crate::{linked_list, vec_deque}; #[stable(feature = "rust1", since = "1.0.0")] pub use self::hash_map::HashMap; @@ -446,7 +446,7 @@ pub mod range { } #[unstable(feature = "try_reserve", reason = "new API", issue="48043")] -pub use alloc::allocator::CollectionAllocErr; +pub use heap::CollectionAllocErr; mod hash; diff --git a/src/libstd/error.rs b/src/libstd/error.rs index 3d0c96585b5..4edb897350e 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -51,13 +51,13 @@ // coherence challenge (e.g., specialization, neg impls, etc) we can // reconsider what crate these items belong in. -use alloc::allocator; use any::TypeId; use borrow::Cow; use cell; use char; use core::array; use fmt::{self, Debug, Display}; +use heap::{AllocErr, CannotReallocInPlace}; use mem::transmute; use num; use str; @@ -241,18 +241,18 @@ impl Error for ! { #[unstable(feature = "allocator_api", reason = "the precise API and guarantees it provides may be tweaked.", issue = "32838")] -impl Error for allocator::AllocErr { +impl Error for AllocErr { fn description(&self) -> &str { - allocator::AllocErr::description(self) + AllocErr::description(self) } } #[unstable(feature = "allocator_api", reason = "the precise API and guarantees it provides may be tweaked.", issue = "32838")] -impl Error for allocator::CannotReallocInPlace { +impl Error for CannotReallocInPlace { fn description(&self) -> &str { - allocator::CannotReallocInPlace::description(self) + CannotReallocInPlace::description(self) } } diff --git a/src/libstd/heap.rs b/src/libstd/heap.rs index 2cf06018087..b42a1052c49 100644 --- a/src/libstd/heap.rs +++ b/src/libstd/heap.rs @@ -12,7 +12,7 @@ #![unstable(issue = "32838", feature = "allocator_api")] -pub use alloc::heap::Heap; +pub use alloc_crate::heap::Heap; pub use alloc_system::System; #[doc(inline)] pub use core::heap::*; diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index c82d600e4a1..ef4205e7a62 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -351,7 +351,7 @@ extern crate core as __core; #[macro_use] #[macro_reexport(vec, format)] -extern crate alloc; +extern crate alloc as alloc_crate; extern crate alloc_system; #[doc(masked)] extern crate libc; @@ -437,21 +437,21 @@ pub use core::u32; #[stable(feature = "rust1", since = "1.0.0")] pub use core::u64; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::boxed; +pub use alloc_crate::boxed; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::rc; +pub use alloc_crate::rc; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::borrow; +pub use alloc_crate::borrow; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::fmt; +pub use alloc_crate::fmt; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::slice; +pub use alloc_crate::slice; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::str; +pub use alloc_crate::str; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::string; +pub use alloc_crate::string; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::vec; +pub use alloc_crate::vec; #[stable(feature = "rust1", since = "1.0.0")] pub use core::char; #[stable(feature = "i128", since = "1.26.0")] diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 289b47b3484..642b284c6c7 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -18,7 +18,7 @@ #![stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc::arc::{Arc, Weak}; +pub use alloc_crate::arc::{Arc, Weak}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::sync::atomic; diff --git a/src/libstd/sync/mpsc/mpsc_queue.rs b/src/libstd/sync/mpsc/mpsc_queue.rs index 296773d20f6..df945ac3859 100644 --- a/src/libstd/sync/mpsc/mpsc_queue.rs +++ b/src/libstd/sync/mpsc/mpsc_queue.rs @@ -23,10 +23,9 @@ pub use self::PopResult::*; -use alloc::boxed::Box; use core::ptr; use core::cell::UnsafeCell; - +use boxed::Box; use sync::atomic::{AtomicPtr, Ordering}; /// A result of the `pop` function. diff --git a/src/libstd/sync/mpsc/spsc_queue.rs b/src/libstd/sync/mpsc/spsc_queue.rs index cc4be92276a..9482f6958b3 100644 --- a/src/libstd/sync/mpsc/spsc_queue.rs +++ b/src/libstd/sync/mpsc/spsc_queue.rs @@ -16,7 +16,7 @@ // http://www.1024cores.net/home/lock-free-algorithms/queues/unbounded-spsc-queue -use alloc::boxed::Box; +use boxed::Box; use core::ptr; use core::cell::UnsafeCell; diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs index a22d9053b69..5d66936b2a4 100644 --- a/src/libstd/sys/cloudabi/thread.rs +++ b/src/libstd/sys/cloudabi/thread.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::boxed::FnBox; +use boxed::FnBox; use cmp; use ffi::CStr; use io; diff --git a/src/libstd/sys/redox/thread.rs b/src/libstd/sys/redox/thread.rs index f20350269b7..110d46ca3ab 100644 --- a/src/libstd/sys/redox/thread.rs +++ b/src/libstd/sys/redox/thread.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::boxed::FnBox; +use boxed::FnBox; use ffi::CStr; use io; use mem; diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index 2db3d4a5744..9e388808030 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::boxed::FnBox; +use boxed::FnBox; use cmp; use ffi::CStr; use io; diff --git a/src/libstd/sys/wasm/thread.rs b/src/libstd/sys/wasm/thread.rs index 7345843b975..728e678a2e8 100644 --- a/src/libstd/sys/wasm/thread.rs +++ b/src/libstd/sys/wasm/thread.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::boxed::FnBox; +use boxed::FnBox; use ffi::CStr; use io; use sys::{unsupported, Void}; diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index bd5507e8f89..be442f41374 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -31,7 +31,7 @@ use sys::stdio; use sys::cvt; use sys_common::{AsInner, FromInner, IntoInner}; use sys_common::process::{CommandEnv, EnvKey}; -use alloc::borrow::Borrow; +use borrow::Borrow; //////////////////////////////////////////////////////////////////////////////// // Command diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index 4b3d1b586b5..b6f63303dc2 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::boxed::FnBox; +use boxed::FnBox; use io; use ffi::CStr; use mem; diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index ce6fd4cb075..26da51c9825 100644 --- a/src/libstd/sys_common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs @@ -12,7 +12,7 @@ //! //! Documentation can be found on the `rt::at_exit` function. -use alloc::boxed::FnBox; +use boxed::FnBox; use ptr; use sys_common::mutex::Mutex; diff --git a/src/libstd/sys_common/process.rs b/src/libstd/sys_common/process.rs index d0c5951bd6c..ddf0ebe603e 100644 --- a/src/libstd/sys_common/process.rs +++ b/src/libstd/sys_common/process.rs @@ -14,7 +14,7 @@ use ffi::{OsStr, OsString}; use env; use collections::BTreeMap; -use alloc::borrow::Borrow; +use borrow::Borrow; pub trait EnvKey: From + Into + diff --git a/src/libstd/sys_common/thread.rs b/src/libstd/sys_common/thread.rs index f1379b6ec63..da6f58ef6bb 100644 --- a/src/libstd/sys_common/thread.rs +++ b/src/libstd/sys_common/thread.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use alloc::boxed::FnBox; +use boxed::FnBox; use env; use sync::atomic::{self, Ordering}; use sys::stack_overflow; -- cgit 1.4.1-3-g733a5 From c3a5d6b130e27d7d7587f56581247d5b08c38594 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Thu, 29 Mar 2018 14:59:13 -0700 Subject: std: Minimize size of panicking on wasm This commit applies a few code size optimizations for the wasm target to the standard library, namely around panics. We notably know that in most configurations it's impossible for us to print anything in wasm32-unknown-unknown so we can skip larger portions of panicking that are otherwise simply informative. This allows us to get quite a nice size reduction. Finally we can also tweak where the allocation happens for the `Box` that we panic with. By only allocating once unwinding starts we can reduce the size of a panicking wasm module from 44k to 350 bytes. --- src/ci/docker/wasm32-unknown/Dockerfile | 6 ++ src/libcore/panic.rs | 10 ++++ src/libpanic_abort/lib.rs | 2 +- src/libpanic_unwind/lib.rs | 12 ++-- src/libstd/lib.rs | 1 + src/libstd/panicking.rs | 88 ++++++++++++++++++++++------- src/libstd/sys/cloudabi/stdio.rs | 4 ++ src/libstd/sys/redox/stdio.rs | 4 ++ src/libstd/sys/unix/stdio.rs | 4 ++ src/libstd/sys/wasm/rwlock.rs | 4 +- src/libstd/sys/wasm/stdio.rs | 4 ++ src/libstd/sys/windows/stdio.rs | 4 ++ src/libstd/sys_common/backtrace.rs | 13 ++--- src/libstd/sys_common/mod.rs | 14 +++-- src/libstd/sys_common/thread_local.rs | 4 +- src/libstd/sys_common/util.rs | 5 +- src/libstd/thread/local.rs | 41 +++++++++++++- src/libstd/thread/mod.rs | 3 + src/test/run-make/wasm-panic-small/Makefile | 11 ++++ src/test/run-make/wasm-panic-small/foo.rs | 16 ++++++ 20 files changed, 205 insertions(+), 45 deletions(-) create mode 100644 src/test/run-make/wasm-panic-small/Makefile create mode 100644 src/test/run-make/wasm-panic-small/foo.rs (limited to 'src/libstd/sys_common') diff --git a/src/ci/docker/wasm32-unknown/Dockerfile b/src/ci/docker/wasm32-unknown/Dockerfile index 853923ad947..56eda548071 100644 --- a/src/ci/docker/wasm32-unknown/Dockerfile +++ b/src/ci/docker/wasm32-unknown/Dockerfile @@ -25,6 +25,12 @@ ENV RUST_CONFIGURE_ARGS \ --set build.nodejs=/node-v9.2.0-linux-x64/bin/node \ --set rust.lld +# Some run-make tests have assertions about code size, and enabling debug +# assertions in libstd causes the binary to be much bigger than it would +# otherwise normally be. We already test libstd with debug assertions in lots of +# other contexts as well +ENV NO_DEBUG_ASSERTIONS=1 + ENV SCRIPT python2.7 /checkout/x.py test --target $TARGETS \ src/test/run-make \ src/test/ui \ diff --git a/src/libcore/panic.rs b/src/libcore/panic.rs index 1720c9d8c60..37c79f2fafe 100644 --- a/src/libcore/panic.rs +++ b/src/libcore/panic.rs @@ -251,3 +251,13 @@ impl<'a> fmt::Display for Location<'a> { write!(formatter, "{}:{}:{}", self.file, self.line, self.col) } } + +/// An internal trait used by libstd to pass data from libstd to `panic_unwind` +/// and other panic runtimes. Not intended to be stabilized any time soon, do +/// not use. +#[unstable(feature = "std_internals", issue = "0")] +#[doc(hidden)] +pub unsafe trait BoxMeUp { + fn box_me_up(&mut self) -> *mut (Any + Send); + fn get(&self) -> &(Any + Send); +} diff --git a/src/libpanic_abort/lib.rs b/src/libpanic_abort/lib.rs index 43c5bbbc618..392bf17968f 100644 --- a/src/libpanic_abort/lib.rs +++ b/src/libpanic_abort/lib.rs @@ -52,7 +52,7 @@ pub unsafe extern fn __rust_maybe_catch_panic(f: fn(*mut u8), // now hopefully. #[no_mangle] #[rustc_std_internal_symbol] -pub unsafe extern fn __rust_start_panic(_data: usize, _vtable: usize) -> u32 { +pub unsafe extern fn __rust_start_panic(_payload: usize) -> u32 { abort(); #[cfg(any(unix, target_os = "cloudabi"))] diff --git a/src/libpanic_unwind/lib.rs b/src/libpanic_unwind/lib.rs index 9321d6917d1..6c52c0fa10c 100644 --- a/src/libpanic_unwind/lib.rs +++ b/src/libpanic_unwind/lib.rs @@ -29,6 +29,7 @@ html_root_url = "https://doc.rust-lang.org/nightly/", issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/")] +#![feature(allocator_api)] #![feature(alloc)] #![feature(core_intrinsics)] #![feature(lang_items)] @@ -36,6 +37,7 @@ #![feature(panic_unwind)] #![feature(raw)] #![feature(staged_api)] +#![feature(std_internals)] #![feature(unwind_attributes)] #![cfg_attr(target_env = "msvc", feature(raw))] @@ -47,9 +49,11 @@ extern crate libc; #[cfg(not(any(target_env = "msvc", all(windows, target_arch = "x86_64", target_env = "gnu"))))] extern crate unwind; +use alloc::boxed::Box; use core::intrinsics; use core::mem; use core::raw; +use core::panic::BoxMeUp; // Rust runtime's startup objects depend on these symbols, so make them public. #[cfg(all(target_os="windows", target_arch = "x86", target_env="gnu"))] @@ -112,9 +116,7 @@ pub unsafe extern "C" fn __rust_maybe_catch_panic(f: fn(*mut u8), // implementation. #[no_mangle] #[unwind(allowed)] -pub unsafe extern "C" fn __rust_start_panic(data: usize, vtable: usize) -> u32 { - imp::panic(mem::transmute(raw::TraitObject { - data: data as *mut (), - vtable: vtable as *mut (), - })) +pub unsafe extern "C" fn __rust_start_panic(payload: usize) -> u32 { + let payload = payload as *mut &mut BoxMeUp; + imp::panic(Box::from_raw((*payload).box_me_up())) } diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index a34fcb5a7f9..dd96c57538c 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -292,6 +292,7 @@ #![feature(rand)] #![feature(raw)] #![feature(rustc_attrs)] +#![feature(std_internals)] #![feature(stdsimd)] #![feature(shrink_to)] #![feature(slice_bytes)] diff --git a/src/libstd/panicking.rs b/src/libstd/panicking.rs index fba3269204e..715fd45e490 100644 --- a/src/libstd/panicking.rs +++ b/src/libstd/panicking.rs @@ -17,6 +17,8 @@ //! * Executing a panic up to doing the actual implementation //! * Shims around "try" +use core::panic::BoxMeUp; + use io::prelude::*; use any::Any; @@ -27,7 +29,7 @@ use intrinsics; use mem; use ptr; use raw; -use sys::stdio::Stderr; +use sys::stdio::{Stderr, stderr_prints_nothing}; use sys_common::rwlock::RWLock; use sys_common::thread_info; use sys_common::util; @@ -56,7 +58,7 @@ extern { data_ptr: *mut usize, vtable_ptr: *mut usize) -> u32; #[unwind(allowed)] - fn __rust_start_panic(data: usize, vtable: usize) -> u32; + fn __rust_start_panic(payload: usize) -> u32; } #[derive(Copy, Clone)] @@ -163,6 +165,12 @@ fn default_hook(info: &PanicInfo) { #[cfg(feature = "backtrace")] use sys_common::backtrace; + // Some platforms know that printing to stderr won't ever actually print + // anything, and if that's the case we can skip everything below. + if stderr_prints_nothing() { + return + } + // If this is a double panic, make sure that we print a backtrace // for this panic. Otherwise only print it if logging is enabled. #[cfg(feature = "backtrace")] @@ -212,15 +220,15 @@ fn default_hook(info: &PanicInfo) { let prev = LOCAL_STDERR.with(|s| s.borrow_mut().take()); match (prev, err.as_mut()) { - (Some(mut stderr), _) => { - write(&mut *stderr); - let mut s = Some(stderr); - LOCAL_STDERR.with(|slot| { - *slot.borrow_mut() = s.take(); - }); - } - (None, Some(ref mut err)) => { write(err) } - _ => {} + (Some(mut stderr), _) => { + write(&mut *stderr); + let mut s = Some(stderr); + LOCAL_STDERR.with(|slot| { + *slot.borrow_mut() = s.take(); + }); + } + (None, Some(ref mut err)) => { write(err) } + _ => {} } } @@ -344,7 +352,7 @@ pub fn begin_panic_fmt(msg: &fmt::Arguments, let mut s = String::new(); let _ = s.write_fmt(*msg); - rust_panic_with_hook(Box::new(s), Some(msg), file_line_col) + rust_panic_with_hook(&mut PanicPayload::new(s), Some(msg), file_line_col) } /// This is the entry point of panicking for panic!() and assert!(). @@ -360,7 +368,34 @@ pub fn begin_panic(msg: M, file_line_col: &(&'static str, u32, u3 // be performed in the parent of this thread instead of the thread that's // panicking. - rust_panic_with_hook(Box::new(msg), None, file_line_col) + rust_panic_with_hook(&mut PanicPayload::new(msg), None, file_line_col) +} + +struct PanicPayload { + inner: Option, +} + +impl PanicPayload { + fn new(inner: A) -> PanicPayload { + PanicPayload { inner: Some(inner) } + } +} + +unsafe impl BoxMeUp for PanicPayload { + fn box_me_up(&mut self) -> *mut (Any + Send) { + let data = match self.inner.take() { + Some(a) => Box::new(a) as Box, + None => Box::new(()), + }; + Box::into_raw(data) + } + + fn get(&self) -> &(Any + Send) { + match self.inner { + Some(ref a) => a, + None => &(), + } + } } /// Executes the primary logic for a panic, including checking for recursive @@ -369,9 +404,7 @@ pub fn begin_panic(msg: M, file_line_col: &(&'static str, u32, u3 /// This is the entry point or panics from libcore, formatted panics, and /// `Box` panics. Here we'll verify that we're not panicking recursively, /// run panic hooks, and then delegate to the actual implementation of panics. -#[inline(never)] -#[cold] -fn rust_panic_with_hook(payload: Box, +fn rust_panic_with_hook(payload: &mut BoxMeUp, message: Option<&fmt::Arguments>, file_line_col: &(&'static str, u32, u32)) -> ! { let (file, line, col) = *file_line_col; @@ -391,7 +424,7 @@ fn rust_panic_with_hook(payload: Box, unsafe { let info = PanicInfo::internal_constructor( - &*payload, + payload.get(), message, Location::internal_constructor(file, line, col), ); @@ -419,16 +452,29 @@ fn rust_panic_with_hook(payload: Box, /// Shim around rust_panic. Called by resume_unwind. pub fn update_count_then_panic(msg: Box) -> ! { update_panic_count(1); - rust_panic(msg) + + struct RewrapBox(Box); + + unsafe impl BoxMeUp for RewrapBox { + fn box_me_up(&mut self) -> *mut (Any + Send) { + Box::into_raw(mem::replace(&mut self.0, Box::new(()))) + } + + fn get(&self) -> &(Any + Send) { + &*self.0 + } + } + + rust_panic(&mut RewrapBox(msg)) } /// A private no-mangle function on which to slap yer breakpoints. #[no_mangle] #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints -pub fn rust_panic(msg: Box) -> ! { +pub fn rust_panic(mut msg: &mut BoxMeUp) -> ! { let code = unsafe { - let obj = mem::transmute::<_, raw::TraitObject>(msg); - __rust_start_panic(obj.data as usize, obj.vtable as usize) + let obj = &mut msg as *mut &mut BoxMeUp; + __rust_start_panic(obj as usize) }; rtabort!("failed to initiate panic, error {}", code) } diff --git a/src/libstd/sys/cloudabi/stdio.rs b/src/libstd/sys/cloudabi/stdio.rs index 9519a926471..1d7344f921c 100644 --- a/src/libstd/sys/cloudabi/stdio.rs +++ b/src/libstd/sys/cloudabi/stdio.rs @@ -77,3 +77,7 @@ pub fn is_ebadf(err: &io::Error) -> bool { } pub const STDIN_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE; + +pub fn stderr_prints_nothing() -> bool { + false +} diff --git a/src/libstd/sys/redox/stdio.rs b/src/libstd/sys/redox/stdio.rs index 3abb094ac34..7a4d11b0ecb 100644 --- a/src/libstd/sys/redox/stdio.rs +++ b/src/libstd/sys/redox/stdio.rs @@ -75,3 +75,7 @@ pub fn is_ebadf(err: &io::Error) -> bool { } pub const STDIN_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE; + +pub fn stderr_prints_nothing() -> bool { + false +} diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs index e9b3d4affc7..87ba2aef4f1 100644 --- a/src/libstd/sys/unix/stdio.rs +++ b/src/libstd/sys/unix/stdio.rs @@ -75,3 +75,7 @@ pub fn is_ebadf(err: &io::Error) -> bool { } pub const STDIN_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE; + +pub fn stderr_prints_nothing() -> bool { + false +} diff --git a/src/libstd/sys/wasm/rwlock.rs b/src/libstd/sys/wasm/rwlock.rs index 8b06f541674..6516010af47 100644 --- a/src/libstd/sys/wasm/rwlock.rs +++ b/src/libstd/sys/wasm/rwlock.rs @@ -30,7 +30,7 @@ impl RWLock { if *mode >= 0 { *mode += 1; } else { - panic!("rwlock locked for writing"); + rtabort!("rwlock locked for writing"); } } @@ -51,7 +51,7 @@ impl RWLock { if *mode == 0 { *mode = -1; } else { - panic!("rwlock locked for reading") + rtabort!("rwlock locked for reading") } } diff --git a/src/libstd/sys/wasm/stdio.rs b/src/libstd/sys/wasm/stdio.rs index beb19c0ed2c..023f29576a2 100644 --- a/src/libstd/sys/wasm/stdio.rs +++ b/src/libstd/sys/wasm/stdio.rs @@ -69,3 +69,7 @@ pub const STDIN_BUF_SIZE: usize = 0; pub fn is_ebadf(_err: &io::Error) -> bool { true } + +pub fn stderr_prints_nothing() -> bool { + !cfg!(feature = "wasm_syscall") +} diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs index b43df20bddd..81b89da21d3 100644 --- a/src/libstd/sys/windows/stdio.rs +++ b/src/libstd/sys/windows/stdio.rs @@ -227,3 +227,7 @@ pub fn is_ebadf(err: &io::Error) -> bool { // idea is that on windows we use a slightly smaller buffer that's // been seen to be acceptable. pub const STDIN_BUF_SIZE: usize = 8 * 1024; + +pub fn stderr_prints_nothing() -> bool { + false +} diff --git a/src/libstd/sys_common/backtrace.rs b/src/libstd/sys_common/backtrace.rs index 1955f3ec9a2..20109d2d0d5 100644 --- a/src/libstd/sys_common/backtrace.rs +++ b/src/libstd/sys_common/backtrace.rs @@ -139,10 +139,10 @@ pub fn __rust_begin_short_backtrace(f: F) -> T /// Controls how the backtrace should be formatted. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum PrintFormat { - /// Show all the frames with absolute path for files. - Full = 2, /// Show only relevant data from the backtrace. - Short = 3, + Short = 2, + /// Show all the frames with absolute path for files. + Full = 3, } // For now logging is turned off by default, and this function checks to see @@ -150,11 +150,10 @@ pub enum PrintFormat { pub fn log_enabled() -> Option { static ENABLED: atomic::AtomicIsize = atomic::AtomicIsize::new(0); match ENABLED.load(Ordering::SeqCst) { - 0 => {}, + 0 => {} 1 => return None, - 2 => return Some(PrintFormat::Full), - 3 => return Some(PrintFormat::Short), - _ => unreachable!(), + 2 => return Some(PrintFormat::Short), + _ => return Some(PrintFormat::Full), } let val = match env::var_os("RUST_BACKTRACE") { diff --git a/src/libstd/sys_common/mod.rs b/src/libstd/sys_common/mod.rs index 27504d374dd..d0c4d6a7737 100644 --- a/src/libstd/sys_common/mod.rs +++ b/src/libstd/sys_common/mod.rs @@ -28,6 +28,16 @@ use sync::Once; use sys; +macro_rules! rtabort { + ($($t:tt)*) => (::sys_common::util::abort(format_args!($($t)*))) +} + +macro_rules! rtassert { + ($e:expr) => (if !$e { + rtabort!(concat!("assertion failed: ", stringify!($e))); + }) +} + pub mod at_exit_imp; #[cfg(feature = "backtrace")] pub mod backtrace; @@ -101,10 +111,6 @@ pub fn at_exit(f: F) -> Result<(), ()> { if at_exit_imp::push(Box::new(f)) {Ok(())} else {Err(())} } -macro_rules! rtabort { - ($($t:tt)*) => (::sys_common::util::abort(format_args!($($t)*))) -} - /// One-time runtime cleanup. pub fn cleanup() { static CLEANUP: Once = Once::new(); diff --git a/src/libstd/sys_common/thread_local.rs b/src/libstd/sys_common/thread_local.rs index a4aa3d96d25..d0d6224de0a 100644 --- a/src/libstd/sys_common/thread_local.rs +++ b/src/libstd/sys_common/thread_local.rs @@ -169,7 +169,7 @@ impl StaticKey { self.key.store(key, Ordering::SeqCst); } INIT_LOCK.unlock(); - assert!(key != 0); + rtassert!(key != 0); return key } @@ -190,7 +190,7 @@ impl StaticKey { imp::destroy(key1); key2 }; - assert!(key != 0); + rtassert!(key != 0); match self.key.compare_and_swap(0, key as usize, Ordering::SeqCst) { // The CAS succeeded, so we've created the actual key 0 => key as usize, diff --git a/src/libstd/sys_common/util.rs b/src/libstd/sys_common/util.rs index a391c7cc6ef..a373e980b97 100644 --- a/src/libstd/sys_common/util.rs +++ b/src/libstd/sys_common/util.rs @@ -10,10 +10,13 @@ use fmt; use io::prelude::*; -use sys::stdio::Stderr; +use sys::stdio::{Stderr, stderr_prints_nothing}; use thread; pub fn dumb_print(args: fmt::Arguments) { + if stderr_prints_nothing() { + return + } let _ = Stderr::new().map(|mut stderr| stderr.write_fmt(args)); } diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index 99479bc56ef..40d3280baa6 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -172,12 +172,16 @@ macro_rules! __thread_local_inner { &'static $crate::cell::UnsafeCell< $crate::option::Option<$t>>> { + #[cfg(target_arch = "wasm32")] + static __KEY: $crate::thread::__StaticLocalKeyInner<$t> = + $crate::thread::__StaticLocalKeyInner::new(); + #[thread_local] - #[cfg(target_thread_local)] + #[cfg(all(target_thread_local, not(target_arch = "wasm32")))] static __KEY: $crate::thread::__FastLocalKeyInner<$t> = $crate::thread::__FastLocalKeyInner::new(); - #[cfg(not(target_thread_local))] + #[cfg(all(not(target_thread_local), not(target_arch = "wasm32")))] static __KEY: $crate::thread::__OsLocalKeyInner<$t> = $crate::thread::__OsLocalKeyInner::new(); @@ -295,6 +299,39 @@ impl LocalKey { } } +/// On some platforms like wasm32 there's no threads, so no need to generate +/// thread locals and we can instead just use plain statics! +#[doc(hidden)] +#[cfg(target_arch = "wasm32")] +pub mod statik { + use cell::UnsafeCell; + use fmt; + + pub struct Key { + inner: UnsafeCell>, + } + + unsafe impl ::marker::Sync for Key { } + + impl fmt::Debug for Key { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.pad("Key { .. }") + } + } + + impl Key { + pub const fn new() -> Key { + Key { + inner: UnsafeCell::new(None), + } + } + + pub unsafe fn get(&self) -> Option<&'static UnsafeCell>> { + Some(&*(&self.inner as *const _)) + } + } +} + #[doc(hidden)] #[cfg(target_thread_local)] pub mod fast { diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 71aee673cfe..1b976b79b4c 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -202,6 +202,9 @@ pub use self::local::{LocalKey, AccessError}; // where fast TLS was not available; end-user code is compiled with fast TLS // where available, but both are needed. +#[unstable(feature = "libstd_thread_internals", issue = "0")] +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] pub use self::local::statik::Key as __StaticLocalKeyInner; #[unstable(feature = "libstd_thread_internals", issue = "0")] #[cfg(target_thread_local)] #[doc(hidden)] pub use self::local::fast::Key as __FastLocalKeyInner; diff --git a/src/test/run-make/wasm-panic-small/Makefile b/src/test/run-make/wasm-panic-small/Makefile new file mode 100644 index 00000000000..a11fba23595 --- /dev/null +++ b/src/test/run-make/wasm-panic-small/Makefile @@ -0,0 +1,11 @@ +-include ../../run-make-fulldeps/tools.mk + +ifeq ($(TARGET),wasm32-unknown-unknown) +all: + $(RUSTC) foo.rs -C lto -O --target wasm32-unknown-unknown + wc -c < $(TMPDIR)/foo.wasm + [ "`wc -c < $(TMPDIR)/foo.wasm`" -lt "1024" ] +else +all: +endif + diff --git a/src/test/run-make/wasm-panic-small/foo.rs b/src/test/run-make/wasm-panic-small/foo.rs new file mode 100644 index 00000000000..9654d5f7c09 --- /dev/null +++ b/src/test/run-make/wasm-panic-small/foo.rs @@ -0,0 +1,16 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![crate_type = "cdylib"] + +#[no_mangle] +pub fn foo() { + panic!("test"); +} -- cgit 1.4.1-3-g733a5 From 572256772e10513ff61e9932d421d0a1e4656e02 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Sat, 7 Apr 2018 11:12:35 +0200 Subject: Remove unused methods on the private Wtf8 type MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The type and its direct parent module are `pub`, but they’re not reachable outside of std --- src/libstd/sys_common/wtf8.rs | 14 -------------- 1 file changed, 14 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index dda4e1bab3b..fe7e058091e 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -876,21 +876,7 @@ impl Hash for Wtf8 { } impl Wtf8 { - pub fn is_ascii(&self) -> bool { - self.bytes.is_ascii() - } - pub fn to_ascii_uppercase(&self) -> Wtf8Buf { - Wtf8Buf { bytes: self.bytes.to_ascii_uppercase() } - } - pub fn to_ascii_lowercase(&self) -> Wtf8Buf { - Wtf8Buf { bytes: self.bytes.to_ascii_lowercase() } - } - pub fn eq_ignore_ascii_case(&self, other: &Wtf8) -> bool { - self.bytes.eq_ignore_ascii_case(&other.bytes) - } - pub fn make_ascii_uppercase(&mut self) { self.bytes.make_ascii_uppercase() } - pub fn make_ascii_lowercase(&mut self) { self.bytes.make_ascii_lowercase() } } #[cfg(test)] -- cgit 1.4.1-3-g733a5 From f8b774fbf1f57e520b58ae3828e4b3a1ddf1d97c Mon Sep 17 00:00:00 2001 From: Manish Goregaokar Date: Mon, 7 May 2018 09:27:50 -0700 Subject: Add explanation for #[must_use] on mutex guards --- src/libstd/sync/mutex.rs | 2 +- src/libstd/sync/rwlock.rs | 4 ++-- src/libstd/sys_common/remutex.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 3b4904c98e8..f3503b0b3a6 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -150,7 +150,7 @@ unsafe impl Sync for Mutex { } /// [`lock`]: struct.Mutex.html#method.lock /// [`try_lock`]: struct.Mutex.html#method.try_lock /// [`Mutex`]: struct.Mutex.html -#[must_use] +#[must_use = "if unused the Mutex will immediately unlock"] #[stable(feature = "rust1", since = "1.0.0")] pub struct MutexGuard<'a, T: ?Sized + 'a> { // funny underscores due to how Deref/DerefMut currently work (they diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index f7fdedc0d21..e3db60cff84 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -94,7 +94,7 @@ unsafe impl Sync for RwLock {} /// [`read`]: struct.RwLock.html#method.read /// [`try_read`]: struct.RwLock.html#method.try_read /// [`RwLock`]: struct.RwLock.html -#[must_use] +#[must_use = "if unused the RwLock will immediately unlock"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RwLockReadGuard<'a, T: ?Sized + 'a> { __lock: &'a RwLock, @@ -115,7 +115,7 @@ unsafe impl<'a, T: ?Sized + Sync> Sync for RwLockReadGuard<'a, T> {} /// [`write`]: struct.RwLock.html#method.write /// [`try_write`]: struct.RwLock.html#method.try_write /// [`RwLock`]: struct.RwLock.html -#[must_use] +#[must_use = "if unused the RwLock will immediately unlock"] #[stable(feature = "rust1", since = "1.0.0")] pub struct RwLockWriteGuard<'a, T: ?Sized + 'a> { __lock: &'a RwLock, diff --git a/src/libstd/sys_common/remutex.rs b/src/libstd/sys_common/remutex.rs index ce43ec6d9ab..022056f8a8a 100644 --- a/src/libstd/sys_common/remutex.rs +++ b/src/libstd/sys_common/remutex.rs @@ -41,7 +41,7 @@ unsafe impl Sync for ReentrantMutex {} /// because implementation of the trait would violate Rust’s reference aliasing /// rules. Use interior mutability (usually `RefCell`) in order to mutate the /// guarded data. -#[must_use] +#[must_use = "if unused the ReentrantMutex will immediately unlock"] pub struct ReentrantMutexGuard<'a, T: 'a> { // funny underscores due to how Deref currently works (it disregards field // privacy). -- cgit 1.4.1-3-g733a5 From e333725664c45874262ecb11e511c17cfd4672f0 Mon Sep 17 00:00:00 2001 From: Andre Bogus Date: Wed, 9 May 2018 01:41:44 +0200 Subject: use fmt::Result where applicable --- src/librustc/ich/fingerprint.rs | 2 +- src/librustc_data_structures/control_flow_graph/dominators/mod.rs | 4 ++-- src/librustc_data_structures/owning_ref/mod.rs | 6 +++--- src/librustc_errors/lib.rs | 4 ++-- src/librustc_mir/borrow_check/nll/region_infer/mod.rs | 2 +- src/librustc_mir/transform/elaborate_drops.rs | 2 +- src/librustdoc/html/render.rs | 4 ++-- src/libstd/path.rs | 2 +- src/libstd/sys/redox/syscall/error.rs | 4 ++-- src/libstd/sys_common/wtf8.rs | 4 ++-- src/libsyntax_ext/format_foreign.rs | 2 +- src/test/run-pass/atomic-print.rs | 2 +- src/test/run-pass/union/union-trait-impl.rs | 2 +- 13 files changed, 20 insertions(+), 20 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/librustc/ich/fingerprint.rs b/src/librustc/ich/fingerprint.rs index a7adf28c481..f56f4e12e7a 100644 --- a/src/librustc/ich/fingerprint.rs +++ b/src/librustc/ich/fingerprint.rs @@ -67,7 +67,7 @@ impl Fingerprint { } impl ::std::fmt::Display for Fingerprint { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(formatter, "{:x}-{:x}", self.0, self.1) } } diff --git a/src/librustc_data_structures/control_flow_graph/dominators/mod.rs b/src/librustc_data_structures/control_flow_graph/dominators/mod.rs index dc487f1162c..54407658e6c 100644 --- a/src/librustc_data_structures/control_flow_graph/dominators/mod.rs +++ b/src/librustc_data_structures/control_flow_graph/dominators/mod.rs @@ -175,7 +175,7 @@ impl DominatorTree { } impl fmt::Debug for DominatorTree { - fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&DominatorTreeNode { tree: self, node: self.root, @@ -190,7 +190,7 @@ struct DominatorTreeNode<'tree, Node: Idx> { } impl<'tree, Node: Idx> fmt::Debug for DominatorTreeNode<'tree, Node> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let subtrees: Vec<_> = self.tree .children(self.node) .iter() diff --git a/src/librustc_data_structures/owning_ref/mod.rs b/src/librustc_data_structures/owning_ref/mod.rs index c466b8f8ad1..aa113fac9fb 100644 --- a/src/librustc_data_structures/owning_ref/mod.rs +++ b/src/librustc_data_structures/owning_ref/mod.rs @@ -1002,7 +1002,7 @@ impl Debug for OwningRef where O: Debug, T: Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "OwningRef {{ owner: {:?}, reference: {:?} }}", self.owner(), @@ -1014,7 +1014,7 @@ impl Debug for OwningRefMut where O: Debug, T: Debug, { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "OwningRefMut {{ owner: {:?}, reference: {:?} }}", self.owner(), @@ -1047,7 +1047,7 @@ unsafe impl Sync for OwningRefMut where O: Sync, for<'a> (&'a mut T): Sync {} impl Debug for Erased { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "",) } } diff --git a/src/librustc_errors/lib.rs b/src/librustc_errors/lib.rs index c2b442e9497..fd90e1cbe08 100644 --- a/src/librustc_errors/lib.rs +++ b/src/librustc_errors/lib.rs @@ -232,7 +232,7 @@ impl FatalError { } impl fmt::Display for FatalError { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "parser fatal error") } } @@ -249,7 +249,7 @@ impl error::Error for FatalError { pub struct ExplicitBug; impl fmt::Display for ExplicitBug { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "parser internal bug") } } diff --git a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs index 4d1f3e2b430..57b8824191f 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs @@ -1185,7 +1185,7 @@ impl<'tcx> RegionDefinition<'tcx> { } impl fmt::Debug for Constraint { - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!( formatter, "({:?}: {:?} @ {:?}) due to {:?}", diff --git a/src/librustc_mir/transform/elaborate_drops.rs b/src/librustc_mir/transform/elaborate_drops.rs index 5397d18cdd7..79252e7654b 100644 --- a/src/librustc_mir/transform/elaborate_drops.rs +++ b/src/librustc_mir/transform/elaborate_drops.rs @@ -174,7 +174,7 @@ struct Elaborator<'a, 'b: 'a, 'tcx: 'b> { } impl<'a, 'b, 'tcx> fmt::Debug for Elaborator<'a, 'b, 'tcx> { - fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 21de2db1dfe..fe9fc3ddd68 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -2579,7 +2579,7 @@ fn item_function(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, } fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter, - implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> Result<(), fmt::Error> { + implementor_dups: &FxHashMap<&str, (DefId, bool)>) -> fmt::Result { write!(w, "
  • ")?; // If there's already another implementor that has the same abbridged name, use the // full path, for example in `std::iter::ExactSizeIterator` @@ -2612,7 +2612,7 @@ fn render_implementor(cx: &Context, implementor: &Impl, w: &mut fmt::Formatter, fn render_impls(cx: &Context, w: &mut fmt::Formatter, traits: &[&&Impl], - containing_item: &clean::Item) -> Result<(), fmt::Error> { + containing_item: &clean::Item) -> fmt::Result { for i in traits { let did = i.trait_did().unwrap(); let assoc_link = AssocItemLink::GotoSource(did, &i.inner_impl().provided_trait_methods); diff --git a/src/libstd/path.rs b/src/libstd/path.rs index 696711a70d4..5d35a786173 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -1460,7 +1460,7 @@ impl> iter::Extend

    for PathBuf { #[stable(feature = "rust1", since = "1.0.0")] impl fmt::Debug for PathBuf { - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, formatter) } } diff --git a/src/libstd/sys/redox/syscall/error.rs b/src/libstd/sys/redox/syscall/error.rs index d8d78d55016..1ef79547431 100644 --- a/src/libstd/sys/redox/syscall/error.rs +++ b/src/libstd/sys/redox/syscall/error.rs @@ -48,13 +48,13 @@ impl Error { } impl fmt::Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.text()) } } impl fmt::Display for Error { - fn fmt(&self, f: &mut fmt::Formatter) -> result::Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.text()) } } diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index fe7e058091e..14a2555adf9 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -56,7 +56,7 @@ pub struct CodePoint { /// Example: `U+1F4A9` impl fmt::Debug for CodePoint { #[inline] - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write!(formatter, "U+{:04X}", self.value) } } @@ -144,7 +144,7 @@ impl ops::DerefMut for Wtf8Buf { /// Example: `"a\u{D800}"` for a string with code points [U+0061, U+D800] impl fmt::Debug for Wtf8Buf { #[inline] - fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, formatter) } } diff --git a/src/libsyntax_ext/format_foreign.rs b/src/libsyntax_ext/format_foreign.rs index e95c6f2e124..2b8603c75a5 100644 --- a/src/libsyntax_ext/format_foreign.rs +++ b/src/libsyntax_ext/format_foreign.rs @@ -989,7 +989,7 @@ mod strcursor { } impl<'a> std::fmt::Debug for StrCursor<'a> { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { + fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { write!(fmt, "StrCursor({:?} | {:?})", self.slice_before(), self.slice_after()) } } diff --git a/src/test/run-pass/atomic-print.rs b/src/test/run-pass/atomic-print.rs index 914b89dfb4d..2d478e954e7 100644 --- a/src/test/run-pass/atomic-print.rs +++ b/src/test/run-pass/atomic-print.rs @@ -15,7 +15,7 @@ use std::{env, fmt, process, sync, thread}; struct SlowFmt(u32); impl fmt::Debug for SlowFmt { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { thread::sleep_ms(3); self.0.fmt(f) } diff --git a/src/test/run-pass/union/union-trait-impl.rs b/src/test/run-pass/union/union-trait-impl.rs index 1cdaff2cab7..c1e408cc02a 100644 --- a/src/test/run-pass/union/union-trait-impl.rs +++ b/src/test/run-pass/union/union-trait-impl.rs @@ -15,7 +15,7 @@ union U { } impl fmt::Display for U { - fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { unsafe { write!(f, "Oh hai {}", self.a) } } } -- cgit 1.4.1-3-g733a5 From b81da278623d9dcda1776008612bd42e1922e9c3 Mon Sep 17 00:00:00 2001 From: "NODA, Kai" Date: Sat, 9 Jun 2018 21:13:04 +0800 Subject: libstd: add an RAII utility for sys_common::mutex::Mutex Signed-off-by: NODA, Kai --- src/libstd/io/lazy.rs | 21 +++++++++++---------- src/libstd/sync/mutex.rs | 4 ++-- src/libstd/sys/redox/args.rs | 16 ++++++---------- src/libstd/sys/unix/args.rs | 14 +++++--------- src/libstd/sys/unix/os.rs | 26 +++++++++----------------- src/libstd/sys_common/at_exit_imp.rs | 27 ++++++++++++++------------- src/libstd/sys_common/mutex.rs | 26 ++++++++++++++++++++++++-- src/libstd/sys_common/thread_local.rs | 3 +-- src/libstd/thread/mod.rs | 5 +---- 9 files changed, 73 insertions(+), 69 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs index 9cef4e3cdf1..d357966be92 100644 --- a/src/libstd/io/lazy.rs +++ b/src/libstd/io/lazy.rs @@ -20,6 +20,9 @@ pub struct Lazy { init: fn() -> Arc, } +#[inline] +const fn done() -> *mut Arc { 1_usize as *mut _ } + unsafe impl Sync for Lazy {} impl Lazy { @@ -33,17 +36,15 @@ impl Lazy { pub fn get(&'static self) -> Option> { unsafe { - self.lock.lock(); + let _guard = self.lock.lock(); let ptr = self.ptr.get(); - let ret = if ptr.is_null() { + if ptr.is_null() { Some(self.init()) - } else if ptr as usize == 1 { + } else if ptr == done() { None } else { Some((*ptr).clone()) - }; - self.lock.unlock(); - return ret + } } } @@ -53,10 +54,10 @@ impl Lazy { // the at exit handler). Otherwise we just return the freshly allocated // `Arc`. let registered = sys_common::at_exit(move || { - self.lock.lock(); - let ptr = self.ptr.get(); - self.ptr.set(1 as *mut _); - self.lock.unlock(); + let ptr = { + let _guard = self.lock.lock(); + self.ptr.replace(done()) + }; drop(Box::from_raw(ptr)) }); let ret = (self.init)(); diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index f3503b0b3a6..e5a410644b9 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -227,7 +227,7 @@ impl Mutex { #[stable(feature = "rust1", since = "1.0.0")] pub fn lock(&self) -> LockResult> { unsafe { - self.inner.lock(); + self.inner.raw_lock(); MutexGuard::new(self) } } @@ -454,7 +454,7 @@ impl<'a, T: ?Sized> Drop for MutexGuard<'a, T> { fn drop(&mut self) { unsafe { self.__lock.poison.done(&self.__poison); - self.__lock.inner.unlock(); + self.__lock.inner.raw_unlock(); } } } diff --git a/src/libstd/sys/redox/args.rs b/src/libstd/sys/redox/args.rs index 59ae2a74a6d..556ed77372e 100644 --- a/src/libstd/sys/redox/args.rs +++ b/src/libstd/sys/redox/args.rs @@ -73,17 +73,15 @@ mod imp { CStr::from_ptr(*argv.offset(i) as *const libc::c_char).to_bytes().to_vec() }).collect(); - LOCK.lock(); + let _guard = LOCK.lock(); let ptr = get_global_ptr(); assert!((*ptr).is_none()); (*ptr) = Some(box args); - LOCK.unlock(); } pub unsafe fn cleanup() { - LOCK.lock(); + let _guard = LOCK.lock(); *get_global_ptr() = None; - LOCK.unlock(); } pub fn args() -> Args { @@ -96,16 +94,14 @@ mod imp { fn clone() -> Option>> { unsafe { - LOCK.lock(); + let _guard = LOCK.lock(); let ptr = get_global_ptr(); - let ret = (*ptr).as_ref().map(|s| (**s).clone()); - LOCK.unlock(); - return ret + (*ptr).as_ref().map(|s| (**s).clone()) } } - fn get_global_ptr() -> *mut Option>>> { - unsafe { mem::transmute(&GLOBAL_ARGS_PTR) } + unsafe fn get_global_ptr() -> *mut Option>>> { + mem::transmute(&GLOBAL_ARGS_PTR) } } diff --git a/src/libstd/sys/unix/args.rs b/src/libstd/sys/unix/args.rs index e1c7ffc19e5..dc1dba6f2f9 100644 --- a/src/libstd/sys/unix/args.rs +++ b/src/libstd/sys/unix/args.rs @@ -82,17 +82,15 @@ mod imp { static LOCK: Mutex = Mutex::new(); pub unsafe fn init(argc: isize, argv: *const *const u8) { - LOCK.lock(); + let _guard = LOCK.lock(); ARGC = argc; ARGV = argv; - LOCK.unlock(); } pub unsafe fn cleanup() { - LOCK.lock(); + let _guard = LOCK.lock(); ARGC = 0; ARGV = ptr::null(); - LOCK.unlock(); } pub fn args() -> Args { @@ -104,13 +102,11 @@ mod imp { fn clone() -> Vec { unsafe { - LOCK.lock(); - let ret = (0..ARGC).map(|i| { + let _guard = LOCK.lock(); + (0..ARGC).map(|i| { let cstr = CStr::from_ptr(*ARGV.offset(i) as *const libc::c_char); OsStringExt::from_vec(cstr.to_bytes().to_vec()) - }).collect(); - LOCK.unlock(); - return ret + }).collect() } } } diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 4c86fddee4b..82d05f78850 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -409,10 +409,9 @@ pub unsafe fn environ() -> *mut *const *const c_char { /// environment variables of the current process. pub fn env() -> Env { unsafe { - ENV_LOCK.lock(); + let _guard = ENV_LOCK.lock(); let mut environ = *environ(); if environ == ptr::null() { - ENV_LOCK.unlock(); panic!("os::env() failure getting env string from OS: {}", io::Error::last_os_error()); } @@ -423,12 +422,10 @@ pub fn env() -> Env { } environ = environ.offset(1); } - let ret = Env { + return Env { iter: result.into_iter(), _dont_send_or_sync_me: PhantomData, - }; - ENV_LOCK.unlock(); - return ret + } } fn parse(input: &[u8]) -> Option<(OsString, OsString)> { @@ -452,15 +449,14 @@ pub fn getenv(k: &OsStr) -> io::Result> { // always None as well let k = CString::new(k.as_bytes())?; unsafe { - ENV_LOCK.lock(); + let _guard = ENV_LOCK.lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char; let ret = if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) }; - ENV_LOCK.unlock(); - return Ok(ret) + Ok(ret) } } @@ -469,10 +465,8 @@ pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let v = CString::new(v.as_bytes())?; unsafe { - ENV_LOCK.lock(); - let ret = cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ()); - ENV_LOCK.unlock(); - return ret + let _guard = ENV_LOCK.lock(); + cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(|_| ()) } } @@ -480,10 +474,8 @@ pub fn unsetenv(n: &OsStr) -> io::Result<()> { let nbuf = CString::new(n.as_bytes())?; unsafe { - ENV_LOCK.lock(); - let ret = cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ()); - ENV_LOCK.unlock(); - return ret + let _guard = ENV_LOCK.lock(); + cvt(libc::unsetenv(nbuf.as_ptr())).map(|_| ()) } } diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index 26da51c9825..d268d9ad6f9 100644 --- a/src/libstd/sys_common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs @@ -14,6 +14,7 @@ use boxed::FnBox; use ptr; +use mem; use sys_common::mutex::Mutex; type Queue = Vec>; @@ -25,6 +26,8 @@ type Queue = Vec>; static LOCK: Mutex = Mutex::new(); static mut QUEUE: *mut Queue = ptr::null_mut(); +const DONE: *mut Queue = 1_usize as *mut _; + // The maximum number of times the cleanup routines will be run. While running // the at_exit closures new ones may be registered, and this count is the number // of times the new closures will be allowed to register successfully. After @@ -35,7 +38,7 @@ unsafe fn init() -> bool { if QUEUE.is_null() { let state: Box = box Vec::new(); QUEUE = Box::into_raw(state); - } else if QUEUE as usize == 1 { + } else if QUEUE == DONE { // can't re-init after a cleanup return false } @@ -44,18 +47,18 @@ unsafe fn init() -> bool { } pub fn cleanup() { - for i in 0..ITERS { + for i in 1..=ITERS { unsafe { - LOCK.lock(); - let queue = QUEUE; - QUEUE = if i == ITERS - 1 {1} else {0} as *mut _; - LOCK.unlock(); + let queue = { + let _guard = LOCK.lock(); + mem::replace(&mut QUEUE, if i == ITERS { DONE } else { ptr::null_mut() }) + }; // make sure we're not recursively cleaning up - assert!(queue as usize != 1); + assert!(queue != DONE); // If we never called init, not need to cleanup! - if queue as usize != 0 { + if !queue.is_null() { let queue: Box = Box::from_raw(queue); for to_run in *queue { to_run(); @@ -66,15 +69,13 @@ pub fn cleanup() { } pub fn push(f: Box) -> bool { - let mut ret = true; unsafe { - LOCK.lock(); + let _guard = LOCK.lock(); if init() { (*QUEUE).push(f); + true } else { - ret = false; + false } - LOCK.unlock(); } - ret } diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs index d1a738770d3..608355b7d70 100644 --- a/src/libstd/sys_common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs @@ -37,7 +37,15 @@ impl Mutex { /// Behavior is undefined if the mutex has been moved between this and any /// previous function call. #[inline] - pub unsafe fn lock(&self) { self.0.lock() } + pub unsafe fn raw_lock(&self) { self.0.lock() } + + /// Calls raw_lock() and then returns an RAII guard to guarantee the mutex + /// will be unlocked. + #[inline] + pub unsafe fn lock(&self) -> MutexGuard { + self.raw_lock(); + MutexGuard(&self.0) + } /// Attempts to lock the mutex without blocking, returning whether it was /// successfully acquired or not. @@ -51,8 +59,11 @@ impl Mutex { /// /// Behavior is undefined if the current thread does not actually hold the /// mutex. + /// + /// Consider switching from the pair of raw_lock() and raw_unlock() to + /// lock() whenever possible. #[inline] - pub unsafe fn unlock(&self) { self.0.unlock() } + pub unsafe fn raw_unlock(&self) { self.0.unlock() } /// Deallocates all resources associated with this mutex. /// @@ -64,3 +75,14 @@ impl Mutex { // not meant to be exported to the outside world, just the containing module pub fn raw(mutex: &Mutex) -> &imp::Mutex { &mutex.0 } + +#[must_use] +/// A simple RAII utility for the above Mutex without the poisoning semantics. +pub struct MutexGuard<'a>(&'a imp::Mutex); + +impl<'a> Drop for MutexGuard<'a> { + #[inline] + fn drop(&mut self) { + unsafe { self.0.unlock(); } + } +} diff --git a/src/libstd/sys_common/thread_local.rs b/src/libstd/sys_common/thread_local.rs index d0d6224de0a..75f6b9ac7fd 100644 --- a/src/libstd/sys_common/thread_local.rs +++ b/src/libstd/sys_common/thread_local.rs @@ -162,13 +162,12 @@ impl StaticKey { // we just simplify the whole branch. if imp::requires_synchronized_create() { static INIT_LOCK: Mutex = Mutex::new(); - INIT_LOCK.lock(); + let _guard = INIT_LOCK.lock(); let mut key = self.key.load(Ordering::SeqCst); if key == 0 { key = imp::create(self.dtor) as usize; self.key.store(key, Ordering::SeqCst); } - INIT_LOCK.unlock(); rtassert!(key != 0); return key } diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 1b976b79b4c..1dacf99b64b 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -935,20 +935,17 @@ impl ThreadId { static mut COUNTER: u64 = 0; unsafe { - GUARD.lock(); + let _guard = GUARD.lock(); // If we somehow use up all our bits, panic so that we're not // covering up subtle bugs of IDs being reused. if COUNTER == ::u64::MAX { - GUARD.unlock(); panic!("failed to generate unique thread ID: bitspace exhausted"); } let id = COUNTER; COUNTER += 1; - GUARD.unlock(); - ThreadId(id) } } -- cgit 1.4.1-3-g733a5 From 057715557b51af125847da6d19b2e016283c5ae7 Mon Sep 17 00:00:00 2001 From: "Zack M. Davis" Date: Mon, 28 May 2018 19:42:11 -0700 Subject: migrate codebase to `..=` inclusive range patterns These were stabilized in March 2018's #47813, and are the Preferred Way to Do It going forward (q.v. #51043). --- src/libcore/ascii.rs | 4 +- src/libcore/char/decode.rs | 18 ++++---- src/libcore/char/methods.rs | 18 ++++---- src/libcore/fmt/num.rs | 14 +++--- src/libcore/slice/mod.rs | 6 +-- src/libcore/str/lossy.rs | 14 +++--- src/libcore/str/mod.rs | 14 +++--- src/libcore/tests/slice.rs | 4 +- src/librustc_apfloat/ieee.rs | 4 +- src/librustc_codegen_utils/symbol_names.rs | 2 +- src/librustc_mir/diagnostics.rs | 4 +- src/librustc_mir/hair/pattern/check_match.rs | 2 +- src/librustc_target/abi/call/mod.rs | 10 ++--- src/librustc_target/abi/mod.rs | 16 +++---- src/librustc_typeck/diagnostics.rs | 6 +-- src/libserialize/hex.rs | 6 +-- src/libserialize/json.rs | 22 ++++----- src/libstd/sys_common/backtrace.rs | 2 +- src/libstd/sys_common/wtf8.rs | 12 ++--- src/libsyntax/ast.rs | 4 +- src/libsyntax/parse/lexer/mod.rs | 4 +- src/libsyntax_ext/format_foreign.rs | 14 +++--- src/libsyntax_pos/lib.rs | 4 +- src/libterm/terminfo/parm.rs | 10 ++--- src/test/compile-fail/associated-path-shl.rs | 2 +- src/test/compile-fail/issue-27895.rs | 2 +- src/test/compile-fail/issue-41255.rs | 2 +- src/test/compile-fail/match-range-fail-2.rs | 4 +- src/test/compile-fail/match-range-fail.rs | 6 +-- .../compile-fail/non-constant-in-const-path.rs | 2 +- src/test/compile-fail/patkind-litrange-no-expr.rs | 3 +- src/test/compile-fail/qualified-path-params.rs | 2 +- src/test/compile-fail/refutable-pattern-errors.rs | 4 +- src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs | 8 ++-- src/test/run-pass/byte-literals.rs | 2 +- .../run-pass/inferred-suffix-in-pattern-range.rs | 6 +-- src/test/run-pass/issue-12582.rs | 4 +- src/test/run-pass/issue-13027.rs | 52 +++++++++++----------- src/test/run-pass/issue-13867.rs | 14 +++--- src/test/run-pass/issue-18060.rs | 6 +-- src/test/run-pass/issue-18464.rs | 2 +- src/test/run-pass/issue-21475.rs | 6 +-- src/test/run-pass/issue-26251.rs | 4 +- src/test/run-pass/issue-35423.rs | 2 +- src/test/run-pass/issue-7222.rs | 2 +- src/test/run-pass/macro-literal.rs | 20 ++++----- src/test/run-pass/match-range-infer.rs | 6 +-- src/test/run-pass/match-range-static.rs | 2 +- src/test/run-pass/match-range.rs | 14 +++--- .../rfc-2005-default-binding-mode/range.rs | 4 +- src/test/ui/check_match/issue-43253.rs | 8 ++-- src/test/ui/check_match/issue-43253.stderr | 4 +- src/test/ui/const-eval/const_signed_pat.rs | 2 +- src/test/ui/const-eval/ref_to_int_match.rs | 4 +- src/test/ui/const-eval/ref_to_int_match.stderr | 2 +- src/test/ui/error-codes/E0029-teach.rs | 2 +- src/test/ui/error-codes/E0029-teach.stderr | 2 +- src/test/ui/error-codes/E0029.rs | 2 +- src/test/ui/error-codes/E0029.stderr | 2 +- src/test/ui/error-codes/E0030-teach.rs | 2 +- src/test/ui/error-codes/E0030-teach.stderr | 2 +- src/test/ui/error-codes/E0030.rs | 2 +- src/test/ui/error-codes/E0030.stderr | 2 +- src/test/ui/error-codes/E0308-4.rs | 2 +- src/test/ui/error-codes/E0308-4.stderr | 2 +- 65 files changed, 217 insertions(+), 218 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libcore/ascii.rs b/src/libcore/ascii.rs index e6b0569281f..6ee91e0b22f 100644 --- a/src/libcore/ascii.rs +++ b/src/libcore/ascii.rs @@ -108,7 +108,7 @@ pub fn escape_default(c: u8) -> EscapeDefault { b'\\' => ([b'\\', b'\\', 0, 0], 2), b'\'' => ([b'\\', b'\'', 0, 0], 2), b'"' => ([b'\\', b'"', 0, 0], 2), - b'\x20' ... b'\x7e' => ([c, 0, 0, 0], 1), + b'\x20' ..= b'\x7e' => ([c, 0, 0, 0], 1), _ => ([b'\\', b'x', hexify(c >> 4), hexify(c & 0xf)], 4), }; @@ -116,7 +116,7 @@ pub fn escape_default(c: u8) -> EscapeDefault { fn hexify(b: u8) -> u8 { match b { - 0 ... 9 => b'0' + b, + 0 ..= 9 => b'0' + b, _ => b'a' + b - 10, } } diff --git a/src/libcore/char/decode.rs b/src/libcore/char/decode.rs index 45a73191db2..0b8dce19dff 100644 --- a/src/libcore/char/decode.rs +++ b/src/libcore/char/decode.rs @@ -64,7 +64,7 @@ impl> Iterator for DecodeUtf8 { } } macro_rules! continuation_byte { - () => { continuation_byte!(0x80...0xBF) }; + () => { continuation_byte!(0x80..=0xBF) }; ($range: pat) => { match self.0.peek() { Some(&byte @ $range) => { @@ -77,35 +77,35 @@ impl> Iterator for DecodeUtf8 { } match first_byte { - 0x00...0x7F => { + 0x00..=0x7F => { first_byte!(0b1111_1111); } - 0xC2...0xDF => { + 0xC2..=0xDF => { first_byte!(0b0001_1111); continuation_byte!(); } 0xE0 => { first_byte!(0b0000_1111); - continuation_byte!(0xA0...0xBF); // 0x80...0x9F here are overlong + continuation_byte!(0xA0..=0xBF); // 0x80..=0x9F here are overlong continuation_byte!(); } - 0xE1...0xEC | 0xEE...0xEF => { + 0xE1..=0xEC | 0xEE..=0xEF => { first_byte!(0b0000_1111); continuation_byte!(); continuation_byte!(); } 0xED => { first_byte!(0b0000_1111); - continuation_byte!(0x80...0x9F); // 0xA0..0xBF here are surrogates + continuation_byte!(0x80..=0x9F); // 0xA0..0xBF here are surrogates continuation_byte!(); } 0xF0 => { first_byte!(0b0000_0111); - continuation_byte!(0x90...0xBF); // 0x80..0x8F here are overlong + continuation_byte!(0x90..=0xBF); // 0x80..0x8F here are overlong continuation_byte!(); continuation_byte!(); } - 0xF1...0xF3 => { + 0xF1..=0xF3 => { first_byte!(0b0000_0111); continuation_byte!(); continuation_byte!(); @@ -113,7 +113,7 @@ impl> Iterator for DecodeUtf8 { } 0xF4 => { first_byte!(0b0000_0111); - continuation_byte!(0x80...0x8F); // 0x90..0xBF here are beyond char::MAX + continuation_byte!(0x80..=0x8F); // 0x90..0xBF here are beyond char::MAX continuation_byte!(); continuation_byte!(); } diff --git a/src/libcore/char/methods.rs b/src/libcore/char/methods.rs index f6b201fe06d..eee78de9036 100644 --- a/src/libcore/char/methods.rs +++ b/src/libcore/char/methods.rs @@ -125,9 +125,9 @@ impl char { panic!("to_digit: radix is too high (maximum 36)"); } let val = match self { - '0' ... '9' => self as u32 - '0' as u32, - 'a' ... 'z' => self as u32 - 'a' as u32 + 10, - 'A' ... 'Z' => self as u32 - 'A' as u32 + 10, + '0' ..= '9' => self as u32 - '0' as u32, + 'a' ..= 'z' => self as u32 - 'a' as u32 + 10, + 'A' ..= 'Z' => self as u32 - 'A' as u32 + 10, _ => return None, }; if val < radix { Some(val) } @@ -305,7 +305,7 @@ impl char { '\r' => EscapeDefaultState::Backslash('r'), '\n' => EscapeDefaultState::Backslash('n'), '\\' | '\'' | '"' => EscapeDefaultState::Backslash(self), - '\x20' ... '\x7e' => EscapeDefaultState::Char(self), + '\x20' ..= '\x7e' => EscapeDefaultState::Char(self), _ => EscapeDefaultState::Unicode(self.escape_unicode()) }; EscapeDefault { state: init_state } @@ -543,7 +543,7 @@ impl char { #[inline] pub fn is_alphabetic(self) -> bool { match self { - 'a'...'z' | 'A'...'Z' => true, + 'a'..='z' | 'A'..='Z' => true, c if c > '\x7f' => derived_property::Alphabetic(c), _ => false, } @@ -599,7 +599,7 @@ impl char { #[inline] pub fn is_lowercase(self) -> bool { match self { - 'a'...'z' => true, + 'a'..='z' => true, c if c > '\x7f' => derived_property::Lowercase(c), _ => false, } @@ -627,7 +627,7 @@ impl char { #[inline] pub fn is_uppercase(self) -> bool { match self { - 'A'...'Z' => true, + 'A'..='Z' => true, c if c > '\x7f' => derived_property::Uppercase(c), _ => false, } @@ -654,7 +654,7 @@ impl char { #[inline] pub fn is_whitespace(self) -> bool { match self { - ' ' | '\x09'...'\x0d' => true, + ' ' | '\x09'..='\x0d' => true, c if c > '\x7f' => property::White_Space(c), _ => false, } @@ -737,7 +737,7 @@ impl char { #[inline] pub fn is_numeric(self) -> bool { match self { - '0'...'9' => true, + '0'..='9' => true, c if c > '\x7f' => general_category::N(c), _ => false, } diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index 4451ab445cc..51391fa50d5 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -121,19 +121,19 @@ macro_rules! radix { fn digit(x: u8) -> u8 { match x { $($x => $conv,)+ - x => panic!("number not in the range 0..{}: {}", Self::BASE - 1, x), + x => panic!("number not in the range 0..={}: {}", Self::BASE - 1, x), } } } } } -radix! { Binary, 2, "0b", x @ 0 ... 1 => b'0' + x } -radix! { Octal, 8, "0o", x @ 0 ... 7 => b'0' + x } -radix! { LowerHex, 16, "0x", x @ 0 ... 9 => b'0' + x, - x @ 10 ... 15 => b'a' + (x - 10) } -radix! { UpperHex, 16, "0x", x @ 0 ... 9 => b'0' + x, - x @ 10 ... 15 => b'A' + (x - 10) } +radix! { Binary, 2, "0b", x @ 0 ..= 1 => b'0' + x } +radix! { Octal, 8, "0o", x @ 0 ..= 7 => b'0' + x } +radix! { LowerHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, + x @ 10 ..= 15 => b'a' + (x - 10) } +radix! { UpperHex, 16, "0x", x @ 0 ..= 9 => b'0' + x, + x @ 10 ..= 15 => b'A' + (x - 10) } macro_rules! int_base { ($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => { diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 6f4c130d8f3..e74e527927d 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -1230,7 +1230,7 @@ impl [T] { /// assert_eq!(s.binary_search(&4), Err(7)); /// assert_eq!(s.binary_search(&100), Err(13)); /// let r = s.binary_search(&1); - /// assert!(match r { Ok(1...4) => true, _ => false, }); + /// assert!(match r { Ok(1..=4) => true, _ => false, }); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn binary_search(&self, x: &T) -> Result @@ -1268,7 +1268,7 @@ impl [T] { /// assert_eq!(s.binary_search_by(|probe| probe.cmp(&seek)), Err(13)); /// let seek = 1; /// let r = s.binary_search_by(|probe| probe.cmp(&seek)); - /// assert!(match r { Ok(1...4) => true, _ => false, }); + /// assert!(match r { Ok(1..=4) => true, _ => false, }); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] @@ -1325,7 +1325,7 @@ impl [T] { /// assert_eq!(s.binary_search_by_key(&4, |&(a,b)| b), Err(7)); /// assert_eq!(s.binary_search_by_key(&100, |&(a,b)| b), Err(13)); /// let r = s.binary_search_by_key(&1, |&(a,b)| b); - /// assert!(match r { Ok(1...4) => true, _ => false, }); + /// assert!(match r { Ok(1..=4) => true, _ => false, }); /// ``` #[stable(feature = "slice_binary_search_by_key", since = "1.10.0")] #[inline] diff --git a/src/libcore/str/lossy.rs b/src/libcore/str/lossy.rs index 30b7267da7c..5cfb36d3b19 100644 --- a/src/libcore/str/lossy.rs +++ b/src/libcore/str/lossy.rs @@ -101,10 +101,10 @@ impl<'a> Iterator for Utf8LossyChunksIter<'a> { } 3 => { match (byte, safe_get(self.source, i)) { - (0xE0, 0xA0 ... 0xBF) => (), - (0xE1 ... 0xEC, 0x80 ... 0xBF) => (), - (0xED, 0x80 ... 0x9F) => (), - (0xEE ... 0xEF, 0x80 ... 0xBF) => (), + (0xE0, 0xA0 ..= 0xBF) => (), + (0xE1 ..= 0xEC, 0x80 ..= 0xBF) => (), + (0xED, 0x80 ..= 0x9F) => (), + (0xEE ..= 0xEF, 0x80 ..= 0xBF) => (), _ => { error!(); } @@ -117,9 +117,9 @@ impl<'a> Iterator for Utf8LossyChunksIter<'a> { } 4 => { match (byte, safe_get(self.source, i)) { - (0xF0, 0x90 ... 0xBF) => (), - (0xF1 ... 0xF3, 0x80 ... 0xBF) => (), - (0xF4, 0x80 ... 0x8F) => (), + (0xF0, 0x90 ..= 0xBF) => (), + (0xF1 ..= 0xF3, 0x80 ..= 0xBF) => (), + (0xF4, 0x80 ..= 0x8F) => (), _ => { error!(); } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 5e1a9c25a21..42fb1bc238b 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1484,10 +1484,10 @@ fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { }, 3 => { match (first, next!()) { - (0xE0 , 0xA0 ... 0xBF) | - (0xE1 ... 0xEC, 0x80 ... 0xBF) | - (0xED , 0x80 ... 0x9F) | - (0xEE ... 0xEF, 0x80 ... 0xBF) => {} + (0xE0 , 0xA0 ..= 0xBF) | + (0xE1 ..= 0xEC, 0x80 ..= 0xBF) | + (0xED , 0x80 ..= 0x9F) | + (0xEE ..= 0xEF, 0x80 ..= 0xBF) => {} _ => err!(Some(1)) } if next!() & !CONT_MASK != TAG_CONT_U8 { @@ -1496,9 +1496,9 @@ fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { } 4 => { match (first, next!()) { - (0xF0 , 0x90 ... 0xBF) | - (0xF1 ... 0xF3, 0x80 ... 0xBF) | - (0xF4 , 0x80 ... 0x8F) => {} + (0xF0 , 0x90 ..= 0xBF) | + (0xF1 ..= 0xF3, 0x80 ..= 0xBF) | + (0xF4 , 0x80 ..= 0x8F) => {} _ => err!(Some(1)) } if next!() & !CONT_MASK != TAG_CONT_U8 { diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index fcd79222e16..7981567067d 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -60,8 +60,8 @@ fn test_binary_search() { assert_eq!(b.binary_search(&0), Err(0)); assert_eq!(b.binary_search(&1), Ok(0)); assert_eq!(b.binary_search(&2), Err(1)); - assert!(match b.binary_search(&3) { Ok(1...3) => true, _ => false }); - assert!(match b.binary_search(&3) { Ok(1...3) => true, _ => false }); + assert!(match b.binary_search(&3) { Ok(1..=3) => true, _ => false }); + assert!(match b.binary_search(&3) { Ok(1..=3) => true, _ => false }); assert_eq!(b.binary_search(&4), Err(4)); assert_eq!(b.binary_search(&5), Err(4)); assert_eq!(b.binary_search(&6), Err(4)); diff --git a/src/librustc_apfloat/ieee.rs b/src/librustc_apfloat/ieee.rs index 7abd02b6656..b21448df582 100644 --- a/src/librustc_apfloat/ieee.rs +++ b/src/librustc_apfloat/ieee.rs @@ -1753,9 +1753,9 @@ impl IeeeFloat { } else { loss = Some(match hex_value { 0 => Loss::ExactlyZero, - 1...7 => Loss::LessThanHalf, + 1..=7 => Loss::LessThanHalf, 8 => Loss::ExactlyHalf, - 9...15 => Loss::MoreThanHalf, + 9..=15 => Loss::MoreThanHalf, _ => unreachable!(), }); } diff --git a/src/librustc_codegen_utils/symbol_names.rs b/src/librustc_codegen_utils/symbol_names.rs index dcb82e5c424..ac71ecff964 100644 --- a/src/librustc_codegen_utils/symbol_names.rs +++ b/src/librustc_codegen_utils/symbol_names.rs @@ -424,7 +424,7 @@ pub fn sanitize(result: &mut String, s: &str) -> bool { '-' | ':' => result.push('.'), // These are legal symbols - 'a'...'z' | 'A'...'Z' | '0'...'9' | '_' | '.' | '$' => result.push(c), + 'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => result.push(c), _ => { result.push('$'); diff --git a/src/librustc_mir/diagnostics.rs b/src/librustc_mir/diagnostics.rs index f195775bf86..c2da1bee395 100644 --- a/src/librustc_mir/diagnostics.rs +++ b/src/librustc_mir/diagnostics.rs @@ -306,9 +306,9 @@ For example: ```compile_fail match 5u32 { // This range is ok, albeit pointless. - 1 ... 1 => {} + 1 ..= 1 => {} // This range is empty, and the compiler can tell. - 1000 ... 5 => {} + 1000 ..= 5 => {} } ``` "##, diff --git a/src/librustc_mir/hair/pattern/check_match.rs b/src/librustc_mir/hair/pattern/check_match.rs index 4ac896d84ff..24301e970f5 100644 --- a/src/librustc_mir/hair/pattern/check_match.rs +++ b/src/librustc_mir/hair/pattern/check_match.rs @@ -481,7 +481,7 @@ fn check_exhaustive<'a, 'tcx>(cx: &mut MatchCheckCtxt<'a, 'tcx>, let joined_patterns = match witnesses.len() { 0 => bug!(), 1 => format!("`{}`", witnesses[0]), - 2...LIMIT => { + 2..=LIMIT => { let (tail, head) = witnesses.split_last().unwrap(); let head: Vec<_> = head.iter().map(|w| w.to_string()).collect(); format!("`{}` and `{}`", head.join("`, `"), tail) diff --git a/src/librustc_target/abi/call/mod.rs b/src/librustc_target/abi/call/mod.rs index fcae9ea22bb..3195823eb09 100644 --- a/src/librustc_target/abi/call/mod.rs +++ b/src/librustc_target/abi/call/mod.rs @@ -139,11 +139,11 @@ impl Reg { RegKind::Integer => { match self.size.bits() { 1 => dl.i1_align, - 2...8 => dl.i8_align, - 9...16 => dl.i16_align, - 17...32 => dl.i32_align, - 33...64 => dl.i64_align, - 65...128 => dl.i128_align, + 2..=8 => dl.i8_align, + 9..=16 => dl.i16_align, + 17..=32 => dl.i32_align, + 33..=64 => dl.i64_align, + 65..=128 => dl.i128_align, _ => panic!("unsupported integer: {:?}", self) } } diff --git a/src/librustc_target/abi/mod.rs b/src/librustc_target/abi/mod.rs index 7ff04df6233..9003e30357c 100644 --- a/src/librustc_target/abi/mod.rs +++ b/src/librustc_target/abi/mod.rs @@ -441,10 +441,10 @@ impl Integer { /// Find the smallest Integer type which can represent the signed value. pub fn fit_signed(x: i128) -> Integer { match x { - -0x0000_0000_0000_0080...0x0000_0000_0000_007f => I8, - -0x0000_0000_0000_8000...0x0000_0000_0000_7fff => I16, - -0x0000_0000_8000_0000...0x0000_0000_7fff_ffff => I32, - -0x8000_0000_0000_0000...0x7fff_ffff_ffff_ffff => I64, + -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8, + -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16, + -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32, + -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64, _ => I128 } } @@ -452,10 +452,10 @@ impl Integer { /// Find the smallest Integer type which can represent the unsigned value. pub fn fit_unsigned(x: u128) -> Integer { match x { - 0...0x0000_0000_0000_00ff => I8, - 0...0x0000_0000_0000_ffff => I16, - 0...0x0000_0000_ffff_ffff => I32, - 0...0xffff_ffff_ffff_ffff => I64, + 0..=0x0000_0000_0000_00ff => I8, + 0..=0x0000_0000_0000_ffff => I16, + 0..=0x0000_0000_ffff_ffff => I32, + 0..=0xffff_ffff_ffff_ffff => I64, _ => I128, } } diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index b0b72256edc..dd09bf96da5 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -207,7 +207,7 @@ let string = "salutations !"; // The ordering relation for strings can't be evaluated at compile time, // so this doesn't work: match string { - "hello" ... "world" => {} + "hello" ..= "world" => {} _ => {} } @@ -2146,7 +2146,7 @@ fn main() -> i32 { 0 } let x = 1u8; match x { - 0u8...3i8 => (), + 0u8..=3i8 => (), // error: mismatched types in range: expected u8, found i8 _ => () } @@ -2189,7 +2189,7 @@ as the type you're matching on. Example: let x = 1u8; match x { - 0u8...3u8 => (), // ok! + 0u8..=3u8 => (), // ok! _ => () } ``` diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index b5b344e8d5f..4c306d9b2d3 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -125,9 +125,9 @@ impl FromHex for str { buf <<= 4; match byte { - b'A'...b'F' => buf |= byte - b'A' + 10, - b'a'...b'f' => buf |= byte - b'a' + 10, - b'0'...b'9' => buf |= byte - b'0', + b'A'..=b'F' => buf |= byte - b'A' + 10, + b'a'..=b'f' => buf |= byte - b'a' + 10, + b'0'..=b'9' => buf |= byte - b'0', b' '|b'\r'|b'\n'|b'\t' => { buf >>= 4; continue diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index efdad7d801a..9959d5ce40d 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -1557,14 +1557,14 @@ impl> Parser { self.bump(); // A leading '0' must be the only digit before the decimal point. - if let '0' ... '9' = self.ch_or_null() { + if let '0' ..= '9' = self.ch_or_null() { return self.error(InvalidNumber) } }, - '1' ... '9' => { + '1' ..= '9' => { while !self.eof() { match self.ch_or_null() { - c @ '0' ... '9' => { + c @ '0' ..= '9' => { accum = accum.wrapping_mul(10); accum = accum.wrapping_add((c as u64) - ('0' as u64)); @@ -1588,14 +1588,14 @@ impl> Parser { // Make sure a digit follows the decimal place. match self.ch_or_null() { - '0' ... '9' => (), + '0' ..= '9' => (), _ => return self.error(InvalidNumber) } let mut dec = 1.0; while !self.eof() { match self.ch_or_null() { - c @ '0' ... '9' => { + c @ '0' ..= '9' => { dec /= 10.0; res += (((c as isize) - ('0' as isize)) as f64) * dec; self.bump(); @@ -1622,12 +1622,12 @@ impl> Parser { // Make sure a digit follows the exponent place. match self.ch_or_null() { - '0' ... '9' => (), + '0' ..= '9' => (), _ => return self.error(InvalidNumber) } while !self.eof() { match self.ch_or_null() { - c @ '0' ... '9' => { + c @ '0' ..= '9' => { exp *= 10; exp += (c as usize) - ('0' as usize); @@ -1653,7 +1653,7 @@ impl> Parser { while i < 4 && !self.eof() { self.bump(); n = match self.ch_or_null() { - c @ '0' ... '9' => n * 16 + ((c as u16) - ('0' as u16)), + 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, @@ -1695,13 +1695,13 @@ impl> Parser { 'r' => res.push('\r'), 't' => res.push('\t'), 'u' => match self.decode_hex_escape()? { - 0xDC00 ... 0xDFFF => { + 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 => { + n1 @ 0xD800 ..= 0xDBFF => { match (self.next_char(), self.next_char()) { (Some('\\'), Some('u')) => (), _ => return self.error(UnexpectedEndOfHexEscape), @@ -1928,7 +1928,7 @@ impl> Parser { '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(), + '0' ..= '9' | '-' => self.parse_number(), '"' => match self.parse_str() { Ok(s) => StringValue(s), Err(e) => Error(e), diff --git a/src/libstd/sys_common/backtrace.rs b/src/libstd/sys_common/backtrace.rs index 20109d2d0d5..61d7ed463dd 100644 --- a/src/libstd/sys_common/backtrace.rs +++ b/src/libstd/sys_common/backtrace.rs @@ -263,7 +263,7 @@ pub fn demangle(writer: &mut Write, mut s: &str, format: PrintFormat) -> io::Res let candidate = &s[i + llvm.len()..]; let all_hex = candidate.chars().all(|c| { match c { - 'A' ... 'F' | '0' ... '9' => true, + 'A' ..= 'F' | '0' ..= '9' => true, _ => false, } }); diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index 14a2555adf9..bbb5980bd9d 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -76,7 +76,7 @@ impl CodePoint { #[inline] pub fn from_u32(value: u32) -> Option { match value { - 0 ... 0x10FFFF => Some(CodePoint { value: value }), + 0 ..= 0x10FFFF => Some(CodePoint { value: value }), _ => None } } @@ -101,7 +101,7 @@ impl CodePoint { #[inline] pub fn to_char(&self) -> Option { match self.value { - 0xD800 ... 0xDFFF => None, + 0xD800 ..= 0xDFFF => None, _ => Some(unsafe { char::from_u32_unchecked(self.value) }) } } @@ -305,7 +305,7 @@ impl Wtf8Buf { /// like concatenating ill-formed UTF-16 strings effectively would. #[inline] pub fn push(&mut self, code_point: CodePoint) { - if let trail @ 0xDC00...0xDFFF = code_point.to_u32() { + if let trail @ 0xDC00..=0xDFFF = code_point.to_u32() { if let Some(lead) = (&*self).final_lead_surrogate() { let len_without_lead_surrogate = self.len() - 3; self.bytes.truncate(len_without_lead_surrogate); @@ -525,7 +525,7 @@ impl Wtf8 { #[inline] pub fn ascii_byte_at(&self, position: usize) -> u8 { match self.bytes[position] { - ascii_byte @ 0x00 ... 0x7F => ascii_byte, + ascii_byte @ 0x00 ..= 0x7F => ascii_byte, _ => 0xFF } } @@ -630,7 +630,7 @@ impl Wtf8 { return None } match &self.bytes[(len - 3)..] { - &[0xED, b2 @ 0xA0...0xAF, b3] => Some(decode_surrogate(b2, b3)), + &[0xED, b2 @ 0xA0..=0xAF, b3] => Some(decode_surrogate(b2, b3)), _ => None } } @@ -642,7 +642,7 @@ impl Wtf8 { return None } match &self.bytes[..3] { - &[0xED, b2 @ 0xB0...0xBF, b3] => Some(decode_surrogate(b2, b3)), + &[0xED, b2 @ 0xB0..=0xBF, b3] => Some(decode_surrogate(b2, b3)), _ => None } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index a57a9b95e5f..a09055e6c4a 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -843,11 +843,11 @@ pub struct Local { /// An arm of a 'match'. /// -/// E.g. `0...10 => { println!("match!") }` as in +/// E.g. `0..=10 => { println!("match!") }` as in /// /// ``` /// match 123 { -/// 0...10 => { println!("match!") }, +/// 0..=10 => { println!("match!") }, /// _ => { println!("no match!") }, /// } /// ``` diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 5353ff9a1e1..c09cfd910d2 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -266,7 +266,7 @@ impl<'a> StringReader<'a> { /// Pushes a character to a message string for error reporting fn push_escaped_char_for_msg(m: &mut String, c: char) { match c { - '\u{20}'...'\u{7e}' => { + '\u{20}'..='\u{7e}' => { // Don't escape \, ' or " for user-facing messages m.push(c); } @@ -779,7 +779,7 @@ impl<'a> StringReader<'a> { base = 16; num_digits = self.scan_digits(16, 16); } - '0'...'9' | '_' | '.' | 'e' | 'E' => { + '0'..='9' | '_' | '.' | 'e' | 'E' => { num_digits = self.scan_digits(10, 10) + 1; } _ => { diff --git a/src/libsyntax_ext/format_foreign.rs b/src/libsyntax_ext/format_foreign.rs index 0dd8f0c55d8..2393af76c34 100644 --- a/src/libsyntax_ext/format_foreign.rs +++ b/src/libsyntax_ext/format_foreign.rs @@ -374,7 +374,7 @@ pub mod printf { if let Start = state { match c { - '1'...'9' => { + '1'..='9' => { let end = at_next_cp_while(next, is_digit); match end.next_cp() { // Yes, this *is* the parameter. @@ -416,7 +416,7 @@ pub mod printf { state = WidthArg; move_to!(next); }, - '1' ... '9' => { + '1' ..= '9' => { let end = at_next_cp_while(next, is_digit); state = Prec; width = Some(Num::from_str(at.slice_between(end).unwrap(), None)); @@ -477,7 +477,7 @@ pub mod printf { } } }, - '0' ... '9' => { + '0' ..= '9' => { let end = at_next_cp_while(next, is_digit); state = Length; precision = Some(Num::from_str(at.slice_between(end).unwrap(), None)); @@ -570,7 +570,7 @@ pub mod printf { fn is_digit(c: char) -> bool { match c { - '0' ... '9' => true, + '0' ..= '9' => true, _ => false } } @@ -799,7 +799,7 @@ pub mod shell { let start = s.find('$')?; match s[start+1..].chars().next()? { '$' => return Some((Substitution::Escape, &s[start+2..])), - c @ '0' ... '9' => { + c @ '0' ..= '9' => { let n = (c as u8) - b'0'; return Some((Substitution::Ordinal(n), &s[start+2..])); }, @@ -836,14 +836,14 @@ pub mod shell { fn is_ident_head(c: char) -> bool { match c { - 'a' ... 'z' | 'A' ... 'Z' | '_' => true, + 'a' ..= 'z' | 'A' ..= 'Z' | '_' => true, _ => false } } fn is_ident_tail(c: char) -> bool { match c { - '0' ... '9' => true, + '0' ..= '9' => true, c => is_ident_head(c) } } diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index a4fb9571ecb..756e0c059a7 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -818,8 +818,8 @@ impl Encodable for FileMap { }; let bytes_per_diff: u8 = match max_line_length { - 0 ... 0xFF => 1, - 0x100 ... 0xFFFF => 2, + 0 ..= 0xFF => 1, + 0x100 ..= 0xFFFF => 2, _ => 4 }; diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index bd5ab92e8b0..b720d55594f 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -215,7 +215,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result { + ':' | '#' | ' ' | '.' | '0'..='9' => { let mut flags = Flags::new(); let mut fstate = FormatStateFlags; match cur { @@ -223,7 +223,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result flags.alternate = true, ' ' => flags.space = true, '.' => fstate = FormatStatePrecision, - '0'...'9' => { + '0'..='9' => { flags.width = cur as usize - '0' as usize; fstate = FormatStateWidth; } @@ -337,14 +337,14 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result { flags.space = true; } - (FormatStateFlags, '0'...'9') => { + (FormatStateFlags, '0'..='9') => { flags.width = cur as usize - '0' as usize; *fstate = FormatStateWidth; } (FormatStateFlags, '.') => { *fstate = FormatStatePrecision; } - (FormatStateWidth, '0'...'9') => { + (FormatStateWidth, '0'..='9') => { let old = flags.width; flags.width = flags.width * 10 + (cur as usize - '0' as usize); if flags.width < old { @@ -354,7 +354,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) -> Result { *fstate = FormatStatePrecision; } - (FormatStatePrecision, '0'...'9') => { + (FormatStatePrecision, '0'..='9') => { let old = flags.precision; flags.precision = flags.precision * 10 + (cur as usize - '0' as usize); if flags.precision < old { diff --git a/src/test/compile-fail/associated-path-shl.rs b/src/test/compile-fail/associated-path-shl.rs index 64afd702f5d..7daf0d3c4e2 100644 --- a/src/test/compile-fail/associated-path-shl.rs +++ b/src/test/compile-fail/associated-path-shl.rs @@ -14,7 +14,7 @@ fn main() { let _: <::B>::C; //~ ERROR cannot find type `A` in this scope let _ = <::B>::C; //~ ERROR cannot find type `A` in this scope let <::B>::C; //~ ERROR cannot find type `A` in this scope - let 0 ... <::B>::C; //~ ERROR cannot find type `A` in this scope + let 0 ..= <::B>::C; //~ ERROR cannot find type `A` in this scope //~^ ERROR only char and numeric types are allowed in range patterns <::B>::C; //~ ERROR cannot find type `A` in this scope } diff --git a/src/test/compile-fail/issue-27895.rs b/src/test/compile-fail/issue-27895.rs index be76796c5c4..6063755c04f 100644 --- a/src/test/compile-fail/issue-27895.rs +++ b/src/test/compile-fail/issue-27895.rs @@ -13,7 +13,7 @@ fn main() { let index = 6; match i { - 0...index => println!("winner"), + 0..=index => println!("winner"), //~^ ERROR runtime values cannot be referenced in patterns _ => println!("hello"), } diff --git a/src/test/compile-fail/issue-41255.rs b/src/test/compile-fail/issue-41255.rs index bdd502d4420..29912de37eb 100644 --- a/src/test/compile-fail/issue-41255.rs +++ b/src/test/compile-fail/issue-41255.rs @@ -27,7 +27,7 @@ fn main() { //~| WARNING hard error //~| ERROR floating-point types cannot be used in patterns //~| WARNING hard error - 39.0 ... 70.0 => {}, //~ ERROR floating-point types cannot be used in patterns + 39.0 ..= 70.0 => {}, //~ ERROR floating-point types cannot be used in patterns //~| WARNING hard error //~| ERROR floating-point types cannot be used in patterns //~| WARNING hard error diff --git a/src/test/compile-fail/match-range-fail-2.rs b/src/test/compile-fail/match-range-fail-2.rs index 91ad2b3507a..b42e2ff919a 100644 --- a/src/test/compile-fail/match-range-fail-2.rs +++ b/src/test/compile-fail/match-range-fail-2.rs @@ -12,7 +12,7 @@ fn main() { match 5 { - 6 ... 1 => { } + 6 ..= 1 => { } _ => { } }; //~^^^ ERROR lower range bound must be less than or equal to upper @@ -24,7 +24,7 @@ fn main() { //~^^^ ERROR lower range bound must be less than upper match 5u64 { - 0xFFFF_FFFF_FFFF_FFFF ... 1 => { } + 0xFFFF_FFFF_FFFF_FFFF ..= 1 => { } _ => { } }; //~^^^ ERROR lower range bound must be less than or equal to upper diff --git a/src/test/compile-fail/match-range-fail.rs b/src/test/compile-fail/match-range-fail.rs index f89b3e39390..ca99b0c7b89 100644 --- a/src/test/compile-fail/match-range-fail.rs +++ b/src/test/compile-fail/match-range-fail.rs @@ -10,21 +10,21 @@ fn main() { match "wow" { - "bar" ... "foo" => { } + "bar" ..= "foo" => { } }; //~^^ ERROR only char and numeric types are allowed in range //~| start type: &'static str //~| end type: &'static str match "wow" { - 10 ... "what" => () + 10 ..= "what" => () }; //~^^ ERROR only char and numeric types are allowed in range //~| start type: {integer} //~| end type: &'static str match 5 { - 'c' ... 100 => { } + 'c' ..= 100 => { } _ => { } }; //~^^^ ERROR mismatched types diff --git a/src/test/compile-fail/non-constant-in-const-path.rs b/src/test/compile-fail/non-constant-in-const-path.rs index fe88ab4e117..1aae25105a8 100644 --- a/src/test/compile-fail/non-constant-in-const-path.rs +++ b/src/test/compile-fail/non-constant-in-const-path.rs @@ -11,7 +11,7 @@ fn main() { let x = 0; match 1 { - 0 ... x => {} + 0 ..= x => {} //~^ ERROR runtime values cannot be referenced in patterns }; } diff --git a/src/test/compile-fail/patkind-litrange-no-expr.rs b/src/test/compile-fail/patkind-litrange-no-expr.rs index d57a23f26c4..8fef98f815f 100644 --- a/src/test/compile-fail/patkind-litrange-no-expr.rs +++ b/src/test/compile-fail/patkind-litrange-no-expr.rs @@ -17,7 +17,7 @@ macro_rules! enum_number { fn foo(value: i32) -> Option<$name> { match value { $( $value => Some($name::$variant), )* // PatKind::Lit - $( $value ... 42 => Some($name::$variant), )* // PatKind::Range + $( $value ..= 42 => Some($name::$variant), )* // PatKind::Range _ => None } } @@ -32,4 +32,3 @@ enum_number!(Change { }); fn main() {} - diff --git a/src/test/compile-fail/qualified-path-params.rs b/src/test/compile-fail/qualified-path-params.rs index a7bc27e1749..018a3b2ae32 100644 --- a/src/test/compile-fail/qualified-path-params.rs +++ b/src/test/compile-fail/qualified-path-params.rs @@ -29,6 +29,6 @@ fn main() { match 10 { ::A::f:: => {} //~^ ERROR expected unit struct/variant or constant, found method `<::A>::f` - 0 ... ::A::f:: => {} //~ ERROR only char and numeric types are allowed in range + 0 ..= ::A::f:: => {} //~ ERROR only char and numeric types are allowed in range } } diff --git a/src/test/compile-fail/refutable-pattern-errors.rs b/src/test/compile-fail/refutable-pattern-errors.rs index ce93e1875ae..7b4009481ab 100644 --- a/src/test/compile-fail/refutable-pattern-errors.rs +++ b/src/test/compile-fail/refutable-pattern-errors.rs @@ -9,10 +9,10 @@ // except according to those terms. -fn func((1, (Some(1), 2...3)): (isize, (Option, isize))) { } +fn func((1, (Some(1), 2..=3)): (isize, (Option, isize))) { } //~^ ERROR refutable pattern in function argument: `(_, _)` not covered fn main() { - let (1, (Some(1), 2...3)) = (1, (None, 2)); + let (1, (Some(1), 2..=3)) = (1, (None, 2)); //~^ ERROR refutable pattern in local binding: `(_, _)` not covered } diff --git a/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs b/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs index 62cb870c7bb..f9d1ce34535 100644 --- a/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs +++ b/src/test/run-pass-fulldeps/ast_stmt_expr_attr.rs @@ -286,16 +286,16 @@ fn run() { // would require parens in patterns to allow disambiguation... reject_expr_parse("match 0 { - 0...#[attr] 10 => () + 0..=#[attr] 10 => () }"); reject_expr_parse("match 0 { - 0...#[attr] -10 => () + 0..=#[attr] -10 => () }"); reject_expr_parse("match 0 { - 0...-#[attr] 10 => () + 0..=-#[attr] 10 => () }"); reject_expr_parse("match 0 { - 0...#[attr] FOO => () + 0..=#[attr] FOO => () }"); // make sure we don't catch this bug again... diff --git a/src/test/run-pass/byte-literals.rs b/src/test/run-pass/byte-literals.rs index ad779d26f9e..f5acb72429a 100644 --- a/src/test/run-pass/byte-literals.rs +++ b/src/test/run-pass/byte-literals.rs @@ -36,7 +36,7 @@ pub fn main() { } match 100 { - b'a' ... b'z' => {}, + b'a' ..= b'z' => {}, _ => panic!() } diff --git a/src/test/run-pass/inferred-suffix-in-pattern-range.rs b/src/test/run-pass/inferred-suffix-in-pattern-range.rs index 22369c77ed3..89d26aade2e 100644 --- a/src/test/run-pass/inferred-suffix-in-pattern-range.rs +++ b/src/test/run-pass/inferred-suffix-in-pattern-range.rs @@ -12,21 +12,21 @@ pub fn main() { let x = 2; let x_message = match x { - 0 ... 1 => { "not many".to_string() } + 0 ..= 1 => { "not many".to_string() } _ => { "lots".to_string() } }; assert_eq!(x_message, "lots".to_string()); let y = 2; let y_message = match y { - 0 ... 1 => { "not many".to_string() } + 0 ..= 1 => { "not many".to_string() } _ => { "lots".to_string() } }; assert_eq!(y_message, "lots".to_string()); let z = 1u64; let z_message = match z { - 0 ... 1 => { "not many".to_string() } + 0 ..= 1 => { "not many".to_string() } _ => { "lots".to_string() } }; assert_eq!(z_message, "not many".to_string()); diff --git a/src/test/run-pass/issue-12582.rs b/src/test/run-pass/issue-12582.rs index 7bab2ddfed0..b89964d968e 100644 --- a/src/test/run-pass/issue-12582.rs +++ b/src/test/run-pass/issue-12582.rs @@ -16,7 +16,7 @@ pub fn main() { assert_eq!(3, match (x, y) { (1, 1) => 1, (2, 2) => 2, - (1...2, 2) => 3, + (1..=2, 2) => 3, _ => 4, }); @@ -24,7 +24,7 @@ pub fn main() { assert_eq!(3, match ((x, y),) { ((1, 1),) => 1, ((2, 2),) => 2, - ((1...2, 2),) => 3, + ((1..=2, 2),) => 3, _ => 4, }); } diff --git a/src/test/run-pass/issue-13027.rs b/src/test/run-pass/issue-13027.rs index d28ea94ec1a..2c460900ef6 100644 --- a/src/test/run-pass/issue-13027.rs +++ b/src/test/run-pass/issue-13027.rs @@ -30,7 +30,7 @@ pub fn main() { fn lit_shadow_range() { assert_eq!(2, match 1 { 1 if false => 1, - 1...2 => 2, + 1..=2 => 2, _ => 3 }); @@ -38,34 +38,34 @@ fn lit_shadow_range() { assert_eq!(2, match x+1 { 0 => 0, 1 if false => 1, - 1...2 => 2, + 1..=2 => 2, _ => 3 }); assert_eq!(2, match val() { 1 if false => 1, - 1...2 => 2, + 1..=2 => 2, _ => 3 }); assert_eq!(2, match CONST { 0 => 0, 1 if false => 1, - 1...2 => 2, + 1..=2 => 2, _ => 3 }); // value is out of the range of second arm, should match wildcard pattern assert_eq!(3, match 3 { 1 if false => 1, - 1...2 => 2, + 1..=2 => 2, _ => 3 }); } fn range_shadow_lit() { assert_eq!(2, match 1 { - 1...2 if false => 1, + 1..=2 if false => 1, 1 => 2, _ => 3 }); @@ -73,27 +73,27 @@ fn range_shadow_lit() { let x = 0; assert_eq!(2, match x+1 { 0 => 0, - 1...2 if false => 1, + 1..=2 if false => 1, 1 => 2, _ => 3 }); assert_eq!(2, match val() { - 1...2 if false => 1, + 1..=2 if false => 1, 1 => 2, _ => 3 }); assert_eq!(2, match CONST { 0 => 0, - 1...2 if false => 1, + 1..=2 if false => 1, 1 => 2, _ => 3 }); // ditto assert_eq!(3, match 3 { - 1...2 if false => 1, + 1..=2 if false => 1, 1 => 2, _ => 3 }); @@ -101,36 +101,36 @@ fn range_shadow_lit() { fn range_shadow_range() { assert_eq!(2, match 1 { - 0...2 if false => 1, - 1...3 => 2, + 0..=2 if false => 1, + 1..=3 => 2, _ => 3, }); let x = 0; assert_eq!(2, match x+1 { 100 => 0, - 0...2 if false => 1, - 1...3 => 2, + 0..=2 if false => 1, + 1..=3 => 2, _ => 3, }); assert_eq!(2, match val() { - 0...2 if false => 1, - 1...3 => 2, + 0..=2 if false => 1, + 1..=3 => 2, _ => 3, }); assert_eq!(2, match CONST { 100 => 0, - 0...2 if false => 1, - 1...3 => 2, + 0..=2 if false => 1, + 1..=3 => 2, _ => 3, }); // ditto assert_eq!(3, match 5 { - 0...2 if false => 1, - 1...3 => 2, + 0..=2 if false => 1, + 1..=3 => 2, _ => 3, }); } @@ -138,7 +138,7 @@ fn range_shadow_range() { fn multi_pats_shadow_lit() { assert_eq!(2, match 1 { 100 => 0, - 0 | 1...10 if false => 1, + 0 | 1..=10 if false => 1, 1 => 2, _ => 3, }); @@ -147,8 +147,8 @@ fn multi_pats_shadow_lit() { fn multi_pats_shadow_range() { assert_eq!(2, match 1 { 100 => 0, - 0 | 1...10 if false => 1, - 1...3 => 2, + 0 | 1..=10 if false => 1, + 1..=3 => 2, _ => 3, }); } @@ -157,7 +157,7 @@ fn lit_shadow_multi_pats() { assert_eq!(2, match 1 { 100 => 0, 1 if false => 1, - 0 | 1...10 => 2, + 0 | 1..=10 => 2, _ => 3, }); } @@ -165,8 +165,8 @@ fn lit_shadow_multi_pats() { fn range_shadow_multi_pats() { assert_eq!(2, match 1 { 100 => 0, - 1...3 if false => 1, - 0 | 1...10 => 2, + 1..=3 if false => 1, + 0 | 1..=10 => 2, _ => 3, }); } diff --git a/src/test/run-pass/issue-13867.rs b/src/test/run-pass/issue-13867.rs index e21070e2eaf..bc28dc54de6 100644 --- a/src/test/run-pass/issue-13867.rs +++ b/src/test/run-pass/issue-13867.rs @@ -19,14 +19,14 @@ enum Foo { fn main() { let r = match (Foo::FooNullary, 'a') { - (Foo::FooUint(..), 'a'...'z') => 1, + (Foo::FooUint(..), 'a'..='z') => 1, (Foo::FooNullary, 'x') => 2, _ => 0 }; assert_eq!(r, 0); let r = match (Foo::FooUint(0), 'a') { - (Foo::FooUint(1), 'a'...'z') => 1, + (Foo::FooUint(1), 'a'..='z') => 1, (Foo::FooUint(..), 'x') => 2, (Foo::FooNullary, 'a') => 3, _ => 0 @@ -34,7 +34,7 @@ fn main() { assert_eq!(r, 0); let r = match ('a', Foo::FooUint(0)) { - ('a'...'z', Foo::FooUint(1)) => 1, + ('a'..='z', Foo::FooUint(1)) => 1, ('x', Foo::FooUint(..)) => 2, ('a', Foo::FooNullary) => 3, _ => 0 @@ -42,15 +42,15 @@ fn main() { assert_eq!(r, 0); let r = match ('a', 'a') { - ('a'...'z', 'b') => 1, - ('x', 'a'...'z') => 2, + ('a'..='z', 'b') => 1, + ('x', 'a'..='z') => 2, _ => 0 }; assert_eq!(r, 0); let r = match ('a', 'a') { - ('a'...'z', 'b') => 1, - ('x', 'a'...'z') => 2, + ('a'..='z', 'b') => 1, + ('x', 'a'..='z') => 2, ('a', 'a') => 3, _ => 0 }; diff --git a/src/test/run-pass/issue-18060.rs b/src/test/run-pass/issue-18060.rs index d6c9a92ca02..322a3d8c9bb 100644 --- a/src/test/run-pass/issue-18060.rs +++ b/src/test/run-pass/issue-18060.rs @@ -11,7 +11,7 @@ // Regression test for #18060: match arms were matching in the wrong order. fn main() { - assert_eq!(2, match (1, 3) { (0, 2...5) => 1, (1, 3) => 2, (_, 2...5) => 3, (_, _) => 4 }); - assert_eq!(2, match (1, 3) { (1, 3) => 2, (_, 2...5) => 3, (_, _) => 4 }); - assert_eq!(2, match (1, 7) { (0, 2...5) => 1, (1, 7) => 2, (_, 2...5) => 3, (_, _) => 4 }); + assert_eq!(2, match (1, 3) { (0, 2..=5) => 1, (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 }); + assert_eq!(2, match (1, 3) { (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 }); + assert_eq!(2, match (1, 7) { (0, 2..=5) => 1, (1, 7) => 2, (_, 2..=5) => 3, (_, _) => 4 }); } diff --git a/src/test/run-pass/issue-18464.rs b/src/test/run-pass/issue-18464.rs index dff86bc1b45..f4faab5e468 100644 --- a/src/test/run-pass/issue-18464.rs +++ b/src/test/run-pass/issue-18464.rs @@ -15,7 +15,7 @@ const HIGH_RANGE: char = '9'; fn main() { match '5' { - LOW_RANGE...HIGH_RANGE => (), + LOW_RANGE..=HIGH_RANGE => (), _ => () }; } diff --git a/src/test/run-pass/issue-21475.rs b/src/test/run-pass/issue-21475.rs index 0666a1f133f..99839b56506 100644 --- a/src/test/run-pass/issue-21475.rs +++ b/src/test/run-pass/issue-21475.rs @@ -14,9 +14,9 @@ use m::{START, END}; fn main() { match 42 { - m::START...m::END => {}, - 0...m::END => {}, - m::START...59 => {}, + m::START..=m::END => {}, + 0..=m::END => {}, + m::START..=59 => {}, _ => {}, } } diff --git a/src/test/run-pass/issue-26251.rs b/src/test/run-pass/issue-26251.rs index 1e77d54fbf9..3735d36147d 100644 --- a/src/test/run-pass/issue-26251.rs +++ b/src/test/run-pass/issue-26251.rs @@ -12,9 +12,9 @@ fn main() { let x = 'a'; let y = match x { - 'a'...'b' if false => "one", + 'a'..='b' if false => "one", 'a' => "two", - 'a'...'b' => "three", + 'a'..='b' => "three", _ => panic!("what?"), }; diff --git a/src/test/run-pass/issue-35423.rs b/src/test/run-pass/issue-35423.rs index 35d0c305ed8..34cb2930db0 100644 --- a/src/test/run-pass/issue-35423.rs +++ b/src/test/run-pass/issue-35423.rs @@ -12,7 +12,7 @@ fn main () { let x = 4; match x { ref r if *r < 0 => println!("got negative num {} < 0", r), - e @ 1 ... 100 => println!("got number within range [1,100] {}", e), + e @ 1 ..= 100 => println!("got number within range [1,100] {}", e), _ => println!("no"), } } diff --git a/src/test/run-pass/issue-7222.rs b/src/test/run-pass/issue-7222.rs index 1bf343e23f0..3eb39ad6aad 100644 --- a/src/test/run-pass/issue-7222.rs +++ b/src/test/run-pass/issue-7222.rs @@ -14,7 +14,7 @@ pub fn main() { const FOO: f64 = 10.0; match 0.0 { - 0.0 ... FOO => (), + 0.0 ..= FOO => (), _ => () } } diff --git a/src/test/run-pass/macro-literal.rs b/src/test/run-pass/macro-literal.rs index 0bcda7bc144..6d5e8bc97c0 100644 --- a/src/test/run-pass/macro-literal.rs +++ b/src/test/run-pass/macro-literal.rs @@ -41,18 +41,18 @@ macro_rules! mtester_dbg { } macro_rules! catch_range { - ($s:literal ... $e:literal) => { - &format!("macro caught literal: {} ... {}", $s, $e) + ($s:literal ..= $e:literal) => { + &format!("macro caught literal: {} ..= {}", $s, $e) }; - (($s:expr) ... ($e:expr)) => { // Must use ')' before '...' - &format!("macro caught expr: {} ... {}", $s, $e) + (($s:expr) ..= ($e:expr)) => { // Must use ')' before '..=' + &format!("macro caught expr: {} ..= {}", $s, $e) }; } macro_rules! pat_match { - ($s:literal ... $e:literal) => { + ($s:literal ..= $e:literal) => { match 3 { - $s ... $e => "literal, in range", + $s ..= $e => "literal, in range", _ => "literal, other", } }; @@ -115,22 +115,22 @@ pub fn main() { assert_eq!(mtester!('c'), "macro caught literal: c"); assert_eq!(mtester!(-1.2), "macro caught literal: -1.2"); assert_eq!(two_negative_literals!(-2 -3), "macro caught literals: -2, -3"); - assert_eq!(catch_range!(2 ... 3), "macro caught literal: 2 ... 3"); + assert_eq!(catch_range!(2 ..= 3), "macro caught literal: 2 ..= 3"); assert_eq!(match_attr!(#[attr] 1), "attr matched literal"); assert_eq!(test_user!(10, 20), "literal"); assert_eq!(mtester!(false), "macro caught literal: false"); assert_eq!(mtester!(true), "macro caught literal: true"); match_produced_attr!("a"); let _a = LiteralProduced; - assert_eq!(pat_match!(1 ... 3), "literal, in range"); - assert_eq!(pat_match!(4 ... 6), "literal, other"); + assert_eq!(pat_match!(1 ..= 3), "literal, in range"); + assert_eq!(pat_match!(4 ..= 6), "literal, other"); // Cases where 'expr' catches assert_eq!(mtester!((-1.2)), "macro caught expr: -1.2"); assert_eq!(only_expr!(-1.2), "macro caught expr: -1.2"); assert_eq!(mtester!((1 + 3)), "macro caught expr: 4"); assert_eq!(mtester_dbg!(()), "macro caught expr: ()"); - assert_eq!(catch_range!((1 + 1) ... (2 + 2)), "macro caught expr: 2 ... 4"); + assert_eq!(catch_range!((1 + 1) ..= (2 + 2)), "macro caught expr: 2 ..= 4"); assert_eq!(match_attr!(#[attr] (1 + 2)), "attr matched expr"); assert_eq!(test_user!(10, (20 + 2)), "expr"); diff --git a/src/test/run-pass/match-range-infer.rs b/src/test/run-pass/match-range-infer.rs index 74f513ef081..cf07345d343 100644 --- a/src/test/run-pass/match-range-infer.rs +++ b/src/test/run-pass/match-range-infer.rs @@ -12,15 +12,15 @@ pub fn main() { match 1 { - 1 ... 3 => {} + 1 ..= 3 => {} _ => panic!("should match range") } match 1 { - 1 ... 3u16 => {} + 1 ..= 3u16 => {} _ => panic!("should match range with inferred start type") } match 1 { - 1u16 ... 3 => {} + 1u16 ..= 3 => {} _ => panic!("should match range with inferred end type") } } diff --git a/src/test/run-pass/match-range-static.rs b/src/test/run-pass/match-range-static.rs index 9aafcda1b02..b63ca7defd6 100644 --- a/src/test/run-pass/match-range-static.rs +++ b/src/test/run-pass/match-range-static.rs @@ -15,7 +15,7 @@ const e: isize = 42; pub fn main() { match 7 { - s...e => (), + s..=e => (), _ => (), } } diff --git a/src/test/run-pass/match-range.rs b/src/test/run-pass/match-range.rs index cf695a77ce1..859edb80a07 100644 --- a/src/test/run-pass/match-range.rs +++ b/src/test/run-pass/match-range.rs @@ -12,7 +12,7 @@ pub fn main() { match 5_usize { - 1_usize...5_usize => {} + 1_usize..=5_usize => {} _ => panic!("should match range"), } match 1_usize { @@ -20,7 +20,7 @@ pub fn main() { _ => panic!("should match range start"), } match 5_usize { - 6_usize...7_usize => panic!("shouldn't match range"), + 6_usize..=7_usize => panic!("shouldn't match range"), _ => {} } match 7_usize { @@ -29,23 +29,23 @@ pub fn main() { } match 5_usize { 1_usize => panic!("should match non-first range"), - 2_usize...6_usize => {} + 2_usize..=6_usize => {} _ => panic!("math is broken") } match 'c' { - 'a'...'z' => {} + 'a'..='z' => {} _ => panic!("should suppport char ranges") } match -3 { - -7...5 => {} + -7..=5 => {} _ => panic!("should match signed range") } match 3.0f64 { - 1.0...5.0 => {} + 1.0..=5.0 => {} _ => panic!("should match float range") } match -1.5f64 { - -3.6...3.6 => {} + -3.6..=3.6 => {} _ => panic!("should match negative float range") } match 3.5 { diff --git a/src/test/run-pass/rfc-2005-default-binding-mode/range.rs b/src/test/run-pass/rfc-2005-default-binding-mode/range.rs index 2292d97eaf4..f38bd2de869 100644 --- a/src/test/run-pass/rfc-2005-default-binding-mode/range.rs +++ b/src/test/run-pass/rfc-2005-default-binding-mode/range.rs @@ -11,8 +11,8 @@ pub fn main() { let i = 5; match &&&&i { - 1 ... 3 => panic!(), - 3 ... 8 => {}, + 1 ..= 3 => panic!(), + 3 ..= 8 => {}, _ => panic!(), } } diff --git a/src/test/ui/check_match/issue-43253.rs b/src/test/ui/check_match/issue-43253.rs index a01ebb768b4..aace8c0c02b 100644 --- a/src/test/ui/check_match/issue-43253.rs +++ b/src/test/ui/check_match/issue-43253.rs @@ -23,13 +23,13 @@ fn main() { match 10 { 1..10 => {}, - 9...10 => {}, + 9..=10 => {}, _ => {}, } match 10 { 1..10 => {}, - 10...10 => {}, + 10..=10 => {}, _ => {}, } @@ -42,13 +42,13 @@ fn main() { match 10 { 1..10 => {}, - 8...9 => {}, + 8..=9 => {}, _ => {}, } match 10 { 1..10 => {}, - 9...9 => {}, + 9..=9 => {}, _ => {}, } } diff --git a/src/test/ui/check_match/issue-43253.stderr b/src/test/ui/check_match/issue-43253.stderr index 111f4e44ee9..2af6a2a6368 100644 --- a/src/test/ui/check_match/issue-43253.stderr +++ b/src/test/ui/check_match/issue-43253.stderr @@ -13,12 +13,12 @@ LL | #![warn(unreachable_patterns)] warning: unreachable pattern --> $DIR/issue-43253.rs:45:9 | -LL | 8...9 => {}, +LL | 8..=9 => {}, | ^^^^^ warning: unreachable pattern --> $DIR/issue-43253.rs:51:9 | -LL | 9...9 => {}, +LL | 9..=9 => {}, | ^^^^^ diff --git a/src/test/ui/const-eval/const_signed_pat.rs b/src/test/ui/const-eval/const_signed_pat.rs index f53d6f3fa0a..008ebf13c63 100644 --- a/src/test/ui/const-eval/const_signed_pat.rs +++ b/src/test/ui/const-eval/const_signed_pat.rs @@ -13,7 +13,7 @@ fn main() { const MIN: i8 = -5; match 5i8 { - MIN...-1 => {}, + MIN..=-1 => {}, _ => {}, } } diff --git a/src/test/ui/const-eval/ref_to_int_match.rs b/src/test/ui/const-eval/ref_to_int_match.rs index 4c5fc6c3797..8ad7f11f0ce 100644 --- a/src/test/ui/const-eval/ref_to_int_match.rs +++ b/src/test/ui/const-eval/ref_to_int_match.rs @@ -11,8 +11,8 @@ fn main() { let n: Int = 40; match n { - 0...10 => {}, - 10...BAR => {}, //~ ERROR lower range bound must be less than or equal to upper + 0..=10 => {}, + 10..=BAR => {}, //~ ERROR lower range bound must be less than or equal to upper _ => {}, } } diff --git a/src/test/ui/const-eval/ref_to_int_match.stderr b/src/test/ui/const-eval/ref_to_int_match.stderr index eef7b6df252..64ea57702d7 100644 --- a/src/test/ui/const-eval/ref_to_int_match.stderr +++ b/src/test/ui/const-eval/ref_to_int_match.stderr @@ -1,7 +1,7 @@ error[E0030]: lower range bound must be less than or equal to upper --> $DIR/ref_to_int_match.rs:15:9 | -LL | 10...BAR => {}, //~ ERROR lower range bound must be less than or equal to upper +LL | 10..=BAR => {}, //~ ERROR lower range bound must be less than or equal to upper | ^^ lower bound larger than upper bound error: aborting due to previous error diff --git a/src/test/ui/error-codes/E0029-teach.rs b/src/test/ui/error-codes/E0029-teach.rs index 1bc2c2d58b1..328c46311af 100644 --- a/src/test/ui/error-codes/E0029-teach.rs +++ b/src/test/ui/error-codes/E0029-teach.rs @@ -14,7 +14,7 @@ fn main() { let s = "hoho"; match s { - "hello" ... "world" => {} + "hello" ..= "world" => {} //~^ ERROR only char and numeric types are allowed in range patterns _ => {} } diff --git a/src/test/ui/error-codes/E0029-teach.stderr b/src/test/ui/error-codes/E0029-teach.stderr index 4bb71f68a98..bb4fac9a4cb 100644 --- a/src/test/ui/error-codes/E0029-teach.stderr +++ b/src/test/ui/error-codes/E0029-teach.stderr @@ -1,7 +1,7 @@ error[E0029]: only char and numeric types are allowed in range patterns --> $DIR/E0029-teach.rs:17:9 | -LL | "hello" ... "world" => {} +LL | "hello" ..= "world" => {} | ^^^^^^^^^^^^^^^^^^^ ranges require char or numeric types | = note: start type: &'static str diff --git a/src/test/ui/error-codes/E0029.rs b/src/test/ui/error-codes/E0029.rs index 29b6fe44113..c89b4f5b377 100644 --- a/src/test/ui/error-codes/E0029.rs +++ b/src/test/ui/error-codes/E0029.rs @@ -12,7 +12,7 @@ fn main() { let s = "hoho"; match s { - "hello" ... "world" => {} + "hello" ..= "world" => {} //~^ ERROR only char and numeric types are allowed in range patterns _ => {} } diff --git a/src/test/ui/error-codes/E0029.stderr b/src/test/ui/error-codes/E0029.stderr index bcdfa387111..d25666f9cf8 100644 --- a/src/test/ui/error-codes/E0029.stderr +++ b/src/test/ui/error-codes/E0029.stderr @@ -1,7 +1,7 @@ error[E0029]: only char and numeric types are allowed in range patterns --> $DIR/E0029.rs:15:9 | -LL | "hello" ... "world" => {} +LL | "hello" ..= "world" => {} | ^^^^^^^^^^^^^^^^^^^ ranges require char or numeric types | = note: start type: &'static str diff --git a/src/test/ui/error-codes/E0030-teach.rs b/src/test/ui/error-codes/E0030-teach.rs index 2af32eda62b..cf860cea24c 100644 --- a/src/test/ui/error-codes/E0030-teach.rs +++ b/src/test/ui/error-codes/E0030-teach.rs @@ -12,7 +12,7 @@ fn main() { match 5u32 { - 1000 ... 5 => {} + 1000 ..= 5 => {} //~^ ERROR lower range bound must be less than or equal to upper } } diff --git a/src/test/ui/error-codes/E0030-teach.stderr b/src/test/ui/error-codes/E0030-teach.stderr index 8b262d5b296..2a7243a9569 100644 --- a/src/test/ui/error-codes/E0030-teach.stderr +++ b/src/test/ui/error-codes/E0030-teach.stderr @@ -1,7 +1,7 @@ error[E0030]: lower range bound must be less than or equal to upper --> $DIR/E0030-teach.rs:15:9 | -LL | 1000 ... 5 => {} +LL | 1000 ..= 5 => {} | ^^^^ lower bound larger than upper bound | = note: When matching against a range, the compiler verifies that the range is non-empty. Range patterns include both end-points, so this is equivalent to requiring the start of the range to be less than or equal to the end of the range. diff --git a/src/test/ui/error-codes/E0030.rs b/src/test/ui/error-codes/E0030.rs index ef3bded4bef..e147dd932b0 100644 --- a/src/test/ui/error-codes/E0030.rs +++ b/src/test/ui/error-codes/E0030.rs @@ -11,7 +11,7 @@ fn main() { match 5u32 { - 1000 ... 5 => {} + 1000 ..= 5 => {} //~^ ERROR lower range bound must be less than or equal to upper } } diff --git a/src/test/ui/error-codes/E0030.stderr b/src/test/ui/error-codes/E0030.stderr index 0949cfb50b6..020655ee45b 100644 --- a/src/test/ui/error-codes/E0030.stderr +++ b/src/test/ui/error-codes/E0030.stderr @@ -1,7 +1,7 @@ error[E0030]: lower range bound must be less than or equal to upper --> $DIR/E0030.rs:14:9 | -LL | 1000 ... 5 => {} +LL | 1000 ..= 5 => {} | ^^^^ lower bound larger than upper bound error: aborting due to previous error diff --git a/src/test/ui/error-codes/E0308-4.rs b/src/test/ui/error-codes/E0308-4.rs index bb4cd143416..106c55817c1 100644 --- a/src/test/ui/error-codes/E0308-4.rs +++ b/src/test/ui/error-codes/E0308-4.rs @@ -11,7 +11,7 @@ fn main() { let x = 1u8; match x { - 0u8...3i8 => (), //~ ERROR E0308 + 0u8..=3i8 => (), //~ ERROR E0308 _ => () } } diff --git a/src/test/ui/error-codes/E0308-4.stderr b/src/test/ui/error-codes/E0308-4.stderr index 31875349bac..8943c7332e9 100644 --- a/src/test/ui/error-codes/E0308-4.stderr +++ b/src/test/ui/error-codes/E0308-4.stderr @@ -1,7 +1,7 @@ error[E0308]: mismatched types --> $DIR/E0308-4.rs:14:9 | -LL | 0u8...3i8 => (), //~ ERROR E0308 +LL | 0u8..=3i8 => (), //~ ERROR E0308 | ^^^^^^^^^ expected u8, found i8 error: aborting due to previous error -- cgit 1.4.1-3-g733a5 From 9797665b286db3f34cc475560a68380012fadde7 Mon Sep 17 00:00:00 2001 From: Evan Simmons Date: Sun, 1 Jul 2018 14:30:16 -0700 Subject: Make Stdio handle UnwindSafe --- src/libstd/io/stdio.rs | 22 ++++++++++++++++++++++ src/libstd/sys_common/remutex.rs | 4 ++++ 2 files changed, 26 insertions(+) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 2472bed5ba4..fce85a200ba 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -712,9 +712,31 @@ pub fn _eprint(args: fmt::Arguments) { #[cfg(test)] mod tests { + use panic::{UnwindSafe, RefUnwindSafe}; use thread; use super::*; + #[test] + fn stdout_unwind_safe() { + assert_unwind_safe::(); + } + #[test] + fn stdoutlock_unwind_safe() { + assert_unwind_safe::(); + assert_unwind_safe::>(); + } + #[test] + fn stderr_unwind_safe() { + assert_unwind_safe::(); + } + #[test] + fn stderrlock_unwind_safe() { + assert_unwind_safe::(); + assert_unwind_safe::>(); + } + + fn assert_unwind_safe() {} + #[test] #[cfg_attr(target_os = "emscripten", ignore)] fn panic_doesnt_poison() { diff --git a/src/libstd/sys_common/remutex.rs b/src/libstd/sys_common/remutex.rs index 022056f8a8a..071a3a25c7a 100644 --- a/src/libstd/sys_common/remutex.rs +++ b/src/libstd/sys_common/remutex.rs @@ -13,6 +13,7 @@ use marker; use ops::Deref; use sys_common::poison::{self, TryLockError, TryLockResult, LockResult}; use sys::mutex as sys; +use panic::{UnwindSafe, RefUnwindSafe}; /// A re-entrant mutual exclusion /// @@ -28,6 +29,9 @@ pub struct ReentrantMutex { unsafe impl Send for ReentrantMutex {} unsafe impl Sync for ReentrantMutex {} +impl UnwindSafe for ReentrantMutex {} +impl RefUnwindSafe for ReentrantMutex {} + /// An RAII implementation of a "scoped lock" of a mutex. When this structure is /// dropped (falls out of scope), the lock will be unlocked. -- cgit 1.4.1-3-g733a5 From 560d8079ec26f2a45ecb80e95d24917025e02104 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Tue, 10 Jul 2018 20:35:36 +0200 Subject: Deny bare trait objects in `src/libstd`. --- src/libstd/error.rs | 86 ++++++++++++++++++------------------ src/libstd/ffi/c_str.rs | 2 +- src/libstd/io/error.rs | 14 +++--- src/libstd/io/mod.rs | 4 +- src/libstd/io/stdio.rs | 8 ++-- src/libstd/lib.rs | 1 + src/libstd/net/parser.rs | 2 +- src/libstd/panic.rs | 2 +- src/libstd/panicking.rs | 36 +++++++-------- src/libstd/process.rs | 4 +- src/libstd/rt.rs | 2 +- src/libstd/sync/mpsc/mod.rs | 10 ++--- src/libstd/sync/mpsc/select.rs | 2 +- src/libstd/sync/once.rs | 2 +- src/libstd/sys/windows/thread.rs | 2 +- src/libstd/sys_common/at_exit_imp.rs | 4 +- src/libstd/sys_common/backtrace.rs | 10 ++--- src/libstd/sys_common/poison.rs | 2 +- src/libstd/sys_common/thread.rs | 2 +- src/libstd/thread/mod.rs | 2 +- 20 files changed, 99 insertions(+), 98 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/error.rs b/src/libstd/error.rs index 1958915602f..8d715ac0ec3 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -138,7 +138,7 @@ pub trait Error: Debug + Display { /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] - fn cause(&self) -> Option<&Error> { None } + fn cause(&self) -> Option<&dyn Error> { None } /// Get the `TypeId` of `self` #[doc(hidden)] @@ -151,22 +151,22 @@ pub trait Error: Debug + Display { } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, E: Error + 'a> From for Box { - fn from(err: E) -> Box { +impl<'a, E: Error + 'a> From for Box { + fn from(err: E) -> Box { Box::new(err) } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, E: Error + Send + Sync + 'a> From for Box { - fn from(err: E) -> Box { +impl<'a, E: Error + Send + Sync + 'a> From for Box { + fn from(err: E) -> Box { Box::new(err) } } #[stable(feature = "rust1", since = "1.0.0")] -impl From for Box { - fn from(err: String) -> Box { +impl From for Box { + fn from(err: String) -> Box { #[derive(Debug)] struct StringError(String); @@ -185,38 +185,38 @@ impl From for Box { } #[stable(feature = "string_box_error", since = "1.6.0")] -impl From for Box { - fn from(str_err: String) -> Box { - let err1: Box = From::from(str_err); - let err2: Box = err1; +impl From for Box { + fn from(str_err: String) -> Box { + let err1: Box = From::from(str_err); + let err2: Box = err1; err2 } } #[stable(feature = "rust1", since = "1.0.0")] -impl<'a, 'b> From<&'b str> for Box { - fn from(err: &'b str) -> Box { +impl<'a, 'b> From<&'b str> for Box { + fn from(err: &'b str) -> Box { From::from(String::from(err)) } } #[stable(feature = "string_box_error", since = "1.6.0")] -impl<'a> From<&'a str> for Box { - fn from(err: &'a str) -> Box { +impl<'a> From<&'a str> for Box { + fn from(err: &'a str) -> Box { From::from(String::from(err)) } } #[stable(feature = "cow_box_error", since = "1.22.0")] -impl<'a, 'b> From> for Box { - fn from(err: Cow<'b, str>) -> Box { +impl<'a, 'b> From> for Box { + fn from(err: Cow<'b, str>) -> Box { From::from(String::from(err)) } } #[stable(feature = "cow_box_error", since = "1.22.0")] -impl<'a> From> for Box { - fn from(err: Cow<'a, str>) -> Box { +impl<'a> From> for Box { + fn from(err: Cow<'a, str>) -> Box { From::from(String::from(err)) } } @@ -327,7 +327,7 @@ impl Error for Box { Error::description(&**self) } - fn cause(&self) -> Option<&Error> { + fn cause(&self) -> Option<&dyn Error> { Error::cause(&**self) } } @@ -368,7 +368,7 @@ impl Error for char::ParseCharError { } // copied from any.rs -impl Error + 'static { +impl dyn Error + 'static { /// Returns true if the boxed type is the same as `T` #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] @@ -390,7 +390,7 @@ impl Error + 'static { pub fn downcast_ref(&self) -> Option<&T> { if self.is::() { unsafe { - Some(&*(self as *const Error as *const T)) + Some(&*(self as *const dyn Error as *const T)) } } else { None @@ -404,7 +404,7 @@ impl Error + 'static { pub fn downcast_mut(&mut self) -> Option<&mut T> { if self.is::() { unsafe { - Some(&mut *(self as *mut Error as *mut T)) + Some(&mut *(self as *mut dyn Error as *mut T)) } } else { None @@ -412,60 +412,60 @@ impl Error + 'static { } } -impl Error + 'static + Send { +impl dyn Error + 'static + Send { /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn is(&self) -> bool { - ::is::(self) + ::is::(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_ref(&self) -> Option<&T> { - ::downcast_ref::(self) + ::downcast_ref::(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_mut(&mut self) -> Option<&mut T> { - ::downcast_mut::(self) + ::downcast_mut::(self) } } -impl Error + 'static + Send + Sync { +impl dyn Error + 'static + Send + Sync { /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn is(&self) -> bool { - ::is::(self) + ::is::(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_ref(&self) -> Option<&T> { - ::downcast_ref::(self) + ::downcast_ref::(self) } /// Forwards to the method defined on the type `Any`. #[stable(feature = "error_downcast", since = "1.3.0")] #[inline] pub fn downcast_mut(&mut self) -> Option<&mut T> { - ::downcast_mut::(self) + ::downcast_mut::(self) } } -impl Error { +impl dyn Error { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] /// Attempt to downcast the box to a concrete type. - pub fn downcast(self: Box) -> Result, Box> { + pub fn downcast(self: Box) -> Result, Box> { if self.is::() { unsafe { - let raw: *mut Error = Box::into_raw(self); + let raw: *mut dyn Error = Box::into_raw(self); Ok(Box::from_raw(raw as *mut T)) } } else { @@ -474,30 +474,30 @@ impl Error { } } -impl Error + Send { +impl dyn Error + Send { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] /// Attempt to downcast the box to a concrete type. pub fn downcast(self: Box) - -> Result, Box> { - let err: Box = self; - ::downcast(err).map_err(|s| unsafe { + -> Result, Box> { + let err: Box = self; + ::downcast(err).map_err(|s| unsafe { // reapply the Send marker - transmute::, Box>(s) + transmute::, Box>(s) }) } } -impl Error + Send + Sync { +impl dyn Error + Send + Sync { #[inline] #[stable(feature = "error_downcast", since = "1.3.0")] /// Attempt to downcast the box to a concrete type. pub fn downcast(self: Box) -> Result, Box> { - let err: Box = self; - ::downcast(err).map_err(|s| unsafe { + let err: Box = self; + ::downcast(err).map_err(|s| unsafe { // reapply the Send+Sync marker - transmute::, Box>(s) + transmute::, Box>(s) }) } } diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 6513d11dd51..03e0d0aa6dd 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -883,7 +883,7 @@ impl Error for IntoStringError { "C string contained non-utf8 bytes" } - fn cause(&self) -> Option<&Error> { + fn cause(&self) -> Option<&dyn Error> { Some(&self.error) } } diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index bdd675e6e2b..02a3ce8b9c4 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -83,7 +83,7 @@ enum Repr { #[derive(Debug)] struct Custom { kind: ErrorKind, - error: Box, + error: Box, } /// A list specifying general categories of I/O error. @@ -250,12 +250,12 @@ impl Error { /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn new(kind: ErrorKind, error: E) -> Error - where E: Into> + where E: Into> { Self::_new(kind, error.into()) } - fn _new(kind: ErrorKind, error: Box) -> Error { + fn _new(kind: ErrorKind, error: Box) -> Error { Error { repr: Repr::Custom(Box::new(Custom { kind, @@ -373,7 +373,7 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn get_ref(&self) -> Option<&(error::Error+Send+Sync+'static)> { + pub fn get_ref(&self) -> Option<&(dyn error::Error+Send+Sync+'static)> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, @@ -444,7 +444,7 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn get_mut(&mut self) -> Option<&mut (error::Error+Send+Sync+'static)> { + pub fn get_mut(&mut self) -> Option<&mut (dyn error::Error+Send+Sync+'static)> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, @@ -478,7 +478,7 @@ impl Error { /// } /// ``` #[stable(feature = "io_error_inner", since = "1.3.0")] - pub fn into_inner(self) -> Option> { + pub fn into_inner(self) -> Option> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, @@ -551,7 +551,7 @@ impl error::Error for Error { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { match self.repr { Repr::Os(..) => None, Repr::Simple(..) => None, diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 2b4644bd013..85304874848 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1972,7 +1972,7 @@ impl BufRead for Take { } } -fn read_one_byte(reader: &mut Read) -> Option> { +fn read_one_byte(reader: &mut dyn Read) -> Option> { let mut buf = [0]; loop { return match reader.read(&mut buf) { @@ -2081,7 +2081,7 @@ impl std_error::Error for CharsError { CharsError::Other(ref e) => std_error::Error::description(e), } } - fn cause(&self) -> Option<&std_error::Error> { + fn cause(&self) -> Option<&dyn std_error::Error> { match *self { CharsError::NotUtf8 => None, CharsError::Other(ref e) => e.cause(), diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index fce85a200ba..fffe8fc559b 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -21,7 +21,7 @@ use thread::LocalKey; /// Stdout used by print! and println! macros thread_local! { - static LOCAL_STDOUT: RefCell>> = { + static LOCAL_STDOUT: RefCell>> = { RefCell::new(None) } } @@ -624,7 +624,7 @@ impl<'a> fmt::Debug for StderrLock<'a> { with a more general mechanism", issue = "0")] #[doc(hidden)] -pub fn set_panic(sink: Option>) -> Option> { +pub fn set_panic(sink: Option>) -> Option> { use panicking::LOCAL_STDERR; use mem; LOCAL_STDERR.with(move |slot| { @@ -648,7 +648,7 @@ pub fn set_panic(sink: Option>) -> Option> { with a more general mechanism", issue = "0")] #[doc(hidden)] -pub fn set_print(sink: Option>) -> Option> { +pub fn set_print(sink: Option>) -> Option> { use mem; LOCAL_STDOUT.with(move |slot| { mem::replace(&mut *slot.borrow_mut(), sink) @@ -670,7 +670,7 @@ pub fn set_print(sink: Option>) -> Option> { /// However, if the actual I/O causes an error, this function does panic. fn print_to( args: fmt::Arguments, - local_s: &'static LocalKey>>>, + local_s: &'static LocalKey>>>, global_s: fn() -> T, label: &str, ) diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index d73cb1f8349..006922383cf 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -221,6 +221,7 @@ // Don't link to std. We are std. #![no_std] +#![deny(bare_trait_objects)] #![deny(missing_docs)] #![deny(missing_debug_implementations)] diff --git a/src/libstd/net/parser.rs b/src/libstd/net/parser.rs index ae5037cc44e..234c5618a06 100644 --- a/src/libstd/net/parser.rs +++ b/src/libstd/net/parser.rs @@ -61,7 +61,7 @@ impl<'a> Parser<'a> { } // Return result of first successful parser - fn read_or(&mut self, parsers: &mut [Box Option + 'static>]) + fn read_or(&mut self, parsers: &mut [Box Option + 'static>]) -> Option { for pf in parsers { if let Some(r) = self.read_atomically(|p: &mut Parser| pf(p)) { diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index 451420ae88a..b8c1c4f9e68 100644 --- a/src/libstd/panic.rs +++ b/src/libstd/panic.rs @@ -421,6 +421,6 @@ pub fn catch_unwind R + UnwindSafe, R>(f: F) -> Result { /// } /// ``` #[stable(feature = "resume_unwind", since = "1.9.0")] -pub fn resume_unwind(payload: Box) -> ! { +pub fn resume_unwind(payload: Box) -> ! { panicking::update_count_then_panic(payload) } diff --git a/src/libstd/panicking.rs b/src/libstd/panicking.rs index 46b6cf60705..283fd36af41 100644 --- a/src/libstd/panicking.rs +++ b/src/libstd/panicking.rs @@ -36,7 +36,7 @@ use sys_common::util; use thread; thread_local! { - pub static LOCAL_STDERR: RefCell>> = { + pub static LOCAL_STDERR: RefCell>> = { RefCell::new(None) } } @@ -64,7 +64,7 @@ extern { #[derive(Copy, Clone)] enum Hook { Default, - Custom(*mut (Fn(&PanicInfo) + 'static + Sync + Send)), + Custom(*mut (dyn Fn(&PanicInfo) + 'static + Sync + Send)), } static HOOK_LOCK: RWLock = RWLock::new(); @@ -104,7 +104,7 @@ static mut HOOK: Hook = Hook::Default; /// panic!("Normal panic"); /// ``` #[stable(feature = "panic_hooks", since = "1.10.0")] -pub fn set_hook(hook: Box) { +pub fn set_hook(hook: Box) { if thread::panicking() { panic!("cannot modify the panic hook from a panicking thread"); } @@ -149,7 +149,7 @@ pub fn set_hook(hook: Box) { /// panic!("Normal panic"); /// ``` #[stable(feature = "panic_hooks", since = "1.10.0")] -pub fn take_hook() -> Box { +pub fn take_hook() -> Box { if thread::panicking() { panic!("cannot modify the panic hook from a panicking thread"); } @@ -197,7 +197,7 @@ fn default_hook(info: &PanicInfo) { let thread = thread_info::current_thread(); let name = thread.as_ref().and_then(|t| t.name()).unwrap_or(""); - let write = |err: &mut ::io::Write| { + let write = |err: &mut dyn (::io::Write)| { let _ = writeln!(err, "thread '{}' panicked at '{}', {}", name, msg, location); @@ -248,7 +248,7 @@ pub fn update_panic_count(amt: isize) -> usize { pub use realstd::rt::update_panic_count; /// Invoke a closure, capturing the cause of an unwinding panic if one occurs. -pub unsafe fn try R>(f: F) -> Result> { +pub unsafe fn try R>(f: F) -> Result> { #[allow(unions_with_drop_fields)] union Data { f: F, @@ -369,12 +369,12 @@ fn continue_panic_fmt(info: &PanicInfo) -> ! { } unsafe impl<'a> BoxMeUp for PanicPayload<'a> { - fn box_me_up(&mut self) -> *mut (Any + Send) { + fn box_me_up(&mut self) -> *mut (dyn Any + Send) { let contents = mem::replace(self.fill(), String::new()); Box::into_raw(Box::new(contents)) } - fn get(&mut self) -> &(Any + Send) { + fn get(&mut self) -> &(dyn Any + Send) { self.fill() } } @@ -419,15 +419,15 @@ pub fn begin_panic(msg: M, file_line_col: &(&'static str, u32, u3 } unsafe impl BoxMeUp for PanicPayload { - fn box_me_up(&mut self) -> *mut (Any + Send) { + fn box_me_up(&mut self) -> *mut (dyn Any + Send) { let data = match self.inner.take() { - Some(a) => Box::new(a) as Box, + Some(a) => Box::new(a) as Box, None => Box::new(()), }; Box::into_raw(data) } - fn get(&mut self) -> &(Any + Send) { + fn get(&mut self) -> &(dyn Any + Send) { match self.inner { Some(ref a) => a, None => &(), @@ -441,7 +441,7 @@ pub fn begin_panic(msg: M, file_line_col: &(&'static str, u32, u3 /// Executes the primary logic for a panic, including checking for recursive /// panics, panic hooks, and finally dispatching to the panic runtime to either /// abort or unwind. -fn rust_panic_with_hook(payload: &mut BoxMeUp, +fn rust_panic_with_hook(payload: &mut dyn BoxMeUp, message: Option<&fmt::Arguments>, file_line_col: &(&str, u32, u32)) -> ! { let (file, line, col) = *file_line_col; @@ -496,17 +496,17 @@ fn rust_panic_with_hook(payload: &mut BoxMeUp, } /// Shim around rust_panic. Called by resume_unwind. -pub fn update_count_then_panic(msg: Box) -> ! { +pub fn update_count_then_panic(msg: Box) -> ! { update_panic_count(1); - struct RewrapBox(Box); + struct RewrapBox(Box); unsafe impl BoxMeUp for RewrapBox { - fn box_me_up(&mut self) -> *mut (Any + Send) { + fn box_me_up(&mut self) -> *mut (dyn Any + Send) { Box::into_raw(mem::replace(&mut self.0, Box::new(()))) } - fn get(&mut self) -> &(Any + Send) { + fn get(&mut self) -> &(dyn Any + Send) { &*self.0 } } @@ -517,9 +517,9 @@ pub fn update_count_then_panic(msg: Box) -> ! { /// A private no-mangle function on which to slap yer breakpoints. #[no_mangle] #[allow(private_no_mangle_fns)] // yes we get it, but we like breakpoints -pub fn rust_panic(mut msg: &mut BoxMeUp) -> ! { +pub fn rust_panic(mut msg: &mut dyn BoxMeUp) -> ! { let code = unsafe { - let obj = &mut msg as *mut &mut BoxMeUp; + let obj = &mut msg as *mut &mut dyn BoxMeUp; __rust_start_panic(obj as usize) }; rtabort!("failed to initiate panic, error {}", code) diff --git a/src/libstd/process.rs b/src/libstd/process.rs index 00051d4487a..39692836866 100644 --- a/src/libstd/process.rs +++ b/src/libstd/process.rs @@ -813,13 +813,13 @@ impl fmt::Debug for Output { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let stdout_utf8 = str::from_utf8(&self.stdout); - let stdout_debug: &fmt::Debug = match stdout_utf8 { + let stdout_debug: &dyn fmt::Debug = match stdout_utf8 { Ok(ref str) => str, Err(_) => &self.stdout }; let stderr_utf8 = str::from_utf8(&self.stderr); - let stderr_debug: &fmt::Debug = match stderr_utf8 { + let stderr_debug: &dyn fmt::Debug = match stderr_utf8 { Ok(ref str) => str, Err(_) => &self.stderr }; diff --git a/src/libstd/rt.rs b/src/libstd/rt.rs index 8f945470b7e..9e957bd87d7 100644 --- a/src/libstd/rt.rs +++ b/src/libstd/rt.rs @@ -29,7 +29,7 @@ pub use panicking::{begin_panic, begin_panic_fmt, update_panic_count}; // To reduce the generated code of the new `lang_start`, this function is doing // the real work. #[cfg(not(test))] -fn lang_start_internal(main: &(Fn() -> i32 + Sync + ::panic::RefUnwindSafe), +fn lang_start_internal(main: &(dyn Fn() -> i32 + Sync + ::panic::RefUnwindSafe), argc: isize, argv: *const *const u8) -> isize { use panic; use sys; diff --git a/src/libstd/sync/mpsc/mod.rs b/src/libstd/sync/mpsc/mod.rs index 2dd3aebe610..1dc0b1c0042 100644 --- a/src/libstd/sync/mpsc/mod.rs +++ b/src/libstd/sync/mpsc/mod.rs @@ -1638,7 +1638,7 @@ impl error::Error for SendError { "sending on a closed channel" } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -1681,7 +1681,7 @@ impl error::Error for TrySendError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -1709,7 +1709,7 @@ impl error::Error for RecvError { "receiving on a closed channel" } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -1742,7 +1742,7 @@ impl error::Error for TryRecvError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } @@ -1783,7 +1783,7 @@ impl error::Error for RecvTimeoutError { } } - fn cause(&self) -> Option<&error::Error> { + fn cause(&self) -> Option<&dyn error::Error> { None } } diff --git a/src/libstd/sync/mpsc/select.rs b/src/libstd/sync/mpsc/select.rs index 9310dad9172..a7a284cfb79 100644 --- a/src/libstd/sync/mpsc/select.rs +++ b/src/libstd/sync/mpsc/select.rs @@ -93,7 +93,7 @@ pub struct Handle<'rx, T:Send+'rx> { next: *mut Handle<'static, ()>, prev: *mut Handle<'static, ()>, added: bool, - packet: &'rx (Packet+'rx), + packet: &'rx (dyn Packet+'rx), // due to our fun transmutes, we be sure to place this at the end. (nothing // previous relies on T) diff --git a/src/libstd/sync/once.rs b/src/libstd/sync/once.rs index 7eb7be23128..1c63f99753a 100644 --- a/src/libstd/sync/once.rs +++ b/src/libstd/sync/once.rs @@ -301,7 +301,7 @@ impl Once { #[cold] fn call_inner(&'static self, ignore_poisoning: bool, - init: &mut FnMut(bool)) { + init: &mut dyn FnMut(bool)) { let mut state = self.state.load(Ordering::SeqCst); 'outer: loop { diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index b6f63303dc2..44ec872b244 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -28,7 +28,7 @@ pub struct Thread { } impl Thread { - pub unsafe fn new<'a>(stack: usize, p: Box) + pub unsafe fn new<'a>(stack: usize, p: Box) -> io::Result { let p = box p; diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index d268d9ad6f9..b28a4d2f8be 100644 --- a/src/libstd/sys_common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs @@ -17,7 +17,7 @@ use ptr; use mem; use sys_common::mutex::Mutex; -type Queue = Vec>; +type Queue = Vec>; // NB these are specifically not types from `std::sync` as they currently rely // on poisoning and this module needs to operate at a lower level than requiring @@ -68,7 +68,7 @@ pub fn cleanup() { } } -pub fn push(f: Box) -> bool { +pub fn push(f: Box) -> bool { unsafe { let _guard = LOCK.lock(); if init() { diff --git a/src/libstd/sys_common/backtrace.rs b/src/libstd/sys_common/backtrace.rs index 61d7ed463dd..6184ba4ded6 100644 --- a/src/libstd/sys_common/backtrace.rs +++ b/src/libstd/sys_common/backtrace.rs @@ -49,7 +49,7 @@ pub struct Frame { const MAX_NB_FRAMES: usize = 100; /// Prints the current backtrace. -pub fn print(w: &mut Write, format: PrintFormat) -> io::Result<()> { +pub fn print(w: &mut dyn Write, format: PrintFormat) -> io::Result<()> { static LOCK: Mutex = Mutex::new(); // Use a lock to prevent mixed output in multithreading context. @@ -62,7 +62,7 @@ pub fn print(w: &mut Write, format: PrintFormat) -> io::Result<()> { } } -fn _print(w: &mut Write, format: PrintFormat) -> io::Result<()> { +fn _print(w: &mut dyn Write, format: PrintFormat) -> io::Result<()> { let mut frames = [Frame { exact_position: ptr::null(), symbol_addr: ptr::null(), @@ -177,7 +177,7 @@ pub fn log_enabled() -> Option { /// /// These output functions should now be used everywhere to ensure consistency. /// You may want to also use `output_fileline`. -fn output(w: &mut Write, idx: usize, frame: Frame, +fn output(w: &mut dyn Write, idx: usize, frame: Frame, s: Option<&str>, format: PrintFormat) -> io::Result<()> { // Remove the `17: 0x0 - ` line. if format == PrintFormat::Short && frame.exact_position == ptr::null() { @@ -202,7 +202,7 @@ fn output(w: &mut Write, idx: usize, frame: Frame, /// /// See also `output`. #[allow(dead_code)] -fn output_fileline(w: &mut Write, +fn output_fileline(w: &mut dyn Write, file: &[u8], line: u32, format: PrintFormat) -> io::Result<()> { @@ -254,7 +254,7 @@ fn output_fileline(w: &mut Write, // Note that this demangler isn't quite as fancy as it could be. We have lots // of other information in our symbols like hashes, version, type information, // etc. Additionally, this doesn't handle glue symbols at all. -pub fn demangle(writer: &mut Write, mut s: &str, format: PrintFormat) -> io::Result<()> { +pub fn demangle(writer: &mut dyn Write, mut s: &str, format: PrintFormat) -> io::Result<()> { // During ThinLTO LLVM may import and rename internal symbols, so strip out // those endings first as they're one of the last manglings applied to // symbol names. diff --git a/src/libstd/sys_common/poison.rs b/src/libstd/sys_common/poison.rs index e74c40ae04b..1625efe4a2a 100644 --- a/src/libstd/sys_common/poison.rs +++ b/src/libstd/sys_common/poison.rs @@ -251,7 +251,7 @@ impl Error for TryLockError { } } - fn cause(&self) -> Option<&Error> { + fn cause(&self) -> Option<&dyn Error> { match *self { TryLockError::Poisoned(ref p) => Some(p), _ => None diff --git a/src/libstd/sys_common/thread.rs b/src/libstd/sys_common/thread.rs index da6f58ef6bb..86a5e2b8694 100644 --- a/src/libstd/sys_common/thread.rs +++ b/src/libstd/sys_common/thread.rs @@ -21,7 +21,7 @@ pub unsafe fn start_thread(main: *mut u8) { let _handler = stack_overflow::Handler::new(); // Finally, let's run some code. - Box::from_raw(main as *mut Box)() + Box::from_raw(main as *mut Box)() } pub fn min_stack() -> usize { diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 90f054186d1..cc0ec8a5b4d 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -1175,7 +1175,7 @@ impl fmt::Debug for Thread { /// /// [`Result`]: ../../std/result/enum.Result.html #[stable(feature = "rust1", since = "1.0.0")] -pub type Result = ::result::Result>; +pub type Result = ::result::Result>; // This packet is used to communicate the return value between the child thread // and the parent thread. Memory is shared through the `Arc` within and there's -- cgit 1.4.1-3-g733a5 From 4f3ab4986ec96d9c93f34dc53d0a4a1279288451 Mon Sep 17 00:00:00 2001 From: Colin Wallace Date: Mon, 23 Jul 2018 22:00:51 -0700 Subject: libstd: Prefer `Option::map`/etc over `match` where applicable --- src/libstd/net/parser.rs | 5 +---- src/libstd/path.rs | 5 +---- src/libstd/sys_common/backtrace.rs | 9 ++++----- 3 files changed, 6 insertions(+), 13 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/net/parser.rs b/src/libstd/net/parser.rs index ae5037cc44e..008c5da171f 100644 --- a/src/libstd/net/parser.rs +++ b/src/libstd/net/parser.rs @@ -53,10 +53,7 @@ impl<'a> Parser<'a> { F: FnOnce(&mut Parser) -> Option, { self.read_atomically(move |p| { - match cb(p) { - Some(x) => if p.is_eof() {Some(x)} else {None}, - None => None, - } + cb(p).filter(|_| p.is_eof()) }) } diff --git a/src/libstd/path.rs b/src/libstd/path.rs index 0c60129494d..688a7e99f10 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -1065,10 +1065,7 @@ impl<'a> Iterator for Ancestors<'a> { fn next(&mut self) -> Option { let next = self.next; - self.next = match next { - Some(path) => path.parent(), - None => None, - }; + self.next = next.and_then(Path::parent); next } } diff --git a/src/libstd/sys_common/backtrace.rs b/src/libstd/sys_common/backtrace.rs index 61d7ed463dd..2db47bd5947 100644 --- a/src/libstd/sys_common/backtrace.rs +++ b/src/libstd/sys_common/backtrace.rs @@ -156,16 +156,15 @@ pub fn log_enabled() -> Option { _ => return Some(PrintFormat::Full), } - let val = match env::var_os("RUST_BACKTRACE") { - Some(x) => if &x == "0" { + let val = env::var_os("RUST_BACKTRACE").and_then(|x| + if &x == "0" { None } else if &x == "full" { Some(PrintFormat::Full) } else { Some(PrintFormat::Short) - }, - None => None, - }; + } + ); ENABLED.store(match val { Some(v) => v as isize, None => 1, -- cgit 1.4.1-3-g733a5 From 57a5a9b05423c4f832cd9a3aaa7e06d55fab6efa Mon Sep 17 00:00:00 2001 From: ljedrz Date: Fri, 27 Jul 2018 11:11:18 +0200 Subject: Prefer to_string() to format!() --- src/bootstrap/builder.rs | 2 +- src/libcore/tests/str_lossy.rs | 2 +- src/librustc/infer/error_reporting/mod.rs | 26 +++++++++---------- .../nice_region_error/static_impl_trait.rs | 2 +- src/librustc/mir/mod.rs | 2 +- src/librustc/session/code_stats.rs | 4 +-- src/librustc/traits/error_reporting.rs | 16 ++++++------ src/librustc/ty/item_path.rs | 2 +- src/librustc/ty/mod.rs | 2 +- src/librustc/util/common.rs | 2 +- src/librustc_borrowck/borrowck/mod.rs | 2 +- src/librustc_codegen_llvm/back/archive.rs | 2 +- src/librustc_codegen_llvm/back/link.rs | 2 +- src/librustc_driver/lib.rs | 4 +-- src/librustc_lint/builtin.rs | 4 +-- src/librustc_metadata/locator.rs | 2 +- src/librustc_mir/borrow_check/borrow_set.rs | 2 +- src/librustc_mir/borrow_check/error_reporting.rs | 12 ++++----- src/librustc_mir/borrow_check/flows.rs | 6 ++--- src/librustc_mir/borrow_check/move_errors.rs | 2 +- src/librustc_traits/lowering.rs | 2 +- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/outlives/mod.rs | 4 +-- src/librustdoc/html/format.rs | 10 ++++---- src/librustdoc/html/markdown.rs | 8 +++--- src/librustdoc/html/render.rs | 12 ++++----- src/librustdoc/html/toc.rs | 2 +- src/librustdoc/markdown.rs | 4 +-- src/libserialize/json.rs | 30 +++++++++++----------- src/libstd/sys/redox/net/udp.rs | 2 +- src/libstd/sys_common/wtf8.rs | 2 +- src/libsyntax/ext/expand.rs | 4 +-- src/libsyntax/parse/parser.rs | 2 +- src/libsyntax/print/pprust.rs | 2 +- src/libsyntax_ext/concat.rs | 4 +-- src/libterm/terminfo/parser/compiled.rs | 2 +- 36 files changed, 95 insertions(+), 95 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index c67787b5b0a..724d3b74190 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -925,7 +925,7 @@ impl<'a> Builder<'a> { cargo.env("RUSTC_VERIFY_LLVM_IR", "1"); } - cargo.env("RUSTC_VERBOSE", format!("{}", self.verbosity)); + cargo.env("RUSTC_VERBOSE", self.verbosity.to_string()); // in std, we want to avoid denying warnings for stage 0 as that makes cfg's painful. if self.config.deny_warnings && !(mode == Mode::Std && stage == 0) { diff --git a/src/libcore/tests/str_lossy.rs b/src/libcore/tests/str_lossy.rs index 69e28256da9..56ef3f070c1 100644 --- a/src/libcore/tests/str_lossy.rs +++ b/src/libcore/tests/str_lossy.rs @@ -79,7 +79,7 @@ fn chunks() { fn display() { assert_eq!( "Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye", - &format!("{}", Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye"))); + &Utf8Lossy::from_bytes(b"Hello\xC0\x80 There\xE6\x83 Goodbye").to_string()); } #[test] diff --git a/src/librustc/infer/error_reporting/mod.rs b/src/librustc/infer/error_reporting/mod.rs index 4ad60f2f85e..9050ffe8c8e 100644 --- a/src/librustc/infer/error_reporting/mod.rs +++ b/src/librustc/infer/error_reporting/mod.rs @@ -557,7 +557,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { // Output the lifetimes fot the first type let lifetimes = sub.regions() .map(|lifetime| { - let s = format!("{}", lifetime); + let s = lifetime.to_string(); if s.is_empty() { "'_".to_string() } else { @@ -582,7 +582,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { value.0.extend((values.0).0); other_value.0.extend((values.1).0); } else { - value.push_highlighted(format!("{}", type_arg)); + value.push_highlighted(type_arg.to_string()); } if len > 0 && i != len - 1 { @@ -716,7 +716,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { mutbl: hir::Mutability, s: &mut DiagnosticStyledString, ) { - let r = &format!("{}", r); + let r = &r.to_string(); s.push_highlighted(format!( "&{}{}{}", r, @@ -727,7 +727,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { "" } )); - s.push_normal(format!("{}", ty)); + s.push_normal(ty.to_string()); } match (&t1.sty, &t2.sty) { @@ -768,7 +768,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { } fn lifetime_display(lifetime: Region) -> String { - let s = format!("{}", lifetime); + let s = lifetime.to_string(); if s.is_empty() { "'_".to_string() } else { @@ -863,8 +863,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { // We couldn't find anything in common, highlight everything. // let x: Bar = y::>(); ( - DiagnosticStyledString::highlighted(format!("{}", t1)), - DiagnosticStyledString::highlighted(format!("{}", t2)), + DiagnosticStyledString::highlighted(t1.to_string()), + DiagnosticStyledString::highlighted(t2.to_string()), ) } } @@ -873,12 +873,12 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { (&ty::TyRef(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => { let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new()); push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0); - values.1.push_normal(format!("{}", t2)); + values.1.push_normal(t2.to_string()); values } (_, &ty::TyRef(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => { let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new()); - values.0.push_normal(format!("{}", t1)); + values.0.push_normal(t1.to_string()); push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1); values } @@ -902,8 +902,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { } else { // We couldn't find anything in common, highlight everything. ( - DiagnosticStyledString::highlighted(format!("{}", t1)), - DiagnosticStyledString::highlighted(format!("{}", t2)), + DiagnosticStyledString::highlighted(t1.to_string()), + DiagnosticStyledString::highlighted(t2.to_string()), ) } } @@ -1073,8 +1073,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { } Some(( - DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)), - DiagnosticStyledString::highlighted(format!("{}", exp_found.found)), + DiagnosticStyledString::highlighted(exp_found.expected.to_string()), + DiagnosticStyledString::highlighted(exp_found.found.to_string()), )) } diff --git a/src/librustc/infer/error_reporting/nice_region_error/static_impl_trait.rs b/src/librustc/infer/error_reporting/nice_region_error/static_impl_trait.rs index f9ec5fa13c9..193f86a3827 100644 --- a/src/librustc/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/src/librustc/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -57,7 +57,7 @@ impl<'a, 'gcx, 'tcx> NiceRegionError<'a, 'gcx, 'tcx> { let lifetime_name = match sup_r { RegionKind::ReFree(FreeRegion { bound_region: BoundRegion::BrNamed(_, ref name), .. - }) => format!("{}", name), + }) => name.to_string(), _ => "'_".to_owned(), }; if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(return_sp) { diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index f1f826486a5..4bfb4c96497 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -2093,7 +2093,7 @@ impl<'tcx> Debug for Rvalue<'tcx> { // When printing regions, add trailing space if necessary. let region = if ppaux::verbose() || ppaux::identify_regions() { - let mut region = format!("{}", region); + let mut region = region.to_string(); if region.len() > 0 { region.push(' '); } diff --git a/src/librustc/session/code_stats.rs b/src/librustc/session/code_stats.rs index df4060e71e5..1eee6508c59 100644 --- a/src/librustc/session/code_stats.rs +++ b/src/librustc/session/code_stats.rs @@ -135,8 +135,8 @@ impl CodeStats { let VariantInfo { ref name, kind: _, align: _, size, ref fields } = *variant_info; let indent = if !struct_like { let name = match name.as_ref() { - Some(name) => format!("{}", name), - None => format!("{}", i), + Some(name) => name.to_owned(), + None => i.to_string(), }; println!("print-type-size {}variant `{}`: {} bytes", indent, name, size - discr_size); diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs index 8300f98fb1c..05a21161dd5 100644 --- a/src/librustc/traits/error_reporting.rs +++ b/src/librustc/traits/error_reporting.rs @@ -543,7 +543,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { &data.parent_trait_ref); match self.get_parent_trait_ref(&data.parent_code) { Some(t) => Some(t), - None => Some(format!("{}", parent_trait_ref.skip_binder().self_ty())), + None => Some(parent_trait_ref.skip_binder().self_ty().to_string()), } } _ => None, @@ -797,12 +797,12 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { ty::TypeVariants::TyTuple(ref tys) => ArgKind::Tuple( Some(span), tys.iter() - .map(|ty| ("_".to_owned(), format!("{}", ty.sty))) + .map(|ty| ("_".to_owned(), ty.sty.to_string())) .collect::>() ), - _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)), + _ => ArgKind::Arg("_".to_owned(), t.sty.to_string()), }).collect(), - ref sty => vec![ArgKind::Arg("_".to_owned(), format!("{}", sty))], + ref sty => vec![ArgKind::Arg("_".to_owned(), sty.to_string())], }; if found.len() == expected.len() { self.report_closure_arg_mismatch(span, @@ -989,7 +989,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { }) => { (self.tcx.sess.codemap().def_span(span), fields.iter().map(|field| { - ArgKind::Arg(format!("{}", field.ident), "_".to_string()) + ArgKind::Arg(field.ident.to_string(), "_".to_string()) }).collect::>()) } hir::map::NodeStructCtor(ref variant_data) => { @@ -1152,7 +1152,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { ::rustc_target::spec::abi::Abi::Rust ) }; - format!("{}", ty::Binder::bind(sig)) + ty::Binder::bind(sig).to_string() } let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure(); @@ -1575,10 +1575,10 @@ impl ArgKind { ty::TyTuple(ref tys) => ArgKind::Tuple( None, tys.iter() - .map(|ty| ("_".to_owned(), format!("{}", ty.sty))) + .map(|ty| ("_".to_owned(), ty.sty.to_string())) .collect::>() ), - _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)), + _ => ArgKind::Arg("_".to_owned(), t.sty.to_string()), } } } diff --git a/src/librustc/ty/item_path.rs b/src/librustc/ty/item_path.rs index a44962c77b5..c44b7327a08 100644 --- a/src/librustc/ty/item_path.rs +++ b/src/librustc/ty/item_path.rs @@ -315,7 +315,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { ty::TyUint(_) | ty::TyFloat(_) | ty::TyStr => { - buffer.push(&format!("{}", self_ty)); + buffer.push(&self_ty.to_string()); } _ => { diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index b0797c31461..4fda3bdca3d 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -225,7 +225,7 @@ impl AssociatedItem { // late-bound regions, and we don't want method signatures to show up // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound // regions just fine, showing `fn(&MyType)`. - format!("{}", tcx.fn_sig(self.def_id).skip_binder()) + tcx.fn_sig(self.def_id).skip_binder().to_string() } ty::AssociatedKind::Type => format!("type {};", self.ident), ty::AssociatedKind::Existential => format!("existential type {};", self.ident), diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 85533caffce..97a798842a3 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -243,7 +243,7 @@ pub fn to_readable_str(mut val: usize) -> String { val /= 1000; if val == 0 { - groups.push(format!("{}", group)); + groups.push(group.to_string()); break; } else { groups.push(format!("{:03}", group)); diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 3ae1e5aac50..b5edf7226de 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -683,7 +683,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { let mut err = self.cannot_act_on_moved_value(use_span, verb, msg, - Some(format!("{}", nl)), + Some(nl.to_string()), Origin::Ast); let need_note = match lp.ty.sty { ty::TypeVariants::TyClosure(id, _) => { diff --git a/src/librustc_codegen_llvm/back/archive.rs b/src/librustc_codegen_llvm/back/archive.rs index 9ea6c44502a..b99835cb5c6 100644 --- a/src/librustc_codegen_llvm/back/archive.rs +++ b/src/librustc_codegen_llvm/back/archive.rs @@ -149,7 +149,7 @@ impl<'a> ArchiveBuilder<'a> { // Ignoring obj file starting with the crate name // as simple comparison is not enough - there // might be also an extra name suffix - let obj_start = format!("{}", name); + let obj_start = name.to_owned(); self.add_archive(rlib, move |fname: &str| { // Ignore bytecode/metadata files, no matter the name. diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index f2b17584adc..7aa1c6cf4e8 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -810,7 +810,7 @@ fn link_natively(sess: &Session, } }; - linker_error.note(&format!("{}", e)); + linker_error.note(&e.to_string()); if !linker_not_found { linker_error.note(&format!("{:?}", &cmd)); diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index 000025c49a6..3c73728e94b 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -533,7 +533,7 @@ fn run_compiler_with_pool<'a>( if let Some(err) = input_err { // Immediately stop compilation if there was an issue reading // the input (for example if the input stream is not UTF-8). - sess.err(&format!("{}", err)); + sess.err(&err.to_string()); return (Err(CompileIncomplete::Stopped), Some(sess)); } @@ -1113,7 +1113,7 @@ impl RustcDefaultCalls { cfgs.push(if let Some(value) = value { format!("{}=\"{}\"", name, value) } else { - format!("{}", name) + name.to_string() }); } diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index e6aa7c0d16c..8df6df15511 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -190,7 +190,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns { fieldpat.span, &format!("the `{}:` in this pattern is redundant", ident)); let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':'); - err.span_suggestion_short(subspan, "remove this", format!("{}", ident)); + err.span_suggestion_short(subspan, "remove this", ident.to_string()); err.emit(); } } @@ -701,7 +701,7 @@ impl EarlyLintPass for BadRepr { attr.span, "`repr` attribute isn't configurable with a literal", ); - match format!("{}", lit).as_ref() { + match lit.to_string().as_ref() { | "C" | "packed" | "rust" | "transparent" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" => { diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index 42af5db8294..f68bcdd62c6 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -722,7 +722,7 @@ impl<'a> Context<'a> { root.triple); self.rejected_via_triple.push(CrateMismatch { path: libpath.to_path_buf(), - got: format!("{}", root.triple), + got: root.triple.to_string(), }); return None; } diff --git a/src/librustc_mir/borrow_check/borrow_set.rs b/src/librustc_mir/borrow_check/borrow_set.rs index e9e0c5c3613..81ad8e324ba 100644 --- a/src/librustc_mir/borrow_check/borrow_set.rs +++ b/src/librustc_mir/borrow_check/borrow_set.rs @@ -86,7 +86,7 @@ impl<'tcx> fmt::Display for BorrowData<'tcx> { mir::BorrowKind::Unique => "uniq ", mir::BorrowKind::Mut { .. } => "mut ", }; - let region = format!("{}", self.region); + let region = self.region.to_string(); let region = if region.len() > 0 { format!("{} ", region) } else { diff --git a/src/librustc_mir/borrow_check/error_reporting.rs b/src/librustc_mir/borrow_check/error_reporting.rs index e20e608a2cd..e2ac7dde558 100644 --- a/src/librustc_mir/borrow_check/error_reporting.rs +++ b/src/librustc_mir/borrow_check/error_reporting.rs @@ -642,7 +642,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { self.append_local_to_string(local, buf)?; } Place::Static(ref static_) => { - buf.push_str(&format!("{}", &self.tcx.item_name(static_.def_id))); + buf.push_str(&self.tcx.item_name(static_.def_id).to_string()); } Place::Projection(ref proj) => { match proj.elem { @@ -766,7 +766,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { let local = &self.mir.local_decls[local_index]; match local.name { Some(name) => { - buf.push_str(&format!("{}", name)); + buf.push_str(&name.to_string()); Ok(()) } None => Err(()), @@ -794,7 +794,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { ProjectionElem::Index(..) | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => { - format!("{}", self.describe_field(&proj.base, field)) + self.describe_field(&proj.base, field).to_string() } }, } @@ -808,11 +808,11 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { } else { match ty.sty { ty::TyAdt(def, _) => if def.is_enum() { - format!("{}", field.index()) + field.index().to_string() } else { - format!("{}", def.non_enum_variant().fields[field.index()].ident) + def.non_enum_variant().fields[field.index()].ident.to_string() }, - ty::TyTuple(_) => format!("{}", field.index()), + ty::TyTuple(_) => field.index().to_string(), ty::TyRef(_, ty, _) | ty::TyRawPtr(ty::TypeAndMut { ty, .. }) => { self.describe_field_from_ty(&ty, field) } diff --git a/src/librustc_mir/borrow_check/flows.rs b/src/librustc_mir/borrow_check/flows.rs index 6dfcece3071..90dc96cbd3c 100644 --- a/src/librustc_mir/borrow_check/flows.rs +++ b/src/librustc_mir/borrow_check/flows.rs @@ -114,7 +114,7 @@ impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> { }; saw_one = true; let borrow_data = &self.borrows.operator().borrows()[borrow]; - s.push_str(&format!("{}", borrow_data)); + s.push_str(&borrow_data.to_string()); }); s.push_str("] "); @@ -126,7 +126,7 @@ impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> { }; saw_one = true; let borrow_data = &self.borrows.operator().borrows()[borrow]; - s.push_str(&format!("{}", borrow_data)); + s.push_str(&borrow_data.to_string()); }); s.push_str("] "); @@ -138,7 +138,7 @@ impl<'b, 'gcx, 'tcx> fmt::Display for Flows<'b, 'gcx, 'tcx> { }; saw_one = true; let move_path = &self.uninits.operator().move_data().move_paths[mpi_uninit]; - s.push_str(&format!("{}", move_path)); + s.push_str(&move_path.to_string()); }); s.push_str("] "); diff --git a/src/librustc_mir/borrow_check/move_errors.rs b/src/librustc_mir/borrow_check/move_errors.rs index 4aa38fb5f37..43f30225e9b 100644 --- a/src/librustc_mir/borrow_check/move_errors.rs +++ b/src/librustc_mir/borrow_check/move_errors.rs @@ -312,7 +312,7 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> { err.span_suggestion( span, "consider removing this dereference operator", - format!("{}", &snippet[1..]), + (&snippet[1..]).to_owned(), ); } _ => { diff --git a/src/librustc_traits/lowering.rs b/src/librustc_traits/lowering.rs index cf612585776..a3c24f8af22 100644 --- a/src/librustc_traits/lowering.rs +++ b/src/librustc_traits/lowering.rs @@ -523,7 +523,7 @@ impl<'a, 'tcx> ClauseDumper<'a, 'tcx> { Clause::Implies(program_clause) => program_clause, Clause::ForAll(program_clause) => program_clause.skip_binder(), }; - format!("{}", program_clause) + program_clause.to_string() }) .collect(); diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 2cfeb251392..4cde171f1bf 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -2838,7 +2838,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { ty::TyFnDef(..) => { let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx)); let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty); - variadic_error(tcx.sess, arg.span, arg_ty, &format!("{}", ptr_ty)); + variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string()); } _ => {} } diff --git a/src/librustc_typeck/outlives/mod.rs b/src/librustc_typeck/outlives/mod.rs index 5801a6ada3f..74ef62e0c63 100644 --- a/src/librustc_typeck/outlives/mod.rs +++ b/src/librustc_typeck/outlives/mod.rs @@ -54,9 +54,9 @@ fn inferred_outlives_of<'a, 'tcx>( let mut pred: Vec = predicates .iter() .map(|out_pred| match out_pred { - ty::Predicate::RegionOutlives(p) => format!("{}", &p), + ty::Predicate::RegionOutlives(p) => p.to_string(), - ty::Predicate::TypeOutlives(p) => format!("{}", &p), + ty::Predicate::TypeOutlives(p) => p.to_string(), err => bug!("unexpected predicate {:?}", err), }) diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 2377354b85f..bec34e1490c 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -207,7 +207,7 @@ impl<'a> fmt::Display for WhereClause<'a> { clause.push_str(" + "); } - clause.push_str(&format!("{}", lifetime)); + clause.push_str(&lifetime.to_string()); } } &clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => { @@ -460,10 +460,10 @@ fn resolved_path(w: &mut fmt::Formatter, did: DefId, path: &clean::Path, fqp[..fqp.len() - 1].join("::"), HRef::new(did, fqp.last().unwrap())) } - None => format!("{}", HRef::new(did, &last.name)), + None => HRef::new(did, &last.name).to_string(), } } else { - format!("{}", HRef::new(did, &last.name)) + HRef::new(did, &last.name).to_string() }; write!(w, "{}{}", path, last.args)?; } @@ -881,7 +881,7 @@ impl<'a> fmt::Display for Method<'a> { if f.alternate() { args.push_str(&format!("{:#}", input.type_)); } else { - args.push_str(&format!("{}", input.type_)); + args.push_str(&input.type_.to_string()); } args_plain.push_str(&format!("{:#}", input.type_)); } @@ -900,7 +900,7 @@ impl<'a> fmt::Display for Method<'a> { let arrow = if f.alternate() { format!("{:#}", decl.output) } else { - format!("{}", decl.output) + decl.output.to_string() }; let pad = repeat(" ").take(name_len).collect::(); diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 8040548ce6b..8d85adfb3d0 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -881,14 +881,14 @@ mod tests { #[test] fn issue_17736() { let markdown = "# title"; - format!("{}", Markdown(markdown, &[])); + Markdown(markdown, &[]).to_string(); reset_ids(true); } #[test] fn test_header() { fn t(input: &str, expect: &str) { - let output = format!("{}", Markdown(input, &[])); + let output = Markdown(input, &[]).to_string(); assert_eq!(output, expect, "original: {}", input); reset_ids(true); } @@ -910,7 +910,7 @@ mod tests { #[test] fn test_header_ids_multiple_blocks() { fn t(input: &str, expect: &str) { - let output = format!("{}", Markdown(input, &[])); + let output = Markdown(input, &[]).to_string(); assert_eq!(output, expect, "original: {}", input); } @@ -951,7 +951,7 @@ mod tests { #[test] fn test_markdown_html_escape() { fn t(input: &str, expect: &str) { - let output = format!("{}", MarkdownHtml(input)); + let output = MarkdownHtml(input).to_string(); assert_eq!(output, expect, "original: {}", input); } diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ade33c8dd7d..4dcec0a3af2 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -2059,7 +2059,7 @@ impl<'a> Item<'a> { }; let lines = if self.item.source.loline == self.item.source.hiline { - format!("{}", self.item.source.loline) + self.item.source.loline.to_string() } else { format!("{}-{}", self.item.source.loline, self.item.source.hiline) }; @@ -2235,7 +2235,7 @@ fn document_short(w: &mut fmt::Formatter, item: &clean::Item, link: AssocItemLin format!("{} [Read more]({})", &plain_summary_line(Some(s)), naive_assoc_href(item, link)) } else { - format!("{}", &plain_summary_line(Some(s))) + plain_summary_line(Some(s)).to_string() }; render_markdown(w, &markdown, item.links(), prefix)?; } else if !prefix.is_empty() { @@ -2732,7 +2732,7 @@ fn bounds(t_bounds: &[clean::GenericBound]) -> String { bounds.push_str(" + "); bounds_plain.push_str(" + "); } - bounds.push_str(&format!("{}", *p)); + bounds.push_str(&(*p).to_string()); bounds_plain.push_str(&format!("{:#}", *p)); } } @@ -3393,7 +3393,7 @@ fn render_attribute(attr: &ast::MetaItem) -> Option { let name = attr.name(); if attr.is_word() { - Some(format!("{}", name)) + Some(name.to_string()) } else if let Some(v) = attr.value_str() { Some(format!("{} = {:?}", name, v.as_str())) } else if let Some(values) = attr.meta_item_list() { @@ -3637,7 +3637,7 @@ fn render_assoc_items(w: &mut fmt::Formatter, } } - let impls = format!("{}", RendererStruct(cx, concrete, containing_item)); + let impls = RendererStruct(cx, concrete, containing_item).to_string(); if !impls.is_empty() { write!(w, "

    @@ -3740,7 +3740,7 @@ fn spotlight_decl(decl: &clean::FnDecl) -> Result { &format!("

    Important traits for {}

    \ ", impl_.for_)); - trait_.push_str(&format!("{}", impl_.for_)); + trait_.push_str(&impl_.for_.to_string()); } //use the "where" class here to make it small diff --git a/src/librustdoc/html/toc.rs b/src/librustdoc/html/toc.rs index f3379b33155..88ada5c7f7f 100644 --- a/src/librustdoc/html/toc.rs +++ b/src/librustdoc/html/toc.rs @@ -157,7 +157,7 @@ impl TocBuilder { sec_number.push_str("0."); } let number = toc.count_entries_with_level(level); - sec_number.push_str(&format!("{}", number + 1)) + sec_number.push_str(&(number + 1).to_string()) } self.chain.push(TocEntry { diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index bf7b025884d..36a8fc94dba 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -89,9 +89,9 @@ pub fn render(input: &Path, mut output: PathBuf, matches: &getopts::Matches, reset_ids(false); let text = if include_toc { - format!("{}", MarkdownWithToc(text)) + MarkdownWithToc(text).to_string() } else { - format!("{}", Markdown(text, &[])) + Markdown(text, &[]).to_string() }; let err = write!( diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 88cc9373113..b15321f4ba7 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -2094,7 +2094,7 @@ macro_rules! expect { match $e { Json::Null => Ok(()), other => Err(ExpectedError("Null".to_owned(), - format!("{}", other))) + other.to_string())) } }); ($e:expr, $t:ident) => ({ @@ -2102,7 +2102,7 @@ macro_rules! expect { Json::$t(v) => Ok(v), other => { Err(ExpectedError(stringify!($t).to_owned(), - format!("{}", other))) + other.to_string())) } } }) @@ -2114,14 +2114,14 @@ macro_rules! read_primitive { match self.pop() { Json::I64(f) => Ok(f as $ty), Json::U64(f) => Ok(f as $ty), - Json::F64(f) => Err(ExpectedError("Integer".to_owned(), format!("{}", f))), + Json::F64(f) => Err(ExpectedError("Integer".to_owned(), f.to_string())), // 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().ok() { Some(f) => Ok(f), None => Err(ExpectedError("Number".to_owned(), s)), }, - value => Err(ExpectedError("Number".to_owned(), format!("{}", value))), + value => Err(ExpectedError("Number".to_owned(), value.to_string())), } } } @@ -2163,7 +2163,7 @@ impl ::Decoder for Decoder { } }, Json::Null => Ok(f64::NAN), - value => Err(ExpectedError("Number".to_owned(), format!("{}", value))) + value => Err(ExpectedError("Number".to_owned(), value.to_string())) } } @@ -2181,7 +2181,7 @@ impl ::Decoder for Decoder { _ => () } } - Err(ExpectedError("single character string".to_owned(), format!("{}", s))) + Err(ExpectedError("single character string".to_owned(), s.to_string())) } fn read_str(&mut self) -> DecodeResult> { @@ -2204,7 +2204,7 @@ impl ::Decoder for Decoder { let n = match o.remove(&"variant".to_owned()) { Some(Json::String(s)) => s, Some(val) => { - return Err(ExpectedError("String".to_owned(), format!("{}", val))) + return Err(ExpectedError("String".to_owned(), val.to_string())) } None => { return Err(MissingFieldError("variant".to_owned())) @@ -2217,7 +2217,7 @@ impl ::Decoder for Decoder { } }, Some(val) => { - return Err(ExpectedError("Array".to_owned(), format!("{}", val))) + return Err(ExpectedError("Array".to_owned(), val.to_string())) } None => { return Err(MissingFieldError("fields".to_owned())) @@ -2226,7 +2226,7 @@ impl ::Decoder for Decoder { n } json => { - return Err(ExpectedError("String or Object".to_owned(), format!("{}", json))) + return Err(ExpectedError("String or Object".to_owned(), json.to_string())) } }; let idx = match names.iter().position(|n| *n == &name[..]) { @@ -2845,21 +2845,21 @@ mod tests { fn test_write_enum() { let animal = Dog; assert_eq!( - format!("{}", super::as_json(&animal)), + super::as_json(&animal).to_string(), "\"Dog\"" ); assert_eq!( - format!("{}", super::as_pretty_json(&animal)), + super::as_pretty_json(&animal).to_string(), "\"Dog\"" ); let animal = Frog("Henry".to_string(), 349); assert_eq!( - format!("{}", super::as_json(&animal)), + super::as_json(&animal).to_string(), "{\"variant\":\"Frog\",\"fields\":[\"Henry\",349]}" ); assert_eq!( - format!("{}", super::as_pretty_json(&animal)), + super::as_pretty_json(&animal).to_string(), "{\n \ \"variant\": \"Frog\",\n \ \"fields\": [\n \ @@ -2872,10 +2872,10 @@ mod tests { macro_rules! check_encoder_for_simple { ($value:expr, $expected:expr) => ({ - let s = format!("{}", super::as_json(&$value)); + let s = super::as_json(&$value).to_string(); assert_eq!(s, $expected); - let s = format!("{}", super::as_pretty_json(&$value)); + let s = super::as_pretty_json(&$value).to_string(); assert_eq!(s, $expected); }) } diff --git a/src/libstd/sys/redox/net/udp.rs b/src/libstd/sys/redox/net/udp.rs index 2ed67bd2836..22af02079e7 100644 --- a/src/libstd/sys/redox/net/udp.rs +++ b/src/libstd/sys/redox/net/udp.rs @@ -58,7 +58,7 @@ impl UdpSocket { pub fn recv(&self, buf: &mut [u8]) -> Result { if let Some(addr) = *self.get_conn() { - let from = self.0.dup(format!("{}", addr).as_bytes())?; + let from = self.0.dup(addr.to_string().as_bytes())?; from.read(buf) } else { Err(Error::new(ErrorKind::Other, "UdpSocket::recv not connected")) diff --git a/src/libstd/sys_common/wtf8.rs b/src/libstd/sys_common/wtf8.rs index bbb5980bd9d..45204b56ead 100644 --- a/src/libstd/sys_common/wtf8.rs +++ b/src/libstd/sys_common/wtf8.rs @@ -1245,7 +1245,7 @@ mod tests { #[test] fn wtf8_display() { fn d(b: &[u8]) -> String { - format!("{}", &unsafe { Wtf8::from_bytes_unchecked(b) }) + (&unsafe { Wtf8::from_bytes_unchecked(b) }).to_string() } assert_eq!("", d("".as_bytes())); diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index b84046d1050..9f8909e1626 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -380,7 +380,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { structs, enums and unions"); if let ast::AttrStyle::Inner = attr.style { let trait_list = traits.iter() - .map(|t| format!("{}", t)).collect::>(); + .map(|t| t.to_string()).collect::>(); let suggestion = format!("#[derive({})]", trait_list.join(", ")); err.span_suggestion_with_applicability( span, "try an outer attribute", suggestion, @@ -558,7 +558,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { invoc.expansion_data.mark.set_expn_info(ExpnInfo { call_site: attr.span, def_site: None, - format: MacroAttribute(Symbol::intern(&format!("{}", attr.path))), + format: MacroAttribute(Symbol::intern(&attr.path.to_string())), allow_internal_unstable: false, allow_internal_unsafe: false, local_inner_macros: false, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 64309dd9b8b..825ff7d181b 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -6320,7 +6320,7 @@ impl<'a> Parser<'a> { mod_name: mod_name.clone(), default_path: default_path_str, secondary_path: secondary_path_str, - dir_path: format!("{}", dir_path.display()), + dir_path: dir_path.display().to_string(), }), (true, true) => Err(Error::DuplicatePaths { mod_name: mod_name.clone(), diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index de68780ef2c..8e051c08de4 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -631,7 +631,7 @@ pub trait PrintState<'a> { self.writer().word(&ut.val_to_string(i)) } ast::LitIntType::Unsuffixed => { - self.writer().word(&format!("{}", i)) + self.writer().word(&i.to_string()) } } } diff --git a/src/libsyntax_ext/concat.rs b/src/libsyntax_ext/concat.rs index 99dba8af754..dcdd2c590e0 100644 --- a/src/libsyntax_ext/concat.rs +++ b/src/libsyntax_ext/concat.rs @@ -42,10 +42,10 @@ pub fn expand_syntax_ext( ast::LitKind::Int(i, ast::LitIntType::Unsigned(_)) | ast::LitKind::Int(i, ast::LitIntType::Signed(_)) | ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) => { - accumulator.push_str(&format!("{}", i)); + accumulator.push_str(&i.to_string()); } ast::LitKind::Bool(b) => { - accumulator.push_str(&format!("{}", b)); + accumulator.push_str(&b.to_string()); } ast::LitKind::Byte(..) | ast::LitKind::ByteStr(..) => { cx.span_err(e.span, "cannot concatenate a byte string literal"); diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index 0cdea64db8b..306b62f6697 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -189,7 +189,7 @@ pub fn parse(file: &mut io::Read, longnames: bool) -> Result { macro_rules! t( ($e:expr) => ( match $e { Ok(e) => e, - Err(e) => return Err(format!("{}", e)) + Err(e) => return Err(e.to_string()) } ) ); -- cgit 1.4.1-3-g733a5 From d3d31105e99f5265880d0f010436ed5c6baab034 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 6 Aug 2018 12:45:27 +0200 Subject: clarify partially initialized Mutex issues --- src/libstd/io/lazy.rs | 7 +++++++ src/libstd/sys/unix/args.rs | 3 +++ src/libstd/sys/unix/mutex.rs | 6 ++++-- src/libstd/sys/unix/os.rs | 3 +++ src/libstd/sys_common/at_exit_imp.rs | 6 ++++++ src/libstd/sys_common/mutex.rs | 4 ++++ src/libstd/sys_common/thread_local.rs | 3 +++ src/libstd/thread/mod.rs | 3 +++ 8 files changed, 33 insertions(+), 2 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs index d357966be92..09b2ddcbcac 100644 --- a/src/libstd/io/lazy.rs +++ b/src/libstd/io/lazy.rs @@ -27,6 +27,9 @@ unsafe impl Sync for Lazy {} impl Lazy { pub const fn new(init: fn() -> Arc) -> Lazy { + // `lock` is never initialized fully, so this mutex is reentrant! + // Do not use it in a way that might be reentrant, that could lead to + // aliasing `&mut`. Lazy { lock: Mutex::new(), ptr: Cell::new(ptr::null_mut()), @@ -48,6 +51,7 @@ impl Lazy { } } + // Must only be called with `lock` held unsafe fn init(&'static self) -> Arc { // If we successfully register an at exit handler, then we cache the // `Arc` allocation in our own internal box (it will get deallocated by @@ -60,6 +64,9 @@ impl Lazy { }; drop(Box::from_raw(ptr)) }); + // This could reentrantly call `init` again, which is a problem + // because our `lock` allows reentrancy! + // FIXME: Add argument why this is okay. let ret = (self.init)(); if registered.is_ok() { self.ptr.set(Box::into_raw(Box::new(ret.clone()))); diff --git a/src/libstd/sys/unix/args.rs b/src/libstd/sys/unix/args.rs index 7e32ec1347e..c91bd5b22af 100644 --- a/src/libstd/sys/unix/args.rs +++ b/src/libstd/sys/unix/args.rs @@ -80,6 +80,9 @@ mod imp { static mut ARGC: isize = 0; static mut ARGV: *const *const u8 = ptr::null(); + // `ENV_LOCK` is never initialized fully, so this mutex is reentrant! + // Do not use it in a way that might be reentrant, that could lead to + // aliasing `&mut`. static LOCK: Mutex = Mutex::new(); pub unsafe fn init(argc: isize, argv: *const *const u8) { diff --git a/src/libstd/sys/unix/mutex.rs b/src/libstd/sys/unix/mutex.rs index 52cf3f97c5c..f0711b60320 100644 --- a/src/libstd/sys/unix/mutex.rs +++ b/src/libstd/sys/unix/mutex.rs @@ -25,8 +25,10 @@ unsafe impl Sync for Mutex {} #[allow(dead_code)] // sys isn't exported yet impl Mutex { pub const fn new() -> Mutex { - // Might be moved and address is changing it is better to avoid - // initialization of potentially opaque OS data before it landed + // Might be moved to a different address, so it is better to avoid + // initialization of potentially opaque OS data before it landed. + // Be very careful using this newly constructed `Mutex`, it should + // be initialized by calling `init()` first! Mutex { inner: UnsafeCell::new(libc::PTHREAD_MUTEX_INITIALIZER) } } #[inline] diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 1d92e8fc97c..6ef9502ba62 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -33,6 +33,9 @@ use sys::fd; use vec; const TMPBUF_SZ: usize = 128; +// `ENV_LOCK` is never initialized fully, so this mutex is reentrant! +// Do not use it in a way that might be reentrant, that could lead to +// aliasing `&mut`. static ENV_LOCK: Mutex = Mutex::new(); diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index b28a4d2f8be..633605039af 100644 --- a/src/libstd/sys_common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs @@ -23,6 +23,9 @@ type Queue = Vec>; // on poisoning and this module needs to operate at a lower level than requiring // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). +// `LOCK` is never initialized fully, so this mutex is reentrant! +// Do not use it in a way that might be reentrant, that could lead to +// aliasing `&mut`. static LOCK: Mutex = Mutex::new(); static mut QUEUE: *mut Queue = ptr::null_mut(); @@ -72,6 +75,9 @@ pub fn push(f: Box) -> bool { unsafe { let _guard = LOCK.lock(); if init() { + // This could reentrantly call `push` again, which is a problem because + // `LOCK` allows reentrancy! + // FIXME: Add argument why this is okay. (*QUEUE).push(f); true } else { diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs index 608355b7d70..77a33e4c6be 100644 --- a/src/libstd/sys_common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs @@ -24,11 +24,15 @@ impl Mutex { /// /// Behavior is undefined if the mutex is moved after it is /// first used with any of the functions below. + /// Also, the mutex might not be fully functional without calling + /// `init`! For example, on unix, the mutex is reentrant + /// until `init` reconfigures it appropriately. pub const fn new() -> Mutex { Mutex(imp::Mutex::new()) } /// Prepare the mutex for use. /// /// This should be called once the mutex is at a stable memory address. + /// It must not be called concurrently with any other operation. #[inline] pub unsafe fn init(&mut self) { self.0.init() } diff --git a/src/libstd/sys_common/thread_local.rs b/src/libstd/sys_common/thread_local.rs index 75f6b9ac7fd..2cc5372e268 100644 --- a/src/libstd/sys_common/thread_local.rs +++ b/src/libstd/sys_common/thread_local.rs @@ -161,6 +161,9 @@ impl StaticKey { // Additionally a 0-index of a tls key hasn't been seen on windows, so // we just simplify the whole branch. if imp::requires_synchronized_create() { + // `INIT_LOCK` is never initialized fully, so this mutex is reentrant! + // Do not use it in a way that might be reentrant, that could lead to + // aliasing `&mut`. static INIT_LOCK: Mutex = Mutex::new(); let _guard = INIT_LOCK.lock(); let mut key = self.key.load(Ordering::SeqCst); diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index bbe80df7e8b..98b4ca36c26 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -940,6 +940,9 @@ pub struct ThreadId(u64); impl ThreadId { // Generate a new unique thread ID. fn new() -> ThreadId { + // `GUARD` is never initialized fully, so this mutex is reentrant! + // Do not use it in a way that might be reentrant, that could lead to + // aliasing `&mut`. static GUARD: mutex::Mutex = mutex::Mutex::new(); static mut COUNTER: u64 = 0; -- cgit 1.4.1-3-g733a5 From 819645bfc461af9c02aa60a3385b008f490ed164 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 6 Aug 2018 13:39:47 +0200 Subject: I think we have to strengthen Mutex::init UB --- src/libstd/sys_common/mutex.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs index 77a33e4c6be..a4efe4d128e 100644 --- a/src/libstd/sys_common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs @@ -32,7 +32,7 @@ impl Mutex { /// Prepare the mutex for use. /// /// This should be called once the mutex is at a stable memory address. - /// It must not be called concurrently with any other operation. + /// Behavior is undefined unless this is called before any other operation. #[inline] pub unsafe fn init(&mut self) { self.0.init() } -- cgit 1.4.1-3-g733a5 From ab3e4a27894295ec0fca28b492450f2b22fbad4e Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 6 Aug 2018 13:53:38 +0200 Subject: argue why at_exit_imp is fine --- src/libstd/sys_common/at_exit_imp.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index 633605039af..30019088eb6 100644 --- a/src/libstd/sys_common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs @@ -64,6 +64,7 @@ pub fn cleanup() { if !queue.is_null() { let queue: Box = Box::from_raw(queue); for to_run in *queue { + // We are not holding any lock, so reentrancy is fine. to_run(); } } @@ -75,9 +76,8 @@ pub fn push(f: Box) -> bool { unsafe { let _guard = LOCK.lock(); if init() { - // This could reentrantly call `push` again, which is a problem because - // `LOCK` allows reentrancy! - // FIXME: Add argument why this is okay. + // We are just moving `f` around, not calling it. + // There is no possibility of reentrancy here. (*QUEUE).push(f); true } else { -- cgit 1.4.1-3-g733a5 From 645388583ca47357a6a2e5878a9cde84e2e579d3 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Mon, 6 Aug 2018 14:39:55 +0200 Subject: actually, reentrant uninitialized mutex acquisition is outright UB --- src/libstd/io/lazy.rs | 5 ++--- src/libstd/sys/unix/args.rs | 5 ++--- src/libstd/sys/unix/os.rs | 5 ++--- src/libstd/sys_common/at_exit_imp.rs | 5 ++--- src/libstd/sys_common/mutex.rs | 6 +++--- src/libstd/sys_common/thread_local.rs | 5 ++--- src/libstd/thread/mod.rs | 5 ++--- 7 files changed, 15 insertions(+), 21 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs index 9513cc7fb2d..5743ea51af3 100644 --- a/src/libstd/io/lazy.rs +++ b/src/libstd/io/lazy.rs @@ -29,9 +29,8 @@ impl Lazy { /// Safety: `init` must not call `get` on the variable that is being /// initialized. pub const unsafe fn new(init: fn() -> Arc) -> Lazy { - // `lock` is never initialized fully, so this mutex is reentrant! - // Do not use it in a way that might be reentrant, that could lead to - // aliasing `&mut`. + // `lock` is never initialized fully, so it is UB to attempt to + // acquire this mutex reentrantly! Lazy { lock: Mutex::new(), ptr: Cell::new(ptr::null_mut()), diff --git a/src/libstd/sys/unix/args.rs b/src/libstd/sys/unix/args.rs index c91bd5b22af..220bd11b1f1 100644 --- a/src/libstd/sys/unix/args.rs +++ b/src/libstd/sys/unix/args.rs @@ -80,9 +80,8 @@ mod imp { static mut ARGC: isize = 0; static mut ARGV: *const *const u8 = ptr::null(); - // `ENV_LOCK` is never initialized fully, so this mutex is reentrant! - // Do not use it in a way that might be reentrant, that could lead to - // aliasing `&mut`. + // `ENV_LOCK` is never initialized fully, so it is UB to attempt to + // acquire this mutex reentrantly! static LOCK: Mutex = Mutex::new(); pub unsafe fn init(argc: isize, argv: *const *const u8) { diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 6ef9502ba62..3d98b2efdf1 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -33,9 +33,8 @@ use sys::fd; use vec; const TMPBUF_SZ: usize = 128; -// `ENV_LOCK` is never initialized fully, so this mutex is reentrant! -// Do not use it in a way that might be reentrant, that could lead to -// aliasing `&mut`. +// `ENV_LOCK` is never initialized fully, so it is UB to attempt to +// acquire this mutex reentrantly! static ENV_LOCK: Mutex = Mutex::new(); diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index 30019088eb6..85679837312 100644 --- a/src/libstd/sys_common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs @@ -23,9 +23,8 @@ type Queue = Vec>; // on poisoning and this module needs to operate at a lower level than requiring // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). -// `LOCK` is never initialized fully, so this mutex is reentrant! -// Do not use it in a way that might be reentrant, that could lead to -// aliasing `&mut`. +// `LOCK` is never initialized fully, so it is UB to attempt to +// acquire this mutex reentrantly! static LOCK: Mutex = Mutex::new(); static mut QUEUE: *mut Queue = ptr::null_mut(); diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs index a4efe4d128e..74e1defd9f4 100644 --- a/src/libstd/sys_common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs @@ -24,9 +24,9 @@ impl Mutex { /// /// Behavior is undefined if the mutex is moved after it is /// first used with any of the functions below. - /// Also, the mutex might not be fully functional without calling - /// `init`! For example, on unix, the mutex is reentrant - /// until `init` reconfigures it appropriately. + /// Also, until `init` is called, behavior is undefined if this + /// mutex is ever used reentrantly, i.e., `raw_lock` or `try_lock` + /// are called by the thread currently holding the lock. pub const fn new() -> Mutex { Mutex(imp::Mutex::new()) } /// Prepare the mutex for use. diff --git a/src/libstd/sys_common/thread_local.rs b/src/libstd/sys_common/thread_local.rs index 2cc5372e268..9db7d732698 100644 --- a/src/libstd/sys_common/thread_local.rs +++ b/src/libstd/sys_common/thread_local.rs @@ -161,9 +161,8 @@ impl StaticKey { // Additionally a 0-index of a tls key hasn't been seen on windows, so // we just simplify the whole branch. if imp::requires_synchronized_create() { - // `INIT_LOCK` is never initialized fully, so this mutex is reentrant! - // Do not use it in a way that might be reentrant, that could lead to - // aliasing `&mut`. + // `INIT_LOCK` is never initialized fully, so it is UB to attempt to + // acquire this mutex reentrantly! static INIT_LOCK: Mutex = Mutex::new(); let _guard = INIT_LOCK.lock(); let mut key = self.key.load(Ordering::SeqCst); diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 98b4ca36c26..0078a05e597 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -940,9 +940,8 @@ pub struct ThreadId(u64); impl ThreadId { // Generate a new unique thread ID. fn new() -> ThreadId { - // `GUARD` is never initialized fully, so this mutex is reentrant! - // Do not use it in a way that might be reentrant, that could lead to - // aliasing `&mut`. + // `GUARD` is never initialized fully, so it is UB to attempt to + // acquire this mutex reentrantly! static GUARD: mutex::Mutex = mutex::Mutex::new(); static mut COUNTER: u64 = 0; -- cgit 1.4.1-3-g733a5 From 31bec788f46c73ab14c72868dc6141141320a058 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Wed, 8 Aug 2018 18:12:33 +0200 Subject: avoid using the word 'initialized' to talk about that non-reentrant-capable state of the mutex --- src/libstd/io/lazy.rs | 3 +-- src/libstd/sys/unix/args.rs | 2 +- src/libstd/sys/unix/os.rs | 2 +- src/libstd/sys_common/at_exit_imp.rs | 2 +- src/libstd/sys_common/mutex.rs | 4 +++- src/libstd/sys_common/thread_local.rs | 2 +- src/libstd/thread/mod.rs | 2 +- 7 files changed, 9 insertions(+), 8 deletions(-) (limited to 'src/libstd/sys_common') diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs index 5743ea51af3..4fb367fb6ba 100644 --- a/src/libstd/io/lazy.rs +++ b/src/libstd/io/lazy.rs @@ -15,6 +15,7 @@ use sys_common; use sys_common::mutex::Mutex; pub struct Lazy { + // We never call `lock.init()`, so it is UB to attempt to acquire this mutex reentrantly! lock: Mutex, ptr: Cell<*mut Arc>, init: fn() -> Arc, @@ -29,8 +30,6 @@ impl Lazy { /// Safety: `init` must not call `get` on the variable that is being /// initialized. pub const unsafe fn new(init: fn() -> Arc) -> Lazy { - // `lock` is never initialized fully, so it is UB to attempt to - // acquire this mutex reentrantly! Lazy { lock: Mutex::new(), ptr: Cell::new(ptr::null_mut()), diff --git a/src/libstd/sys/unix/args.rs b/src/libstd/sys/unix/args.rs index 220bd11b1f1..c3c033dfbc7 100644 --- a/src/libstd/sys/unix/args.rs +++ b/src/libstd/sys/unix/args.rs @@ -80,7 +80,7 @@ mod imp { static mut ARGC: isize = 0; static mut ARGV: *const *const u8 = ptr::null(); - // `ENV_LOCK` is never initialized fully, so it is UB to attempt to + // We never call `ENV_LOCK.init()`, so it is UB to attempt to // acquire this mutex reentrantly! static LOCK: Mutex = Mutex::new(); diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 3d98b2efdf1..08c3e154978 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -33,7 +33,7 @@ use sys::fd; use vec; const TMPBUF_SZ: usize = 128; -// `ENV_LOCK` is never initialized fully, so it is UB to attempt to +// We never call `ENV_LOCK.init()`, so it is UB to attempt to // acquire this mutex reentrantly! static ENV_LOCK: Mutex = Mutex::new(); diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs index 85679837312..76e5df2c865 100644 --- a/src/libstd/sys_common/at_exit_imp.rs +++ b/src/libstd/sys_common/at_exit_imp.rs @@ -23,7 +23,7 @@ type Queue = Vec>; // on poisoning and this module needs to operate at a lower level than requiring // the thread infrastructure to be in place (useful on the borders of // initialization/destruction). -// `LOCK` is never initialized fully, so it is UB to attempt to +// We never call `LOCK.init()`, so it is UB to attempt to // acquire this mutex reentrantly! static LOCK: Mutex = Mutex::new(); static mut QUEUE: *mut Queue = ptr::null_mut(); diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs index 74e1defd9f4..c6d531c7a1a 100644 --- a/src/libstd/sys_common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs @@ -32,7 +32,9 @@ impl Mutex { /// Prepare the mutex for use. /// /// This should be called once the mutex is at a stable memory address. - /// Behavior is undefined unless this is called before any other operation. + /// If called, this must be the very first thing that happens to the mutex. + /// Calling it in parallel with or after any operation (including another + /// `init()`) is undefined behavior. #[inline] pub unsafe fn init(&mut self) { self.0.init() } diff --git a/src/libstd/sys_common/thread_local.rs b/src/libstd/sys_common/thread_local.rs index 9db7d732698..bb72cb0930a 100644 --- a/src/libstd/sys_common/thread_local.rs +++ b/src/libstd/sys_common/thread_local.rs @@ -161,7 +161,7 @@ impl StaticKey { // Additionally a 0-index of a tls key hasn't been seen on windows, so // we just simplify the whole branch. if imp::requires_synchronized_create() { - // `INIT_LOCK` is never initialized fully, so it is UB to attempt to + // We never call `INIT_LOCK.init()`, so it is UB to attempt to // acquire this mutex reentrantly! static INIT_LOCK: Mutex = Mutex::new(); let _guard = INIT_LOCK.lock(); diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 0078a05e597..61c6084a250 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -940,7 +940,7 @@ pub struct ThreadId(u64); impl ThreadId { // Generate a new unique thread ID. fn new() -> ThreadId { - // `GUARD` is never initialized fully, so it is UB to attempt to + // We never call `GUARD.init()`, so it is UB to attempt to // acquire this mutex reentrantly! static GUARD: mutex::Mutex = mutex::Mutex::new(); static mut COUNTER: u64 = 0; -- cgit 1.4.1-3-g733a5