From 8c4129cd9ae079fc010b8e3d73a72659b2f0a986 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Tue, 4 Dec 2018 10:21:42 +0100 Subject: cleanup: remove static lifetimes from consts in libstd --- src/libstd/sys/cloudabi/shims/env.rs | 14 +- src/libstd/sys/redox/env.rs | 14 +- src/libstd/sys/redox/path.rs | 2 +- src/libstd/sys/redox/process.rs | 2 +- src/libstd/sys/unix/env.rs | 224 ++++++++++++++-------------- src/libstd/sys/unix/path.rs | 2 +- src/libstd/sys/unix/process/process_unix.rs | 2 +- src/libstd/sys/wasm/env.rs | 14 +- src/libstd/sys/wasm/path.rs | 2 +- src/libstd/sys/windows/env.rs | 14 +- src/libstd/sys/windows/os.rs | 4 +- src/libstd/sys/windows/path.rs | 2 +- 12 files changed, 148 insertions(+), 148 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/cloudabi/shims/env.rs b/src/libstd/sys/cloudabi/shims/env.rs index 31777aa94bc..c7691e3b2df 100644 --- a/src/libstd/sys/cloudabi/shims/env.rs +++ b/src/libstd/sys/cloudabi/shims/env.rs @@ -9,11 +9,11 @@ // except according to those terms. pub mod os { - pub const FAMILY: &'static str = "cloudabi"; - pub const OS: &'static str = "cloudabi"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "cloudabi"; + pub const OS: &str = "cloudabi"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } diff --git a/src/libstd/sys/redox/env.rs b/src/libstd/sys/redox/env.rs index 669b7520df8..75e35046fb7 100644 --- a/src/libstd/sys/redox/env.rs +++ b/src/libstd/sys/redox/env.rs @@ -9,11 +9,11 @@ // except according to those terms. pub mod os { - pub const FAMILY: &'static str = "redox"; - pub const OS: &'static str = "redox"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "redox"; + pub const OS: &str = "redox"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } diff --git a/src/libstd/sys/redox/path.rs b/src/libstd/sys/redox/path.rs index e6a267dd5d9..b1a4ed30404 100644 --- a/src/libstd/sys/redox/path.rs +++ b/src/libstd/sys/redox/path.rs @@ -35,5 +35,5 @@ pub fn parse_prefix(path: &OsStr) -> Option { } } -pub const MAIN_SEP_STR: &'static str = "/"; +pub const MAIN_SEP_STR: &str = "/"; pub const MAIN_SEP: char = '/'; diff --git a/src/libstd/sys/redox/process.rs b/src/libstd/sys/redox/process.rs index 4370c1e0502..8f6d83c544a 100644 --- a/src/libstd/sys/redox/process.rs +++ b/src/libstd/sys/redox/process.rs @@ -143,7 +143,7 @@ impl Command { pub fn spawn(&mut self, default: Stdio, needs_stdin: bool) -> io::Result<(Process, StdioPipes)> { - const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX"; + const CLOEXEC_MSG_FOOTER: &[u8] = b"NOEX"; if self.saw_nul { return Err(io::Error::new(ErrorKind::InvalidInput, diff --git a/src/libstd/sys/unix/env.rs b/src/libstd/sys/unix/env.rs index ad116c57f55..1b6838f0295 100644 --- a/src/libstd/sys/unix/env.rs +++ b/src/libstd/sys/unix/env.rs @@ -10,176 +10,176 @@ #[cfg(target_os = "linux")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "linux"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "linux"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "macos")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "macos"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".dylib"; - pub const DLL_EXTENSION: &'static str = "dylib"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "macos"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".dylib"; + pub const DLL_EXTENSION: &str = "dylib"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "ios")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "ios"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".dylib"; - pub const DLL_EXTENSION: &'static str = "dylib"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "ios"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".dylib"; + pub const DLL_EXTENSION: &str = "dylib"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "freebsd")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "freebsd"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "freebsd"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "dragonfly")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "dragonfly"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "dragonfly"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "bitrig")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "bitrig"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "bitrig"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "netbsd")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "netbsd"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "netbsd"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "openbsd")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "openbsd"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "openbsd"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "android")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "android"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "android"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "solaris")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "solaris"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "solaris"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "haiku")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "haiku"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "haiku"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(all(target_os = "emscripten", target_arch = "asmjs"))] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "emscripten"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ".js"; - pub const EXE_EXTENSION: &'static str = "js"; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "emscripten"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ".js"; + pub const EXE_EXTENSION: &str = "js"; } #[cfg(all(target_os = "emscripten", target_arch = "wasm32"))] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "emscripten"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ".js"; - pub const EXE_EXTENSION: &'static str = "js"; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "emscripten"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ".js"; + pub const EXE_EXTENSION: &str = "js"; } #[cfg(target_os = "fuchsia")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "fuchsia"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "fuchsia"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "l4re")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "l4re"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "l4re"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } #[cfg(target_os = "hermit")] pub mod os { - pub const FAMILY: &'static str = "unix"; - pub const OS: &'static str = "hermit"; - pub const DLL_PREFIX: &'static str = "lib"; - pub const DLL_SUFFIX: &'static str = ".so"; - pub const DLL_EXTENSION: &'static str = "so"; - pub const EXE_SUFFIX: &'static str = ""; - pub const EXE_EXTENSION: &'static str = ""; + pub const FAMILY: &str = "unix"; + pub const OS: &str = "hermit"; + pub const DLL_PREFIX: &str = "lib"; + pub const DLL_SUFFIX: &str = ".so"; + pub const DLL_EXTENSION: &str = "so"; + pub const EXE_SUFFIX: &str = ""; + pub const EXE_EXTENSION: &str = ""; } diff --git a/src/libstd/sys/unix/path.rs b/src/libstd/sys/unix/path.rs index bf9af7a4353..834b4b448dc 100644 --- a/src/libstd/sys/unix/path.rs +++ b/src/libstd/sys/unix/path.rs @@ -25,5 +25,5 @@ pub fn parse_prefix(_: &OsStr) -> Option { None } -pub const MAIN_SEP_STR: &'static str = "/"; +pub const MAIN_SEP_STR: &str = "/"; pub const MAIN_SEP: char = '/'; diff --git a/src/libstd/sys/unix/process/process_unix.rs b/src/libstd/sys/unix/process/process_unix.rs index bfbf12f34ee..3248f424460 100644 --- a/src/libstd/sys/unix/process/process_unix.rs +++ b/src/libstd/sys/unix/process/process_unix.rs @@ -22,7 +22,7 @@ use sys; impl Command { pub fn spawn(&mut self, default: Stdio, needs_stdin: bool) -> io::Result<(Process, StdioPipes)> { - const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX"; + const CLOEXEC_MSG_FOOTER: &[u8] = b"NOEX"; let envp = self.capture_env(); diff --git a/src/libstd/sys/wasm/env.rs b/src/libstd/sys/wasm/env.rs index 1422042bd02..09235a944ee 100644 --- a/src/libstd/sys/wasm/env.rs +++ b/src/libstd/sys/wasm/env.rs @@ -9,11 +9,11 @@ // except according to those terms. pub mod os { - pub const FAMILY: &'static str = ""; - pub const OS: &'static str = ""; - pub const DLL_PREFIX: &'static str = ""; - pub const DLL_SUFFIX: &'static str = ".wasm"; - pub const DLL_EXTENSION: &'static str = "wasm"; - pub const EXE_SUFFIX: &'static str = ".wasm"; - pub const EXE_EXTENSION: &'static str = "wasm"; + pub const FAMILY: &str = ""; + pub const OS: &str = ""; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ".wasm"; + pub const DLL_EXTENSION: &str = "wasm"; + pub const EXE_SUFFIX: &str = ".wasm"; + pub const EXE_EXTENSION: &str = "wasm"; } diff --git a/src/libstd/sys/wasm/path.rs b/src/libstd/sys/wasm/path.rs index 395b8c1e40e..fcc9d617a87 100644 --- a/src/libstd/sys/wasm/path.rs +++ b/src/libstd/sys/wasm/path.rs @@ -25,5 +25,5 @@ pub fn parse_prefix(_: &OsStr) -> Option { None } -pub const MAIN_SEP_STR: &'static str = "/"; +pub const MAIN_SEP_STR: &str = "/"; pub const MAIN_SEP: char = '/'; diff --git a/src/libstd/sys/windows/env.rs b/src/libstd/sys/windows/env.rs index e6d74895774..4523df04f24 100644 --- a/src/libstd/sys/windows/env.rs +++ b/src/libstd/sys/windows/env.rs @@ -9,11 +9,11 @@ // except according to those terms. pub mod os { - pub const FAMILY: &'static str = "windows"; - pub const OS: &'static str = "windows"; - pub const DLL_PREFIX: &'static str = ""; - pub const DLL_SUFFIX: &'static str = ".dll"; - pub const DLL_EXTENSION: &'static str = "dll"; - pub const EXE_SUFFIX: &'static str = ".exe"; - pub const EXE_EXTENSION: &'static str = "exe"; + pub const FAMILY: &str = "windows"; + pub const OS: &str = "windows"; + pub const DLL_PREFIX: &str = ""; + pub const DLL_SUFFIX: &str = ".dll"; + pub const DLL_EXTENSION: &str = "dll"; + pub const EXE_SUFFIX: &str = ".exe"; + pub const EXE_EXTENSION: &str = "exe"; } diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index 29ea82c2053..4d7b7236c59 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -48,8 +48,8 @@ pub fn error_string(mut errnum: i32) -> String { // `[MS-ERREF]`: https://msdn.microsoft.com/en-us/library/cc231198.aspx if (errnum & c::FACILITY_NT_BIT as i32) != 0 { // format according to https://support.microsoft.com/en-us/help/259693 - const NTDLL_DLL: &'static [u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, - '.' as _, 'D' as _, 'L' as _, 'L' as _, 0]; + const NTDLL_DLL: &[u16] = &['N' as _, 'T' as _, 'D' as _, 'L' as _, 'L' as _, + '.' as _, 'D' as _, 'L' as _, 'L' as _, 0]; module = c::GetModuleHandleW(NTDLL_DLL.as_ptr()); if module != ptr::null_mut() { diff --git a/src/libstd/sys/windows/path.rs b/src/libstd/sys/windows/path.rs index 98d62a0c953..c5524a74d83 100644 --- a/src/libstd/sys/windows/path.rs +++ b/src/libstd/sys/windows/path.rs @@ -102,5 +102,5 @@ pub fn parse_prefix<'a>(path: &'a OsStr) -> Option { } } -pub const MAIN_SEP_STR: &'static str = "\\"; +pub const MAIN_SEP_STR: &str = "\\"; pub const MAIN_SEP: char = '\\'; -- cgit 1.4.1-3-g733a5 From 9012af6f19d999869824e3b933de5f7b30986877 Mon Sep 17 00:00:00 2001 From: Corey Farwell Date: Tue, 20 Nov 2018 23:01:56 -0500 Subject: Utilize `?` instead of `return None`. --- src/libcore/str/mod.rs | 7 +++---- src/librustc/middle/region.rs | 5 +---- src/librustc/session/search_paths.rs | 11 +++++------ src/librustc_incremental/persist/work_product.rs | 8 ++------ src/librustc_mir/borrow_check/prefixes.rs | 5 +---- src/librustdoc/clean/mod.rs | 10 ++-------- src/librustdoc/html/render.rs | 8 ++++---- src/libstd/sys/windows/path.rs | 5 +---- src/test/run-pass/impl-trait/example-calendar.rs | 5 +---- src/tools/compiletest/src/errors.rs | 5 +---- src/tools/compiletest/src/header.rs | 20 ++++---------------- src/tools/linkchecker/main.rs | 5 +---- 12 files changed, 26 insertions(+), 68 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index a2782dd8e2e..71aec7126e0 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -536,10 +536,9 @@ fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option where I: DoubleEndedIterator, { // Decode UTF-8 - let w = match bytes.next_back() { - None => return None, - Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32), - Some(&back_byte) => back_byte, + let w = match *bytes.next_back()? { + next_byte if next_byte < 128 => return Some(next_byte as u32), + back_byte => back_byte, }; // Multibyte case follows diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index d00fbdeca21..774b5f0ab11 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -592,10 +592,7 @@ impl<'tcx> ScopeTree { return Some(scope.item_local_id()); } - match self.opt_encl_scope(scope) { - None => return None, - Some(parent) => scope = parent, - } + scope = self.opt_encl_scope(scope)?; } } diff --git a/src/librustc/session/search_paths.rs b/src/librustc/session/search_paths.rs index 768d4f1e5fb..6b0a8a0af2b 100644 --- a/src/librustc/session/search_paths.rs +++ b/src/librustc/session/search_paths.rs @@ -67,14 +67,13 @@ impl<'a> Iterator for Iter<'a> { fn next(&mut self) -> Option<(&'a Path, PathKind)> { loop { - match self.iter.next() { - Some(&(kind, ref p)) if self.kind == PathKind::All || - kind == PathKind::All || - kind == self.kind => { + match *self.iter.next()? { + (kind, ref p) if self.kind == PathKind::All || + kind == PathKind::All || + kind == self.kind => { return Some((p, kind)) } - Some(..) => {} - None => return None, + _ => {} } } } diff --git a/src/librustc_incremental/persist/work_product.rs b/src/librustc_incremental/persist/work_product.rs index cfe59b1f672..ddd28eb5393 100644 --- a/src/librustc_incremental/persist/work_product.rs +++ b/src/librustc_incremental/persist/work_product.rs @@ -29,7 +29,7 @@ pub fn copy_cgu_workproducts_to_incr_comp_cache_dir( return None } - let saved_files: Option> = + let saved_files = files.iter() .map(|&(kind, ref path)| { let extension = match kind { @@ -51,11 +51,7 @@ pub fn copy_cgu_workproducts_to_incr_comp_cache_dir( } } }) - .collect(); - let saved_files = match saved_files { - None => return None, - Some(v) => v, - }; + .collect::>>()?; let work_product = WorkProduct { cgu_name: cgu_name.to_string(), diff --git a/src/librustc_mir/borrow_check/prefixes.rs b/src/librustc_mir/borrow_check/prefixes.rs index f73e08eb135..7d583b4f541 100644 --- a/src/librustc_mir/borrow_check/prefixes.rs +++ b/src/librustc_mir/borrow_check/prefixes.rs @@ -87,10 +87,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { impl<'cx, 'gcx, 'tcx> Iterator for Prefixes<'cx, 'gcx, 'tcx> { type Item = &'cx Place<'tcx>; fn next(&mut self) -> Option { - let mut cursor = match self.next { - None => return None, - Some(place) => place, - }; + let mut cursor = self.next?; // Post-processing `place`: Enqueue any remaining // work. Also, `place` may not be a prefix itself, but diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 88240e844ed..fa879e6309c 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -3923,10 +3923,7 @@ pub fn path_to_def_local(tcx: &TyCtxt, path: &[&str]) -> Option { let mut path_it = path.iter().peekable(); loop { - let segment = match path_it.next() { - Some(segment) => segment, - None => return None, - }; + let segment = path_it.next()?; for item_id in mem::replace(&mut items, HirVec::new()).iter() { let item = tcx.hir.expect_item(item_id.id); @@ -3961,10 +3958,7 @@ pub fn path_to_def(tcx: &TyCtxt, path: &[&str]) -> Option { let mut path_it = path.iter().skip(1).peekable(); loop { - let segment = match path_it.next() { - Some(segment) => segment, - None => return None, - }; + let segment = path_it.next()?; for item in mem::replace(&mut items, Lrc::new(vec![])).iter() { if item.ident.name == *segment { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 8b35ede4a02..07ff8791c34 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -2079,13 +2079,13 @@ impl<'a> Item<'a> { return None; } } else { - let (krate, src_root) = match cache.extern_locations.get(&self.item.def_id.krate) { - Some(&(ref name, ref src, Local)) => (name, src), - Some(&(ref name, ref src, Remote(ref s))) => { + let (krate, src_root) = match *cache.extern_locations.get(&self.item.def_id.krate)? { + (ref name, ref src, Local) => (name, src), + (ref name, ref src, Remote(ref s)) => { root = s.to_string(); (name, src) } - Some(&(_, _, Unknown)) | None => return None, + (_, _, Unknown) => return None, }; clean_srcpath(&src_root, file, false, |component| { diff --git a/src/libstd/sys/windows/path.rs b/src/libstd/sys/windows/path.rs index 98d62a0c953..ff910a50226 100644 --- a/src/libstd/sys/windows/path.rs +++ b/src/libstd/sys/windows/path.rs @@ -91,10 +91,7 @@ pub fn parse_prefix<'a>(path: &'a OsStr) -> Option { } fn parse_two_comps(mut path: &[u8], f: fn(u8) -> bool) -> Option<(&[u8], &[u8])> { - let first = match path.iter().position(|x| f(*x)) { - None => return None, - Some(x) => &path[..x], - }; + let first = &path[..path.iter().position(|x| f(*x))?]; path = &path[(first.len() + 1)..]; let idx = path.iter().position(|x| f(*x)); let second = &path[..idx.unwrap_or(path.len())]; diff --git a/src/test/run-pass/impl-trait/example-calendar.rs b/src/test/run-pass/impl-trait/example-calendar.rs index 6cf06d15621..42a94fca36c 100644 --- a/src/test/run-pass/impl-trait/example-calendar.rs +++ b/src/test/run-pass/impl-trait/example-calendar.rs @@ -753,10 +753,7 @@ where It: Iterator { type Item = Vec; fn next(&mut self) -> Option> { - let first = match self.it.next() { - Some(e) => e, - None => return None - }; + let first = self.it.next()?; let mut result = Vec::with_capacity(self.n); result.push(first); diff --git a/src/tools/compiletest/src/errors.rs b/src/tools/compiletest/src/errors.rs index dd2e5557c16..8d20a9e2717 100644 --- a/src/tools/compiletest/src/errors.rs +++ b/src/tools/compiletest/src/errors.rs @@ -119,10 +119,7 @@ fn parse_expected( line: &str, tag: &str, ) -> Option<(WhichLine, Error)> { - let start = match line.find(tag) { - Some(i) => i, - None => return None, - }; + let start = line.find(tag)?; let (follow, adjusts) = if line[start + tag.len()..].chars().next().unwrap() == '|' { (true, 0) } else { diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 06eeef61a19..eeb3f5e6f44 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -684,14 +684,8 @@ impl Config { fn parse_custom_normalization(&self, mut line: &str, prefix: &str) -> Option<(String, String)> { if self.parse_cfg_name_directive(line, prefix) == ParsedNameDirective::Match { - let from = match parse_normalization_string(&mut line) { - Some(s) => s, - None => return None, - }; - let to = match parse_normalization_string(&mut line) { - Some(s) => s, - None => return None, - }; + let from = parse_normalization_string(&mut line)?; + let to = parse_normalization_string(&mut line)?; Some((from, to)) } else { None @@ -850,14 +844,8 @@ fn expand_variables(mut value: String, config: &Config) -> String { /// ``` fn parse_normalization_string(line: &mut &str) -> Option { // FIXME support escapes in strings. - let begin = match line.find('"') { - Some(i) => i + 1, - None => return None, - }; - let end = match line[begin..].find('"') { - Some(i) => i + begin, - None => return None, - }; + let begin = line.find('"')? + 1; + let end = line[begin..].find('"')? + begin; let result = line[begin..end].to_owned(); *line = &line[end + 1..]; Some(result) diff --git a/src/tools/linkchecker/main.rs b/src/tools/linkchecker/main.rs index 41ad4e7180e..89930923335 100644 --- a/src/tools/linkchecker/main.rs +++ b/src/tools/linkchecker/main.rs @@ -332,10 +332,7 @@ fn maybe_redirect(source: &str) -> Option { const REDIRECT: &'static str = "

Redirecting to = (0..i + 1).collect(); + let expected: Vec<_> = (0..=i).collect(); assert_eq!(left, &expected[..]); assert_eq!(right, []); } @@ -869,7 +869,7 @@ fn test_as_slices() { for j in -last..0 { ring.push_front(j); let (left, right) = ring.as_slices(); - let expected_left: Vec<_> = (-last..j + 1).rev().collect(); + let expected_left: Vec<_> = (-last..=j).rev().collect(); let expected_right: Vec<_> = (0..first).collect(); assert_eq!(left, &expected_left[..]); assert_eq!(right, &expected_right[..]); @@ -889,7 +889,7 @@ fn test_as_mut_slices() { ring.push_back(i); let (left, right) = ring.as_mut_slices(); - let expected: Vec<_> = (0..i + 1).collect(); + let expected: Vec<_> = (0..=i).collect(); assert_eq!(left, &expected[..]); assert_eq!(right, []); } @@ -897,7 +897,7 @@ fn test_as_mut_slices() { for j in -last..0 { ring.push_front(j); let (left, right) = ring.as_mut_slices(); - let expected_left: Vec<_> = (-last..j + 1).rev().collect(); + let expected_left: Vec<_> = (-last..=j).rev().collect(); let expected_right: Vec<_> = (0..first).collect(); assert_eq!(left, &expected_left[..]); assert_eq!(right, &expected_right[..]); diff --git a/src/librustc/hir/map/hir_id_validator.rs b/src/librustc/hir/map/hir_id_validator.rs index ac4119dc372..58d1a780f12 100644 --- a/src/librustc/hir/map/hir_id_validator.rs +++ b/src/librustc/hir/map/hir_id_validator.rs @@ -100,7 +100,7 @@ impl<'a, 'hir: 'a> HirIdValidator<'a, 'hir> { if max != self.hir_ids_seen.len() - 1 { // Collect the missing ItemLocalIds - let missing: Vec<_> = (0 .. max as u32 + 1) + let missing: Vec<_> = (0 ..= max as u32) .filter(|&i| !self.hir_ids_seen.contains_key(&ItemLocalId::from_u32(i))) .collect(); diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index 368f83eb611..9028d3f4480 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -339,7 +339,7 @@ impl<'tcx> Mir<'tcx> { #[inline] pub fn args_iter(&self) -> impl Iterator { let arg_count = self.arg_count; - (1..arg_count + 1).map(Local::new) + (1..=arg_count).map(Local::new) } /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all diff --git a/src/librustc_apfloat/ieee.rs b/src/librustc_apfloat/ieee.rs index adcb9857ee3..2ad83fc93ef 100644 --- a/src/librustc_apfloat/ieee.rs +++ b/src/librustc_apfloat/ieee.rs @@ -571,7 +571,7 @@ impl fmt::Display for IeeeFloat { } // Fill with zeros up to precision. if !truncate_zero && precision > digits - 1 { - for _ in 0..precision - digits + 1 { + for _ in 0..=precision - digits { f.write_char('0')?; } } @@ -1969,7 +1969,7 @@ impl IeeeFloat { // in a Limb. When this would overflow do we do a single // bignum multiplication, and then revert again to multiplication // in a Limb. - let mut chars = s[first_sig_digit..last_sig_digit + 1].chars(); + let mut chars = s[first_sig_digit..=last_sig_digit].chars(); loop { let mut val = 0; let mut multiplier = 1; diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index 7e69e98071d..aa8b53ff375 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -549,7 +549,7 @@ impl EmitterWriter { // 3 | // 4 | } // | - for pos in 0..line_len + 1 { + for pos in 0..=line_len { draw_col_separator(buffer, line_offset + pos + 1, width_offset - 2); buffer.putc(line_offset + pos + 1, width_offset - 2, @@ -617,7 +617,7 @@ impl EmitterWriter { let pos = pos + 1; if pos > 1 && (annotation.has_label() || annotation.takes_space()) { - for p in line_offset + 1..line_offset + pos + 1 { + for p in line_offset + 1..=line_offset + pos { buffer.putc(p, code_offset + annotation.start_col, '|', @@ -634,7 +634,7 @@ impl EmitterWriter { } } AnnotationType::MultilineEnd(depth) => { - for p in line_offset..line_offset + pos + 1 { + for p in line_offset..=line_offset + pos { buffer.putc(p, width_offset + depth - 1, '|', diff --git a/src/librustc_incremental/persist/fs.rs b/src/librustc_incremental/persist/fs.rs index 75cdefaf49f..ed1176d04ea 100644 --- a/src/librustc_incremental/persist/fs.rs +++ b/src/librustc_incremental/persist/fs.rs @@ -354,7 +354,7 @@ pub fn finalize_session_directory(sess: &Session, svh: Svh) { } // State: "s-{timestamp}-{random-number}-" - let mut new_sub_dir_name = String::from(&old_sub_dir_name[.. dash_indices[2] + 1]); + let mut new_sub_dir_name = String::from(&old_sub_dir_name[..= dash_indices[2]]); // Append the svh base_n::push_str(svh.as_u64() as u128, INT_ENCODE_BASE, &mut new_sub_dir_name); 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 69e2c896d33..c7512f4b67f 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/values.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/values.rs @@ -48,7 +48,7 @@ impl RegionValueElements { let mut basic_blocks = IndexVec::with_capacity(num_points); for (bb, bb_data) in mir.basic_blocks().iter_enumerated() { - basic_blocks.extend((0..bb_data.statements.len() + 1).map(|_| bb)); + basic_blocks.extend((0..=bb_data.statements.len()).map(|_| bb)); } Self { diff --git a/src/librustc_mir/build/matches/mod.rs b/src/librustc_mir/build/matches/mod.rs index 342aaf9039d..172ff95ed10 100644 --- a/src/librustc_mir/build/matches/mod.rs +++ b/src/librustc_mir/build/matches/mod.rs @@ -101,7 +101,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { // create binding start block for link them by false edges let candidate_count = arms.iter().fold(0, |ac, c| ac + c.patterns.len()); - let pre_binding_blocks: Vec<_> = (0..candidate_count + 1) + let pre_binding_blocks: Vec<_> = (0..=candidate_count) .map(|_| self.cfg.start_new_block()) .collect(); diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index fdac1e3b816..5597c679a59 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -3614,7 +3614,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { let res = self.smart_resolve_path_fragment( id, None, - &path[..qself.position + 1], + &path[..=qself.position], span, PathSource::TraitItem(ns), CrateLint::QPathTrait { diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 2c4ddf38e98..c2c67c0bbc0 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -4796,7 +4796,7 @@ impl<'a> fmt::Display for Source<'a> { tmp /= 10; } write!(fmt, "

")?;
-        for i in 1..lines + 1 {
+        for i in 1..=lines {
             write!(fmt, "{0:1$}\n", i, cols)?;
         }
         write!(fmt, "
")?; diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 536ce2e16a0..1eea920c623 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -3610,7 +3610,7 @@ mod test_map { for i in 1..1001 { assert!(m.insert(i, i).is_none()); - for j in 1..i + 1 { + for j in 1..=i { let r = m.get(&j); assert_eq!(r, Some(&j)); } @@ -3629,7 +3629,7 @@ mod test_map { for i in 1..1001 { assert!(m.remove(&i).is_some()); - for j in 1..i + 1 { + for j in 1..=i { assert!(!m.contains_key(&j)); } diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 476ee3f71ca..7ede050da6c 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -918,7 +918,7 @@ impl Write for LineWriter { // some data then we *must* report that we wrote that data, so future // errors are ignored. We set our internal `need_flush` flag, though, in // case flushing fails and we need to try it first next time. - let n = self.inner.write(&buf[..i + 1])?; + let n = self.inner.write(&buf[..=i])?; self.need_flush = true; if self.flush().is_err() || n != i + 1 { return Ok(n) diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 076524e624a..dc97701d889 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -1261,7 +1261,7 @@ fn read_until(r: &mut R, delim: u8, buf: &mut Vec) }; match memchr::memchr(delim, available) { Some(i) => { - buf.extend_from_slice(&available[..i + 1]); + buf.extend_from_slice(&available[..=i]); (true, i + 1) } None => { diff --git a/src/libstd/sys/windows/process.rs b/src/libstd/sys/windows/process.rs index ff1ee0d26fe..03c1bb54af8 100644 --- a/src/libstd/sys/windows/process.rs +++ b/src/libstd/sys/windows/process.rs @@ -487,7 +487,7 @@ fn make_command_line(prog: &OsStr, args: &[OsString]) -> io::Result> { } else { if x == '"' as u16 { // Add n+1 backslashes to total 2n+1 before internal '"'. - cmd.extend((0..(backslashes + 1)).map(|_| '\\' as u16)); + cmd.extend((0..=backslashes).map(|_| '\\' as u16)); } backslashes = 0; } diff --git a/src/libsyntax/util/lev_distance.rs b/src/libsyntax/util/lev_distance.rs index feee2422cb6..283d28ca6c6 100644 --- a/src/libsyntax/util/lev_distance.rs +++ b/src/libsyntax/util/lev_distance.rs @@ -20,7 +20,7 @@ pub fn lev_distance(a: &str, b: &str) -> usize { return a.chars().count(); } - let mut dcol: Vec<_> = (0..b.len() + 1).collect(); + let mut dcol: Vec<_> = (0..=b.len()).collect(); let mut t_last = 0; for (i, sc) in a.chars().enumerate() { -- cgit 1.4.1-3-g733a5 From 3512fb046799fe02555b12d1e180d0ef83aba849 Mon Sep 17 00:00:00 2001 From: John-John Tedro Date: Wed, 5 Dec 2018 02:48:18 +0100 Subject: Avoid extra copy and syscall in std::env::current_exe --- src/libstd/sys/unix/os.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index b387a8d59a5..03e81a720dc 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -283,11 +283,14 @@ pub fn current_exe() -> io::Result { #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))] pub fn current_exe() -> io::Result { - let selfexe = PathBuf::from("/proc/self/exe"); - if selfexe.exists() { - ::fs::read_link(selfexe) - } else { - Err(io::Error::new(io::ErrorKind::Other, "no /proc/self/exe available. Is /proc mounted?")) + match ::fs::read_link("/proc/self/exe") { + Err(ref e) if e.kind() == io::ErrorKind::NotFound => { + Err(io::Error::new( + io::ErrorKind::Other, + "no /proc/self/exe available. Is /proc mounted?" + )) + }, + other => other, } } -- cgit 1.4.1-3-g733a5 From 030b1ed7f709539f5ca422758e9fe00d173aee76 Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Mon, 27 Aug 2018 09:57:51 -0700 Subject: Refactor stderr_prints_nothing into a more modular function --- src/libstd/panicking.rs | 26 +++++++++++--------------- 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/stdio.rs | 8 ++++++-- src/libstd/sys/windows/stdio.rs | 4 ++-- src/libstd/sys_common/util.rs | 7 +++---- 7 files changed, 28 insertions(+), 29 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/panicking.rs b/src/libstd/panicking.rs index 4930d356608..b70d56f9e59 100644 --- a/src/libstd/panicking.rs +++ b/src/libstd/panicking.rs @@ -29,7 +29,7 @@ use intrinsics; use mem; use ptr; use raw; -use sys::stdio::{Stderr, stderr_prints_nothing}; +use sys::stdio::panic_output; use sys_common::rwlock::RWLock; use sys_common::thread_info; use sys_common::util; @@ -193,7 +193,6 @@ fn default_hook(info: &PanicInfo) { None => "Box", } }; - let mut err = Stderr::new().ok(); let thread = thread_info::current_thread(); let name = thread.as_ref().and_then(|t| t.name()).unwrap_or(""); @@ -215,17 +214,14 @@ 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) } - _ => {} + if let Some(mut local) = LOCAL_STDERR.with(|s| s.borrow_mut().take()) { + write(&mut *local); + let mut s = Some(local); + LOCAL_STDERR.with(|slot| { + *slot.borrow_mut() = s.take(); + }); + } else if let Some(mut out) = panic_output() { + write(&mut out); } } @@ -485,7 +481,7 @@ fn rust_panic_with_hook(payload: &mut dyn BoxMeUp, // Some platforms know that printing to stderr won't ever actually // print anything, and if that's the case we can skip the default // hook. - Hook::Default if stderr_prints_nothing() => {} + Hook::Default if panic_output().is_none() => {} Hook::Default => { info.set_payload(payload.get()); default_hook(&info); @@ -494,7 +490,7 @@ fn rust_panic_with_hook(payload: &mut dyn BoxMeUp, info.set_payload(payload.get()); (*ptr)(&info); } - } + }; HOOK_LOCK.read_unlock(); } diff --git a/src/libstd/sys/cloudabi/stdio.rs b/src/libstd/sys/cloudabi/stdio.rs index 1d7344f921c..c90dbd8beab 100644 --- a/src/libstd/sys/cloudabi/stdio.rs +++ b/src/libstd/sys/cloudabi/stdio.rs @@ -78,6 +78,6 @@ 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 +pub fn panic_output() -> Option { + Stderr::new().ok() } diff --git a/src/libstd/sys/redox/stdio.rs b/src/libstd/sys/redox/stdio.rs index 7a4d11b0ecb..52cd9334ffb 100644 --- a/src/libstd/sys/redox/stdio.rs +++ b/src/libstd/sys/redox/stdio.rs @@ -76,6 +76,6 @@ 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 +pub fn panic_output() -> Option { + Stderr::new().ok() } diff --git a/src/libstd/sys/unix/stdio.rs b/src/libstd/sys/unix/stdio.rs index 87ba2aef4f1..63e341abb2c 100644 --- a/src/libstd/sys/unix/stdio.rs +++ b/src/libstd/sys/unix/stdio.rs @@ -76,6 +76,6 @@ 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 +pub fn panic_output() -> Option { + Stderr::new().ok() } diff --git a/src/libstd/sys/wasm/stdio.rs b/src/libstd/sys/wasm/stdio.rs index 023f29576a2..e51aba75333 100644 --- a/src/libstd/sys/wasm/stdio.rs +++ b/src/libstd/sys/wasm/stdio.rs @@ -70,6 +70,10 @@ pub fn is_ebadf(_err: &io::Error) -> bool { true } -pub fn stderr_prints_nothing() -> bool { - !cfg!(feature = "wasm_syscall") +pub fn panic_output() -> Option { + if cfg!(feature = "wasm_syscall") { + Stderr::new().ok() + } else { + None + } } diff --git a/src/libstd/sys/windows/stdio.rs b/src/libstd/sys/windows/stdio.rs index c3a94698a0f..61e0db87ebe 100644 --- a/src/libstd/sys/windows/stdio.rs +++ b/src/libstd/sys/windows/stdio.rs @@ -228,6 +228,6 @@ pub fn is_ebadf(err: &io::Error) -> bool { // been seen to be acceptable. pub const STDIN_BUF_SIZE: usize = 8 * 1024; -pub fn stderr_prints_nothing() -> bool { - false +pub fn panic_output() -> Option { + Stderr::new().ok() } diff --git a/src/libstd/sys_common/util.rs b/src/libstd/sys_common/util.rs index a373e980b97..fc86a59d17f 100644 --- a/src/libstd/sys_common/util.rs +++ b/src/libstd/sys_common/util.rs @@ -10,14 +10,13 @@ use fmt; use io::prelude::*; -use sys::stdio::{Stderr, stderr_prints_nothing}; +use sys::stdio::panic_output; use thread; pub fn dumb_print(args: fmt::Arguments) { - if stderr_prints_nothing() { - return + if let Some(mut out) = panic_output() { + let _ = out.write_fmt(args); } - let _ = Stderr::new().map(|mut stderr| stderr.write_fmt(args)); } // Other platforms should use the appropriate platform-specific mechanism for -- cgit 1.4.1-3-g733a5 From 22c43689937a81cf5ad6ecfe22d9e63e3cebed04 Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Tue, 18 Sep 2018 15:25:08 -0700 Subject: Refactor net::each_addr/lookup_host to forward error from resolve --- src/libstd/net/addr.rs | 28 ++----- src/libstd/net/mod.rs | 10 ++- src/libstd/sys/cloudabi/shims/net.rs | 31 +++++-- src/libstd/sys/redox/net/mod.rs | 153 +++++++++++++++++++++-------------- src/libstd/sys/redox/net/tcp.rs | 8 +- src/libstd/sys/redox/net/udp.rs | 8 +- src/libstd/sys/unix/l4re.rs | 33 ++++++-- src/libstd/sys/wasm/net.rs | 31 +++++-- src/libstd/sys_common/net.rs | 74 +++++++++++++---- 9 files changed, 250 insertions(+), 126 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index ff35325ab4f..1ac0bdf922f 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -16,10 +16,11 @@ use net::{ntoh, hton, IpAddr, Ipv4Addr, Ipv6Addr}; use option; use sys::net::netc as c; use sys_common::{FromInner, AsInner, IntoInner}; -use sys_common::net::lookup_host; +use sys_common::net::LookupHost; use vec; use iter; use slice; +use convert::TryInto; /// An internet socket address, either IPv4 or IPv6. /// @@ -863,9 +864,9 @@ impl ToSocketAddrs for (Ipv6Addr, u16) { } } -fn resolve_socket_addr(s: &str, p: u16) -> io::Result> { - let ips = lookup_host(s)?; - let v: Vec<_> = ips.map(|mut a| { a.set_port(p); a }).collect(); +fn resolve_socket_addr(lh: LookupHost) -> io::Result> { + let p = lh.port(); + let v: Vec<_> = lh.map(|mut a| { a.set_port(p); a }).collect(); Ok(v.into_iter()) } @@ -885,7 +886,7 @@ impl<'a> ToSocketAddrs for (&'a str, u16) { return Ok(vec![SocketAddr::V6(addr)].into_iter()) } - resolve_socket_addr(host, port) + resolve_socket_addr((host, port).try_into()?) } } @@ -899,22 +900,7 @@ impl ToSocketAddrs for str { return Ok(vec![addr].into_iter()); } - macro_rules! try_opt { - ($e:expr, $msg:expr) => ( - match $e { - Some(r) => r, - None => return Err(io::Error::new(io::ErrorKind::InvalidInput, - $msg)), - } - ) - } - - // split the string by ':' and convert the second part to u16 - let mut parts_iter = self.rsplitn(2, ':'); - let port_str = try_opt!(parts_iter.next(), "invalid socket address"); - let host = try_opt!(parts_iter.next(), "invalid socket address"); - let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value"); - resolve_socket_addr(host, port) + resolve_socket_addr(self.try_into()?) } } diff --git a/src/libstd/net/mod.rs b/src/libstd/net/mod.rs index be4bcee8a68..ff579a5feb1 100644 --- a/src/libstd/net/mod.rs +++ b/src/libstd/net/mod.rs @@ -112,11 +112,15 @@ fn hton(i: I) -> I { i.to_be() } fn ntoh(i: I) -> I { I::from_be(i) } fn each_addr(addr: A, mut f: F) -> io::Result - where F: FnMut(&SocketAddr) -> io::Result + where F: FnMut(io::Result<&SocketAddr>) -> io::Result { + let addrs = match addr.to_socket_addrs() { + Ok(addrs) => addrs, + Err(e) => return f(Err(e)) + }; let mut last_err = None; - for addr in addr.to_socket_addrs()? { - match f(&addr) { + for addr in addrs { + match f(Ok(&addr)) { Ok(l) => return Ok(l), Err(e) => last_err = Some(e), } diff --git a/src/libstd/sys/cloudabi/shims/net.rs b/src/libstd/sys/cloudabi/shims/net.rs index 93eaf6a9e7d..7229e71d175 100644 --- a/src/libstd/sys/cloudabi/shims/net.rs +++ b/src/libstd/sys/cloudabi/shims/net.rs @@ -13,13 +13,14 @@ use io; use net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use time::Duration; use sys::{unsupported, Void}; +use convert::TryFrom; pub extern crate libc as netc; pub struct TcpStream(Void); impl TcpStream { - pub fn connect(_: &SocketAddr) -> io::Result { + pub fn connect(_: io::Result<&SocketAddr>) -> io::Result { unsupported() } @@ -105,7 +106,7 @@ impl fmt::Debug for TcpStream { pub struct TcpListener(Void); impl TcpListener { - pub fn bind(_: &SocketAddr) -> io::Result { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { unsupported() } @@ -155,7 +156,7 @@ impl fmt::Debug for TcpListener { pub struct UdpSocket(Void); impl UdpSocket { - pub fn bind(_: &SocketAddr) -> io::Result { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { unsupported() } @@ -271,7 +272,7 @@ impl UdpSocket { match self.0 {} } - pub fn connect(&self, _: &SocketAddr) -> io::Result<()> { + pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> { match self.0 {} } } @@ -284,6 +285,12 @@ impl fmt::Debug for UdpSocket { pub struct LookupHost(Void); +impl LookupHost { + pub fn port(&self) -> u16 { + match self.0 {} + } +} + impl Iterator for LookupHost { type Item = SocketAddr; fn next(&mut self) -> Option { @@ -291,6 +298,18 @@ impl Iterator for LookupHost { } } -pub fn lookup_host(_: &str) -> io::Result { - unsupported() +impl<'a> TryFrom<&'a str> for LookupHost { + type Error = io::Error; + + fn try_from(_v: &'a str) -> io::Result { + unsupported() + } +} + +impl<'a> TryFrom<(&'a str, u16)> for LookupHost { + type Error = io::Error; + + fn try_from(_v: (&'a str, u16)) -> io::Result { + unsupported() + } } diff --git a/src/libstd/sys/redox/net/mod.rs b/src/libstd/sys/redox/net/mod.rs index 67f22231d5f..04a183f2417 100644 --- a/src/libstd/sys/redox/net/mod.rs +++ b/src/libstd/sys/redox/net/mod.rs @@ -9,7 +9,7 @@ // except according to those terms. use fs::File; -use io::{Error, Result, Read}; +use io::{Error, Read, self}; use iter::Iterator; use net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use str::FromStr; @@ -17,6 +17,7 @@ use string::{String, ToString}; use sys::syscall::EINVAL; use time::{self, Duration}; use vec::{IntoIter, Vec}; +use convert::{TryFrom, TryInto}; use self::dns::{Dns, DnsQuery}; @@ -29,7 +30,13 @@ mod dns; mod tcp; mod udp; -pub struct LookupHost(IntoIter); +pub struct LookupHost(IntoIter, u16); + +impl LookupHost { + pub fn port(&self) -> u16 { + self.1 + } +} impl Iterator for LookupHost { type Item = SocketAddr; @@ -38,65 +45,93 @@ impl Iterator for LookupHost { } } -pub fn lookup_host(host: &str) -> Result { - let mut ip_string = String::new(); - File::open("/etc/net/ip")?.read_to_string(&mut ip_string)?; - let ip: Vec = ip_string.trim().split('.').map(|part| part.parse::() - .unwrap_or(0)).collect(); - - let mut dns_string = String::new(); - File::open("/etc/net/dns")?.read_to_string(&mut dns_string)?; - let dns: Vec = dns_string.trim().split('.').map(|part| part.parse::() - .unwrap_or(0)).collect(); - - if ip.len() == 4 && dns.len() == 4 { - let time = time::SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap(); - let tid = (time.subsec_nanos() >> 16) as u16; - - let packet = Dns { - transaction_id: tid, - flags: 0x0100, - queries: vec![DnsQuery { - name: host.to_string(), - q_type: 0x0001, - q_class: 0x0001, - }], - answers: vec![] - }; - - let packet_data = packet.compile(); - - let my_ip = Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]); - let dns_ip = Ipv4Addr::new(dns[0], dns[1], dns[2], dns[3]); - let socket = UdpSocket::bind(&SocketAddr::V4(SocketAddrV4::new(my_ip, 0)))?; - socket.set_read_timeout(Some(Duration::new(5, 0)))?; - socket.set_write_timeout(Some(Duration::new(5, 0)))?; - socket.connect(&SocketAddr::V4(SocketAddrV4::new(dns_ip, 53)))?; - socket.send(&packet_data)?; - - let mut buf = [0; 65536]; - let count = socket.recv(&mut buf)?; - - match Dns::parse(&buf[.. count]) { - Ok(response) => { - let mut addrs = vec![]; - for answer in response.answers.iter() { - if answer.a_type == 0x0001 && answer.a_class == 0x0001 - && answer.data.len() == 4 - { - let answer_ip = Ipv4Addr::new(answer.data[0], - answer.data[1], - answer.data[2], - answer.data[3]); - addrs.push(SocketAddr::V4(SocketAddrV4::new(answer_ip, 0))); - } +impl<'a> TryFrom<&'a str> for LookupHost { + type Error = io::Error; + + fn try_from(s: &str) -> io::Result { + macro_rules! try_opt { + ($e:expr, $msg:expr) => ( + match $e { + Some(r) => r, + None => return Err(io::Error::new(io::ErrorKind::InvalidInput, + $msg)), } - Ok(LookupHost(addrs.into_iter())) - }, - Err(_err) => Err(Error::from_raw_os_error(EINVAL)) + ) + } + + // split the string by ':' and convert the second part to u16 + let mut parts_iter = s.rsplitn(2, ':'); + let port_str = try_opt!(parts_iter.next(), "invalid socket address"); + let host = try_opt!(parts_iter.next(), "invalid socket address"); + let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value"); + + (host, port).try_into() + } +} + +impl<'a> TryFrom<(&'a str, u16)> for LookupHost { + type Error = io::Error; + + fn try_from((host, port): (&'a str, u16)) -> io::Result { + let mut ip_string = String::new(); + File::open("/etc/net/ip")?.read_to_string(&mut ip_string)?; + let ip: Vec = ip_string.trim().split('.').map(|part| part.parse::() + .unwrap_or(0)).collect(); + + let mut dns_string = String::new(); + File::open("/etc/net/dns")?.read_to_string(&mut dns_string)?; + let dns: Vec = dns_string.trim().split('.').map(|part| part.parse::() + .unwrap_or(0)).collect(); + + if ip.len() == 4 && dns.len() == 4 { + let time = time::SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap(); + let tid = (time.subsec_nanos() >> 16) as u16; + + let packet = Dns { + transaction_id: tid, + flags: 0x0100, + queries: vec![DnsQuery { + name: host.to_string(), + q_type: 0x0001, + q_class: 0x0001, + }], + answers: vec![] + }; + + let packet_data = packet.compile(); + + let my_ip = Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]); + let dns_ip = Ipv4Addr::new(dns[0], dns[1], dns[2], dns[3]); + let socket = UdpSocket::bind(Ok(&SocketAddr::V4(SocketAddrV4::new(my_ip, 0))))?; + socket.set_read_timeout(Some(Duration::new(5, 0)))?; + socket.set_write_timeout(Some(Duration::new(5, 0)))?; + socket.connect(Ok(&SocketAddr::V4(SocketAddrV4::new(dns_ip, 53))))?; + socket.send(&packet_data)?; + + let mut buf = [0; 65536]; + let count = socket.recv(&mut buf)?; + + match Dns::parse(&buf[.. count]) { + Ok(response) => { + let mut addrs = vec![]; + for answer in response.answers.iter() { + if answer.a_type == 0x0001 && answer.a_class == 0x0001 + && answer.data.len() == 4 + { + let answer_ip = Ipv4Addr::new(answer.data[0], + answer.data[1], + answer.data[2], + answer.data[3]); + addrs.push(SocketAddr::V4(SocketAddrV4::new(answer_ip, 0))); + } + } + Ok(LookupHost(addrs.into_iter(), port)) + }, + Err(_err) => Err(Error::from_raw_os_error(EINVAL)) + } + } else { + Err(Error::from_raw_os_error(EINVAL)) } - } else { - Err(Error::from_raw_os_error(EINVAL)) } } diff --git a/src/libstd/sys/redox/net/tcp.rs b/src/libstd/sys/redox/net/tcp.rs index b5664908479..37457d87f33 100644 --- a/src/libstd/sys/redox/net/tcp.rs +++ b/src/libstd/sys/redox/net/tcp.rs @@ -24,8 +24,8 @@ use super::{path_to_peer_addr, path_to_local_addr}; pub struct TcpStream(File); impl TcpStream { - pub fn connect(addr: &SocketAddr) -> Result { - let path = format!("tcp:{}", addr); + pub fn connect(addr: Result<&SocketAddr>) -> Result { + let path = format!("tcp:{}", addr?); let mut options = OpenOptions::new(); options.read(true); options.write(true); @@ -180,8 +180,8 @@ impl IntoInner for TcpStream { pub struct TcpListener(File); impl TcpListener { - pub fn bind(addr: &SocketAddr) -> Result { - let path = format!("tcp:/{}", addr); + pub fn bind(addr: Result<&SocketAddr>) -> Result { + let path = format!("tcp:/{}", addr?); let mut options = OpenOptions::new(); options.read(true); options.write(true); diff --git a/src/libstd/sys/redox/net/udp.rs b/src/libstd/sys/redox/net/udp.rs index 22af02079e7..85bfd425924 100644 --- a/src/libstd/sys/redox/net/udp.rs +++ b/src/libstd/sys/redox/net/udp.rs @@ -25,8 +25,8 @@ use super::{path_to_peer_addr, path_to_local_addr}; pub struct UdpSocket(File, UnsafeCell>); impl UdpSocket { - pub fn bind(addr: &SocketAddr) -> Result { - let path = format!("udp:/{}", addr); + pub fn bind(addr: Result<&SocketAddr>) -> Result { + let path = format!("udp:/{}", addr?); let mut options = OpenOptions::new(); options.read(true); options.write(true); @@ -37,8 +37,8 @@ impl UdpSocket { unsafe { &mut *(self.1.get()) } } - pub fn connect(&self, addr: &SocketAddr) -> Result<()> { - unsafe { *self.1.get() = Some(*addr) }; + pub fn connect(&self, addr: Result<&SocketAddr>) -> Result<()> { + unsafe { *self.1.get() = Some(*addr?) }; Ok(()) } diff --git a/src/libstd/sys/unix/l4re.rs b/src/libstd/sys/unix/l4re.rs index 21218489679..bbb0fd45ba3 100644 --- a/src/libstd/sys/unix/l4re.rs +++ b/src/libstd/sys/unix/l4re.rs @@ -21,7 +21,7 @@ pub mod net { use sys_common::{AsInner, FromInner, IntoInner}; use sys::fd::FileDesc; use time::Duration; - + use convert::TryFrom; pub extern crate libc as netc; @@ -118,7 +118,7 @@ pub mod net { } impl TcpStream { - pub fn connect(_: &SocketAddr) -> io::Result { + pub fn connect(_: io::Result<&SocketAddr>) -> io::Result { unimpl!(); } @@ -216,7 +216,7 @@ pub mod net { } impl TcpListener { - pub fn bind(_: &SocketAddr) -> io::Result { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { unimpl!(); } @@ -278,7 +278,7 @@ pub mod net { } impl UdpSocket { - pub fn bind(_: &SocketAddr) -> io::Result { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { unimpl!(); } @@ -402,7 +402,7 @@ pub mod net { unimpl!(); } - pub fn connect(&self, _: &SocketAddr) -> io::Result<()> { + pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> { unimpl!(); } } @@ -431,11 +431,30 @@ pub mod net { } } + impl LookupHost { + pub fn port(&self) -> u16 { + unimpl!(); + } + } + unsafe impl Sync for LookupHost {} unsafe impl Send for LookupHost {} - pub fn lookup_host(_: &str) -> io::Result { - unimpl!(); + + impl<'a> TryFrom<&'a str> for LookupHost { + type Error = io::Error; + + fn try_from(_v: &'a str) -> io::Result { + unimpl!(); + } + } + + impl<'a> TryFrom<(&'a str, u16)> for LookupHost { + type Error = io::Error; + + fn try_from(_v: (&'a str, u16)) -> io::Result { + unimpl!(); + } } } diff --git a/src/libstd/sys/wasm/net.rs b/src/libstd/sys/wasm/net.rs index 03a5b2d779e..e1c33b09cb4 100644 --- a/src/libstd/sys/wasm/net.rs +++ b/src/libstd/sys/wasm/net.rs @@ -13,11 +13,12 @@ use io; use net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; use time::Duration; use sys::{unsupported, Void}; +use convert::TryFrom; pub struct TcpStream(Void); impl TcpStream { - pub fn connect(_: &SocketAddr) -> io::Result { + pub fn connect(_: io::Result<&SocketAddr>) -> io::Result { unsupported() } @@ -103,7 +104,7 @@ impl fmt::Debug for TcpStream { pub struct TcpListener(Void); impl TcpListener { - pub fn bind(_: &SocketAddr) -> io::Result { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { unsupported() } @@ -153,7 +154,7 @@ impl fmt::Debug for TcpListener { pub struct UdpSocket(Void); impl UdpSocket { - pub fn bind(_: &SocketAddr) -> io::Result { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { unsupported() } @@ -273,7 +274,7 @@ impl UdpSocket { match self.0 {} } - pub fn connect(&self, _: &SocketAddr) -> io::Result<()> { + pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> { match self.0 {} } } @@ -286,6 +287,12 @@ impl fmt::Debug for UdpSocket { pub struct LookupHost(Void); +impl LookupHost { + pub fn port(&self) -> u16 { + match self.0 {} + } +} + impl Iterator for LookupHost { type Item = SocketAddr; fn next(&mut self) -> Option { @@ -293,8 +300,20 @@ impl Iterator for LookupHost { } } -pub fn lookup_host(_: &str) -> io::Result { - unsupported() +impl<'a> TryFrom<&'a str> for LookupHost { + type Error = io::Error; + + fn try_from(_v: &'a str) -> io::Result { + unsupported() + } +} + +impl<'a> TryFrom<(&'a str, u16)> for LookupHost { + type Error = io::Error; + + fn try_from(_v: (&'a str, u16)) -> io::Result { + unsupported() + } } #[allow(nonstandard_style)] diff --git a/src/libstd/sys_common/net.rs b/src/libstd/sys_common/net.rs index d09a233ed89..dce2bf71cec 100644 --- a/src/libstd/sys_common/net.rs +++ b/src/libstd/sys_common/net.rs @@ -20,6 +20,7 @@ use sys::net::{cvt, cvt_r, cvt_gai, Socket, init, wrlen_t}; use sys::net::netc as c; use sys_common::{AsInner, FromInner, IntoInner}; use time::Duration; +use convert::{TryFrom, TryInto}; #[cfg(any(target_os = "dragonfly", target_os = "freebsd", target_os = "ios", target_os = "macos", @@ -129,6 +130,13 @@ fn to_ipv6mr_interface(value: u32) -> ::libc::c_uint { pub struct LookupHost { original: *mut c::addrinfo, cur: *mut c::addrinfo, + port: u16 +} + +impl LookupHost { + pub fn port(&self) -> u16 { + self.port + } } impl Iterator for LookupHost { @@ -158,17 +166,45 @@ impl Drop for LookupHost { } } -pub fn lookup_host(host: &str) -> io::Result { - init(); +impl<'a> TryFrom<&'a str> for LookupHost { + type Error = io::Error; - let c_host = CString::new(host)?; - let mut hints: c::addrinfo = unsafe { mem::zeroed() }; - hints.ai_socktype = c::SOCK_STREAM; - let mut res = ptr::null_mut(); - unsafe { - cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)).map(|_| { - LookupHost { original: res, cur: res } - }) + fn try_from(s: &str) -> io::Result { + macro_rules! try_opt { + ($e:expr, $msg:expr) => ( + match $e { + Some(r) => r, + None => return Err(io::Error::new(io::ErrorKind::InvalidInput, + $msg)), + } + ) + } + + // split the string by ':' and convert the second part to u16 + let mut parts_iter = s.rsplitn(2, ':'); + let port_str = try_opt!(parts_iter.next(), "invalid socket address"); + let host = try_opt!(parts_iter.next(), "invalid socket address"); + let port: u16 = try_opt!(port_str.parse().ok(), "invalid port value"); + + (host, port).try_into() + } +} + +impl<'a> TryFrom<(&'a str, u16)> for LookupHost { + type Error = io::Error; + + fn try_from((host, port): (&'a str, u16)) -> io::Result { + init(); + + let c_host = CString::new(host)?; + let mut hints: c::addrinfo = unsafe { mem::zeroed() }; + hints.ai_socktype = c::SOCK_STREAM; + let mut res = ptr::null_mut(); + unsafe { + cvt_gai(c::getaddrinfo(c_host.as_ptr(), ptr::null(), &hints, &mut res)).map(|_| { + LookupHost { original: res, cur: res, port } + }) + } } } @@ -181,7 +217,9 @@ pub struct TcpStream { } impl TcpStream { - pub fn connect(addr: &SocketAddr) -> io::Result { + pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result { + let addr = addr?; + init(); let sock = Socket::new(addr, c::SOCK_STREAM)?; @@ -317,7 +355,9 @@ pub struct TcpListener { } impl TcpListener { - pub fn bind(addr: &SocketAddr) -> io::Result { + pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result { + let addr = addr?; + init(); let sock = Socket::new(addr, c::SOCK_STREAM)?; @@ -418,7 +458,9 @@ pub struct UdpSocket { } impl UdpSocket { - pub fn bind(addr: &SocketAddr) -> io::Result { + pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result { + let addr = addr?; + init(); let sock = Socket::new(addr, c::SOCK_DGRAM)?; @@ -584,8 +626,8 @@ impl UdpSocket { Ok(ret as usize) } - pub fn connect(&self, addr: &SocketAddr) -> io::Result<()> { - let (addrp, len) = addr.into_inner(); + pub fn connect(&self, addr: io::Result<&SocketAddr>) -> io::Result<()> { + let (addrp, len) = addr?.into_inner(); cvt_r(|| unsafe { c::connect(*self.inner.as_inner(), addrp, len) }).map(|_| ()) } } @@ -618,7 +660,7 @@ mod tests { #[test] fn no_lookup_host_duplicates() { let mut addrs = HashMap::new(); - let lh = match lookup_host("localhost") { + let lh = match LookupHost::try_from(("localhost", 0)) { Ok(lh) => lh, Err(e) => panic!("couldn't resolve `localhost': {}", e) }; -- cgit 1.4.1-3-g733a5 From 6c0364064604d1a3a7755339e7ea81bbea53c005 Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Wed, 21 Nov 2018 14:16:00 +0530 Subject: Update compiler_builtins and remove wasm f32<->f64 math conversions --- src/libcompiler_builtins | 2 +- src/libstd/sys/wasm/cmath.rs | 81 ++++++++------------------------------------ 2 files changed, 15 insertions(+), 68 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libcompiler_builtins b/src/libcompiler_builtins index fe74674f6e4..10f4f35f967 160000 --- a/src/libcompiler_builtins +++ b/src/libcompiler_builtins @@ -1 +1 @@ -Subproject commit fe74674f6e4be76d47b66f67d529ebf4186f4eb1 +Subproject commit 10f4f35f9670bb29715a8c1ec01284852d47ed35 diff --git a/src/libstd/sys/wasm/cmath.rs b/src/libstd/sys/wasm/cmath.rs index 64fc14d42d9..d4f8d66ee3e 100644 --- a/src/libstd/sys/wasm/cmath.rs +++ b/src/libstd/sys/wasm/cmath.rs @@ -8,85 +8,32 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#[inline] -pub unsafe fn cbrtf(n: f32) -> f32 { - f64::cbrt(n as f64) as f32 -} - -#[inline] -pub unsafe fn expm1f(n: f32) -> f32 { - f64::exp_m1(n as f64) as f32 -} - -#[inline] -#[allow(deprecated)] -pub unsafe fn fdimf(a: f32, b: f32) -> f32 { - f64::abs_sub(a as f64, b as f64) as f32 -} - -#[inline] -pub unsafe fn log1pf(n: f32) -> f32 { - f64::ln_1p(n as f64) as f32 -} - -#[inline] -pub unsafe fn hypotf(x: f32, y: f32) -> f32 { - f64::hypot(x as f64, y as f64) as f32 -} - -#[inline] -pub unsafe fn acosf(n: f32) -> f32 { - f64::acos(n as f64) as f32 -} - -#[inline] -pub unsafe fn asinf(n: f32) -> f32 { - f64::asin(n as f64) as f32 -} - -#[inline] -pub unsafe fn atan2f(n: f32, b: f32) -> f32 { - f64::atan2(n as f64, b as f64) as f32 -} - -#[inline] -pub unsafe fn atanf(n: f32) -> f32 { - f64::atan(n as f64) as f32 -} - -#[inline] -pub unsafe fn coshf(n: f32) -> f32 { - f64::cosh(n as f64) as f32 -} - -#[inline] -pub unsafe fn sinhf(n: f32) -> f32 { - f64::sinh(n as f64) as f32 -} - -#[inline] -pub unsafe fn tanf(n: f32) -> f32 { - f64::tan(n as f64) as f32 -} - -#[inline] -pub unsafe fn tanhf(n: f32) -> f32 { - f64::tanh(n as f64) as f32 -} - // These symbols are all defined in `compiler-builtins` extern { pub fn acos(n: f64) -> f64; + pub fn acosf(n: f32) -> f32; pub fn asin(n: f64) -> f64; + pub fn asinf(n: f32) -> f32; pub fn atan(n: f64) -> f64; pub fn atan2(a: f64, b: f64) -> f64; + pub fn atan2f(a: f32, b: f32) -> f32; + pub fn atanf(n: f32) -> f32; pub fn cbrt(n: f64) -> f64; + pub fn cbrtf(n: f32) -> f32; pub fn cosh(n: f64) -> f64; + pub fn coshf(n: f32) -> f32; pub fn expm1(n: f64) -> f64; + pub fn expm1f(n: f32) -> f32; pub fn fdim(a: f64, b: f64) -> f64; + pub fn fdimf(a: f32, b: f32) -> f32; + pub fn hypot(x: f64, y: f64) -> f64; + pub fn hypotf(x: f32, y: f32) -> f32; pub fn log1p(n: f64) -> f64; + pub fn log1pf(n: f32) -> f32; pub fn sinh(n: f64) -> f64; + pub fn sinhf(n: f32) -> f32; pub fn tan(n: f64) -> f64; + pub fn tanf(n: f32) -> f32; pub fn tanh(n: f64) -> f64; - pub fn hypot(x: f64, y: f64) -> f64; + pub fn tanhf(n: f32) -> f32; } -- cgit 1.4.1-3-g733a5 From c559216ad0d2f0737f8dbb51a7d42b1727b77b3c Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Fri, 30 Nov 2018 10:39:12 +0530 Subject: Change sys::Thread::new to take the thread entry as Box̣ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/libstd/sys/cloudabi/thread.rs | 3 ++- src/libstd/sys/redox/thread.rs | 3 ++- src/libstd/sys/unix/thread.rs | 3 ++- src/libstd/sys/wasm/thread.rs | 3 ++- src/libstd/sys/windows/thread.rs | 3 ++- src/libstd/thread/mod.rs | 22 +++++++++++++++++++--- 6 files changed, 29 insertions(+), 8 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs index 8cca47efd22..a76e1fa3345 100644 --- a/src/libstd/sys/cloudabi/thread.rs +++ b/src/libstd/sys/cloudabi/thread.rs @@ -32,7 +32,8 @@ unsafe impl Send for Thread {} unsafe impl Sync for Thread {} impl Thread { - pub unsafe fn new<'a>(stack: usize, p: Box) -> io::Result { + // unsafe: see thread::Builder::spawn_unchecked for safety requirements + pub unsafe fn new(stack: usize, p: Box) -> io::Result { let p = box p; let mut native: libc::pthread_t = mem::zeroed(); let mut attr: libc::pthread_attr_t = mem::zeroed(); diff --git a/src/libstd/sys/redox/thread.rs b/src/libstd/sys/redox/thread.rs index bab91b16e6c..ff861805382 100644 --- a/src/libstd/sys/redox/thread.rs +++ b/src/libstd/sys/redox/thread.rs @@ -28,7 +28,8 @@ unsafe impl Send for Thread {} unsafe impl Sync for Thread {} impl Thread { - pub unsafe fn new<'a>(_stack: usize, p: Box) -> io::Result { + // unsafe: see thread::Builder::spawn_unchecked for safety requirements + pub unsafe fn new(_stack: usize, p: Box) -> io::Result { let p = box p; let id = cvt(syscall::clone(syscall::CLONE_VM | syscall::CLONE_FS | syscall::CLONE_FILES))?; diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index f3a45d24657..4ff060018ae 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -49,7 +49,8 @@ unsafe fn pthread_attr_setstacksize(_attr: *mut libc::pthread_attr_t, } impl Thread { - pub unsafe fn new<'a>(stack: usize, p: Box) + // unsafe: see thread::Builder::spawn_unchecked for safety requirements + pub unsafe fn new(stack: usize, p: Box) -> io::Result { let p = box p; let mut native: libc::pthread_t = mem::zeroed(); diff --git a/src/libstd/sys/wasm/thread.rs b/src/libstd/sys/wasm/thread.rs index 4ad89c42b92..3d74ffdc14a 100644 --- a/src/libstd/sys/wasm/thread.rs +++ b/src/libstd/sys/wasm/thread.rs @@ -19,7 +19,8 @@ pub struct Thread(Void); pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; impl Thread { - pub unsafe fn new<'a>(_stack: usize, _p: Box) + // unsafe: see thread::Builder::spawn_unchecked for safety requirements + pub unsafe fn new(_stack: usize, _p: Box) -> io::Result { unsupported() diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index 85588cc6c8e..1a97dd10ced 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -28,7 +28,8 @@ pub struct Thread { } impl Thread { - pub unsafe fn new<'a>(stack: usize, p: Box) + // unsafe: see thread::Builder::spawn_unchecked for safety requirements + pub unsafe fn new(stack: usize, p: Box) -> io::Result { let p = box p; diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 3a9f3ec5c6f..d15b4902412 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -167,10 +167,12 @@ #![stable(feature = "rust1", since = "1.0.0")] use any::Any; +use boxed::FnBox; use cell::UnsafeCell; use ffi::{CStr, CString}; use fmt; use io; +use mem; use panic; use panicking; use str; @@ -452,8 +454,8 @@ impl Builder { /// [`io::Result`]: ../../std/io/type.Result.html /// [`JoinHandle`]: ../../std/thread/struct.JoinHandle.html #[unstable(feature = "thread_spawn_unchecked", issue = "55132")] - pub unsafe fn spawn_unchecked(self, f: F) -> io::Result> where - F: FnOnce() -> T, F: Send, T: Send + pub unsafe fn spawn_unchecked<'a, F, T>(self, f: F) -> io::Result> where + F: FnOnce() -> T, F: Send + 'a, T: Send + 'a { let Builder { name, stack_size } = self; @@ -482,7 +484,21 @@ impl Builder { }; Ok(JoinHandle(JoinInner { - native: Some(imp::Thread::new(stack_size, Box::new(main))?), + // `imp::Thread::new` takes a closure with a `'static` lifetime, since it's passed + // through FFI or otherwise used with low-level threading primitives that have no + // notion of or way to enforce lifetimes. + // + // As mentioned in the `Safety` section of this function's documentation, the caller of + // this function needs to guarantee that the passed-in lifetime is sufficiently long + // for the lifetime of the thread. + // + // Similarly, the `sys` implementation must guarantee that no references to the closure + // exist after the thread has terminated, which is signaled by `Thread::join` + // returning. + native: Some(imp::Thread::new( + stack_size, + mem::transmute::, Box>(Box::new(main)) + )?), thread: my_thread, packet: Packet(my_packet), })) -- cgit 1.4.1-3-g733a5 From 4a3505682e97c8e667338056ae216e4b84b22dd7 Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Mon, 27 Aug 2018 21:33:26 -0700 Subject: Add x86_64-fortanix-unknown-sgx target to libstd and dependencies The files src/libstd/sys/sgx/*.rs are mostly copied/adapted from the wasm target. This also updates the dlmalloc submodule to the very latest version. --- .gitmodules | 4 +- Cargo.lock | 9 + src/bootstrap/dist.rs | 1 + src/dlmalloc | 2 +- src/liblibc | 2 +- src/libpanic_abort/lib.rs | 6 + src/libpanic_unwind/lib.rs | 2 +- src/libstd/Cargo.toml | 5 +- src/libstd/io/error.rs | 2 +- src/libstd/lib.rs | 7 + src/libstd/sys/mod.rs | 3 + src/libstd/sys/sgx/abi/entry.S | 327 ++++++++++++++++++++++++++ src/libstd/sys/sgx/abi/mem.rs | 31 +++ src/libstd/sys/sgx/abi/mod.rs | 94 ++++++++ src/libstd/sys/sgx/abi/panic.rs | 58 +++++ src/libstd/sys/sgx/abi/reloc.rs | 40 ++++ src/libstd/sys/sgx/abi/usercalls/mod.rs | 12 + src/libstd/sys/sgx/abi/usercalls/raw.rs | 231 +++++++++++++++++++ src/libstd/sys/sgx/alloc.rs | 39 ++++ src/libstd/sys/sgx/args.rs | 57 +++++ src/libstd/sys/sgx/backtrace.rs | 37 +++ src/libstd/sys/sgx/cmath.rs | 41 ++++ src/libstd/sys/sgx/condvar.rs | 43 ++++ src/libstd/sys/sgx/env.rs | 19 ++ src/libstd/sys/sgx/fs.rs | 304 ++++++++++++++++++++++++ src/libstd/sys/sgx/memchr.rs | 11 + src/libstd/sys/sgx/mod.rs | 151 ++++++++++++ src/libstd/sys/sgx/mutex.rs | 78 +++++++ src/libstd/sys/sgx/net.rs | 356 +++++++++++++++++++++++++++++ src/libstd/sys/sgx/os.rs | 120 ++++++++++ src/libstd/sys/sgx/os_str.rs | 189 +++++++++++++++ src/libstd/sys/sgx/path.rs | 29 +++ src/libstd/sys/sgx/pipe.rs | 35 +++ src/libstd/sys/sgx/process.rs | 162 +++++++++++++ src/libstd/sys/sgx/rwlock.rs | 82 +++++++ src/libstd/sys/sgx/stack_overflow.rs | 23 ++ src/libstd/sys/sgx/stdio.rs | 73 ++++++ src/libstd/sys/sgx/thread.rs | 51 +++++ src/libstd/sys/sgx/thread_local.rs | 50 ++++ src/libstd/sys/sgx/time.rs | 61 +++++ src/libstd/sys_common/mod.rs | 8 +- src/libtest/lib.rs | 10 +- src/libunwind/lib.rs | 5 +- src/rust-sgx | 1 + src/rustc/fortanix-sgx-abi_shim/Cargo.toml | 14 ++ src/stdsimd | 2 +- src/tools/tidy/src/lib.rs | 1 + 47 files changed, 2873 insertions(+), 15 deletions(-) create mode 100644 src/libstd/sys/sgx/abi/entry.S create mode 100644 src/libstd/sys/sgx/abi/mem.rs create mode 100644 src/libstd/sys/sgx/abi/mod.rs create mode 100644 src/libstd/sys/sgx/abi/panic.rs create mode 100644 src/libstd/sys/sgx/abi/reloc.rs create mode 100644 src/libstd/sys/sgx/abi/usercalls/mod.rs create mode 100644 src/libstd/sys/sgx/abi/usercalls/raw.rs create mode 100644 src/libstd/sys/sgx/alloc.rs create mode 100644 src/libstd/sys/sgx/args.rs create mode 100644 src/libstd/sys/sgx/backtrace.rs create mode 100644 src/libstd/sys/sgx/cmath.rs create mode 100644 src/libstd/sys/sgx/condvar.rs create mode 100644 src/libstd/sys/sgx/env.rs create mode 100644 src/libstd/sys/sgx/fs.rs create mode 100644 src/libstd/sys/sgx/memchr.rs create mode 100644 src/libstd/sys/sgx/mod.rs create mode 100644 src/libstd/sys/sgx/mutex.rs create mode 100644 src/libstd/sys/sgx/net.rs create mode 100644 src/libstd/sys/sgx/os.rs create mode 100644 src/libstd/sys/sgx/os_str.rs create mode 100644 src/libstd/sys/sgx/path.rs create mode 100644 src/libstd/sys/sgx/pipe.rs create mode 100644 src/libstd/sys/sgx/process.rs create mode 100644 src/libstd/sys/sgx/rwlock.rs create mode 100644 src/libstd/sys/sgx/stack_overflow.rs create mode 100644 src/libstd/sys/sgx/stdio.rs create mode 100644 src/libstd/sys/sgx/thread.rs create mode 100644 src/libstd/sys/sgx/thread_local.rs create mode 100644 src/libstd/sys/sgx/time.rs create mode 160000 src/rust-sgx create mode 100644 src/rustc/fortanix-sgx-abi_shim/Cargo.toml (limited to 'src/libstd/sys') diff --git a/.gitmodules b/.gitmodules index 4a136cff1cd..3fc6e45db3e 100644 --- a/.gitmodules +++ b/.gitmodules @@ -61,10 +61,12 @@ path = src/tools/clang url = https://github.com/rust-lang-nursery/clang.git branch = rust-release-80-v2 - [submodule "src/doc/rustc-guide"] path = src/doc/rustc-guide url = https://github.com/rust-lang/rustc-guide.git [submodule "src/doc/edition-guide"] path = src/doc/edition-guide url = https://github.com/rust-lang-nursery/edition-guide +[submodule "src/rust-sgx"] + path = src/rust-sgx + url = https://github.com/fortanix/rust-sgx diff --git a/Cargo.lock b/Cargo.lock index 02c63200a28..316724ca651 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -797,6 +797,14 @@ name = "foreign-types-shared" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "fortanix-sgx-abi" +version = "0.0.0" +dependencies = [ + "compiler_builtins 0.0.0", + "core 0.0.0", +] + [[package]] name = "fs2" version = "0.4.3" @@ -2773,6 +2781,7 @@ dependencies = [ "compiler_builtins 0.0.0", "core 0.0.0", "dlmalloc 0.0.0", + "fortanix-sgx-abi 0.0.0", "libc 0.0.0", "panic_abort 0.0.0", "panic_unwind 0.0.0", diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index cd8d5642b25..6108692e43c 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -874,6 +874,7 @@ impl Step for Src { "src/rustc/compiler_builtins_shim", "src/rustc/libc_shim", "src/rustc/dlmalloc_shim", + "src/rustc/fortanix-sgx-abi_shim", "src/libtest", "src/libterm", "src/libprofiler_builtins", diff --git a/src/dlmalloc b/src/dlmalloc index c99638dc2ec..de99f4b0c88 160000 --- a/src/dlmalloc +++ b/src/dlmalloc @@ -1 +1 @@ -Subproject commit c99638dc2ecfc750cc1656f6edb2bd062c1e0981 +Subproject commit de99f4b0c886f5916cd1a146464276d65bef61b8 diff --git a/src/liblibc b/src/liblibc index c75ca6465a1..5b403753da9 160000 --- a/src/liblibc +++ b/src/liblibc @@ -1 +1 @@ -Subproject commit c75ca6465a139704e00295be355b1f067af2f535 +Subproject commit 5b403753da9ec8ff501adf34cb6d63b319b4a3ae diff --git a/src/libpanic_abort/lib.rs b/src/libpanic_abort/lib.rs index 9235f8e7660..95c3514185e 100644 --- a/src/libpanic_abort/lib.rs +++ b/src/libpanic_abort/lib.rs @@ -66,6 +66,12 @@ pub unsafe extern fn __rust_start_panic(_payload: usize) -> u32 { unsafe fn abort() -> ! { core::intrinsics::abort(); } + + #[cfg(target_env="sgx")] + unsafe fn abort() -> ! { + extern "C" { pub fn panic_exit() -> !; } + panic_exit(); + } } // This... is a bit of an oddity. The tl;dr; is that this is required to link diff --git a/src/libpanic_unwind/lib.rs b/src/libpanic_unwind/lib.rs index cfe671c626b..49f8a429126 100644 --- a/src/libpanic_unwind/lib.rs +++ b/src/libpanic_unwind/lib.rs @@ -62,7 +62,7 @@ cfg_if! { if #[cfg(target_os = "emscripten")] { #[path = "emcc.rs"] mod imp; - } else if #[cfg(target_arch = "wasm32")] { + } else if #[cfg(any(target_arch = "wasm32", target_env = "sgx"))] { #[path = "dummy.rs"] mod imp; } else if #[cfg(all(target_env = "msvc", target_arch = "aarch64"))] { diff --git a/src/libstd/Cargo.toml b/src/libstd/Cargo.toml index cae2f405318..274d5bec662 100644 --- a/src/libstd/Cargo.toml +++ b/src/libstd/Cargo.toml @@ -35,9 +35,12 @@ rustc_lsan = { path = "../librustc_lsan" } rustc_msan = { path = "../librustc_msan" } rustc_tsan = { path = "../librustc_tsan" } -[target.'cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))'.dependencies] +[target.'cfg(any(all(target_arch = "wasm32", not(target_os = "emscripten")), target_env = "sgx"))'.dependencies] dlmalloc = { path = '../rustc/dlmalloc_shim' } +[target.x86_64-fortanix-unknown-sgx.dependencies] +fortanix-sgx-abi = { path = "../rustc/fortanix-sgx-abi_shim" } + [build-dependencies] cc = "1.0" build_helper = { path = "../build_helper" } diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index 386de080b85..32e29962760 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -184,7 +184,7 @@ pub enum ErrorKind { } impl ErrorKind { - fn as_str(&self) -> &'static str { + pub(crate) fn as_str(&self) -> &'static str { match *self { ErrorKind::NotFound => "entity not found", ErrorKind::PermissionDenied => "permission denied", diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 78109a1a690..bf1e64efd37 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -312,6 +312,7 @@ #![feature(non_exhaustive)] #![feature(alloc_layout_extra)] #![feature(maybe_uninit)] +#![cfg_attr(target_env = "sgx", feature(global_asm, range_contains))] #![default_lib_allocator] @@ -354,6 +355,12 @@ extern crate unwind; // testing gives test-std access to real-std lang items and globals. See #2912 #[cfg(test)] extern crate std as realstd; +#[cfg(target_env = "sgx")] +#[macro_use] +#[allow(unused_imports)] // FIXME: without `#[macro_use]`, get error: “cannot + // determine resolution for the macro `usercalls_asm`” +extern crate fortanix_sgx_abi; + // The standard macros that are not built-in to the compiler. #[macro_use] mod macros; diff --git a/src/libstd/sys/mod.rs b/src/libstd/sys/mod.rs index 61e4ce66eec..04c47aeb827 100644 --- a/src/libstd/sys/mod.rs +++ b/src/libstd/sys/mod.rs @@ -48,6 +48,9 @@ cfg_if! { } else if #[cfg(target_arch = "wasm32")] { mod wasm; pub use self::wasm::*; + } else if #[cfg(target_env = "sgx")] { + mod sgx; + pub use self::sgx::*; } else { compile_error!("libstd doesn't compile for this platform yet"); } diff --git a/src/libstd/sys/sgx/abi/entry.S b/src/libstd/sys/sgx/abi/entry.S new file mode 100644 index 00000000000..4d5cc02e11e --- /dev/null +++ b/src/libstd/sys/sgx/abi/entry.S @@ -0,0 +1,327 @@ +/* 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. */ + +/* This symbol is used at runtime to figure out the virtual address that the */ +/* enclave is loaded at. */ +.section absolute +.global IMAGE_BASE +IMAGE_BASE: + +.section .rodata +/* The XSAVE area needs to be a large chunk of readable memory, but since we are */ +/* going to restore everything to its initial state (XSTATE_BV=0), only certain */ +/* parts need to have a defined value. In particular: */ +/* */ +/* * MXCSR in the legacy area. This register is always restored if RFBM[1] or */ +/* RFBM[2] is set, regardless of the value of XSTATE_BV */ +/* * XSAVE header */ +.align 64 +.Lxsave_clear: +.org .+24 +.Lxsave_mxcsr: + .int 0 + +/* We can store a bunch of data in the gap between MXCSR and the XSAVE header */ + +/* The following symbols point at read-only data that will be filled in by the */ +/* post-linker. */ + +/* When using this macro, don't forget to adjust the linker version script! */ +.macro globvar name:req size:req + .global \name + .protected \name + .align \size + .size \name , \size + \name : + .org .+\size +.endm + /* The base address (relative to enclave start) of the heap area */ + globvar HEAP_BASE 8 + /* The heap size in bytes */ + globvar HEAP_SIZE 8 + /* Value of the RELA entry in the dynamic table */ + globvar RELA 8 + /* Value of the RELACOUNT entry in the dynamic table */ + globvar RELACOUNT 8 + /* The enclave size in bytes */ + globvar ENCLAVE_SIZE 8 + /* The base address (relative to enclave start) of the enclave configuration area */ + globvar CFGDATA_BASE 8 + /* Non-zero if debugging is enabled, zero otherwise */ + globvar DEBUG 1 + +.Lreentry_panic_msg: + .asciz "Re-entered panicked enclave!" +.Lreentry_panic_msg_end: + +.Lusercall_panic_msg: + .asciz "Invalid usercall#!" +.Lusercall_panic_msg_end: + +.org .Lxsave_clear+512 +.Lxsave_header: + .int 0, 0 /* XSTATE_BV */ + .int 0, 0 /* XCOMP_BV */ + .org .+48 /* reserved bits */ + +.data +.Lpanicked: + .byte 0 + +/* TCS local storage section */ +.equ tcsls_tos, 0x00 /* initialized by loader to *offset* from image base to TOS */ +.equ tcsls_flags, 0x08 /* initialized by loader */ +.equ tcsls_flag_secondary, 0 /* initialized by loader; 0 = standard TCS, 1 = secondary TCS */ +.equ tcsls_flag_init_once, 1 /* initialized by loader to 0 */ +/* 14 unused bits */ +.equ tcsls_user_fcw, 0x0a +.equ tcsls_user_mxcsr, 0x0c +.equ tcsls_last_rsp, 0x10 /* initialized by loader to 0 */ +.equ tcsls_panic_last_rsp, 0x18 /* initialized by loader to 0 */ +.equ tcsls_debug_panic_buf_ptr, 0x20 /* initialized by loader to 0 */ +.equ tcsls_user_rsp, 0x28 +.equ tcsls_user_retip, 0x30 +.equ tcsls_user_rbp, 0x38 +.equ tcsls_user_r12, 0x40 +.equ tcsls_user_r13, 0x48 +.equ tcsls_user_r14, 0x50 +.equ tcsls_user_r15, 0x58 +.equ tcsls_tls_ptr, 0x60 +.equ tcsls_tcs_addr, 0x68 + +.macro load_tcsls_flag_secondary_bool reg:req comments:vararg + .ifne tcsls_flag_secondary /* to convert to a bool, must be the first bit */ + .abort + .endif + mov $(1< ! { + panic!(msg) +} + +// Called once when a TCS is first entered +extern "C" fn tcs_init(secondary: bool); + +// Standard TCS entrypoint +extern "C" fn entry(p1: u64, p2: u64, p3: u64, secondary: bool, p4: u64, p5: u64) -> (u64, u64); +``` +*/ + +.global get_tcs_addr +get_tcs_addr: + mov %gs:tcsls_tcs_addr,%rax + ret + +.global get_tls_ptr +get_tls_ptr: + mov %gs:tcsls_tls_ptr,%rax + ret + +.global set_tls_ptr +set_tls_ptr: + mov %rdi,%gs:tcsls_tls_ptr + ret + +.global take_debug_panic_buf_ptr +take_debug_panic_buf_ptr: + xor %rax,%rax + xchg %gs:tcsls_debug_panic_buf_ptr,%rax + ret diff --git a/src/libstd/sys/sgx/abi/mem.rs b/src/libstd/sys/sgx/abi/mem.rs new file mode 100644 index 00000000000..aedf6ec7acb --- /dev/null +++ b/src/libstd/sys/sgx/abi/mem.rs @@ -0,0 +1,31 @@ +// 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. + +// Do not remove inline: will result in relocation failure +#[inline(always)] +pub unsafe fn rel_ptr(offset: u64) -> *const T { + (image_base()+offset) as *const T +} + +// Do not remove inline: will result in relocation failure +#[inline(always)] +pub unsafe fn rel_ptr_mut(offset: u64) -> *mut T { + (image_base()+offset) as *mut T +} + +// Do not remove inline: will result in relocation failure +// For the same reason we use inline ASM here instead of an extern static to +// locate the base +#[inline(always)] +fn image_base() -> u64 { + let base; + unsafe{asm!("lea IMAGE_BASE(%rip),$0":"=r"(base))}; + base +} diff --git a/src/libstd/sys/sgx/abi/mod.rs b/src/libstd/sys/sgx/abi/mod.rs new file mode 100644 index 00000000000..cade96e3f52 --- /dev/null +++ b/src/libstd/sys/sgx/abi/mod.rs @@ -0,0 +1,94 @@ +// 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. + +use core::sync::atomic::{AtomicUsize, Ordering}; +use io::Write; + +// runtime features +mod reloc; +mod mem; +pub(super) mod panic; + +// library features +#[macro_use] +mod usercalls; + +global_asm!(concat!(usercalls_asm!(), include_str!("entry.S"))); + +#[no_mangle] +unsafe extern "C" fn tcs_init(secondary: bool) { + // Be very careful when changing this code: it runs before the binary has been + // relocated. Any indirect accesses to symbols will likely fail. + const UNINIT: usize = 0; + const BUSY: usize = 1; + const DONE: usize = 2; + // Three-state spin-lock + static RELOC_STATE: AtomicUsize = AtomicUsize::new(UNINIT); + + if secondary && RELOC_STATE.load(Ordering::Relaxed) != DONE { + panic::panic_msg("Entered secondary TCS before main TCS!") + } + + // Try to atomically swap UNINIT with BUSY. The returned state can be: + match RELOC_STATE.compare_and_swap(UNINIT, BUSY, Ordering::Acquire) { + // This thread just obtained the lock and other threads will observe BUSY + UNINIT => { + reloc::relocate_elf_rela(); + RELOC_STATE.store(DONE, Ordering::Release); + }, + // We need to wait until the initialization is done. + BUSY => while RELOC_STATE.load(Ordering::Acquire) == BUSY { + ::core::arch::x86_64::_mm_pause() + }, + // Initialization is done. + DONE => {}, + _ => unreachable!() + } +} + +// FIXME: this item should only exist if this is linked into an executable +// (main function exists). If this is a library, the crate author should be +// able to specify this +#[no_mangle] +#[allow(unreachable_code)] +extern "C" fn entry(p1: u64, p2: u64, p3: u64, secondary: bool, p4: u64, p5: u64) -> (u64, u64) { + if secondary { + unimplemented!("thread entrypoint"); + + (0, 0) + } else { + extern "C" { + fn main(argc: isize, argv: *const *const u8) -> isize; + } + + // check entry is being called according to ABI + assert_eq!(p3, 0); + assert_eq!(p4, 0); + assert_eq!(p5, 0); + + unsafe { + // The actual types of these arguments are `p1: *const Arg, p2: + // usize`. We can't currently customize the argument list of Rust's + // main function, so we pass these in as the standard pointer-sized + // values in `argc` and `argv`. + let ret = main(p2 as _, p1 as _); + exit_with_code(ret) + } + } +} + +pub(super) fn exit_with_code(code: isize) -> ! { + if code != 0 { + if let Some(mut out) = panic::SgxPanicOutput::new() { + let _ = write!(out, "Exited with status code {}", code); + } + } + unsafe { usercalls::raw::exit(code != 0) }; +} diff --git a/src/libstd/sys/sgx/abi/panic.rs b/src/libstd/sys/sgx/abi/panic.rs new file mode 100644 index 00000000000..dd9159b9fe2 --- /dev/null +++ b/src/libstd/sys/sgx/abi/panic.rs @@ -0,0 +1,58 @@ +// 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. + +use io::{self, Write}; +use slice::from_raw_parts_mut; + +extern "C" { + fn take_debug_panic_buf_ptr() -> *mut u8; + static DEBUG: u8; +} + +pub(crate) struct SgxPanicOutput(Option<&'static mut [u8]>); + +impl SgxPanicOutput { + pub(crate) fn new() -> Option { + if unsafe { DEBUG == 0 } { + None + } else { + Some(SgxPanicOutput(None)) + } + } + + fn init(&mut self) -> &mut &'static mut [u8] { + self.0.get_or_insert_with(|| unsafe { + let ptr = take_debug_panic_buf_ptr(); + if ptr.is_null() { + &mut [] + } else { + from_raw_parts_mut(ptr, 1024) + } + }) + } +} + +impl Write for SgxPanicOutput { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.init().write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.init().flush() + } +} + +#[no_mangle] +pub extern "C" fn panic_msg(msg: &str) -> ! { + let _ = SgxPanicOutput::new().map(|mut out| out.write(msg.as_bytes())); + unsafe { panic_exit(); } +} + +extern "C" { pub fn panic_exit() -> !; } diff --git a/src/libstd/sys/sgx/abi/reloc.rs b/src/libstd/sys/sgx/abi/reloc.rs new file mode 100644 index 00000000000..2d5e14d6ad1 --- /dev/null +++ b/src/libstd/sys/sgx/abi/reloc.rs @@ -0,0 +1,40 @@ +// 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. + +use slice::from_raw_parts; +use super::mem; + +const R_X86_64_RELATIVE: u32 = 8; + +#[repr(packed)] +struct Rela { + offset: T, + info: T, + addend: T, +} + +pub fn relocate_elf_rela() { + extern { + static RELA: u64; + static RELACOUNT: usize; + } + + if unsafe { RELACOUNT } == 0 { return } // unsafe ok: link-time constant + + let relas = unsafe { + from_raw_parts::>(mem::rel_ptr(RELA), RELACOUNT) // unsafe ok: link-time constant + }; + for rela in relas { + if rela.info != (/*0 << 32 |*/ R_X86_64_RELATIVE as u64) { + panic!("Invalid relocation"); + } + unsafe { *mem::rel_ptr_mut::<*const ()>(rela.offset) = mem::rel_ptr(rela.addend) }; + } +} diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs new file mode 100644 index 00000000000..370e058badf --- /dev/null +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -0,0 +1,12 @@ +// 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. + +#[macro_use] +pub mod raw; diff --git a/src/libstd/sys/sgx/abi/usercalls/raw.rs b/src/libstd/sys/sgx/abi/usercalls/raw.rs new file mode 100644 index 00000000000..a28d41c1b74 --- /dev/null +++ b/src/libstd/sys/sgx/abi/usercalls/raw.rs @@ -0,0 +1,231 @@ +// 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. + +#![allow(unused)] + +use fortanix_sgx_abi::*; + +use ptr::NonNull; + +#[repr(C)] +struct UsercallReturn(u64, u64); + +extern "C" { + fn usercall(nr: u64, p1: u64, p2: u64, _ignore: u64, p3: u64, p4: u64) -> UsercallReturn; +} + +unsafe fn do_usercall(nr: u64, p1: u64, p2: u64, p3: u64, p4: u64) -> (u64, u64) { + if nr==0 { panic!("Invalid usercall number {}",nr) } + let UsercallReturn(a, b) = usercall(nr,p1,p2,0,p3,p4); + (a, b) +} + +type Register = u64; + +trait RegisterArgument { + fn from_register(Register) -> Self; + fn into_register(self) -> Register; +} + +trait ReturnValue { + fn from_registers(call: &'static str, regs: (Register, Register)) -> Self; +} + +macro_rules! define_usercalls { + // Using `$r:tt` because `$r:ty` doesn't match ! in `clobber_diverging` + ($(fn $f:ident($($n:ident: $t:ty),*) $(-> $r:tt)*; )*) => { + #[repr(C)] + #[allow(non_camel_case_types)] + enum Usercalls { + __enclave_usercalls_invalid, + $($f,)* + } + + $(enclave_usercalls_internal_define_usercalls!(def fn $f($($n: $t),*) $(-> $r)*);)* + }; +} + +macro_rules! define_usercalls_asm { + ($(fn $f:ident($($n:ident: $t:ty),*) $(-> $r:ty)*; )*) => { + macro_rules! usercalls_asm { + () => { + concat!( + ".equ usercall_nr_LAST, 0\n", + $( + ".equ usercall_nr_", stringify!($f), ", usercall_nr_LAST+1\n", + ".equ usercall_nr_LAST, usercall_nr_", stringify!($f), "\n" + ),* + ) + } + } + }; +} + +macro_rules! define_ra { + (< $i:ident > $t:ty) => { + impl<$i> RegisterArgument for $t { + fn from_register(a: Register) -> Self { + a as _ + } + fn into_register(self) -> Register { + self as _ + } + } + }; + ($i:ty as $t:ty) => { + impl RegisterArgument for $t { + fn from_register(a: Register) -> Self { + a as $i as _ + } + fn into_register(self) -> Register { + self as $i as _ + } + } + }; + ($t:ty) => { + impl RegisterArgument for $t { + fn from_register(a: Register) -> Self { + a as _ + } + fn into_register(self) -> Register { + self as _ + } + } + }; +} + +define_ra!(Register); +define_ra!(i64); +define_ra!(u32); +define_ra!(u32 as i32); +define_ra!(u16); +define_ra!(u16 as i16); +define_ra!(u8); +define_ra!(u8 as i8); +define_ra!(usize); +define_ra!(usize as isize); +define_ra!( *const T); +define_ra!( *mut T); + +impl RegisterArgument for bool { + fn from_register(a: Register) -> bool { + if a != 0 { + true + } else { + false + } + } + fn into_register(self) -> Register { + self as _ + } +} + +impl RegisterArgument for Option> { + fn from_register(a: Register) -> Option> { + NonNull::new(a as _) + } + fn into_register(self) -> Register { + self.map_or(0 as _, NonNull::as_ptr) as _ + } +} + +impl ReturnValue for ! { + fn from_registers(call: &'static str, _regs: (Register, Register)) -> Self { + panic!("Usercall {}: did not expect to be re-entered", call); + } +} + +impl ReturnValue for () { + fn from_registers(call: &'static str, regs: (Register, Register)) -> Self { + assert_eq!(regs.0, 0, "Usercall {}: expected {} return value to be 0", call, "1st"); + assert_eq!(regs.1, 0, "Usercall {}: expected {} return value to be 0", call, "2nd"); + () + } +} + +impl ReturnValue for T { + fn from_registers(call: &'static str, regs: (Register, Register)) -> Self { + assert_eq!(regs.1, 0, "Usercall {}: expected {} return value to be 0", call, "2nd"); + T::from_register(regs.0) + } +} + +impl ReturnValue for (T, U) { + fn from_registers(_call: &'static str, regs: (Register, Register)) -> Self { + ( + T::from_register(regs.0), + U::from_register(regs.1) + ) + } +} + +macro_rules! enclave_usercalls_internal_define_usercalls { + (def fn $f:ident($n1:ident: $t1:ty, $n2:ident: $t2:ty, + $n3:ident: $t3:ty, $n4:ident: $t4:ty) -> $r:ty) => ( + #[inline(always)] + pub unsafe fn $f($n1: $t1, $n2: $t2, $n3: $t3, $n4: $t4) -> $r { + ReturnValue::from_registers(stringify!($f), do_usercall( + Usercalls::$f as Register, + RegisterArgument::into_register($n1), + RegisterArgument::into_register($n2), + RegisterArgument::into_register($n3), + RegisterArgument::into_register($n4), + )) + } + ); + (def fn $f:ident($n1:ident: $t1:ty, $n2:ident: $t2:ty, $n3:ident: $t3:ty) -> $r:ty) => ( + #[inline(always)] + pub unsafe fn $f($n1: $t1, $n2: $t2, $n3: $t3) -> $r { + ReturnValue::from_registers(stringify!($f), do_usercall( + Usercalls::$f as Register, + RegisterArgument::into_register($n1), + RegisterArgument::into_register($n2), + RegisterArgument::into_register($n3), + 0 + )) + } + ); + (def fn $f:ident($n1:ident: $t1:ty, $n2:ident: $t2:ty) -> $r:ty) => ( + #[inline(always)] + pub unsafe fn $f($n1: $t1, $n2: $t2) -> $r { + ReturnValue::from_registers(stringify!($f), do_usercall( + Usercalls::$f as Register, + RegisterArgument::into_register($n1), + RegisterArgument::into_register($n2), + 0,0 + )) + } + ); + (def fn $f:ident($n1:ident: $t1:ty) -> $r:ty) => ( + #[inline(always)] + pub unsafe fn $f($n1: $t1) -> $r { + ReturnValue::from_registers(stringify!($f), do_usercall( + Usercalls::$f as Register, + RegisterArgument::into_register($n1), + 0,0,0 + )) + } + ); + (def fn $f:ident() -> $r:ty) => ( + #[inline(always)] + pub unsafe fn $f() -> $r { + ReturnValue::from_registers(stringify!($f), do_usercall( + Usercalls::$f as Register, + 0,0,0,0 + )) + } + ); + (def fn $f:ident($($n:ident: $t:ty),*)) => ( + enclave_usercalls_internal_define_usercalls!(def fn $f($($n: $t),*) -> ()); + ); +} + +invoke_with_usercalls!(define_usercalls); +invoke_with_usercalls!(define_usercalls_asm); diff --git a/src/libstd/sys/sgx/alloc.rs b/src/libstd/sys/sgx/alloc.rs new file mode 100644 index 00000000000..a31f93ae493 --- /dev/null +++ b/src/libstd/sys/sgx/alloc.rs @@ -0,0 +1,39 @@ +// 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. + +extern crate dlmalloc; + +use alloc::{GlobalAlloc, Layout, System}; + +// FIXME: protect this value for concurrent access +static mut DLMALLOC: dlmalloc::Dlmalloc = dlmalloc::DLMALLOC_INIT; + +#[stable(feature = "alloc_system_type", since = "1.28.0")] +unsafe impl GlobalAlloc for System { + #[inline] + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + DLMALLOC.malloc(layout.size(), layout.align()) + } + + #[inline] + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { + DLMALLOC.calloc(layout.size(), layout.align()) + } + + #[inline] + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + DLMALLOC.free(ptr, layout.size(), layout.align()) + } + + #[inline] + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { + DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) + } +} diff --git a/src/libstd/sys/sgx/args.rs b/src/libstd/sys/sgx/args.rs new file mode 100644 index 00000000000..64cb83b462a --- /dev/null +++ b/src/libstd/sys/sgx/args.rs @@ -0,0 +1,57 @@ +// 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. + +use ffi::OsString; +use fortanix_sgx_abi::ByteBuffer; + +pub unsafe fn init(argc: isize, argv: *const *const u8) { + // See ABI + let _len: usize = argc as _; + let _args: *const ByteBuffer = argv as _; + + // TODO +} + +pub unsafe fn cleanup() { +} + +pub fn args() -> Args { + Args +} + +pub struct Args; + +impl Args { + pub fn inner_debug(&self) -> &[OsString] { + &[] + } +} + +impl Iterator for Args { + type Item = OsString; + fn next(&mut self) -> Option { + None + } + fn size_hint(&self) -> (usize, Option) { + (0, Some(0)) + } +} + +impl ExactSizeIterator for Args { + fn len(&self) -> usize { + 0 + } +} + +impl DoubleEndedIterator for Args { + fn next_back(&mut self) -> Option { + None + } +} diff --git a/src/libstd/sys/sgx/backtrace.rs b/src/libstd/sys/sgx/backtrace.rs new file mode 100644 index 00000000000..ca4a7c9561c --- /dev/null +++ b/src/libstd/sys/sgx/backtrace.rs @@ -0,0 +1,37 @@ +// 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. + +use io; +use sys::unsupported; +use sys_common::backtrace::Frame; + +pub struct BacktraceContext; + +pub fn unwind_backtrace(_frames: &mut [Frame]) + -> io::Result<(usize, BacktraceContext)> +{ + unsupported() +} + +pub fn resolve_symname(_frame: Frame, + _callback: F, + _: &BacktraceContext) -> io::Result<()> + where F: FnOnce(Option<&str>) -> io::Result<()> +{ + unsupported() +} + +pub fn foreach_symbol_fileline(_: Frame, + _: F, + _: &BacktraceContext) -> io::Result + where F: FnMut(&[u8], u32) -> io::Result<()> +{ + unsupported() +} diff --git a/src/libstd/sys/sgx/cmath.rs b/src/libstd/sys/sgx/cmath.rs new file mode 100644 index 00000000000..0c1300f61f8 --- /dev/null +++ b/src/libstd/sys/sgx/cmath.rs @@ -0,0 +1,41 @@ +// 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. + +#![cfg(not(test))] + +// These symbols are all defined in `compiler-builtins` +extern { + pub fn acos(n: f64) -> f64; + pub fn acosf(n: f32) -> f32; + pub fn asin(n: f64) -> f64; + pub fn asinf(n: f32) -> f32; + pub fn atan(n: f64) -> f64; + pub fn atan2(a: f64, b: f64) -> f64; + pub fn atan2f(a: f32, b: f32) -> f32; + pub fn atanf(n: f32) -> f32; + pub fn cbrt(n: f64) -> f64; + pub fn cbrtf(n: f32) -> f32; + pub fn cosh(n: f64) -> f64; + pub fn coshf(n: f32) -> f32; + pub fn expm1(n: f64) -> f64; + pub fn expm1f(n: f32) -> f32; + pub fn fdim(a: f64, b: f64) -> f64; + pub fn fdimf(a: f32, b: f32) -> f32; + pub fn hypot(x: f64, y: f64) -> f64; + pub fn hypotf(x: f32, y: f32) -> f32; + pub fn log1p(n: f64) -> f64; + pub fn log1pf(n: f32) -> f32; + pub fn sinh(n: f64) -> f64; + pub fn sinhf(n: f32) -> f32; + pub fn tan(n: f64) -> f64; + pub fn tanf(n: f32) -> f32; + pub fn tanh(n: f64) -> f64; + pub fn tanhf(n: f32) -> f32; +} diff --git a/src/libstd/sys/sgx/condvar.rs b/src/libstd/sys/sgx/condvar.rs new file mode 100644 index 00000000000..2097280a064 --- /dev/null +++ b/src/libstd/sys/sgx/condvar.rs @@ -0,0 +1,43 @@ +// 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. + +use sys::mutex::Mutex; +use time::Duration; + +pub struct Condvar { } + +impl Condvar { + pub const fn new() -> Condvar { + Condvar { } + } + + #[inline] + pub unsafe fn init(&mut self) {} + + #[inline] + pub unsafe fn notify_one(&self) { + } + + #[inline] + pub unsafe fn notify_all(&self) { + } + + pub unsafe fn wait(&self, _mutex: &Mutex) { + panic!("can't block with web assembly") + } + + pub unsafe fn wait_timeout(&self, _mutex: &Mutex, _dur: Duration) -> bool { + panic!("can't block with web assembly"); + } + + #[inline] + pub unsafe fn destroy(&self) { + } +} diff --git a/src/libstd/sys/sgx/env.rs b/src/libstd/sys/sgx/env.rs new file mode 100644 index 00000000000..146ce02754b --- /dev/null +++ b/src/libstd/sys/sgx/env.rs @@ -0,0 +1,19 @@ +// 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. + +pub mod os { + pub const FAMILY: &'static str = ""; + pub const OS: &'static str = ""; + pub const DLL_PREFIX: &'static str = ""; + pub const DLL_SUFFIX: &'static str = ".sgxs"; + pub const DLL_EXTENSION: &'static str = "sgxs"; + pub const EXE_SUFFIX: &'static str = ".sgxs"; + pub const EXE_EXTENSION: &'static str = "sgxs"; +} diff --git a/src/libstd/sys/sgx/fs.rs b/src/libstd/sys/sgx/fs.rs new file mode 100644 index 00000000000..1dcea3e8eac --- /dev/null +++ b/src/libstd/sys/sgx/fs.rs @@ -0,0 +1,304 @@ +// 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. + +use ffi::OsString; +use fmt; +use hash::{Hash, Hasher}; +use io::{self, SeekFrom}; +use path::{Path, PathBuf}; +use sys::time::SystemTime; +use sys::{unsupported, Void}; + +pub struct File(Void); + +pub struct FileAttr(Void); + +pub struct ReadDir(Void); + +pub struct DirEntry(Void); + +#[derive(Clone, Debug)] +pub struct OpenOptions { } + +pub struct FilePermissions(Void); + +pub struct FileType(Void); + +#[derive(Debug)] +pub struct DirBuilder { } + +impl FileAttr { + pub fn size(&self) -> u64 { + match self.0 {} + } + + pub fn perm(&self) -> FilePermissions { + match self.0 {} + } + + pub fn file_type(&self) -> FileType { + match self.0 {} + } + + pub fn modified(&self) -> io::Result { + match self.0 {} + } + + pub fn accessed(&self) -> io::Result { + match self.0 {} + } + + pub fn created(&self) -> io::Result { + match self.0 {} + } +} + +impl Clone for FileAttr { + fn clone(&self) -> FileAttr { + match self.0 {} + } +} + +impl FilePermissions { + pub fn readonly(&self) -> bool { + match self.0 {} + } + + pub fn set_readonly(&mut self, _readonly: bool) { + match self.0 {} + } +} + +impl Clone for FilePermissions { + fn clone(&self) -> FilePermissions { + match self.0 {} + } +} + +impl PartialEq for FilePermissions { + fn eq(&self, _other: &FilePermissions) -> bool { + match self.0 {} + } +} + +impl Eq for FilePermissions { +} + +impl fmt::Debug for FilePermissions { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +impl FileType { + pub fn is_dir(&self) -> bool { + match self.0 {} + } + + pub fn is_file(&self) -> bool { + match self.0 {} + } + + pub fn is_symlink(&self) -> bool { + match self.0 {} + } +} + +impl Clone for FileType { + fn clone(&self) -> FileType { + match self.0 {} + } +} + +impl Copy for FileType {} + +impl PartialEq for FileType { + fn eq(&self, _other: &FileType) -> bool { + match self.0 {} + } +} + +impl Eq for FileType { +} + +impl Hash for FileType { + fn hash(&self, _h: &mut H) { + match self.0 {} + } +} + +impl fmt::Debug for FileType { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +impl fmt::Debug for ReadDir { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +impl Iterator for ReadDir { + type Item = io::Result; + + fn next(&mut self) -> Option> { + match self.0 {} + } +} + +impl DirEntry { + pub fn path(&self) -> PathBuf { + match self.0 {} + } + + pub fn file_name(&self) -> OsString { + match self.0 {} + } + + pub fn metadata(&self) -> io::Result { + match self.0 {} + } + + pub fn file_type(&self) -> io::Result { + match self.0 {} + } +} + +impl OpenOptions { + pub fn new() -> OpenOptions { + OpenOptions { } + } + + pub fn read(&mut self, _read: bool) { } + pub fn write(&mut self, _write: bool) { } + pub fn append(&mut self, _append: bool) { } + pub fn truncate(&mut self, _truncate: bool) { } + pub fn create(&mut self, _create: bool) { } + pub fn create_new(&mut self, _create_new: bool) { } +} + +impl File { + pub fn open(_path: &Path, _opts: &OpenOptions) -> io::Result { + unsupported() + } + + pub fn file_attr(&self) -> io::Result { + match self.0 {} + } + + pub fn fsync(&self) -> io::Result<()> { + match self.0 {} + } + + pub fn datasync(&self) -> io::Result<()> { + match self.0 {} + } + + pub fn truncate(&self, _size: u64) -> io::Result<()> { + match self.0 {} + } + + pub fn read(&self, _buf: &mut [u8]) -> io::Result { + match self.0 {} + } + + pub fn write(&self, _buf: &[u8]) -> io::Result { + match self.0 {} + } + + pub fn flush(&self) -> io::Result<()> { + match self.0 {} + } + + pub fn seek(&self, _pos: SeekFrom) -> io::Result { + match self.0 {} + } + + pub fn duplicate(&self) -> io::Result { + match self.0 {} + } + + pub fn set_permissions(&self, _perm: FilePermissions) -> io::Result<()> { + match self.0 {} + } + + pub fn diverge(&self) -> ! { + match self.0 {} + } +} + +impl DirBuilder { + pub fn new() -> DirBuilder { + DirBuilder { } + } + + pub fn mkdir(&self, _p: &Path) -> io::Result<()> { + unsupported() + } +} + +impl fmt::Debug for File { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +pub fn readdir(_p: &Path) -> io::Result { + unsupported() +} + +pub fn unlink(_p: &Path) -> io::Result<()> { + unsupported() +} + +pub fn rename(_old: &Path, _new: &Path) -> io::Result<()> { + unsupported() +} + +pub fn set_perm(_p: &Path, perm: FilePermissions) -> io::Result<()> { + match perm.0 {} +} + +pub fn rmdir(_p: &Path) -> io::Result<()> { + unsupported() +} + +pub fn remove_dir_all(_path: &Path) -> io::Result<()> { + unsupported() +} + +pub fn readlink(_p: &Path) -> io::Result { + unsupported() +} + +pub fn symlink(_src: &Path, _dst: &Path) -> io::Result<()> { + unsupported() +} + +pub fn link(_src: &Path, _dst: &Path) -> io::Result<()> { + unsupported() +} + +pub fn stat(_p: &Path) -> io::Result { + unsupported() +} + +pub fn lstat(_p: &Path) -> io::Result { + unsupported() +} + +pub fn canonicalize(_p: &Path) -> io::Result { + unsupported() +} + +pub fn copy(_from: &Path, _to: &Path) -> io::Result { + unsupported() +} diff --git a/src/libstd/sys/sgx/memchr.rs b/src/libstd/sys/sgx/memchr.rs new file mode 100644 index 00000000000..0998bc5db4c --- /dev/null +++ b/src/libstd/sys/sgx/memchr.rs @@ -0,0 +1,11 @@ +// 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. + +pub use core::slice::memchr::{memchr, memrchr}; diff --git a/src/libstd/sys/sgx/mod.rs b/src/libstd/sys/sgx/mod.rs new file mode 100644 index 00000000000..f38c69e90c7 --- /dev/null +++ b/src/libstd/sys/sgx/mod.rs @@ -0,0 +1,151 @@ +// 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. + +//! System bindings for the Fortanix SGX platform +//! +//! This module contains the facade (aka platform-specific) implementations of +//! OS level functionality for Fortanix SGX. + +use io; +use os::raw::c_char; +use sync::atomic::{AtomicBool, Ordering}; + +pub mod abi; + +pub mod alloc; +pub mod args; +#[cfg(feature = "backtrace")] +pub mod backtrace; +pub mod cmath; +pub mod condvar; +pub mod env; +pub mod fs; +pub mod memchr; +pub mod mutex; +pub mod net; +pub mod os; +pub mod os_str; +pub mod path; +pub mod pipe; +pub mod process; +pub mod rwlock; +pub mod stack_overflow; +pub mod thread; +pub mod thread_local; +pub mod time; +pub mod stdio; + +#[cfg(not(test))] +pub fn init() { +} + +/// This function is used to implement functionality that simply doesn't exist. +/// Programs relying on this functionality will need to deal with the error. +pub fn unsupported() -> io::Result { + Err(unsupported_err()) +} + +pub fn unsupported_err() -> io::Error { + io::Error::new(io::ErrorKind::Other, + "operation not supported on SGX yet") +} + +/// This function is used to implement various functions that doesn't exist, +/// but the lack of which might not be reason for error. If no error is +/// returned, the program might very well be able to function normally. This is +/// what happens when `SGX_INEFFECTIVE_ERROR` is set to `true`. If it is +/// `false`, the behavior is the same as `unsupported`. +pub fn sgx_ineffective(v: T) -> io::Result { + static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false); + if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) { + Err(io::Error::new(io::ErrorKind::Other, + "operation can't be trusted to have any effect on SGX")) + } else { + Ok(v) + } +} + +pub fn decode_error_kind(code: i32) -> io::ErrorKind { + use fortanix_sgx_abi::Error; + + // FIXME: not sure how to make sure all variants of Error are covered + if code == Error::NotFound as _ { + io::ErrorKind::NotFound + } else if code == Error::PermissionDenied as _ { + io::ErrorKind::PermissionDenied + } else if code == Error::ConnectionRefused as _ { + io::ErrorKind::ConnectionRefused + } else if code == Error::ConnectionReset as _ { + io::ErrorKind::ConnectionReset + } else if code == Error::ConnectionAborted as _ { + io::ErrorKind::ConnectionAborted + } else if code == Error::NotConnected as _ { + io::ErrorKind::NotConnected + } else if code == Error::AddrInUse as _ { + io::ErrorKind::AddrInUse + } else if code == Error::AddrNotAvailable as _ { + io::ErrorKind::AddrNotAvailable + } else if code == Error::BrokenPipe as _ { + io::ErrorKind::BrokenPipe + } else if code == Error::AlreadyExists as _ { + io::ErrorKind::AlreadyExists + } else if code == Error::WouldBlock as _ { + io::ErrorKind::WouldBlock + } else if code == Error::InvalidInput as _ { + io::ErrorKind::InvalidInput + } else if code == Error::InvalidData as _ { + io::ErrorKind::InvalidData + } else if code == Error::TimedOut as _ { + io::ErrorKind::TimedOut + } else if code == Error::WriteZero as _ { + io::ErrorKind::WriteZero + } else if code == Error::Interrupted as _ { + io::ErrorKind::Interrupted + } else if code == Error::Other as _ { + io::ErrorKind::Other + } else if code == Error::UnexpectedEof as _ { + io::ErrorKind::UnexpectedEof + } else { + io::ErrorKind::Other + } +} + +// This enum is used as the storage for a bunch of types which can't actually +// exist. +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +pub enum Void {} + +pub unsafe fn strlen(mut s: *const c_char) -> usize { + let mut n = 0; + while *s != 0 { + n += 1; + s = s.offset(1); + } + return n +} + +pub unsafe fn abort_internal() -> ! { + abi::panic::panic_exit() +} + +pub fn hashmap_random_keys() -> (u64, u64) { + fn rdrand64() -> u64 { + unsafe { + let mut ret: u64 = ::mem::uninitialized(); + for _ in 0..10 { + if ::arch::x86_64::_rdrand64_step(&mut ret) == 1 { + return ret; + } + } + panic!("Failed to obtain random data"); + } + } + (rdrand64(), rdrand64()) +} diff --git a/src/libstd/sys/sgx/mutex.rs b/src/libstd/sys/sgx/mutex.rs new file mode 100644 index 00000000000..ffaa4014e14 --- /dev/null +++ b/src/libstd/sys/sgx/mutex.rs @@ -0,0 +1,78 @@ +// 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. + +use cell::UnsafeCell; + +pub struct Mutex { + locked: UnsafeCell, +} + +unsafe impl Send for Mutex {} +unsafe impl Sync for Mutex {} // FIXME + +impl Mutex { + pub const fn new() -> Mutex { + Mutex { locked: UnsafeCell::new(false) } + } + + #[inline] + pub unsafe fn init(&mut self) { + } + + #[inline] + pub unsafe fn lock(&self) { + let locked = self.locked.get(); + assert!(!*locked, "cannot recursively acquire mutex"); + *locked = true; + } + + #[inline] + pub unsafe fn unlock(&self) { + *self.locked.get() = false; + } + + #[inline] + pub unsafe fn try_lock(&self) -> bool { + let locked = self.locked.get(); + if *locked { + false + } else { + *locked = true; + true + } + } + + #[inline] + pub unsafe fn destroy(&self) { + } +} + +// FIXME +pub struct ReentrantMutex { +} + +impl ReentrantMutex { + pub unsafe fn uninitialized() -> ReentrantMutex { + ReentrantMutex { } + } + + pub unsafe fn init(&mut self) {} + + pub unsafe fn lock(&self) {} + + #[inline] + pub unsafe fn try_lock(&self) -> bool { + true + } + + pub unsafe fn unlock(&self) {} + + pub unsafe fn destroy(&self) {} +} diff --git a/src/libstd/sys/sgx/net.rs b/src/libstd/sys/sgx/net.rs new file mode 100644 index 00000000000..094683e28b8 --- /dev/null +++ b/src/libstd/sys/sgx/net.rs @@ -0,0 +1,356 @@ +// 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. + +use fmt; +use io; +use net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; +use time::Duration; +use sys::{unsupported, Void}; +use convert::TryFrom; + +pub struct TcpStream(Void); + +impl TcpStream { + pub fn connect(_: io::Result<&SocketAddr>) -> io::Result { + unsupported() + } + + pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result { + unsupported() + } + + pub fn set_read_timeout(&self, _: Option) -> io::Result<()> { + match self.0 {} + } + + pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { + match self.0 {} + } + + pub fn read_timeout(&self) -> io::Result> { + match self.0 {} + } + + pub fn write_timeout(&self) -> io::Result> { + match self.0 {} + } + + pub fn peek(&self, _: &mut [u8]) -> io::Result { + match self.0 {} + } + + pub fn read(&self, _: &mut [u8]) -> io::Result { + match self.0 {} + } + + pub fn write(&self, _: &[u8]) -> io::Result { + match self.0 {} + } + + pub fn peer_addr(&self) -> io::Result { + match self.0 {} + } + + pub fn socket_addr(&self) -> io::Result { + match self.0 {} + } + + pub fn shutdown(&self, _: Shutdown) -> io::Result<()> { + match self.0 {} + } + + pub fn duplicate(&self) -> io::Result { + match self.0 {} + } + + pub fn set_nodelay(&self, _: bool) -> io::Result<()> { + match self.0 {} + } + + pub fn nodelay(&self) -> io::Result { + match self.0 {} + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + match self.0 {} + } + + pub fn ttl(&self) -> io::Result { + match self.0 {} + } + + pub fn take_error(&self) -> io::Result> { + match self.0 {} + } + + pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { + match self.0 {} + } +} + +impl fmt::Debug for TcpStream { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +pub struct TcpListener(Void); + +impl TcpListener { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { + unsupported() + } + + pub fn socket_addr(&self) -> io::Result { + match self.0 {} + } + + pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { + match self.0 {} + } + + pub fn duplicate(&self) -> io::Result { + match self.0 {} + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + match self.0 {} + } + + pub fn ttl(&self) -> io::Result { + match self.0 {} + } + + pub fn set_only_v6(&self, _: bool) -> io::Result<()> { + match self.0 {} + } + + pub fn only_v6(&self) -> io::Result { + match self.0 {} + } + + pub fn take_error(&self) -> io::Result> { + match self.0 {} + } + + pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { + match self.0 {} + } +} + +impl fmt::Debug for TcpListener { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +pub struct UdpSocket(Void); + +impl UdpSocket { + pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { + unsupported() + } + + pub fn socket_addr(&self) -> io::Result { + match self.0 {} + } + + pub fn recv_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + match self.0 {} + } + + pub fn peek_from(&self, _: &mut [u8]) -> io::Result<(usize, SocketAddr)> { + match self.0 {} + } + + pub fn send_to(&self, _: &[u8], _: &SocketAddr) -> io::Result { + match self.0 {} + } + + pub fn duplicate(&self) -> io::Result { + match self.0 {} + } + + pub fn set_read_timeout(&self, _: Option) -> io::Result<()> { + match self.0 {} + } + + pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { + match self.0 {} + } + + pub fn read_timeout(&self) -> io::Result> { + match self.0 {} + } + + pub fn write_timeout(&self) -> io::Result> { + match self.0 {} + } + + pub fn set_broadcast(&self, _: bool) -> io::Result<()> { + match self.0 {} + } + + pub fn broadcast(&self) -> io::Result { + match self.0 {} + } + + pub fn set_multicast_loop_v4(&self, _: bool) -> io::Result<()> { + match self.0 {} + } + + pub fn multicast_loop_v4(&self) -> io::Result { + match self.0 {} + } + + pub fn set_multicast_ttl_v4(&self, _: u32) -> io::Result<()> { + match self.0 {} + } + + pub fn multicast_ttl_v4(&self) -> io::Result { + match self.0 {} + } + + pub fn set_multicast_loop_v6(&self, _: bool) -> io::Result<()> { + match self.0 {} + } + + pub fn multicast_loop_v6(&self) -> io::Result { + match self.0 {} + } + + pub fn join_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) + -> io::Result<()> { + match self.0 {} + } + + pub fn join_multicast_v6(&self, _: &Ipv6Addr, _: u32) + -> io::Result<()> { + match self.0 {} + } + + pub fn leave_multicast_v4(&self, _: &Ipv4Addr, _: &Ipv4Addr) + -> io::Result<()> { + match self.0 {} + } + + pub fn leave_multicast_v6(&self, _: &Ipv6Addr, _: u32) + -> io::Result<()> { + match self.0 {} + } + + pub fn set_ttl(&self, _: u32) -> io::Result<()> { + match self.0 {} + } + + pub fn ttl(&self) -> io::Result { + match self.0 {} + } + + pub fn take_error(&self) -> io::Result> { + match self.0 {} + } + + pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { + match self.0 {} + } + + pub fn recv(&self, _: &mut [u8]) -> io::Result { + match self.0 {} + } + + pub fn peek(&self, _: &mut [u8]) -> io::Result { + match self.0 {} + } + + pub fn send(&self, _: &[u8]) -> io::Result { + match self.0 {} + } + + pub fn connect(&self, _: io::Result<&SocketAddr>) -> io::Result<()> { + match self.0 {} + } +} + +impl fmt::Debug for UdpSocket { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +pub struct LookupHost(Void); + +impl LookupHost { + pub fn port(&self) -> u16 { + match self.0 {} + } +} + +impl Iterator for LookupHost { + type Item = SocketAddr; + fn next(&mut self) -> Option { + match self.0 {} + } +} + +impl<'a> TryFrom<&'a str> for LookupHost { + type Error = io::Error; + + fn try_from(_v: &'a str) -> io::Result { + unsupported() + } +} + +impl<'a> TryFrom<(&'a str, u16)> for LookupHost { + type Error = io::Error; + + fn try_from(_v: (&'a str, u16)) -> io::Result { + unsupported() + } +} + +#[allow(bad_style)] +pub mod netc { + pub const AF_INET: u8 = 0; + pub const AF_INET6: u8 = 1; + pub type sa_family_t = u8; + + #[derive(Copy, Clone)] + pub struct in_addr { + pub s_addr: u32, + } + + #[derive(Copy, Clone)] + pub struct sockaddr_in { + pub sin_family: sa_family_t, + pub sin_port: u16, + pub sin_addr: in_addr, + } + + #[derive(Copy, Clone)] + pub struct in6_addr { + pub s6_addr: [u8; 16], + } + + #[derive(Copy, Clone)] + pub struct sockaddr_in6 { + pub sin6_family: sa_family_t, + pub sin6_port: u16, + pub sin6_addr: in6_addr, + pub sin6_flowinfo: u32, + pub sin6_scope_id: u32, + } + + #[derive(Copy, Clone)] + pub struct sockaddr { + } + + pub type socklen_t = usize; +} diff --git a/src/libstd/sys/sgx/os.rs b/src/libstd/sys/sgx/os.rs new file mode 100644 index 00000000000..38d82efaf17 --- /dev/null +++ b/src/libstd/sys/sgx/os.rs @@ -0,0 +1,120 @@ +// 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. + +use fortanix_sgx_abi::{Error, RESULT_SUCCESS}; + +use error::Error as StdError; +use ffi::{OsString, OsStr}; +use fmt; +use io; +use path::{self, PathBuf}; +use str; +use sys::{unsupported, Void, sgx_ineffective, decode_error_kind}; + +pub fn errno() -> i32 { + RESULT_SUCCESS +} + +pub fn error_string(errno: i32) -> String { + if errno == RESULT_SUCCESS { + "operation succesful".into() + } else if ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&errno) { + format!("user-specified error {:08x}", errno) + } else { + decode_error_kind(errno).as_str().into() + } +} + +pub fn getcwd() -> io::Result { + unsupported() +} + +pub fn chdir(_: &path::Path) -> io::Result<()> { + sgx_ineffective(()) +} + +pub struct SplitPaths<'a>(&'a Void); + +pub fn split_paths(_unparsed: &OsStr) -> SplitPaths { + panic!("unsupported") +} + +impl<'a> Iterator for SplitPaths<'a> { + type Item = PathBuf; + fn next(&mut self) -> Option { + match *self.0 {} + } +} + +#[derive(Debug)] +pub struct JoinPathsError; + +pub fn join_paths(_paths: I) -> Result + where I: Iterator, T: AsRef +{ + Err(JoinPathsError) +} + +impl fmt::Display for JoinPathsError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "not supported in SGX yet".fmt(f) + } +} + +impl StdError for JoinPathsError { + fn description(&self) -> &str { + "not supported in SGX yet" + } +} + +pub fn current_exe() -> io::Result { + unsupported() +} + +pub struct Env; + +impl Iterator for Env { + type Item = (OsString, OsString); + fn next(&mut self) -> Option<(OsString, OsString)> { + None + } +} + +pub fn env() -> Env { + Env +} + +pub fn getenv(_k: &OsStr) -> io::Result> { + unsupported() +} + +pub fn setenv(_k: &OsStr, _v: &OsStr) -> io::Result<()> { + sgx_ineffective(()) // FIXME: this could trigger a panic higher up the stack +} + +pub fn unsetenv(_k: &OsStr) -> io::Result<()> { + sgx_ineffective(()) // FIXME: this could trigger a panic higher up the stack +} + +pub fn temp_dir() -> PathBuf { + panic!("no filesystem in SGX") +} + +pub fn home_dir() -> Option { + None +} + +pub fn exit(code: i32) -> ! { + super::abi::exit_with_code(code as _) +} + +pub fn getpid() -> u32 { + panic!("no pids in SGX") +} diff --git a/src/libstd/sys/sgx/os_str.rs b/src/libstd/sys/sgx/os_str.rs new file mode 100644 index 00000000000..9bfb84db209 --- /dev/null +++ b/src/libstd/sys/sgx/os_str.rs @@ -0,0 +1,189 @@ +// 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. + +/// The underlying OsString/OsStr implementation on Unix systems: just +/// a `Vec`/`[u8]`. + +use borrow::Cow; +use fmt; +use str; +use mem; +use rc::Rc; +use sync::Arc; +use sys_common::{AsInner, IntoInner}; +use sys_common::bytestring::debug_fmt_bytestring; +use core::str::lossy::Utf8Lossy; + +#[derive(Clone, Hash)] +pub struct Buf { + pub inner: Vec +} + +pub struct Slice { + pub inner: [u8] +} + +impl fmt::Debug for Slice { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + debug_fmt_bytestring(&self.inner, formatter) + } +} + +impl fmt::Display for Slice { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&Utf8Lossy::from_bytes(&self.inner), formatter) + } +} + +impl fmt::Debug for Buf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fmt::Debug::fmt(self.as_slice(), formatter) + } +} + +impl fmt::Display for Buf { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(self.as_slice(), formatter) + } +} + +impl IntoInner> for Buf { + fn into_inner(self) -> Vec { + self.inner + } +} + +impl AsInner<[u8]> for Buf { + fn as_inner(&self) -> &[u8] { + &self.inner + } +} + + +impl Buf { + pub fn from_string(s: String) -> Buf { + Buf { inner: s.into_bytes() } + } + + #[inline] + pub fn with_capacity(capacity: usize) -> Buf { + Buf { + inner: Vec::with_capacity(capacity) + } + } + + #[inline] + pub fn clear(&mut self) { + self.inner.clear() + } + + #[inline] + pub fn capacity(&self) -> usize { + self.inner.capacity() + } + + #[inline] + pub fn reserve(&mut self, additional: usize) { + self.inner.reserve(additional) + } + + #[inline] + pub fn reserve_exact(&mut self, additional: usize) { + self.inner.reserve_exact(additional) + } + + #[inline] + pub fn shrink_to_fit(&mut self) { + 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) } + } + + pub fn into_string(self) -> Result { + String::from_utf8(self.inner).map_err(|p| Buf { inner: p.into_bytes() } ) + } + + pub fn push_slice(&mut self, s: &Slice) { + self.inner.extend_from_slice(&s.inner) + } + + #[inline] + pub fn into_box(self) -> Box { + unsafe { mem::transmute(self.inner.into_boxed_slice()) } + } + + #[inline] + pub fn from_box(boxed: Box) -> Buf { + let inner: Box<[u8]> = unsafe { mem::transmute(boxed) }; + Buf { inner: inner.into_vec() } + } + + #[inline] + pub fn into_arc(&self) -> Arc { + self.as_slice().into_arc() + } + + #[inline] + pub fn into_rc(&self) -> Rc { + self.as_slice().into_rc() + } +} + +impl Slice { + fn from_u8_slice(s: &[u8]) -> &Slice { + unsafe { mem::transmute(s) } + } + + pub fn from_str(s: &str) -> &Slice { + Slice::from_u8_slice(s.as_bytes()) + } + + pub fn to_str(&self) -> Option<&str> { + str::from_utf8(&self.inner).ok() + } + + pub fn to_string_lossy(&self) -> Cow { + String::from_utf8_lossy(&self.inner) + } + + pub fn to_owned(&self) -> Buf { + Buf { inner: self.inner.to_vec() } + } + + #[inline] + pub fn into_box(&self) -> Box { + let boxed: Box<[u8]> = self.inner.into(); + unsafe { mem::transmute(boxed) } + } + + pub fn empty_box() -> Box { + let boxed: Box<[u8]> = Default::default(); + unsafe { mem::transmute(boxed) } + } + + #[inline] + pub fn into_arc(&self) -> Arc { + let arc: Arc<[u8]> = Arc::from(&self.inner); + unsafe { Arc::from_raw(Arc::into_raw(arc) as *const Slice) } + } + + #[inline] + pub fn into_rc(&self) -> Rc { + let rc: Rc<[u8]> = Rc::from(&self.inner); + unsafe { Rc::from_raw(Rc::into_raw(rc) as *const Slice) } + } +} diff --git a/src/libstd/sys/sgx/path.rs b/src/libstd/sys/sgx/path.rs new file mode 100644 index 00000000000..afe0c490426 --- /dev/null +++ b/src/libstd/sys/sgx/path.rs @@ -0,0 +1,29 @@ +// 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. + +use path::Prefix; +use ffi::OsStr; + +#[inline] +pub fn is_sep_byte(b: u8) -> bool { + b == b'/' +} + +#[inline] +pub fn is_verbatim_sep(b: u8) -> bool { + b == b'/' +} + +pub fn parse_prefix(_: &OsStr) -> Option { + None +} + +pub const MAIN_SEP_STR: &'static str = "/"; +pub const MAIN_SEP: char = '/'; diff --git a/src/libstd/sys/sgx/pipe.rs b/src/libstd/sys/sgx/pipe.rs new file mode 100644 index 00000000000..6c6cbc14a8a --- /dev/null +++ b/src/libstd/sys/sgx/pipe.rs @@ -0,0 +1,35 @@ +// 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. + +use io; +use sys::Void; + +pub struct AnonPipe(Void); + +impl AnonPipe { + pub fn read(&self, _buf: &mut [u8]) -> io::Result { + match self.0 {} + } + + pub fn write(&self, _buf: &[u8]) -> io::Result { + match self.0 {} + } + + pub fn diverge(&self) -> ! { + match self.0 {} + } +} + +pub fn read2(p1: AnonPipe, + _v1: &mut Vec, + _p2: AnonPipe, + _v2: &mut Vec) -> io::Result<()> { + match p1.0 {} +} diff --git a/src/libstd/sys/sgx/process.rs b/src/libstd/sys/sgx/process.rs new file mode 100644 index 00000000000..01a12fba043 --- /dev/null +++ b/src/libstd/sys/sgx/process.rs @@ -0,0 +1,162 @@ +// 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. + +use ffi::OsStr; +use fmt; +use io; +use sys::fs::File; +use sys::pipe::AnonPipe; +use sys::{unsupported, Void}; +use sys_common::process::{CommandEnv, DefaultEnvKey}; + +//////////////////////////////////////////////////////////////////////////////// +// Command +//////////////////////////////////////////////////////////////////////////////// + +pub struct Command { + env: CommandEnv +} + +// passed back to std::process with the pipes connected to the child, if any +// were requested +pub struct StdioPipes { + pub stdin: Option, + pub stdout: Option, + pub stderr: Option, +} + +pub enum Stdio { + Inherit, + Null, + MakePipe, +} + +impl Command { + pub fn new(_program: &OsStr) -> Command { + Command { + env: Default::default() + } + } + + pub fn arg(&mut self, _arg: &OsStr) { + } + + pub fn env_mut(&mut self) -> &mut CommandEnv { + &mut self.env + } + + pub fn cwd(&mut self, _dir: &OsStr) { + } + + pub fn stdin(&mut self, _stdin: Stdio) { + } + + pub fn stdout(&mut self, _stdout: Stdio) { + } + + pub fn stderr(&mut self, _stderr: Stdio) { + } + + pub fn spawn(&mut self, _default: Stdio, _needs_stdin: bool) + -> io::Result<(Process, StdioPipes)> { + unsupported() + } +} + +impl From for Stdio { + fn from(pipe: AnonPipe) -> Stdio { + pipe.diverge() + } +} + +impl From for Stdio { + fn from(file: File) -> Stdio { + file.diverge() + } +} + +impl fmt::Debug for Command { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + Ok(()) + } +} + +pub struct ExitStatus(Void); + +impl ExitStatus { + pub fn success(&self) -> bool { + match self.0 {} + } + + pub fn code(&self) -> Option { + match self.0 {} + } +} + +impl Clone for ExitStatus { + fn clone(&self) -> ExitStatus { + match self.0 {} + } +} + +impl Copy for ExitStatus {} + +impl PartialEq for ExitStatus { + fn eq(&self, _other: &ExitStatus) -> bool { + match self.0 {} + } +} + +impl Eq for ExitStatus { +} + +impl fmt::Debug for ExitStatus { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +impl fmt::Display for ExitStatus { + fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { + match self.0 {} + } +} + +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub struct ExitCode(bool); + +impl ExitCode { + pub const SUCCESS: ExitCode = ExitCode(false); + pub const FAILURE: ExitCode = ExitCode(true); + + pub fn as_i32(&self) -> i32 { + self.0 as i32 + } +} + +pub struct Process(Void); + +impl Process { + pub fn id(&self) -> u32 { + match self.0 {} + } + + pub fn kill(&mut self) -> io::Result<()> { + match self.0 {} + } + + pub fn wait(&mut self) -> io::Result { + match self.0 {} + } + + pub fn try_wait(&mut self) -> io::Result> { + match self.0 {} + } +} diff --git a/src/libstd/sys/sgx/rwlock.rs b/src/libstd/sys/sgx/rwlock.rs new file mode 100644 index 00000000000..2c0b1a45206 --- /dev/null +++ b/src/libstd/sys/sgx/rwlock.rs @@ -0,0 +1,82 @@ +// 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. + +use cell::UnsafeCell; + +pub struct RWLock { + mode: UnsafeCell, +} + +unsafe impl Send for RWLock {} +unsafe impl Sync for RWLock {} // FIXME + +impl RWLock { + pub const fn new() -> RWLock { + RWLock { + mode: UnsafeCell::new(0), + } + } + + #[inline] + pub unsafe fn read(&self) { + let mode = self.mode.get(); + if *mode >= 0 { + *mode += 1; + } else { + rtabort!("rwlock locked for writing"); + } + } + + #[inline] + pub unsafe fn try_read(&self) -> bool { + let mode = self.mode.get(); + if *mode >= 0 { + *mode += 1; + true + } else { + false + } + } + + #[inline] + pub unsafe fn write(&self) { + let mode = self.mode.get(); + if *mode == 0 { + *mode = -1; + } else { + rtabort!("rwlock locked for reading") + } + } + + #[inline] + pub unsafe fn try_write(&self) -> bool { + let mode = self.mode.get(); + if *mode == 0 { + *mode = -1; + true + } else { + false + } + } + + #[inline] + pub unsafe fn read_unlock(&self) { + *self.mode.get() -= 1; + } + + #[inline] + pub unsafe fn write_unlock(&self) { + *self.mode.get() += 1; + } + + #[inline] + pub unsafe fn destroy(&self) { + } +} diff --git a/src/libstd/sys/sgx/stack_overflow.rs b/src/libstd/sys/sgx/stack_overflow.rs new file mode 100644 index 00000000000..0176b748a87 --- /dev/null +++ b/src/libstd/sys/sgx/stack_overflow.rs @@ -0,0 +1,23 @@ +// 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. + +pub struct Handler; + +impl Handler { + pub unsafe fn new() -> Handler { + Handler + } +} + +pub unsafe fn init() { +} + +pub unsafe fn cleanup() { +} diff --git a/src/libstd/sys/sgx/stdio.rs b/src/libstd/sys/sgx/stdio.rs new file mode 100644 index 00000000000..540599a3596 --- /dev/null +++ b/src/libstd/sys/sgx/stdio.rs @@ -0,0 +1,73 @@ +// 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. + +use io; +use sys::unsupported; + +pub struct Stdin; +pub struct Stdout; +pub struct Stderr; + +impl Stdin { + pub fn new() -> io::Result { + Ok(Stdin) + } + + pub fn read(&self, _data: &mut [u8]) -> io::Result { + unsupported() + } +} + +impl Stdout { + pub fn new() -> io::Result { + Ok(Stdout) + } + + pub fn write(&self, _data: &[u8]) -> io::Result { + unsupported() + } + + pub fn flush(&self) -> io::Result<()> { + Ok(()) + } +} + +impl Stderr { + pub fn new() -> io::Result { + Ok(Stderr) + } + + pub fn write(&self, _data: &[u8]) -> io::Result { + unsupported() + } + + pub fn flush(&self) -> io::Result<()> { + Ok(()) + } +} + +impl io::Write for Stderr { + fn write(&mut self, data: &[u8]) -> io::Result { + (&*self).write(data) + } + fn flush(&mut self) -> io::Result<()> { + (&*self).flush() + } +} + +pub const STDIN_BUF_SIZE: usize = 0; + +pub fn is_ebadf(_err: &io::Error) -> bool { + true +} + +pub fn panic_output() -> Option { + super::abi::panic::SgxPanicOutput::new() +} diff --git a/src/libstd/sys/sgx/thread.rs b/src/libstd/sys/sgx/thread.rs new file mode 100644 index 00000000000..ff8df12302c --- /dev/null +++ b/src/libstd/sys/sgx/thread.rs @@ -0,0 +1,51 @@ +// 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. + +use boxed::FnBox; +use ffi::CStr; +use io; +use sys::{unsupported, Void}; +use time::Duration; + +pub struct Thread(Void); + +pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; + +impl Thread { + // unsafe: see thread::Builder::spawn_unchecked for safety requirements + pub unsafe fn new(_stack: usize, _p: Box) + -> io::Result + { + unsupported() + } + + pub fn yield_now() { + // do nothing + } + + pub fn set_name(_name: &CStr) { + // nope + } + + pub fn sleep(_dur: Duration) { + panic!("can't sleep"); + } + + pub fn join(self) { + match self.0 {} + } +} + +pub mod guard { + pub type Guard = !; + pub unsafe fn current() -> Option { None } + pub unsafe fn init() -> Option { None } + pub unsafe fn deinit() {} +} diff --git a/src/libstd/sys/sgx/thread_local.rs b/src/libstd/sys/sgx/thread_local.rs new file mode 100644 index 00000000000..2126e0a853e --- /dev/null +++ b/src/libstd/sys/sgx/thread_local.rs @@ -0,0 +1,50 @@ +// 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. + +use boxed::Box; +use ptr; + +pub type Key = usize; + +struct Allocated { + value: *mut u8, + dtor: Option, +} + +#[inline] +pub unsafe fn create(dtor: Option) -> Key { + Box::into_raw(Box::new(Allocated { + value: ptr::null_mut(), + dtor, + })) as usize +} + +#[inline] +pub unsafe fn set(key: Key, value: *mut u8) { + (*(key as *mut Allocated)).value = value; +} + +#[inline] +pub unsafe fn get(key: Key) -> *mut u8 { + (*(key as *mut Allocated)).value +} + +#[inline] +pub unsafe fn destroy(key: Key) { + let key = Box::from_raw(key as *mut Allocated); + if let Some(f) = key.dtor { + f(key.value); + } +} + +#[inline] +pub fn requires_synchronized_create() -> bool { + false +} diff --git a/src/libstd/sys/sgx/time.rs b/src/libstd/sys/sgx/time.rs new file mode 100644 index 00000000000..894680b0b65 --- /dev/null +++ b/src/libstd/sys/sgx/time.rs @@ -0,0 +1,61 @@ +// 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. + +use time::Duration; +use sys::unsupported_err; + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +pub struct Instant(Duration); + +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +pub struct SystemTime(Duration); + +pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0)); + +impl Instant { + pub fn now() -> Instant { + panic!("{}", unsupported_err()); + } + + pub fn sub_instant(&self, other: &Instant) -> Duration { + self.0 - other.0 + } + + pub fn add_duration(&self, other: &Duration) -> Instant { + Instant(self.0 + *other) + } + + pub fn sub_duration(&self, other: &Duration) -> Instant { + Instant(self.0 - *other) + } +} + +impl SystemTime { + pub fn now() -> SystemTime { + panic!("{}", unsupported_err()); + } + + pub fn sub_time(&self, other: &SystemTime) + -> Result { + self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) + } + + pub fn add_duration(&self, other: &Duration) -> SystemTime { + SystemTime(self.0 + *other) + } + + pub fn checked_add_duration(&self, other: &Duration) -> Option { + self.0.checked_add(*other).map(|d| SystemTime(d)) + } + + pub fn sub_duration(&self, other: &Duration) -> SystemTime { + SystemTime(self.0 - *other) + } +} diff --git a/src/libstd/sys_common/mod.rs b/src/libstd/sys_common/mod.rs index 4b8cde3d1f4..881794d9f16 100644 --- a/src/libstd/sys_common/mod.rs +++ b/src/libstd/sys_common/mod.rs @@ -57,9 +57,11 @@ pub mod bytestring; pub mod process; cfg_if! { - if #[cfg(any(target_os = "cloudabi", target_os = "l4re", target_os = "redox"))] { - pub use sys::net; - } else if #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] { + if #[cfg(any(target_os = "cloudabi", + target_os = "l4re", + target_os = "redox", + all(target_arch = "wasm32", not(target_os = "emscripten")), + target_env = "sgx"))] { pub use sys::net; } else { pub mod net; diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 7c26d042a7c..b8711a69147 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -1018,10 +1018,12 @@ fn use_color(opts: &TestOpts) -> bool { } } -#[cfg(any(target_os = "cloudabi", target_os = "redox", - all(target_arch = "wasm32", not(target_os = "emscripten"))))] +#[cfg(any(target_os = "cloudabi", + target_os = "redox", + all(target_arch = "wasm32", not(target_os = "emscripten")), + target_env = "sgx"))] fn stdout_isatty() -> bool { - // FIXME: Implement isatty on Redox + // FIXME: Implement isatty on Redox and SGX false } #[cfg(unix)] @@ -1246,7 +1248,7 @@ fn get_concurrency() -> usize { 1 } - #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] + #[cfg(any(all(target_arch = "wasm32", not(target_os = "emscripten")), target_env = "sgx"))] fn num_cpus() -> usize { 1 } diff --git a/src/libunwind/lib.rs b/src/libunwind/lib.rs index 954eb9d6d03..eb53332ab33 100644 --- a/src/libunwind/lib.rs +++ b/src/libunwind/lib.rs @@ -26,7 +26,10 @@ mod macros; cfg_if! { if #[cfg(target_env = "msvc")] { // no extra unwinder support needed - } else if #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] { + } else if #[cfg(any( + all(target_arch = "wasm32", not(target_os = "emscripten")), + target_env = "sgx" + ))] { // no unwinder on the system! } else { extern crate libc; diff --git a/src/rust-sgx b/src/rust-sgx new file mode 160000 index 00000000000..96562608880 --- /dev/null +++ b/src/rust-sgx @@ -0,0 +1 @@ +Subproject commit 9656260888095f44830641ca7bb3da609a793451 diff --git a/src/rustc/fortanix-sgx-abi_shim/Cargo.toml b/src/rustc/fortanix-sgx-abi_shim/Cargo.toml new file mode 100644 index 00000000000..fd81d3db3a7 --- /dev/null +++ b/src/rustc/fortanix-sgx-abi_shim/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "fortanix-sgx-abi" +version = "0.0.0" +authors = ["The Rust Project Developers"] + +[lib] +path = "../../rust-sgx/fortanix-sgx-abi/src/lib.rs" +test = false +bench = false +doc = false + +[dependencies] +core = { path = "../../libcore" } +compiler_builtins = { path = "../../rustc/compiler_builtins_shim" } diff --git a/src/stdsimd b/src/stdsimd index 0309be1ade6..5e628c5120c 160000 --- a/src/stdsimd +++ b/src/stdsimd @@ -1 +1 @@ -Subproject commit 0309be1ade6bf61066f2c69f77ac3567b7dc31b5 +Subproject commit 5e628c5120c619a22799187371f057ec41e06f87 diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index 700103d35d8..53db589beaf 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -76,6 +76,7 @@ fn filter_dirs(path: &Path) -> bool { "src/tools/lldb", "src/target", "src/stdsimd", + "src/rust-sgx", "target", "vendor", ]; -- cgit 1.4.1-3-g733a5 From 39f9751716986b498bfb2b14b481751a4256957f Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Mon, 27 Aug 2018 21:40:08 -0700 Subject: SGX target: add thread local storage --- src/libstd/sys/sgx/abi/mod.rs | 6 + src/libstd/sys/sgx/abi/thread.rs | 20 +++ src/libstd/sys/sgx/abi/tls.rs | 246 +++++++++++++++++++++++++++++++++++++ src/libstd/sys/sgx/thread_local.rs | 22 +--- 4 files changed, 277 insertions(+), 17 deletions(-) create mode 100644 src/libstd/sys/sgx/abi/thread.rs create mode 100644 src/libstd/sys/sgx/abi/tls.rs (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/sgx/abi/mod.rs b/src/libstd/sys/sgx/abi/mod.rs index cade96e3f52..99ea7a381f3 100644 --- a/src/libstd/sys/sgx/abi/mod.rs +++ b/src/libstd/sys/sgx/abi/mod.rs @@ -17,6 +17,8 @@ mod mem; pub(super) mod panic; // library features +pub mod thread; +pub mod tls; #[macro_use] mod usercalls; @@ -59,6 +61,10 @@ unsafe extern "C" fn tcs_init(secondary: bool) { #[no_mangle] #[allow(unreachable_code)] extern "C" fn entry(p1: u64, p2: u64, p3: u64, secondary: bool, p4: u64, p5: u64) -> (u64, u64) { + // FIXME: how to support TLS in library mode? + let tls = Box::new(tls::Tls::new()); + let _tls_guard = unsafe { tls.activate() }; + if secondary { unimplemented!("thread entrypoint"); diff --git a/src/libstd/sys/sgx/abi/thread.rs b/src/libstd/sys/sgx/abi/thread.rs new file mode 100644 index 00000000000..4640b812fea --- /dev/null +++ b/src/libstd/sys/sgx/abi/thread.rs @@ -0,0 +1,20 @@ +// 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. + +use fortanix_sgx_abi::Tcs; + +/// Get the ID for the current thread. The ID is guaranteed to be unique among +/// all currently running threads in the enclave, and it is guaranteed to be +/// constant for the lifetime of the thread. More specifically for SGX, there +/// is a one-to-one correspondence of the ID to the address of the TCS. +pub fn current() -> Tcs { + extern "C" { fn get_tcs_addr() -> Tcs; } + unsafe { get_tcs_addr() } +} diff --git a/src/libstd/sys/sgx/abi/tls.rs b/src/libstd/sys/sgx/abi/tls.rs new file mode 100644 index 00000000000..ab7822182a5 --- /dev/null +++ b/src/libstd/sys/sgx/abi/tls.rs @@ -0,0 +1,246 @@ +// 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. + +use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; +use ptr; +use mem; +use cell::Cell; +use num::NonZeroUsize; +use self::sync_bitset::*; + +#[cfg(target_pointer_width="64")] +const USIZE_BITS: usize = 64; +const TLS_KEYS: usize = 128; // Same as POSIX minimum +const TLS_KEYS_BITSET_SIZE: usize = (TLS_KEYS + (USIZE_BITS - 1)) / USIZE_BITS; + +static TLS_KEY_IN_USE: SyncBitset = SYNC_BITSET_INIT; +macro_rules! dup { + ((* $($exp:tt)*) $($val:tt)*) => (dup!( ($($exp)*) $($val)* $($val)* )); + (() $($val:tt)*) => ([$($val),*]) +} +static TLS_DESTRUCTOR: [AtomicUsize; TLS_KEYS] = dup!((* * * * * * *) ATOMIC_USIZE_INIT); + +extern "C" { + fn get_tls_ptr() -> *const u8; + fn set_tls_ptr(tls: *const u8); +} + +#[derive(Copy, Clone)] +#[repr(C)] +pub struct Key(NonZeroUsize); + +impl Key { + fn to_index(self) -> usize { + self.0.get() - 1 + } + + fn from_index(index: usize) -> Self { + Key(NonZeroUsize::new(index + 1).unwrap()) + } + + pub fn as_usize(self) -> usize { + self.0.get() + } + + pub fn from_usize(index: usize) -> Self { + Key(NonZeroUsize::new(index).unwrap()) + } +} + +#[repr(C)] +pub struct Tls { + data: [Cell<*mut u8>; TLS_KEYS] +} + +pub struct ActiveTls<'a> { + tls: &'a Tls +} + +impl<'a> Drop for ActiveTls<'a> { + fn drop(&mut self) { + let value_with_destructor = |key: usize| { + let ptr = TLS_DESTRUCTOR[key].load(Ordering::Relaxed); + unsafe { mem::transmute::<_,Option>(ptr) } + .map(|dtor| (&self.tls.data[key], dtor)) + }; + + let mut any_non_null_dtor = true; + while any_non_null_dtor { + any_non_null_dtor = false; + for (value, dtor) in TLS_KEY_IN_USE.iter().filter_map(&value_with_destructor) { + let value = value.replace(ptr::null_mut()); + if value != ptr::null_mut() { + any_non_null_dtor = true; + unsafe { dtor(value) } + } + } + } + } +} + +impl Tls { + pub fn new() -> Tls { + Tls { data: dup!((* * * * * * *) (Cell::new(ptr::null_mut()))) } + } + + pub unsafe fn activate(&self) -> ActiveTls { + set_tls_ptr(self as *const Tls as _); + ActiveTls { tls: self } + } + + #[allow(unused)] + pub unsafe fn activate_persistent(self: Box) { + set_tls_ptr((&*self) as *const Tls as _); + mem::forget(self); + } + + unsafe fn current<'a>() -> &'a Tls { + &*(get_tls_ptr() as *const Tls) + } + + pub fn create(dtor: Option) -> Key { + let index = TLS_KEY_IN_USE.set().expect("TLS limit exceeded"); + TLS_DESTRUCTOR[index].store(dtor.map_or(0, |f| f as usize), Ordering::Relaxed); + Key::from_index(index) + } + + pub fn set(key: Key, value: *mut u8) { + let index = key.to_index(); + assert!(TLS_KEY_IN_USE.get(index)); + unsafe { Self::current() }.data[index].set(value); + } + + pub fn get(key: Key) -> *mut u8 { + let index = key.to_index(); + assert!(TLS_KEY_IN_USE.get(index)); + unsafe { Self::current() }.data[index].get() + } + + pub fn destroy(key: Key) { + TLS_KEY_IN_USE.clear(key.to_index()); + } +} + +mod sync_bitset { + use sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; + use iter::{Enumerate, Peekable}; + use slice::Iter; + use super::{TLS_KEYS_BITSET_SIZE, USIZE_BITS}; + + /// A bitset that can be used synchronously. + pub(super) struct SyncBitset([AtomicUsize; TLS_KEYS_BITSET_SIZE]); + + pub(super) const SYNC_BITSET_INIT: SyncBitset = + SyncBitset([ATOMIC_USIZE_INIT, ATOMIC_USIZE_INIT]); + + impl SyncBitset { + pub fn get(&self, index: usize) -> bool { + let (hi, lo) = Self::split(index); + (self.0[hi].load(Ordering::Relaxed) & lo) != 0 + } + + /// Not atomic. + pub fn iter(&self) -> SyncBitsetIter { + SyncBitsetIter { + iter: self.0.iter().enumerate().peekable(), + elem_idx: 0, + } + } + + pub fn clear(&self, index: usize) { + let (hi, lo) = Self::split(index); + self.0[hi].fetch_and(!lo, Ordering::Relaxed); + } + + /// Set any unset bit. Not atomic. Returns `None` if all bits were + /// observed to be set. + pub fn set(&self) -> Option { + 'elems: for (idx, elem) in self.0.iter().enumerate() { + let mut current = elem.load(Ordering::Relaxed); + loop { + if 0 == !current { + continue 'elems; + } + let trailing_ones = (!current).trailing_zeros() as usize; + match elem.compare_exchange( + current, + current | (1 << trailing_ones), + Ordering::AcqRel, + Ordering::Relaxed + ) { + Ok(_) => return Some(idx * USIZE_BITS + trailing_ones), + Err(previous) => current = previous, + } + } + } + None + } + + fn split(index: usize) -> (usize, usize) { + (index / USIZE_BITS, 1 << (index % USIZE_BITS)) + } + } + + pub(super) struct SyncBitsetIter<'a> { + iter: Peekable>>, + elem_idx: usize, + } + + impl<'a> Iterator for SyncBitsetIter<'a> { + type Item = usize; + + fn next(&mut self) -> Option { + self.iter.peek().cloned().and_then(|(idx, elem)| { + let elem = elem.load(Ordering::Relaxed); + let low_mask = (1 << self.elem_idx) - 1; + let next = elem & !low_mask; + let next_idx = next.trailing_zeros() as usize; + self.elem_idx = next_idx + 1; + if self.elem_idx >= 64 { + self.elem_idx = 0; + self.iter.next(); + } + match next_idx { + 64 => self.next(), + _ => Some(idx * USIZE_BITS + next_idx), + } + }) + } + } + + #[cfg(test)] + mod tests { + use super::*; + + fn test_data(bitset: [usize; 2], bit_indices: &[usize]) { + let set = SyncBitset([AtomicUsize::new(bitset[0]), AtomicUsize::new(bitset[1])]); + assert_eq!(set.iter().collect::>(), bit_indices); + for &i in bit_indices { + assert!(set.get(i)); + } + } + + #[test] + fn iter() { + test_data([0b0110_1001, 0], &[0, 3, 5, 6]); + test_data([0x8000_0000_0000_0000, 0x8000_0000_0000_0001], &[63, 64, 127]); + test_data([0, 0], &[]); + } + + #[test] + fn set_get_clear() { + let set = SYNC_BITSET_INIT; + let key = set.set().unwrap(); + assert!(set.get(key)); + set.clear(key); + assert!(!set.get(key)); + } + } +} diff --git a/src/libstd/sys/sgx/thread_local.rs b/src/libstd/sys/sgx/thread_local.rs index 2126e0a853e..3b628bae4fb 100644 --- a/src/libstd/sys/sgx/thread_local.rs +++ b/src/libstd/sys/sgx/thread_local.rs @@ -8,40 +8,28 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use boxed::Box; -use ptr; +use super::abi::tls::{Tls, Key as AbiKey}; pub type Key = usize; -struct Allocated { - value: *mut u8, - dtor: Option, -} - #[inline] pub unsafe fn create(dtor: Option) -> Key { - Box::into_raw(Box::new(Allocated { - value: ptr::null_mut(), - dtor, - })) as usize + Tls::create(dtor).as_usize() } #[inline] pub unsafe fn set(key: Key, value: *mut u8) { - (*(key as *mut Allocated)).value = value; + Tls::set(AbiKey::from_usize(key), value) } #[inline] pub unsafe fn get(key: Key) -> *mut u8 { - (*(key as *mut Allocated)).value + Tls::get(AbiKey::from_usize(key)) } #[inline] pub unsafe fn destroy(key: Key) { - let key = Box::from_raw(key as *mut Allocated); - if let Some(f) = key.dtor { - f(key.value); - } + Tls::destroy(AbiKey::from_usize(key)) } #[inline] -- cgit 1.4.1-3-g733a5 From 1e44e2de6c302855c1da75f79227fca743d9b209 Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Wed, 5 Sep 2018 16:18:53 -0700 Subject: SGX target: implement user memory management --- src/libstd/lib.rs | 3 +- src/libstd/sys/sgx/abi/mem.rs | 24 +- src/libstd/sys/sgx/abi/mod.rs | 2 +- src/libstd/sys/sgx/abi/usercalls/alloc.rs | 404 ++++++++++++++++++++++++++++++ src/libstd/sys/sgx/abi/usercalls/mod.rs | 75 +++++- 5 files changed, 502 insertions(+), 6 deletions(-) create mode 100644 src/libstd/sys/sgx/abi/usercalls/alloc.rs (limited to 'src/libstd/sys') diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index bf1e64efd37..66771b3c4a2 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -312,7 +312,8 @@ #![feature(non_exhaustive)] #![feature(alloc_layout_extra)] #![feature(maybe_uninit)] -#![cfg_attr(target_env = "sgx", feature(global_asm, range_contains))] +#![cfg_attr(target_env = "sgx", feature(global_asm, range_contains, slice_index_methods, + decl_macro, coerce_unsized))] #![default_lib_allocator] diff --git a/src/libstd/sys/sgx/abi/mem.rs b/src/libstd/sys/sgx/abi/mem.rs index aedf6ec7acb..508f2ff4d4f 100644 --- a/src/libstd/sys/sgx/abi/mem.rs +++ b/src/libstd/sys/sgx/abi/mem.rs @@ -11,13 +11,17 @@ // Do not remove inline: will result in relocation failure #[inline(always)] pub unsafe fn rel_ptr(offset: u64) -> *const T { - (image_base()+offset) as *const T + (image_base() + offset) as *const T } // Do not remove inline: will result in relocation failure #[inline(always)] pub unsafe fn rel_ptr_mut(offset: u64) -> *mut T { - (image_base()+offset) as *mut T + (image_base() + offset) as *mut T +} + +extern { + static ENCLAVE_SIZE: usize; } // Do not remove inline: will result in relocation failure @@ -26,6 +30,20 @@ pub unsafe fn rel_ptr_mut(offset: u64) -> *mut T { #[inline(always)] fn image_base() -> u64 { let base; - unsafe{asm!("lea IMAGE_BASE(%rip),$0":"=r"(base))}; + unsafe { asm!("lea IMAGE_BASE(%rip),$0":"=r"(base)) }; base } + +pub fn is_enclave_range(p: *const u8, len: usize) -> bool { + let start=p as u64; + let end=start + (len as u64); + start >= image_base() && + end <= image_base() + (unsafe { ENCLAVE_SIZE } as u64) // unsafe ok: link-time constant +} + +pub fn is_user_range(p: *const u8, len: usize) -> bool { + let start=p as u64; + let end=start + (len as u64); + end <= image_base() || + start >= image_base() + (unsafe { ENCLAVE_SIZE } as u64) // unsafe ok: link-time constant +} diff --git a/src/libstd/sys/sgx/abi/mod.rs b/src/libstd/sys/sgx/abi/mod.rs index 99ea7a381f3..61204904962 100644 --- a/src/libstd/sys/sgx/abi/mod.rs +++ b/src/libstd/sys/sgx/abi/mod.rs @@ -96,5 +96,5 @@ pub(super) fn exit_with_code(code: isize) -> ! { let _ = write!(out, "Exited with status code {}", code); } } - unsafe { usercalls::raw::exit(code != 0) }; + usercalls::exit(code != 0); } diff --git a/src/libstd/sys/sgx/abi/usercalls/alloc.rs b/src/libstd/sys/sgx/abi/usercalls/alloc.rs new file mode 100644 index 00000000000..64968a9970c --- /dev/null +++ b/src/libstd/sys/sgx/abi/usercalls/alloc.rs @@ -0,0 +1,404 @@ +// 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. + +#![allow(unused)] + +use ptr; +use mem; +use cell::UnsafeCell; +use slice; +use ops::{Deref, DerefMut, Index, IndexMut, CoerceUnsized}; +use slice::SliceIndex; + +use fortanix_sgx_abi::*; +use super::super::mem::is_user_range; + +/// A type that can be safely read from or written to userspace. +/// +/// Non-exhaustive list of specific requirements for reading and writing: +/// * **Type is `Copy`** (and therefore also not `Drop`). Copies will be +/// created when copying from/to userspace. Destructors will not be called. +/// * **No references or Rust-style owned pointers** (`Vec`, `Arc`, etc.). When +/// reading from userspace, references into enclave memory must not be +/// created. Also, only enclave memory is considered managed by the Rust +/// compiler's static analysis. When reading from userspace, there can be no +/// guarantee that the value correctly adheres to the expectations of the +/// type. When writing to userspace, memory addresses of data in enclave +/// memory must not be leaked for confidentiality reasons. `User` and +/// `UserRef` are also not allowed for the same reasons. +/// * **No fat pointers.** When reading from userspace, the size or vtable +/// pointer could be automatically interpreted and used by the code. When +/// writing to userspace, memory addresses of data in enclave memory (such +/// as vtable pointers) must not be leaked for confidentiality reasons. +/// +/// Non-exhaustive list of specific requirements for reading from userspace: +/// * Any bit pattern is valid for this type (no `enum`s). There can be no +/// guarantee that the value correctly adheres to the expectations of the +/// type, so any value must be valid for this type. +/// +/// Non-exhaustive list of specific requirements for writing to userspace: +/// * No pointers to enclave memory. Memory addresses of data in enclave memory +/// must not be leaked for confidentiality reasons. +/// * No internal padding. Padding might contain previously-initialized secret +/// data stored at that memory location and must not be leaked for +/// confidentiality reasons. +pub unsafe trait UserSafeSized: Copy + Sized {} + +unsafe impl UserSafeSized for u8 {} +unsafe impl UserSafeSized for FifoDescriptor {} +unsafe impl UserSafeSized for ByteBuffer {} +unsafe impl UserSafeSized for Usercall {} +unsafe impl UserSafeSized for Return {} +unsafe impl UserSafeSized for [T; 2] {} + +/// A type that can be represented in memory as one or more `UserSafeSized`s. +pub unsafe trait UserSafe { + unsafe fn align_of() -> usize; + + /// NB. This takes a size, not a length! + unsafe fn from_raw_sized_unchecked(ptr: *const u8, size: usize) -> *const Self; + + /// NB. This takes a size, not a length! + unsafe fn from_raw_sized(ptr: *const u8, size: usize) -> *const Self { + let ret = Self::from_raw_sized_unchecked(ptr, size); + Self::check_ptr(ret); + ret + } + + unsafe fn check_ptr(ptr: *const Self) { + let is_aligned = |p| -> bool { + 0 == (p as usize) & (Self::align_of() - 1) + }; + + assert!(is_aligned(ptr as *const u8)); + assert!(is_user_range(ptr as _, mem::size_of_val(&*ptr))); + assert!(!ptr.is_null()); + } +} + +unsafe impl UserSafe for T { + unsafe fn align_of() -> usize { + mem::align_of::() + } + + unsafe fn from_raw_sized_unchecked(ptr: *const u8, size: usize) -> *const Self { + assert_eq!(size, mem::size_of::()); + ptr as _ + } +} + +unsafe impl UserSafe for [T] { + unsafe fn align_of() -> usize { + mem::align_of::() + } + + unsafe fn from_raw_sized_unchecked(ptr: *const u8, size: usize) -> *const Self { + let elem_size = mem::size_of::(); + assert_eq!(size % elem_size, 0); + let len = size / elem_size; + slice::from_raw_parts(ptr as _, len) + } +} + +/// A reference to some type in userspace memory. `&UserRef` is equivalent +/// to `&T` in enclave memory. Access to the memory is only allowed by copying +/// to avoid TOCTTOU issues. After copying, code should make sure to completely +/// check the value before use. +pub struct UserRef(UnsafeCell); +/// An owned type in userspace memory. `User` is equivalent to `Box` in +/// enclave memory. Access to the memory is only allowed by copying to avoid +/// TOCTTOU issues. The user memory will be freed when the value is dropped. +/// After copying, code should make sure to completely check the value before +/// use. +pub struct User(*mut UserRef); + +impl User where T: UserSafe { + // This function returns memory that is practically uninitialized, but is + // not considered "unspecified" or "undefined" for purposes of an + // optimizing compiler. This is achieved by returning a pointer from + // from outside as obtained by `super::alloc`. + fn new_uninit_bytes(size: usize) -> Self { + unsafe { + let ptr = super::alloc(size, T::align_of()).expect("User memory allocation failed"); + User(T::from_raw_sized(ptr as _, size) as _) + } + } + + pub fn new_from_enclave(val: &T) -> Self { + unsafe { + let ret = Self::new_uninit_bytes(mem::size_of_val(val)); + ptr::copy( + val as *const T as *const u8, + ret.0 as *mut T as *mut u8, + mem::size_of_val(val) + ); + ret + } + } + + /// Create an owned `User` from a raw pointer. The pointer should be + /// freeable with the `free` usercall and the alignment of `T`. + /// + /// # Panics + /// This function panics if: + /// + /// * The pointer is not aligned + /// * The pointer is null + /// * The pointed-to range is not in user memory + pub unsafe fn from_raw(ptr: *mut T) -> Self { + T::check_ptr(ptr); + User(ptr as _) + } + + /// Convert this value into a raw pointer. The value will no longer be + /// automatically freed. + pub fn into_raw(self) -> *mut T { + let ret = self.0; + mem::forget(self); + ret as _ + } +} + +impl User where T: UserSafe { + pub fn uninitialized() -> Self { + Self::new_uninit_bytes(mem::size_of::()) + } +} + +impl User<[T]> where [T]: UserSafe { + pub fn uninitialized(n: usize) -> Self { + Self::new_uninit_bytes(n * mem::size_of::()) + } + + /// Create an owned `User<[T]>` from a raw thin pointer and a slice length. + /// The pointer should be freeable with the `free` usercall and the + /// alignment of `T`. + /// + /// # Panics + /// This function panics if: + /// + /// * The pointer is not aligned + /// * The pointer is null + /// * The pointed-to range is not in user memory + pub unsafe fn from_raw_parts(ptr: *mut T, len: usize) -> Self { + User(<[T]>::from_raw_sized(ptr as _, len * mem::size_of::()) as _) + } +} + +impl UserRef where T: UserSafe { + /// Create a `&UserRef<[T]>` from a raw pointer. + /// + /// # Panics + /// This function panics if: + /// + /// * The pointer is not aligned + /// * The pointer is null + /// * The pointed-to range is not in user memory + pub unsafe fn from_ptr<'a>(ptr: *const T) -> &'a Self { + T::check_ptr(ptr); + &*(ptr as *const Self) + } + + /// Create a `&mut UserRef<[T]>` from a raw pointer. + /// + /// # Panics + /// This function panics if: + /// + /// * The pointer is not aligned + /// * The pointer is null + /// * The pointed-to range is not in user memory + pub unsafe fn from_mut_ptr<'a>(ptr: *mut T) -> &'a mut Self { + T::check_ptr(ptr); + &mut*(ptr as *mut Self) + } + + /// # Panics + /// This function panics if the destination doesn't have the same size as + /// the source. This can happen for dynamically-sized types such as slices. + pub fn copy_from_enclave(&mut self, val: &T) { + unsafe { + assert_eq!(mem::size_of_val(val), mem::size_of_val( &*self.0.get() )); + ptr::copy( + val as *const T as *const u8, + self.0.get() as *mut T as *mut u8, + mem::size_of_val(val) + ); + } + } + + /// # Panics + /// This function panics if the destination doesn't have the same size as + /// the source. This can happen for dynamically-sized types such as slices. + pub fn copy_to_enclave(&self, dest: &mut T) { + unsafe { + assert_eq!(mem::size_of_val(dest), mem::size_of_val( &*self.0.get() )); + ptr::copy( + self.0.get() as *const T as *const u8, + dest as *mut T as *mut u8, + mem::size_of_val(dest) + ); + } + } + + pub fn as_raw_ptr(&self) -> *const T { + self as *const _ as _ + } + + pub fn as_raw_mut_ptr(&mut self) -> *mut T { + self as *mut _ as _ + } +} + +impl UserRef where T: UserSafe { + pub fn to_enclave(&self) -> T { + unsafe { ptr::read(self.0.get()) } + } +} + +impl UserRef<[T]> where [T]: UserSafe { + /// Create a `&UserRef<[T]>` from a raw thin pointer and a slice length. + /// + /// # Panics + /// This function panics if: + /// + /// * The pointer is not aligned + /// * The pointer is null + /// * The pointed-to range is not in user memory + pub unsafe fn from_raw_parts<'a>(ptr: *const T, len: usize) -> &'a Self { + &*(<[T]>::from_raw_sized(ptr as _, len * mem::size_of::()) as *const Self) + } + + /// Create a `&mut UserRef<[T]>` from a raw thin pointer and a slice length. + /// + /// # Panics + /// This function panics if: + /// + /// * The pointer is not aligned + /// * The pointer is null + /// * The pointed-to range is not in user memory + pub unsafe fn from_raw_parts_mut<'a>(ptr: *mut T, len: usize) -> &'a mut Self { + &mut*(<[T]>::from_raw_sized(ptr as _, len * mem::size_of::()) as *mut Self) + } + + pub fn as_ptr(&self) -> *const T { + self.0.get() as _ + } + + pub fn as_mut_ptr(&mut self) -> *mut T { + self.0.get() as _ + } + + pub fn len(&self) -> usize { + unsafe { (*self.0.get()).len() } + } + + pub fn copy_to_enclave_vec(&self, dest: &mut Vec) { + unsafe { + if let Some(missing) = self.len().checked_sub(dest.capacity()) { + dest.reserve(missing) + } + dest.set_len(self.len()); + self.copy_to_enclave(&mut dest[..]); + } + } + + pub fn to_enclave(&self) -> Vec { + let mut ret = Vec::with_capacity(self.len()); + self.copy_to_enclave_vec(&mut ret); + ret + } + + pub fn iter(&self) -> Iter + where T: UserSafe // FIXME: should be implied by [T]: UserSafe? + { + unsafe { + Iter((&*self.as_raw_ptr()).iter()) + } + } + + pub fn iter_mut(&mut self) -> IterMut + where T: UserSafe // FIXME: should be implied by [T]: UserSafe? + { + unsafe { + IterMut((&mut*self.as_raw_mut_ptr()).iter_mut()) + } + } +} + +pub struct Iter<'a, T: 'a + UserSafe>(slice::Iter<'a, T>); + +impl<'a, T: UserSafe> Iterator for Iter<'a, T> { + type Item = &'a UserRef; + + #[inline] + fn next(&mut self) -> Option { + unsafe { + self.0.next().map(|e| UserRef::from_ptr(e)) + } + } +} + +pub struct IterMut<'a, T: 'a + UserSafe>(slice::IterMut<'a, T>); + +impl<'a, T: UserSafe> Iterator for IterMut<'a, T> { + type Item = &'a mut UserRef; + + #[inline] + fn next(&mut self) -> Option { + unsafe { + self.0.next().map(|e| UserRef::from_mut_ptr(e)) + } + } +} + +impl Deref for User where T: UserSafe { + type Target = UserRef; + + fn deref(&self) -> &Self::Target { + unsafe { &*self.0 } + } +} + +impl DerefMut for User where T: UserSafe { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { &mut*self.0 } + } +} + +impl Drop for User where T: UserSafe { + fn drop(&mut self) { + unsafe { + let ptr = (*self.0).0.get(); + super::free(ptr as _, mem::size_of_val(&mut*ptr), T::align_of()); + } + } +} + +impl, U> CoerceUnsized> for UserRef {} + +impl> Index for UserRef<[T]> where [T]: UserSafe, I::Output: UserSafe { + type Output = UserRef; + + #[inline] + fn index(&self, index: I) -> &UserRef { + unsafe { + UserRef::from_ptr(index.index(&*self.as_raw_ptr())) + } + } +} + +impl> IndexMut for UserRef<[T]> where [T]: UserSafe, I::Output: UserSafe { + #[inline] + fn index_mut(&mut self, index: I) -> &mut UserRef { + unsafe { + UserRef::from_mut_ptr(index.index_mut(&mut*self.as_raw_mut_ptr())) + } + } +} diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs index 370e058badf..f7a9c3da3b2 100644 --- a/src/libstd/sys/sgx/abi/usercalls/mod.rs +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -8,5 +8,78 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +pub use fortanix_sgx_abi::*; + +use io::{Error as IoError, Result as IoResult}; + +mod alloc; #[macro_use] -pub mod raw; +mod raw; + +pub fn exit(panic: bool) -> ! { + unsafe { raw::exit(panic) } +} + +pub fn alloc(size: usize, alignment: usize) -> IoResult<*mut u8> { + unsafe { raw::alloc(size, alignment).from_sgx_result() } +} + +pub use self::raw::free; + +fn check_os_error(err: Result) -> i32 { + // FIXME: not sure how to make sure all variants of Error are covered + if err == Error::NotFound as _ || + err == Error::PermissionDenied as _ || + err == Error::ConnectionRefused as _ || + err == Error::ConnectionReset as _ || + err == Error::ConnectionAborted as _ || + err == Error::NotConnected as _ || + err == Error::AddrInUse as _ || + err == Error::AddrNotAvailable as _ || + err == Error::BrokenPipe as _ || + err == Error::AlreadyExists as _ || + err == Error::WouldBlock as _ || + err == Error::InvalidInput as _ || + err == Error::InvalidData as _ || + err == Error::TimedOut as _ || + err == Error::WriteZero as _ || + err == Error::Interrupted as _ || + err == Error::Other as _ || + err == Error::UnexpectedEof as _ || + ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&err) + { + err + } else { + panic!("Usercall: returned invalid error value {}", err) + } +} + +trait FromSgxResult { + type Return; + + fn from_sgx_result(self) -> IoResult; +} + +impl FromSgxResult for (Result, T) { + type Return = T; + + fn from_sgx_result(self) -> IoResult { + if self.0 == RESULT_SUCCESS { + Ok(self.1) + } else { + Err(IoError::from_raw_os_error(check_os_error(self.0))) + } + } +} + +impl FromSgxResult for Result { + type Return = (); + + fn from_sgx_result(self) -> IoResult { + if self == RESULT_SUCCESS { + Ok(()) + } else { + Err(IoError::from_raw_os_error(check_os_error(self))) + } + } +} -- cgit 1.4.1-3-g733a5 From 8d6edc9f8f71075c55fad3c5ca5a7e28b5e01400 Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Wed, 5 Sep 2018 16:19:35 -0700 Subject: SGX target: implement synchronization primitives and threading --- src/libstd/io/lazy.rs | 1 + src/libstd/sys/sgx/abi/mod.rs | 5 +- src/libstd/sys/sgx/abi/usercalls/mod.rs | 12 + src/libstd/sys/sgx/alloc.rs | 15 +- src/libstd/sys/sgx/condvar.rs | 23 +- src/libstd/sys/sgx/mod.rs | 1 + src/libstd/sys/sgx/mutex.rs | 122 +++++-- src/libstd/sys/sgx/os.rs | 2 +- src/libstd/sys/sgx/rwlock.rs | 106 ++++-- src/libstd/sys/sgx/thread.rs | 66 +++- src/libstd/sys/sgx/waitqueue.rs | 552 ++++++++++++++++++++++++++++++++ src/libstd/sys_common/condvar.rs | 1 + src/libstd/sys_common/mutex.rs | 1 + src/libstd/sys_common/rwlock.rs | 1 + 14 files changed, 832 insertions(+), 76 deletions(-) create mode 100644 src/libstd/sys/sgx/waitqueue.rs (limited to 'src/libstd/sys') diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs index 24965ff6931..c2aaeb98907 100644 --- a/src/libstd/io/lazy.rs +++ b/src/libstd/io/lazy.rs @@ -26,6 +26,7 @@ const fn done() -> *mut Arc { 1_usize as *mut _ } unsafe impl Sync for Lazy {} impl Lazy { + #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Lazy { Lazy { lock: Mutex::new(), diff --git a/src/libstd/sys/sgx/abi/mod.rs b/src/libstd/sys/sgx/abi/mod.rs index 61204904962..069cca3b98e 100644 --- a/src/libstd/sys/sgx/abi/mod.rs +++ b/src/libstd/sys/sgx/abi/mod.rs @@ -20,7 +20,7 @@ pub(super) mod panic; pub mod thread; pub mod tls; #[macro_use] -mod usercalls; +pub mod usercalls; global_asm!(concat!(usercalls_asm!(), include_str!("entry.S"))); @@ -59,14 +59,13 @@ unsafe extern "C" fn tcs_init(secondary: bool) { // (main function exists). If this is a library, the crate author should be // able to specify this #[no_mangle] -#[allow(unreachable_code)] extern "C" fn entry(p1: u64, p2: u64, p3: u64, secondary: bool, p4: u64, p5: u64) -> (u64, u64) { // FIXME: how to support TLS in library mode? let tls = Box::new(tls::Tls::new()); let _tls_guard = unsafe { tls.activate() }; if secondary { - unimplemented!("thread entrypoint"); + super::thread::Thread::entry(); (0, 0) } else { diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs index f7a9c3da3b2..cf422e3e6aa 100644 --- a/src/libstd/sys/sgx/abi/usercalls/mod.rs +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -16,10 +16,22 @@ mod alloc; #[macro_use] mod raw; +pub fn launch_thread() -> IoResult<()> { + unsafe { raw::launch_thread().from_sgx_result() } +} + pub fn exit(panic: bool) -> ! { unsafe { raw::exit(panic) } } +pub fn wait(event_mask: u64, timeout: u64) -> IoResult { + unsafe { raw::wait(event_mask, timeout).from_sgx_result() } +} + +pub fn send(event_set: u64, tcs: Option) -> IoResult<()> { + unsafe { raw::send(event_set, tcs).from_sgx_result() } +} + pub fn alloc(size: usize, alignment: usize) -> IoResult<*mut u8> { unsafe { raw::alloc(size, alignment).from_sgx_result() } } diff --git a/src/libstd/sys/sgx/alloc.rs b/src/libstd/sys/sgx/alloc.rs index a31f93ae493..83c20ace89b 100644 --- a/src/libstd/sys/sgx/alloc.rs +++ b/src/libstd/sys/sgx/alloc.rs @@ -12,28 +12,31 @@ extern crate dlmalloc; use alloc::{GlobalAlloc, Layout, System}; -// FIXME: protect this value for concurrent access -static mut DLMALLOC: dlmalloc::Dlmalloc = dlmalloc::DLMALLOC_INIT; +use super::waitqueue::SpinMutex; + +// Using a SpinMutex because we never want to exit the enclave waiting for the +// allocator. +static DLMALLOC: SpinMutex = SpinMutex::new(dlmalloc::DLMALLOC_INIT); #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { - DLMALLOC.malloc(layout.size(), layout.align()) + DLMALLOC.lock().malloc(layout.size(), layout.align()) } #[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { - DLMALLOC.calloc(layout.size(), layout.align()) + DLMALLOC.lock().calloc(layout.size(), layout.align()) } #[inline] unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { - DLMALLOC.free(ptr, layout.size(), layout.align()) + DLMALLOC.lock().free(ptr, layout.size(), layout.align()) } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { - DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) + DLMALLOC.lock().realloc(ptr, layout.size(), layout.align(), new_size) } } diff --git a/src/libstd/sys/sgx/condvar.rs b/src/libstd/sys/sgx/condvar.rs index 2097280a064..d3e8165f3df 100644 --- a/src/libstd/sys/sgx/condvar.rs +++ b/src/libstd/sys/sgx/condvar.rs @@ -11,11 +11,16 @@ use sys::mutex::Mutex; use time::Duration; -pub struct Condvar { } +use super::waitqueue::{WaitVariable, WaitQueue, SpinMutex}; + +pub struct Condvar { + inner: SpinMutex>, +} impl Condvar { + #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Condvar { - Condvar { } + Condvar { inner: SpinMutex::new(WaitVariable::new(())) } } #[inline] @@ -23,21 +28,25 @@ impl Condvar { #[inline] pub unsafe fn notify_one(&self) { + let _ = WaitQueue::notify_one(self.inner.lock()); } #[inline] pub unsafe fn notify_all(&self) { + let _ = WaitQueue::notify_all(self.inner.lock()); } - pub unsafe fn wait(&self, _mutex: &Mutex) { - panic!("can't block with web assembly") + pub unsafe fn wait(&self, mutex: &Mutex) { + let guard = self.inner.lock(); + mutex.unlock(); + WaitQueue::wait(guard); + mutex.lock() } pub unsafe fn wait_timeout(&self, _mutex: &Mutex, _dur: Duration) -> bool { - panic!("can't block with web assembly"); + panic!("timeout not supported in SGX"); } #[inline] - pub unsafe fn destroy(&self) { - } + pub unsafe fn destroy(&self) {} } diff --git a/src/libstd/sys/sgx/mod.rs b/src/libstd/sys/sgx/mod.rs index f38c69e90c7..68f7479d7cd 100644 --- a/src/libstd/sys/sgx/mod.rs +++ b/src/libstd/sys/sgx/mod.rs @@ -18,6 +18,7 @@ use os::raw::c_char; use sync::atomic::{AtomicBool, Ordering}; pub mod abi; +mod waitqueue; pub mod alloc; pub mod args; diff --git a/src/libstd/sys/sgx/mutex.rs b/src/libstd/sys/sgx/mutex.rs index ffaa4014e14..663361162bc 100644 --- a/src/libstd/sys/sgx/mutex.rs +++ b/src/libstd/sys/sgx/mutex.rs @@ -8,71 +8,145 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use cell::UnsafeCell; +use fortanix_sgx_abi::Tcs; + +use super::abi::thread; + +use super::waitqueue::{WaitVariable, WaitQueue, SpinMutex, NotifiedTcs, try_lock_or_false}; pub struct Mutex { - locked: UnsafeCell, + inner: SpinMutex>, } -unsafe impl Send for Mutex {} -unsafe impl Sync for Mutex {} // FIXME - +// Implementation according to “Operating Systems: Three Easy Pieces”, chapter 28 impl Mutex { + #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Mutex { - Mutex { locked: UnsafeCell::new(false) } + Mutex { inner: SpinMutex::new(WaitVariable::new(false)) } } #[inline] - pub unsafe fn init(&mut self) { - } + pub unsafe fn init(&mut self) {} #[inline] pub unsafe fn lock(&self) { - let locked = self.locked.get(); - assert!(!*locked, "cannot recursively acquire mutex"); - *locked = true; + let mut guard = self.inner.lock(); + if *guard.lock_var() { + // Another thread has the lock, wait + WaitQueue::wait(guard) + // Another thread has passed the lock to us + } else { + // We are just now obtaining the lock + *guard.lock_var_mut() = true; + } } #[inline] pub unsafe fn unlock(&self) { - *self.locked.get() = false; + let guard = self.inner.lock(); + if let Err(mut guard) = WaitQueue::notify_one(guard) { + // No other waiters, unlock + *guard.lock_var_mut() = false; + } else { + // There was a thread waiting, just pass the lock + } } #[inline] pub unsafe fn try_lock(&self) -> bool { - let locked = self.locked.get(); - if *locked { + let mut guard = try_lock_or_false!(self.inner); + if *guard.lock_var() { + // Another thread has the lock false } else { - *locked = true; + // We are just now obtaining the lock + *guard.lock_var_mut() = true; true } } #[inline] - pub unsafe fn destroy(&self) { - } + pub unsafe fn destroy(&self) {} +} + +struct ReentrantLock { + owner: Option, + count: usize } -// FIXME pub struct ReentrantMutex { + inner: SpinMutex>, } impl ReentrantMutex { - pub unsafe fn uninitialized() -> ReentrantMutex { - ReentrantMutex { } + #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn + pub const fn uninitialized() -> ReentrantMutex { + ReentrantMutex { + inner: SpinMutex::new(WaitVariable::new(ReentrantLock { owner: None, count: 0 })) + } } + #[inline] pub unsafe fn init(&mut self) {} - pub unsafe fn lock(&self) {} + #[inline] + pub unsafe fn lock(&self) { + let mut guard = self.inner.lock(); + match guard.lock_var().owner { + Some(tcs) if tcs != thread::current() => { + // Another thread has the lock, wait + WaitQueue::wait(guard); + // Another thread has passed the lock to us + }, + _ => { + // We are just now obtaining the lock + guard.lock_var_mut().owner = Some(thread::current()); + guard.lock_var_mut().count += 1; + }, + } + } #[inline] - pub unsafe fn try_lock(&self) -> bool { - true + pub unsafe fn unlock(&self) { + let mut guard = self.inner.lock(); + if guard.lock_var().count > 1 { + guard.lock_var_mut().count -= 1; + } else { + match WaitQueue::notify_one(guard) { + Err(mut guard) => { + // No other waiters, unlock + guard.lock_var_mut().count = 0; + guard.lock_var_mut().owner = None; + }, + Ok(mut guard) => { + // There was a thread waiting, just pass the lock + if let NotifiedTcs::Single(tcs) = guard.notified_tcs() { + guard.lock_var_mut().owner = Some(tcs) + } else { + unreachable!() // called notify_one + } + } + } + } } - pub unsafe fn unlock(&self) {} + #[inline] + pub unsafe fn try_lock(&self) -> bool { + let mut guard = try_lock_or_false!(self.inner); + match guard.lock_var().owner { + Some(tcs) if tcs != thread::current() => { + // Another thread has the lock + false + }, + _ => { + // We are just now obtaining the lock + guard.lock_var_mut().owner = Some(thread::current()); + guard.lock_var_mut().count += 1; + true + }, + } + } + #[inline] pub unsafe fn destroy(&self) {} } diff --git a/src/libstd/sys/sgx/os.rs b/src/libstd/sys/sgx/os.rs index 38d82efaf17..cb25338ed46 100644 --- a/src/libstd/sys/sgx/os.rs +++ b/src/libstd/sys/sgx/os.rs @@ -92,7 +92,7 @@ pub fn env() -> Env { } pub fn getenv(_k: &OsStr) -> io::Result> { - unsupported() + Ok(None) } pub fn setenv(_k: &OsStr, _v: &OsStr) -> io::Result<()> { diff --git a/src/libstd/sys/sgx/rwlock.rs b/src/libstd/sys/sgx/rwlock.rs index 2c0b1a45206..7b6970b825f 100644 --- a/src/libstd/sys/sgx/rwlock.rs +++ b/src/libstd/sys/sgx/rwlock.rs @@ -8,75 +8,127 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use cell::UnsafeCell; +use num::NonZeroUsize; + +use super::waitqueue::{WaitVariable, WaitQueue, SpinMutex, NotifiedTcs, try_lock_or_false}; pub struct RWLock { - mode: UnsafeCell, + readers: SpinMutex>>, + writer: SpinMutex>, } -unsafe impl Send for RWLock {} -unsafe impl Sync for RWLock {} // FIXME +//unsafe impl Send for RWLock {} +//unsafe impl Sync for RWLock {} // FIXME impl RWLock { + #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> RWLock { RWLock { - mode: UnsafeCell::new(0), + readers: SpinMutex::new(WaitVariable::new(None)), + writer: SpinMutex::new(WaitVariable::new(false)) } } #[inline] pub unsafe fn read(&self) { - let mode = self.mode.get(); - if *mode >= 0 { - *mode += 1; + let mut rguard = self.readers.lock(); + let wguard = self.writer.lock(); + if *wguard.lock_var() || !wguard.queue_empty() { + // Another thread has or is waiting for the write lock, wait + drop(wguard); + WaitQueue::wait(rguard); + // Another thread has passed the lock to us } else { - rtabort!("rwlock locked for writing"); + // No waiting writers, acquire the read lock + *rguard.lock_var_mut() = + NonZeroUsize::new(rguard.lock_var().map_or(0, |n| n.get()) + 1); } } #[inline] pub unsafe fn try_read(&self) -> bool { - let mode = self.mode.get(); - if *mode >= 0 { - *mode += 1; - true - } else { + let mut rguard = try_lock_or_false!(self.readers); + let wguard = try_lock_or_false!(self.writer); + if *wguard.lock_var() || !wguard.queue_empty() { + // Another thread has or is waiting for the write lock false + } else { + // No waiting writers, acquire the read lock + *rguard.lock_var_mut() = + NonZeroUsize::new(rguard.lock_var().map_or(0, |n| n.get()) + 1); + true } } #[inline] pub unsafe fn write(&self) { - let mode = self.mode.get(); - if *mode == 0 { - *mode = -1; + let rguard = self.readers.lock(); + let mut wguard = self.writer.lock(); + if *wguard.lock_var() || rguard.lock_var().is_some() { + // Another thread has the lock, wait + drop(rguard); + WaitQueue::wait(wguard); + // Another thread has passed the lock to us } else { - rtabort!("rwlock locked for reading") + // We are just now obtaining the lock + *wguard.lock_var_mut() = true; } } #[inline] pub unsafe fn try_write(&self) -> bool { - let mode = self.mode.get(); - if *mode == 0 { - *mode = -1; - true - } else { + let rguard = try_lock_or_false!(self.readers); + let mut wguard = try_lock_or_false!(self.writer); + if *wguard.lock_var() || rguard.lock_var().is_some() { + // Another thread has the lock false + } else { + // We are just now obtaining the lock + *wguard.lock_var_mut() = true; + true } } #[inline] pub unsafe fn read_unlock(&self) { - *self.mode.get() -= 1; + let mut rguard = self.readers.lock(); + let wguard = self.writer.lock(); + *rguard.lock_var_mut() = NonZeroUsize::new(rguard.lock_var().unwrap().get() - 1); + if rguard.lock_var().is_some() { + // There are other active readers + } else { + if let Ok(mut wguard) = WaitQueue::notify_one(wguard) { + // A writer was waiting, pass the lock + *wguard.lock_var_mut() = true; + } else { + // No writers were waiting, the lock is released + assert!(rguard.queue_empty()); + } + } } #[inline] pub unsafe fn write_unlock(&self) { - *self.mode.get() += 1; + let rguard = self.readers.lock(); + let wguard = self.writer.lock(); + if let Err(mut wguard) = WaitQueue::notify_one(wguard) { + // No writers waiting, release the write lock + *wguard.lock_var_mut() = false; + if let Ok(mut rguard) = WaitQueue::notify_all(rguard) { + // One or more readers were waiting, pass the lock to them + if let NotifiedTcs::All { count } = rguard.notified_tcs() { + *rguard.lock_var_mut() = Some(count) + } else { + unreachable!() // called notify_all + } + } else { + // No readers waiting, the lock is released + } + } else { + // There was a thread waiting for write, just pass the lock + } } #[inline] - pub unsafe fn destroy(&self) { - } + pub unsafe fn destroy(&self) {} } diff --git a/src/libstd/sys/sgx/thread.rs b/src/libstd/sys/sgx/thread.rs index ff8df12302c..9de12a5e6f1 100644 --- a/src/libstd/sys/sgx/thread.rs +++ b/src/libstd/sys/sgx/thread.rs @@ -11,35 +11,85 @@ use boxed::FnBox; use ffi::CStr; use io; -use sys::{unsupported, Void}; use time::Duration; -pub struct Thread(Void); +use super::abi::usercalls; + +pub struct Thread(task_queue::JoinHandle); pub const DEFAULT_MIN_STACK_SIZE: usize = 4096; +mod task_queue { + use sync::{Mutex, MutexGuard, Once}; + use sync::mpsc; + use boxed::FnBox; + + pub type JoinHandle = mpsc::Receiver<()>; + + pub(super) struct Task { + p: Box, + done: mpsc::Sender<()>, + } + + impl Task { + pub(super) fn new(p: Box) -> (Task, JoinHandle) { + let (done, recv) = mpsc::channel(); + (Task { p, done }, recv) + } + + pub(super) fn run(self) { + (self.p)(); + let _ = self.done.send(()); + } + } + + static TASK_QUEUE_INIT: Once = Once::new(); + static mut TASK_QUEUE: Option>> = None; + + pub(super) fn lock() -> MutexGuard<'static, Vec> { + unsafe { + TASK_QUEUE_INIT.call_once(|| TASK_QUEUE = Some(Default::default()) ); + TASK_QUEUE.as_ref().unwrap().lock().unwrap() + } + } +} + impl Thread { // unsafe: see thread::Builder::spawn_unchecked for safety requirements - pub unsafe fn new(_stack: usize, _p: Box) + pub unsafe fn new(_stack: usize, p: Box) -> io::Result { - unsupported() + let mut queue_lock = task_queue::lock(); + usercalls::launch_thread()?; + let (task, handle) = task_queue::Task::new(p); + queue_lock.push(task); + Ok(Thread(handle)) + } + + pub(super) fn entry() { + let mut guard = task_queue::lock(); + let task = guard.pop().expect("Thread started but no tasks pending"); + drop(guard); // make sure to not hold the task queue lock longer than necessary + task.run() } pub fn yield_now() { - // do nothing + assert_eq!( + usercalls::wait(0, usercalls::WAIT_NO).unwrap_err().kind(), + io::ErrorKind::WouldBlock + ); } pub fn set_name(_name: &CStr) { - // nope + // FIXME: could store this pointer in TLS somewhere } pub fn sleep(_dur: Duration) { - panic!("can't sleep"); + panic!("can't sleep"); // FIXME } pub fn join(self) { - match self.0 {} + let _ = self.0.recv(); } } diff --git a/src/libstd/sys/sgx/waitqueue.rs b/src/libstd/sys/sgx/waitqueue.rs new file mode 100644 index 00000000000..ec1135ba30c --- /dev/null +++ b/src/libstd/sys/sgx/waitqueue.rs @@ -0,0 +1,552 @@ +// 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. + +/// A simple queue implementation for synchronization primitives. +/// +/// This queue is used to implement condition variable and mutexes. +/// +/// Users of this API are expected to use the `WaitVariable` type. Since +/// that type is not `Sync`, it needs to be protected by e.g. a `SpinMutex` to +/// allow shared access. +/// +/// Since userspace may send spurious wake-ups, the wakeup event state is +/// recorded in the enclave. The wakeup event state is protected by a spinlock. +/// The queue and associated wait state are stored in a `WaitVariable`. + +use ops::{Deref, DerefMut}; +use num::NonZeroUsize; + +use fortanix_sgx_abi::{Tcs, EV_UNPARK, WAIT_INDEFINITE}; +use super::abi::usercalls; +use super::abi::thread; + +use self::unsafe_list::{UnsafeList, UnsafeListEntry}; +pub use self::spin_mutex::{SpinMutex, SpinMutexGuard, try_lock_or_false}; + +/// An queue entry in a `WaitQueue`. +struct WaitEntry { + /// TCS address of the thread that is waiting + tcs: Tcs, + /// Whether this thread has been notified to be awoken + wake: bool +} + +/// Data stored with a `WaitQueue` alongside it. This ensures accesses to the +/// queue and the data are synchronized, since the type itself is not `Sync`. +/// +/// Consumers of this API should use a synchronization primitive for shared +/// access, such as `SpinMutex`. +#[derive(Default)] +pub struct WaitVariable { + queue: WaitQueue, + lock: T +} + +impl WaitVariable { + #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn + pub const fn new(var: T) -> Self { + WaitVariable { + queue: WaitQueue::new(), + lock: var + } + } + + pub fn queue_empty(&self) -> bool { + self.queue.is_empty() + } + + pub fn lock_var(&self) -> &T { + &self.lock + } + + pub fn lock_var_mut(&mut self) -> &mut T { + &mut self.lock + } +} + +#[derive(Copy, Clone)] +pub enum NotifiedTcs { + Single(Tcs), + All { count: NonZeroUsize } +} + +/// An RAII guard that will notify a set of target threads as well as unlock +/// a mutex on drop. +pub struct WaitGuard<'a, T: 'a> { + mutex_guard: Option>>, + notified_tcs: NotifiedTcs +} + +/// A queue of threads that are waiting on some synchronization primitive. +/// +/// `UnsafeList` entries are allocated on the waiting thread's stack. This +/// avoids any global locking that might happen in the heap allocator. This is +/// safe because the waiting thread will not return from that stack frame until +/// after it is notified. The notifying thread ensures to clean up any +/// references to the list entries before sending the wakeup event. +pub struct WaitQueue { + // We use an inner Mutex here to protect the data in the face of spurious + // wakeups. + inner: UnsafeList>, +} +unsafe impl Send for WaitQueue {} + +impl Default for WaitQueue { + fn default() -> Self { + Self::new() + } +} + +impl<'a, T> WaitGuard<'a, T> { + /// Returns which TCSes will be notified when this guard drops. + pub fn notified_tcs(&self) -> NotifiedTcs { + self.notified_tcs + } +} + +impl<'a, T> Deref for WaitGuard<'a, T> { + type Target = SpinMutexGuard<'a, WaitVariable>; + + fn deref(&self) -> &Self::Target { + self.mutex_guard.as_ref().unwrap() + } +} + +impl<'a, T> DerefMut for WaitGuard<'a, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.mutex_guard.as_mut().unwrap() + } +} + +impl<'a, T> Drop for WaitGuard<'a, T> { + fn drop(&mut self) { + drop(self.mutex_guard.take()); + let target_tcs = match self.notified_tcs { + NotifiedTcs::Single(tcs) => Some(tcs), + NotifiedTcs::All { .. } => None + }; + usercalls::send(EV_UNPARK, target_tcs).unwrap(); + } +} + +impl WaitQueue { + #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn + pub const fn new() -> Self { + WaitQueue { + inner: UnsafeList::new() + } + } + + pub fn is_empty(&self) -> bool { + self.inner.is_empty() + } + + /// Add the calling thread to the WaitVariable's wait queue, then wait + /// until a wakeup event. + /// + /// This function does not return until this thread has been awoken. + pub fn wait(mut guard: SpinMutexGuard>) { + unsafe { + let mut entry = UnsafeListEntry::new(SpinMutex::new(WaitEntry { + tcs: thread::current(), + wake: false + })); + let entry = guard.queue.inner.push(&mut entry); + drop(guard); + while !entry.lock().wake { + assert_eq!( + usercalls::wait(EV_UNPARK, WAIT_INDEFINITE).unwrap() & EV_UNPARK, + EV_UNPARK + ); + } + } + } + + /// Either find the next waiter on the wait queue, or return the mutex + /// guard unchanged. + /// + /// If a waiter is found, a `WaitGuard` is returned which will notify the + /// waiter when it is dropped. + pub fn notify_one(mut guard: SpinMutexGuard>) + -> Result, SpinMutexGuard>> + { + unsafe { + if let Some(entry) = guard.queue.inner.pop() { + let mut entry_guard = entry.lock(); + let tcs = entry_guard.tcs; + entry_guard.wake = true; + drop(entry); + Ok(WaitGuard { + mutex_guard: Some(guard), + notified_tcs: NotifiedTcs::Single(tcs) + }) + } else { + Err(guard) + } + } + } + + /// Either find any and all waiters on the wait queue, or return the mutex + /// guard unchanged. + /// + /// If at least one waiter is found, a `WaitGuard` is returned which will + /// notify all waiters when it is dropped. + pub fn notify_all(mut guard: SpinMutexGuard>) + -> Result, SpinMutexGuard>> + { + unsafe { + let mut count = 0; + while let Some(entry) = guard.queue.inner.pop() { + count += 1; + let mut entry_guard = entry.lock(); + entry_guard.wake = true; + } + if let Some(count) = NonZeroUsize::new(count) { + Ok(WaitGuard { + mutex_guard: Some(guard), + notified_tcs: NotifiedTcs::All { count } + }) + } else { + Err(guard) + } + } + } +} + +/// A doubly-linked list where callers are in charge of memory allocation +/// of the nodes in the list. +mod unsafe_list { + use ptr::NonNull; + use mem; + + pub struct UnsafeListEntry { + next: NonNull>, + prev: NonNull>, + value: Option + } + + impl UnsafeListEntry { + fn dummy() -> Self { + UnsafeListEntry { + next: NonNull::dangling(), + prev: NonNull::dangling(), + value: None + } + } + + pub fn new(value: T) -> Self { + UnsafeListEntry { + value: Some(value), + ..Self::dummy() + } + } + } + + pub struct UnsafeList { + head_tail: NonNull>, + head_tail_entry: Option>, + } + + impl UnsafeList { + #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn + pub const fn new() -> Self { + unsafe { + UnsafeList { + head_tail: NonNull::new_unchecked(1 as _), + head_tail_entry: None + } + } + } + + unsafe fn init(&mut self) { + if self.head_tail_entry.is_none() { + self.head_tail_entry = Some(UnsafeListEntry::dummy()); + self.head_tail = NonNull::new_unchecked(self.head_tail_entry.as_mut().unwrap()); + self.head_tail.as_mut().next = self.head_tail; + self.head_tail.as_mut().prev = self.head_tail; + } + } + + pub fn is_empty(&self) -> bool { + unsafe { + if self.head_tail_entry.is_some() { + let first = self.head_tail.as_ref().next; + if first == self.head_tail { + // ,-------> /---------\ next ---, + // | |head_tail| | + // `--- prev \---------/ <-------` + assert_eq!(self.head_tail.as_ref().prev, first); + true + } else { + false + } + } else { + true + } + } + } + + /// Pushes an entry onto the back of the list. + /// + /// # Safety + /// + /// The entry must remain allocated until the entry is removed from the + /// list AND the caller who popped is done using the entry. + pub unsafe fn push<'a>(&mut self, entry: &'a mut UnsafeListEntry) -> &'a T { + self.init(); + + // BEFORE: + // /---------\ next ---> /---------\ + // ... |prev_tail| |head_tail| ... + // \---------/ <--- prev \---------/ + // + // AFTER: + // /---------\ next ---> /-----\ next ---> /---------\ + // ... |prev_tail| |entry| |head_tail| ... + // \---------/ <--- prev \-----/ <--- prev \---------/ + let mut entry = NonNull::new_unchecked(entry); + let mut prev_tail = mem::replace(&mut self.head_tail.as_mut().prev, entry); + entry.as_mut().prev = prev_tail; + entry.as_mut().next = self.head_tail; + prev_tail.as_mut().next = entry; + (*entry.as_ptr()).value.as_ref().unwrap() + } + + /// Pops an entry from the front of the list. + /// + /// # Safety + /// + /// The caller must make sure to synchronize ending the borrow of the + /// return value and deallocation of the containing entry. + pub unsafe fn pop<'a>(&mut self) -> Option<&'a T> { + self.init(); + + if self.is_empty() { + None + } else { + // BEFORE: + // /---------\ next ---> /-----\ next ---> /------\ + // ... |head_tail| |first| |second| ... + // \---------/ <--- prev \-----/ <--- prev \------/ + // + // AFTER: + // /---------\ next ---> /------\ + // ... |head_tail| |second| ... + // \---------/ <--- prev \------/ + let mut first = self.head_tail.as_mut().next; + let mut second = first.as_mut().next; + self.head_tail.as_mut().next = second; + second.as_mut().prev = self.head_tail; + first.as_mut().next = NonNull::dangling(); + first.as_mut().prev = NonNull::dangling(); + Some((*first.as_ptr()).value.as_ref().unwrap()) + } + } + } + + #[cfg(test)] + mod tests { + use super::*; + use cell::Cell; + + unsafe fn assert_empty(list: &mut UnsafeList) { + assert!(list.pop().is_none(), "assertion failed: list is not empty"); + } + + #[test] + fn init_empty() { + unsafe { + assert_empty(&mut UnsafeList::::new()); + } + } + + #[test] + fn push_pop() { + unsafe { + let mut node = UnsafeListEntry::new(1234); + let mut list = UnsafeList::new(); + assert_eq!(list.push(&mut node), &1234); + assert_eq!(list.pop().unwrap(), &1234); + assert_empty(&mut list); + } + } + + #[test] + fn complex_pushes_pops() { + unsafe { + let mut node1 = UnsafeListEntry::new(1234); + let mut node2 = UnsafeListEntry::new(4567); + let mut node3 = UnsafeListEntry::new(9999); + let mut node4 = UnsafeListEntry::new(8642); + let mut list = UnsafeList::new(); + list.push(&mut node1); + list.push(&mut node2); + assert_eq!(list.pop().unwrap(), &1234); + list.push(&mut node3); + assert_eq!(list.pop().unwrap(), &4567); + assert_eq!(list.pop().unwrap(), &9999); + assert_empty(&mut list); + list.push(&mut node4); + assert_eq!(list.pop().unwrap(), &8642); + assert_empty(&mut list); + } + } + + #[test] + fn cell() { + unsafe { + let mut node = UnsafeListEntry::new(Cell::new(0)); + let mut list = UnsafeList::new(); + let noderef = list.push(&mut node); + assert_eq!(noderef.get(), 0); + list.pop().unwrap().set(1); + assert_empty(&mut list); + assert_eq!(noderef.get(), 1); + } + } + } +} + +/// Trivial spinlock-based implementation of `sync::Mutex`. +// FIXME: Perhaps use Intel TSX to avoid locking? +mod spin_mutex { + use cell::UnsafeCell; + use sync::atomic::{AtomicBool, Ordering, spin_loop_hint}; + use ops::{Deref, DerefMut}; + + #[derive(Default)] + pub struct SpinMutex { + value: UnsafeCell, + lock: AtomicBool, + } + + unsafe impl Send for SpinMutex {} + unsafe impl Sync for SpinMutex {} + + pub struct SpinMutexGuard<'a, T: 'a> { + mutex: &'a SpinMutex, + } + + impl<'a, T> !Send for SpinMutexGuard<'a, T> {} + unsafe impl<'a, T: Sync> Sync for SpinMutexGuard<'a, T> {} + + impl SpinMutex { + pub const fn new(value: T) -> Self { + SpinMutex { + value: UnsafeCell::new(value), + lock: AtomicBool::new(false) + } + } + + #[inline(always)] + pub fn lock(&self) -> SpinMutexGuard { + loop { + match self.try_lock() { + None => while self.lock.load(Ordering::Relaxed) { + spin_loop_hint() + }, + Some(guard) => return guard + } + } + } + + #[inline(always)] + pub fn try_lock(&self) -> Option> { + if !self.lock.compare_and_swap(false, true, Ordering::Acquire) { + Some(SpinMutexGuard { + mutex: self, + }) + } else { + None + } + } + } + + pub macro try_lock_or_false { + ($e:expr) => { + if let Some(v) = $e.try_lock() { + v + } else { + return false + } + } + } + + impl<'a, T> Deref for SpinMutexGuard<'a, T> { + type Target = T; + + fn deref(&self) -> &T { + unsafe { + &*self.mutex.value.get() + } + } + } + + impl<'a, T> DerefMut for SpinMutexGuard<'a, T> { + fn deref_mut(&mut self) -> &mut T { + unsafe { + &mut*self.mutex.value.get() + } + } + } + + impl<'a, T> Drop for SpinMutexGuard<'a, T> { + fn drop(&mut self) { + self.mutex.lock.store(false, Ordering::Release) + } + } + + #[cfg(test)] + mod tests { + #![allow(deprecated)] + + use super::*; + use sync::Arc; + use thread; + + #[test] + fn sleep() { + let mutex = Arc::new(SpinMutex::::default()); + let mutex2 = mutex.clone(); + let guard = mutex.lock(); + let t1 = thread::spawn(move || { + *mutex2.lock() = 1; + }); + thread::sleep_ms(50); + assert_eq!(*guard, 0); + drop(guard); + t1.join().unwrap(); + assert_eq!(*mutex.lock(), 1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use sync::Arc; + use thread; + + #[test] + fn queue() { + let wq = Arc::new(SpinMutex::>::default()); + let wq2 = wq.clone(); + + let locked = wq.lock(); + + let t1 = thread::spawn(move || { + assert!(WaitQueue::notify_one(wq2.lock()).is_none()) + }); + + WaitQueue::wait(locked); + + t1.join().unwrap(); + } +} diff --git a/src/libstd/sys_common/condvar.rs b/src/libstd/sys_common/condvar.rs index b6f29dd5fc3..16bf0803a8d 100644 --- a/src/libstd/sys_common/condvar.rs +++ b/src/libstd/sys_common/condvar.rs @@ -25,6 +25,7 @@ impl Condvar { /// /// Behavior is undefined if the condition variable is moved after it is /// first used with any of the functions below. + #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Condvar { Condvar(imp::Condvar::new()) } /// Prepares the condition variable for use. diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs index c6d531c7a1a..87684237638 100644 --- a/src/libstd/sys_common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs @@ -27,6 +27,7 @@ impl Mutex { /// 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. + #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Mutex { Mutex(imp::Mutex::new()) } /// Prepare the mutex for use. diff --git a/src/libstd/sys_common/rwlock.rs b/src/libstd/sys_common/rwlock.rs index 71a4f01ec4c..a430c254d3c 100644 --- a/src/libstd/sys_common/rwlock.rs +++ b/src/libstd/sys_common/rwlock.rs @@ -22,6 +22,7 @@ impl RWLock { /// /// Behavior is undefined if the reader-writer lock is moved after it is /// first used with any of the functions below. + #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> RWLock { RWLock(imp::RWLock::new()) } /// Acquires shared access to the underlying lock, blocking the current -- cgit 1.4.1-3-g733a5 From 1a894f135e972c30e79b4d7f836d69dbe49e7ead Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Mon, 17 Sep 2018 16:22:59 -0700 Subject: SGX target: implement streams --- src/libstd/sys/sgx/abi/usercalls/mod.rs | 41 +++++++++++++++++++++- src/libstd/sys/sgx/fd.rs | 58 ++++++++++++++++++++++++++++++ src/libstd/sys/sgx/mod.rs | 1 + src/libstd/sys/sgx/stdio.rs | 62 +++++++++++++++++++-------------- 4 files changed, 134 insertions(+), 28 deletions(-) create mode 100644 src/libstd/sys/sgx/fd.rs (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs index cf422e3e6aa..b8d739f4d2f 100644 --- a/src/libstd/sys/sgx/abi/usercalls/mod.rs +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -12,10 +12,49 @@ pub use fortanix_sgx_abi::*; use io::{Error as IoError, Result as IoResult}; -mod alloc; +pub mod alloc; #[macro_use] mod raw; +pub(crate) fn copy_user_buffer(buf: &alloc::UserRef) -> Vec { + unsafe { + let buf = buf.to_enclave(); + alloc::User::from_raw_parts(buf.data as _, buf.len).to_enclave() + } +} + +pub fn read(fd: Fd, buf: &mut [u8]) -> IoResult { + unsafe { + let mut userbuf = alloc::User::<[u8]>::uninitialized(buf.len()); + let len = raw::read(fd, userbuf.as_mut_ptr(), userbuf.len()).from_sgx_result()?; + userbuf[..len].copy_to_enclave(&mut buf[..len]); + Ok(len) + } +} + +pub fn read_alloc(fd: Fd) -> IoResult> { + unsafe { + let mut userbuf = alloc::User::::uninitialized(); + raw::read_alloc(fd, userbuf.as_raw_mut_ptr()).from_sgx_result()?; + Ok(copy_user_buffer(&userbuf)) + } +} + +pub fn write(fd: Fd, buf: &[u8]) -> IoResult { + unsafe { + let userbuf = alloc::User::new_from_enclave(buf); + raw::write(fd, userbuf.as_ptr(), userbuf.len()).from_sgx_result() + } +} + +pub fn flush(fd: Fd) -> IoResult<()> { + unsafe { raw::flush(fd).from_sgx_result() } +} + +pub fn close(fd: Fd) { + unsafe { raw::close(fd) } +} + pub fn launch_thread() -> IoResult<()> { unsafe { raw::launch_thread().from_sgx_result() } } diff --git a/src/libstd/sys/sgx/fd.rs b/src/libstd/sys/sgx/fd.rs new file mode 100644 index 00000000000..31c4199c6cd --- /dev/null +++ b/src/libstd/sys/sgx/fd.rs @@ -0,0 +1,58 @@ +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use fortanix_sgx_abi::Fd; + +use io; +use mem; +use sys_common::AsInner; +use super::abi::usercalls; + +#[derive(Debug)] +pub struct FileDesc { + fd: Fd, +} + +impl FileDesc { + pub fn new(fd: Fd) -> FileDesc { + FileDesc { fd: fd } + } + + pub fn raw(&self) -> Fd { self.fd } + + /// Extracts the actual filedescriptor without closing it. + pub fn into_raw(self) -> Fd { + let fd = self.fd; + mem::forget(self); + fd + } + + pub fn read(&self, buf: &mut [u8]) -> io::Result { + usercalls::read(self.fd, buf) + } + + pub fn write(&self, buf: &[u8]) -> io::Result { + usercalls::write(self.fd, buf) + } + + pub fn flush(&self) -> io::Result<()> { + usercalls::flush(self.fd) + } +} + +impl AsInner for FileDesc { + fn as_inner(&self) -> &Fd { &self.fd } +} + +impl Drop for FileDesc { + fn drop(&mut self) { + usercalls::close(self.fd) + } +} diff --git a/src/libstd/sys/sgx/mod.rs b/src/libstd/sys/sgx/mod.rs index 68f7479d7cd..dd6862e908e 100644 --- a/src/libstd/sys/sgx/mod.rs +++ b/src/libstd/sys/sgx/mod.rs @@ -27,6 +27,7 @@ pub mod backtrace; pub mod cmath; pub mod condvar; pub mod env; +pub mod fd; pub mod fs; pub mod memchr; pub mod mutex; diff --git a/src/libstd/sys/sgx/stdio.rs b/src/libstd/sys/sgx/stdio.rs index 540599a3596..13c91195569 100644 --- a/src/libstd/sys/sgx/stdio.rs +++ b/src/libstd/sys/sgx/stdio.rs @@ -1,4 +1,4 @@ -// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -8,64 +8,72 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use fortanix_sgx_abi as abi; + use io; -use sys::unsupported; +use sys::fd::FileDesc; + +pub struct Stdin(()); +pub struct Stdout(()); +pub struct Stderr(()); -pub struct Stdin; -pub struct Stdout; -pub struct Stderr; +fn with_std_fd R, R>(fd: abi::Fd, f: F) -> R { + let fd = FileDesc::new(fd); + let ret = f(&fd); + fd.into_raw(); + ret +} impl Stdin { - pub fn new() -> io::Result { - Ok(Stdin) - } + pub fn new() -> io::Result { Ok(Stdin(())) } - pub fn read(&self, _data: &mut [u8]) -> io::Result { - unsupported() + pub fn read(&self, data: &mut [u8]) -> io::Result { + with_std_fd(abi::FD_STDIN, |fd| fd.read(data)) } } impl Stdout { - pub fn new() -> io::Result { - Ok(Stdout) - } + pub fn new() -> io::Result { Ok(Stdout(())) } - pub fn write(&self, _data: &[u8]) -> io::Result { - unsupported() + pub fn write(&self, data: &[u8]) -> io::Result { + with_std_fd(abi::FD_STDOUT, |fd| fd.write(data)) } pub fn flush(&self) -> io::Result<()> { - Ok(()) + with_std_fd(abi::FD_STDOUT, |fd| fd.flush()) } } impl Stderr { - pub fn new() -> io::Result { - Ok(Stderr) - } + pub fn new() -> io::Result { Ok(Stderr(())) } - pub fn write(&self, _data: &[u8]) -> io::Result { - unsupported() + pub fn write(&self, data: &[u8]) -> io::Result { + with_std_fd(abi::FD_STDERR, |fd| fd.write(data)) } pub fn flush(&self) -> io::Result<()> { - Ok(()) + with_std_fd(abi::FD_STDERR, |fd| fd.flush()) } } +// FIXME: right now this raw stderr handle is used in a few places because +// std::io::stderr_raw isn't exposed, but once that's exposed this impl +// should go away impl io::Write for Stderr { fn write(&mut self, data: &[u8]) -> io::Result { - (&*self).write(data) + Stderr::write(self, data) } + fn flush(&mut self) -> io::Result<()> { - (&*self).flush() + Stderr::flush(self) } } -pub const STDIN_BUF_SIZE: usize = 0; +pub const STDIN_BUF_SIZE: usize = ::sys_common::io::DEFAULT_BUF_SIZE; -pub fn is_ebadf(_err: &io::Error) -> bool { - true +pub fn is_ebadf(err: &io::Error) -> bool { + // FIXME: Rust normally maps Unix EBADF to `Other` + err.raw_os_error() == Some(abi::Error::BrokenPipe as _) } pub fn panic_output() -> Option { -- cgit 1.4.1-3-g733a5 From 59b79f71e98fa96ce632d87dfb8cad0d9707bf9d Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Wed, 19 Sep 2018 15:59:06 -0700 Subject: SGX target: implement networking --- src/libstd/sys/sgx/abi/usercalls/mod.rs | 55 +++++++++++ src/libstd/sys/sgx/net.rs | 165 ++++++++++++++++++++++---------- 2 files changed, 167 insertions(+), 53 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs index b8d739f4d2f..3614e1293c1 100644 --- a/src/libstd/sys/sgx/abi/usercalls/mod.rs +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -55,6 +55,61 @@ pub fn close(fd: Fd) { unsafe { raw::close(fd) } } +fn string_from_bytebuffer(buf: &alloc::UserRef, usercall: &str, arg: &str) -> String { + String::from_utf8(copy_user_buffer(buf)) + .unwrap_or_else(|_| panic!("Usercall {}: expected {} to be valid UTF-8", usercall, arg)) +} + +pub fn bind_stream(addr: &str) -> IoResult<(Fd, String)> { + unsafe { + let addr_user = alloc::User::new_from_enclave(addr.as_bytes()); + let mut local = alloc::User::::uninitialized(); + let fd = raw::bind_stream( + addr_user.as_ptr(), + addr_user.len(), + local.as_raw_mut_ptr() + ).from_sgx_result()?; + let local = string_from_bytebuffer(&local, "bind_stream", "local_addr"); + Ok((fd, local)) + } +} + +pub fn accept_stream(fd: Fd) -> IoResult<(Fd, String, String)> { + unsafe { + let mut bufs = alloc::User::<[ByteBuffer; 2]>::uninitialized(); + let mut buf_it = alloc::UserRef::iter_mut(&mut *bufs); // FIXME: can this be done + // without forcing coercion? + let (local, peer) = (buf_it.next().unwrap(), buf_it.next().unwrap()); + let fd = raw::accept_stream( + fd, + local.as_raw_mut_ptr(), + peer.as_raw_mut_ptr() + ).from_sgx_result()?; + let local = string_from_bytebuffer(&local, "accept_stream", "local_addr"); + let peer = string_from_bytebuffer(&peer, "accept_stream", "peer_addr"); + Ok((fd, local, peer)) + } +} + +pub fn connect_stream(addr: &str) -> IoResult<(Fd, String, String)> { + unsafe { + let addr_user = alloc::User::new_from_enclave(addr.as_bytes()); + let mut bufs = alloc::User::<[ByteBuffer; 2]>::uninitialized(); + let mut buf_it = alloc::UserRef::iter_mut(&mut *bufs); // FIXME: can this be done + // without forcing coercion? + let (local, peer) = (buf_it.next().unwrap(), buf_it.next().unwrap()); + let fd = raw::connect_stream( + addr_user.as_ptr(), + addr_user.len(), + local.as_raw_mut_ptr(), + peer.as_raw_mut_ptr() + ).from_sgx_result()?; + let local = string_from_bytebuffer(&local, "connect_stream", "local_addr"); + let peer = string_from_bytebuffer(&peer, "connect_stream", "peer_addr"); + Ok((fd, local, peer)) + } +} + pub fn launch_thread() -> IoResult<()> { unsafe { raw::launch_thread().from_sgx_result() } } diff --git a/src/libstd/sys/sgx/net.rs b/src/libstd/sys/sgx/net.rs index 094683e28b8..176d230846d 100644 --- a/src/libstd/sys/sgx/net.rs +++ b/src/libstd/sys/sgx/net.rs @@ -10,144 +10,182 @@ use fmt; use io; -use net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr}; +use net::{SocketAddr, Shutdown, Ipv4Addr, Ipv6Addr, ToSocketAddrs}; use time::Duration; -use sys::{unsupported, Void}; +use sys::{unsupported, Void, sgx_ineffective}; +use sys::fd::FileDesc; use convert::TryFrom; +use error; +use sync::Arc; -pub struct TcpStream(Void); +use super::abi::usercalls; + +const DEFAULT_FAKE_TTL: u32 = 64; + +#[derive(Debug, Clone)] +struct Socket { + inner: Arc, + local_addr: String, +} + +impl Socket { + fn new(fd: usercalls::Fd, local_addr: String) -> Socket { + Socket { inner: Arc::new(FileDesc::new(fd)), local_addr } + } +} + +#[derive(Debug, Clone)] +pub struct TcpStream { + inner: Socket, + peer_addr: String, +} + +fn io_err_to_addr(result: io::Result<&SocketAddr>) -> io::Result { + match result { + Ok(saddr) => Ok(saddr.to_string()), + // need to downcast twice because io::Error::into_inner doesn't return the original + // value if the conversion fails + Err(e) => if e.get_ref().and_then(|e| e.downcast_ref::()).is_some() { + Ok(e.into_inner().unwrap().downcast::().unwrap().host) + } else { + Err(e) + } + } +} + +fn addr_to_sockaddr(addr: &str) -> io::Result { + // unwrap OK: if an iterator is returned, we're guaranteed to get exactly one entry + addr.to_socket_addrs().map(|mut it| it.next().unwrap()) +} impl TcpStream { - pub fn connect(_: io::Result<&SocketAddr>) -> io::Result { - unsupported() + pub fn connect(addr: io::Result<&SocketAddr>) -> io::Result { + let addr = io_err_to_addr(addr)?; + let (fd, local_addr, peer_addr) = usercalls::connect_stream(&addr)?; + Ok(TcpStream { inner: Socket::new(fd, local_addr), peer_addr }) } - pub fn connect_timeout(_: &SocketAddr, _: Duration) -> io::Result { - unsupported() + pub fn connect_timeout(addr: &SocketAddr, _: Duration) -> io::Result { + Self::connect(Ok(addr)) // FIXME: ignoring timeout } pub fn set_read_timeout(&self, _: Option) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } pub fn set_write_timeout(&self, _: Option) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } pub fn read_timeout(&self) -> io::Result> { - match self.0 {} + sgx_ineffective(None) } pub fn write_timeout(&self) -> io::Result> { - match self.0 {} + sgx_ineffective(None) } pub fn peek(&self, _: &mut [u8]) -> io::Result { - match self.0 {} + Ok(0) } - pub fn read(&self, _: &mut [u8]) -> io::Result { - match self.0 {} + pub fn read(&self, buf: &mut [u8]) -> io::Result { + self.inner.inner.read(buf) } - pub fn write(&self, _: &[u8]) -> io::Result { - match self.0 {} + pub fn write(&self, buf: &[u8]) -> io::Result { + self.inner.inner.write(buf) } pub fn peer_addr(&self) -> io::Result { - match self.0 {} + addr_to_sockaddr(&self.peer_addr) } pub fn socket_addr(&self) -> io::Result { - match self.0 {} + addr_to_sockaddr(&self.inner.local_addr) } pub fn shutdown(&self, _: Shutdown) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } pub fn duplicate(&self) -> io::Result { - match self.0 {} + Ok(self.clone()) } pub fn set_nodelay(&self, _: bool) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } pub fn nodelay(&self) -> io::Result { - match self.0 {} + sgx_ineffective(false) } pub fn set_ttl(&self, _: u32) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } pub fn ttl(&self) -> io::Result { - match self.0 {} + sgx_ineffective(DEFAULT_FAKE_TTL) } pub fn take_error(&self) -> io::Result> { - match self.0 {} + Ok(None) } pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } } -impl fmt::Debug for TcpStream { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - match self.0 {} - } +#[derive(Debug, Clone)] +pub struct TcpListener { + inner: Socket, } -pub struct TcpListener(Void); - impl TcpListener { - pub fn bind(_: io::Result<&SocketAddr>) -> io::Result { - unsupported() + pub fn bind(addr: io::Result<&SocketAddr>) -> io::Result { + let addr = io_err_to_addr(addr)?; + let (fd, local_addr) = usercalls::bind_stream(&addr)?; + Ok(TcpListener { inner: Socket::new(fd, local_addr) }) } pub fn socket_addr(&self) -> io::Result { - match self.0 {} + addr_to_sockaddr(&self.inner.local_addr) } pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> { - match self.0 {} + let (fd, local_addr, peer_addr) = usercalls::accept_stream(self.inner.inner.raw())?; + let ret_peer = addr_to_sockaddr(&peer_addr).unwrap_or_else(|_| ([0; 4], 0).into()); + Ok((TcpStream { inner: Socket::new(fd, local_addr), peer_addr }, ret_peer)) } pub fn duplicate(&self) -> io::Result { - match self.0 {} + Ok(self.clone()) } pub fn set_ttl(&self, _: u32) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } pub fn ttl(&self) -> io::Result { - match self.0 {} + sgx_ineffective(DEFAULT_FAKE_TTL) } pub fn set_only_v6(&self, _: bool) -> io::Result<()> { - match self.0 {} + sgx_ineffective(()) } pub fn only_v6(&self) -> io::Result { - match self.0 {} + sgx_ineffective(false) } pub fn take_error(&self) -> io::Result> { - match self.0 {} + Ok(None) } pub fn set_nonblocking(&self, _: bool) -> io::Result<()> { - match self.0 {} - } -} - -impl fmt::Debug for TcpListener { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - match self.0 {} + sgx_ineffective(()) } } @@ -285,9 +323,30 @@ impl fmt::Debug for UdpSocket { } } +#[derive(Debug)] +pub struct NonIpSockAddr { + host: String +} + +impl error::Error for NonIpSockAddr { + fn description(&self) -> &str { + "Failed to convert address to SocketAddr" + } +} + +impl fmt::Display for NonIpSockAddr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Failed to convert address to SocketAddr: {}", self.host) + } +} + pub struct LookupHost(Void); impl LookupHost { + fn new(host: String) -> io::Result { + Err(io::Error::new(io::ErrorKind::Other, NonIpSockAddr { host })) + } + pub fn port(&self) -> u16 { match self.0 {} } @@ -303,16 +362,16 @@ impl Iterator for LookupHost { impl<'a> TryFrom<&'a str> for LookupHost { type Error = io::Error; - fn try_from(_v: &'a str) -> io::Result { - unsupported() + fn try_from(v: &'a str) -> io::Result { + LookupHost::new(v.to_owned()) } } impl<'a> TryFrom<(&'a str, u16)> for LookupHost { type Error = io::Error; - fn try_from(_v: (&'a str, u16)) -> io::Result { - unsupported() + fn try_from((host, port): (&'a str, u16)) -> io::Result { + LookupHost::new(format!("{}:{}", host, port)) } } -- cgit 1.4.1-3-g733a5 From 6650f43a3f603e32ceba884aaa92bc491972a75b Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Wed, 19 Sep 2018 16:48:04 -0700 Subject: SGX target: implement time --- src/libstd/sys/sgx/abi/usercalls/mod.rs | 6 ++++++ src/libstd/sys/sgx/time.rs | 6 +++--- 2 files changed, 9 insertions(+), 3 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs index 3614e1293c1..2bc32c9fefb 100644 --- a/src/libstd/sys/sgx/abi/usercalls/mod.rs +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -11,6 +11,7 @@ pub use fortanix_sgx_abi::*; use io::{Error as IoError, Result as IoResult}; +use time::Duration; pub mod alloc; #[macro_use] @@ -126,6 +127,11 @@ pub fn send(event_set: u64, tcs: Option) -> IoResult<()> { unsafe { raw::send(event_set, tcs).from_sgx_result() } } +pub fn insecure_time() -> Duration { + let t = unsafe { raw::insecure_time() }; + Duration::new(t / 1_000_000_000, (t % 1_000_000_000) as _) +} + pub fn alloc(size: usize, alignment: usize) -> IoResult<*mut u8> { unsafe { raw::alloc(size, alignment).from_sgx_result() } } diff --git a/src/libstd/sys/sgx/time.rs b/src/libstd/sys/sgx/time.rs index 894680b0b65..b01c992768e 100644 --- a/src/libstd/sys/sgx/time.rs +++ b/src/libstd/sys/sgx/time.rs @@ -9,7 +9,7 @@ // except according to those terms. use time::Duration; -use sys::unsupported_err; +use super::abi::usercalls; #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] pub struct Instant(Duration); @@ -21,7 +21,7 @@ pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0)); impl Instant { pub fn now() -> Instant { - panic!("{}", unsupported_err()); + Instant(usercalls::insecure_time()) } pub fn sub_instant(&self, other: &Instant) -> Duration { @@ -39,7 +39,7 @@ impl Instant { impl SystemTime { pub fn now() -> SystemTime { - panic!("{}", unsupported_err()); + SystemTime(usercalls::insecure_time()) } pub fn sub_time(&self, other: &SystemTime) -- cgit 1.4.1-3-g733a5 From 7bea6a19641118937781d7971ba96e8d4a81497c Mon Sep 17 00:00:00 2001 From: Jethro Beekman Date: Thu, 20 Sep 2018 18:01:10 -0700 Subject: SGX target: implement command-line arguments and environment variables --- src/libstd/sys/sgx/args.rs | 44 +++++++++++++++++++++++++++------------ src/libstd/sys/sgx/os.rs | 51 +++++++++++++++++++++++++++++++++++----------- 2 files changed, 70 insertions(+), 25 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/sgx/args.rs b/src/libstd/sys/sgx/args.rs index 64cb83b462a..8fb35d7ef98 100644 --- a/src/libstd/sys/sgx/args.rs +++ b/src/libstd/sys/sgx/args.rs @@ -9,49 +9,67 @@ // except according to those terms. use ffi::OsString; -use fortanix_sgx_abi::ByteBuffer; +use super::abi::usercalls::{copy_user_buffer, alloc, ByteBuffer}; +use sync::atomic::{AtomicUsize, Ordering}; +use sys::os_str::Buf; +use sys_common::FromInner; +use slice; -pub unsafe fn init(argc: isize, argv: *const *const u8) { - // See ABI - let _len: usize = argc as _; - let _args: *const ByteBuffer = argv as _; +static ARGS: AtomicUsize = AtomicUsize::new(0); +type ArgsStore = Vec; - // TODO +pub unsafe fn init(argc: isize, argv: *const *const u8) { + if argc != 0 { + let args = alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _); + let args = args.iter() + .map( |a| OsString::from_inner(Buf { inner: copy_user_buffer(a) }) ) + .collect::(); + ARGS.store(Box::into_raw(Box::new(args)) as _, Ordering::Relaxed); + } } pub unsafe fn cleanup() { + let args = ARGS.swap(0, Ordering::Relaxed); + if args != 0 { + drop(Box::::from_raw(args as _)) + } } pub fn args() -> Args { - Args + let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() }; + if let Some(args) = args { + Args(args.iter()) + } else { + Args([].iter()) + } } -pub struct Args; +pub struct Args(slice::Iter<'static, OsString>); impl Args { pub fn inner_debug(&self) -> &[OsString] { - &[] + self.0.as_slice() } } impl Iterator for Args { type Item = OsString; fn next(&mut self) -> Option { - None + self.0.next().cloned() } fn size_hint(&self) -> (usize, Option) { - (0, Some(0)) + self.0.size_hint() } } impl ExactSizeIterator for Args { fn len(&self) -> usize { - 0 + self.0.len() } } impl DoubleEndedIterator for Args { fn next_back(&mut self) -> Option { - None + self.0.next_back().cloned() } } diff --git a/src/libstd/sys/sgx/os.rs b/src/libstd/sys/sgx/os.rs index cb25338ed46..79ebafe73f9 100644 --- a/src/libstd/sys/sgx/os.rs +++ b/src/libstd/sys/sgx/os.rs @@ -17,6 +17,11 @@ use io; use path::{self, PathBuf}; use str; use sys::{unsupported, Void, sgx_ineffective, decode_error_kind}; +use collections::HashMap; +use vec; +use sync::Mutex; +use sync::atomic::{AtomicUsize, Ordering}; +use sync::Once; pub fn errno() -> i32 { RESULT_SUCCESS @@ -78,29 +83,51 @@ pub fn current_exe() -> io::Result { unsupported() } -pub struct Env; +static ENV: AtomicUsize = AtomicUsize::new(0); +static ENV_INIT: Once = Once::new(); +type EnvStore = Mutex>; -impl Iterator for Env { - type Item = (OsString, OsString); - fn next(&mut self) -> Option<(OsString, OsString)> { - None +fn get_env_store() -> Option<&'static EnvStore> { + unsafe { (ENV.load(Ordering::Relaxed) as *const EnvStore).as_ref() } +} + +fn create_env_store() -> &'static EnvStore { + ENV_INIT.call_once(|| { + ENV.store(Box::into_raw(Box::new(EnvStore::default())) as _, Ordering::Relaxed) + }); + unsafe { + &*(ENV.load(Ordering::Relaxed) as *const EnvStore) } } +pub type Env = vec::IntoIter<(OsString, OsString)>; + pub fn env() -> Env { - Env + let clone_to_vec = |map: &HashMap| -> Vec<_> { + map.iter().map(|(k, v)| (k.clone(), v.clone()) ).collect() + }; + + get_env_store() + .map(|env| clone_to_vec(&env.lock().unwrap()) ) + .unwrap_or_default() + .into_iter() } -pub fn getenv(_k: &OsStr) -> io::Result> { - Ok(None) +pub fn getenv(k: &OsStr) -> io::Result> { + Ok(get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned() )) } -pub fn setenv(_k: &OsStr, _v: &OsStr) -> io::Result<()> { - sgx_ineffective(()) // FIXME: this could trigger a panic higher up the stack +pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { + let (k, v) = (k.to_owned(), v.to_owned()); + create_env_store().lock().unwrap().insert(k, v); + Ok(()) } -pub fn unsetenv(_k: &OsStr) -> io::Result<()> { - sgx_ineffective(()) // FIXME: this could trigger a panic higher up the stack +pub fn unsetenv(k: &OsStr) -> io::Result<()> { + if let Some(env) = get_env_store() { + env.lock().unwrap().remove(k); + } + Ok(()) } pub fn temp_dir() -> PathBuf { -- cgit 1.4.1-3-g733a5 From ee89c088b057affb5bdb96195e107a218b64b1c5 Mon Sep 17 00:00:00 2001 From: Alexander Regueiro Date: Tue, 27 Nov 2018 02:59:49 +0000 Subject: Various minor/cosmetic improvements to code --- src/bootstrap/builder.rs | 6 +- src/bootstrap/dist.rs | 2 +- src/bootstrap/flags.rs | 4 +- src/bootstrap/job.rs | 10 +- src/bootstrap/lib.rs | 2 +- src/bootstrap/native.rs | 2 +- src/bootstrap/test.rs | 4 +- src/bootstrap/tool.rs | 2 +- src/liballoc/boxed.rs | 2 +- src/liballoc/collections/binary_heap.rs | 2 +- src/liballoc/collections/btree/set.rs | 12 +- src/liballoc/raw_vec.rs | 2 +- src/liballoc/rc.rs | 4 +- src/liballoc/slice.rs | 10 +- src/liballoc/sync.rs | 2 +- src/liballoc/tests/slice.rs | 6 +- src/liballoc/tests/str.rs | 2 +- src/liballoc/vec.rs | 2 +- src/libcore/alloc.rs | 24 +- src/libcore/any.rs | 2 +- src/libcore/cell.rs | 4 +- src/libcore/char/mod.rs | 2 +- src/libcore/clone.rs | 10 +- src/libcore/ffi.rs | 2 +- src/libcore/hash/mod.rs | 2 +- src/libcore/hint.rs | 2 +- src/libcore/intrinsics.rs | 4 +- src/libcore/iter/iterator.rs | 2 +- src/libcore/iter/traits.rs | 2 +- src/libcore/marker.rs | 8 +- src/libcore/mem.rs | 4 +- src/libcore/num/bignum.rs | 2 +- src/libcore/num/dec2flt/algorithm.rs | 6 +- src/libcore/num/dec2flt/rawfp.rs | 2 +- src/libcore/num/flt2dec/mod.rs | 6 +- src/libcore/num/flt2dec/strategy/dragon.rs | 8 +- src/libcore/num/flt2dec/strategy/grisu.rs | 14 +- src/libcore/num/mod.rs | 8 +- src/libcore/num/wrapping.rs | 2 +- src/libcore/ops/function.rs | 6 +- src/libcore/ops/mod.rs | 2 +- src/libcore/option.rs | 2 +- src/libcore/pin.rs | 2 +- src/libcore/ptr.rs | 38 +-- src/libcore/raw.rs | 2 +- src/libcore/slice/mod.rs | 27 +- src/libcore/str/mod.rs | 2 +- src/libcore/str/pattern.rs | 4 +- src/libcore/task/wake.rs | 8 +- src/libcore/tests/num/dec2flt/mod.rs | 2 +- src/libcore/tests/num/flt2dec/random.rs | 2 +- src/libcore/time.rs | 6 +- src/libgraphviz/lib.rs | 8 +- src/libpanic_unwind/dwarf/mod.rs | 2 +- src/libpanic_unwind/gcc.rs | 4 +- src/libpanic_unwind/seh.rs | 4 +- src/libproc_macro/bridge/client.rs | 6 +- src/libproc_macro/bridge/mod.rs | 2 +- src/libproc_macro/bridge/scoped_cell.rs | 2 +- src/libproc_macro/bridge/server.rs | 2 +- src/libproc_macro/lib.rs | 20 +- src/librustc/cfg/construct.rs | 2 +- src/librustc/dep_graph/dep_node.rs | 6 +- src/librustc/diagnostics.rs | 16 +- src/librustc/hir/def.rs | 18 +- src/librustc/hir/intravisit.rs | 12 +- src/librustc/hir/lowering.rs | 149 ++++---- src/librustc/hir/map/blocks.rs | 4 +- src/librustc/hir/map/definitions.rs | 5 +- src/librustc/hir/map/mod.rs | 34 +- src/librustc/hir/mod.rs | 86 ++--- src/librustc/hir/pat_util.rs | 4 +- src/librustc/hir/print.rs | 4 +- src/librustc/ich/hcx.rs | 2 +- src/librustc/infer/combine.rs | 2 +- src/librustc/infer/equate.rs | 4 +- .../nice_region_error/find_anon_type.rs | 4 +- src/librustc/infer/higher_ranked/mod.rs | 2 +- src/librustc/infer/mod.rs | 12 +- src/librustc/infer/nll_relate/mod.rs | 6 +- src/librustc/infer/opaque_types/mod.rs | 4 +- src/librustc/infer/outlives/obligations.rs | 2 +- src/librustc/infer/region_constraints/mod.rs | 4 +- src/librustc/infer/type_variable.rs | 2 +- src/librustc/lib.rs | 2 +- src/librustc/lint/builtin.rs | 4 +- src/librustc/lint/context.rs | 2 +- src/librustc/lint/levels.rs | 4 +- src/librustc/lint/mod.rs | 6 +- src/librustc/middle/cstore.rs | 2 +- src/librustc/middle/dead.rs | 2 +- src/librustc/middle/dependency_format.rs | 4 +- src/librustc/middle/entry.rs | 4 +- src/librustc/middle/expr_use_visitor.rs | 4 +- src/librustc/middle/lang_items.rs | 4 +- src/librustc/middle/lib_features.rs | 6 +- src/librustc/middle/liveness.rs | 2 +- src/librustc/middle/mem_categorization.rs | 8 +- src/librustc/middle/region.rs | 18 +- src/librustc/middle/resolve_lifetime.rs | 10 +- src/librustc/middle/stability.rs | 28 +- src/librustc/mir/interpret/error.rs | 2 +- src/librustc/mir/mod.rs | 16 +- src/librustc/mir/mono.rs | 2 +- src/librustc/mir/traversal.rs | 2 +- src/librustc/mir/visit.rs | 6 +- src/librustc/session/config.rs | 6 +- src/librustc/session/filesearch.rs | 2 +- src/librustc/session/mod.rs | 2 +- src/librustc/traits/auto_trait.rs | 10 +- src/librustc/traits/coherence.rs | 10 +- src/librustc/traits/error_reporting.rs | 2 +- src/librustc/traits/mod.rs | 64 ++-- src/librustc/traits/object_safety.rs | 12 +- src/librustc/traits/project.rs | 8 +- src/librustc/traits/select.rs | 32 +- src/librustc/traits/specialize/mod.rs | 30 +- .../traits/specialize/specialization_graph.rs | 27 +- src/librustc/traits/util.rs | 5 +- src/librustc/ty/adjustment.rs | 2 +- src/librustc/ty/codec.rs | 2 +- src/librustc/ty/context.rs | 24 +- src/librustc/ty/erase_regions.rs | 2 +- src/librustc/ty/fast_reject.rs | 2 +- src/librustc/ty/fold.rs | 2 +- src/librustc/ty/item_path.rs | 2 +- src/librustc/ty/layout.rs | 14 +- src/librustc/ty/mod.rs | 36 +- src/librustc/ty/query/mod.rs | 18 +- src/librustc/ty/relate.rs | 9 +- src/librustc/ty/sty.rs | 30 +- src/librustc/ty/subst.rs | 4 +- src/librustc/ty/util.rs | 8 +- src/librustc/util/common.rs | 2 +- src/librustc_apfloat/ieee.rs | 4 +- src/librustc_apfloat/lib.rs | 8 +- src/librustc_apfloat/ppc.rs | 2 +- src/librustc_borrowck/borrowck/gather_loans/mod.rs | 2 +- src/librustc_borrowck/borrowck/mod.rs | 2 +- src/librustc_borrowck/dataflow.rs | 6 +- src/librustc_codegen_llvm/abi.rs | 2 +- src/librustc_codegen_llvm/attributes.rs | 4 +- src/librustc_codegen_llvm/back/link.rs | 8 +- src/librustc_codegen_llvm/back/write.rs | 2 +- src/librustc_codegen_llvm/common.rs | 2 +- src/librustc_codegen_llvm/consts.rs | 4 +- src/librustc_codegen_llvm/context.rs | 2 +- src/librustc_codegen_llvm/debuginfo/doc.rs | 2 +- src/librustc_codegen_llvm/debuginfo/metadata.rs | 2 +- src/librustc_codegen_llvm/debuginfo/mod.rs | 2 +- src/librustc_codegen_llvm/debuginfo/type_names.rs | 4 +- src/librustc_codegen_llvm/debuginfo/utils.rs | 2 +- src/librustc_codegen_llvm/intrinsic.rs | 4 +- src/librustc_codegen_llvm/llvm/mod.rs | 2 +- src/librustc_codegen_llvm/mono_item.rs | 2 +- src/librustc_codegen_llvm/type_.rs | 2 +- src/librustc_codegen_llvm/type_of.rs | 12 +- src/librustc_codegen_ssa/back/linker.rs | 2 +- src/librustc_codegen_ssa/back/symbol_export.rs | 2 +- src/librustc_codegen_ssa/base.rs | 2 +- src/librustc_codegen_ssa/common.rs | 2 +- src/librustc_codegen_ssa/lib.rs | 2 +- src/librustc_codegen_ssa/mir/analyze.rs | 6 +- src/librustc_codegen_ssa/mir/mod.rs | 4 +- src/librustc_codegen_ssa/mir/place.rs | 4 +- src/librustc_codegen_ssa/mir/rvalue.rs | 4 +- src/librustc_codegen_ssa/traits/declare.rs | 2 +- src/librustc_codegen_ssa/traits/type_.rs | 2 +- src/librustc_codegen_utils/symbol_names.rs | 2 +- .../obligation_forest/mod.rs | 2 +- src/librustc_data_structures/owning_ref/mod.rs | 10 +- src/librustc_data_structures/thin_vec.rs | 2 +- .../transitive_relation.rs | 2 +- src/librustc_driver/driver.rs | 56 +-- src/librustc_driver/pretty.rs | 25 +- src/librustc_driver/test.rs | 37 +- src/librustc_incremental/persist/dirty_clean.rs | 10 +- src/librustc_lint/builtin.rs | 2 +- src/librustc_lint/lib.rs | 29 +- src/librustc_lint/nonstandard_style.rs | 8 +- src/librustc_llvm/lib.rs | 2 +- src/librustc_metadata/cstore.rs | 2 +- src/librustc_metadata/cstore_impl.rs | 2 +- src/librustc_metadata/locator.rs | 2 +- src/librustc_metadata/schema.rs | 2 +- src/librustc_mir/borrow_check/error_reporting.rs | 2 +- src/librustc_mir/borrow_check/mod.rs | 8 +- src/librustc_mir/borrow_check/move_errors.rs | 4 +- .../borrow_check/nll/constraints/mod.rs | 2 +- .../nll/region_infer/error_reporting/var_name.rs | 2 +- .../borrow_check/nll/region_infer/mod.rs | 4 +- .../borrow_check/nll/region_infer/values.rs | 2 +- .../borrow_check/nll/type_check/input_output.rs | 4 +- .../nll/type_check/liveness/local_use_map.rs | 2 +- .../borrow_check/nll/type_check/mod.rs | 1 + src/librustc_mir/borrow_check/places_conflict.rs | 18 +- src/librustc_mir/borrow_check/prefixes.rs | 2 +- src/librustc_mir/build/block.rs | 2 +- src/librustc_mir/build/expr/as_rvalue.rs | 2 +- src/librustc_mir/build/expr/into.rs | 2 +- src/librustc_mir/build/expr/stmt.rs | 2 +- src/librustc_mir/build/into.rs | 2 +- src/librustc_mir/build/matches/mod.rs | 4 +- src/librustc_mir/build/misc.rs | 2 +- src/librustc_mir/build/scope.rs | 6 +- src/librustc_mir/dataflow/at_location.rs | 2 +- src/librustc_mir/dataflow/impls/borrows.rs | 2 +- src/librustc_mir/dataflow/impls/mod.rs | 2 +- src/librustc_mir/dataflow/mod.rs | 8 +- src/librustc_mir/dataflow/move_paths/abs_domain.rs | 2 +- src/librustc_mir/hair/cx/expr.rs | 4 +- src/librustc_mir/hair/pattern/_match.rs | 38 +-- src/librustc_mir/hair/pattern/check_match.rs | 4 +- src/librustc_mir/hair/pattern/mod.rs | 2 +- src/librustc_mir/interpret/machine.rs | 2 +- src/librustc_mir/interpret/memory.rs | 2 +- src/librustc_mir/interpret/place.rs | 6 +- src/librustc_mir/interpret/step.rs | 6 +- src/librustc_mir/interpret/terminator.rs | 2 +- src/librustc_mir/interpret/validity.rs | 4 +- src/librustc_mir/interpret/visitor.rs | 2 +- src/librustc_mir/lints.rs | 8 +- src/librustc_mir/monomorphize/collector.rs | 2 +- src/librustc_mir/monomorphize/partitioning.rs | 2 +- src/librustc_mir/transform/check_unsafety.rs | 2 +- src/librustc_mir/transform/const_prop.rs | 2 +- src/librustc_mir/transform/inline.rs | 4 +- src/librustc_mir/transform/promote_consts.rs | 2 +- src/librustc_mir/transform/qualify_consts.rs | 52 +-- .../transform/remove_noop_landing_pads.rs | 2 +- src/librustc_mir/util/elaborate_drops.rs | 4 +- src/librustc_mir/util/liveness.rs | 2 +- src/librustc_passes/ast_validation.rs | 4 +- src/librustc_passes/rvalue_promotion.rs | 2 +- src/librustc_plugin/load.rs | 2 +- src/librustc_privacy/lib.rs | 155 +++++---- src/librustc_resolve/lib.rs | 24 +- src/librustc_resolve/macros.rs | 4 +- src/librustc_resolve/resolve_imports.rs | 4 +- src/librustc_save_analysis/lib.rs | 2 +- src/librustc_target/abi/call/mod.rs | 4 +- src/librustc_target/abi/call/s390x.rs | 2 +- src/librustc_target/abi/call/x86_64.rs | 2 +- src/librustc_target/abi/mod.rs | 8 +- src/librustc_target/spec/abi.rs | 2 +- src/librustc_target/spec/mod.rs | 2 +- src/librustc_target/spec/thumb_base.rs | 2 +- src/librustc_traits/implied_outlives_bounds.rs | 2 +- src/librustc_traits/lowering/mod.rs | 12 +- src/librustc_typeck/astconv.rs | 74 ++-- src/librustc_typeck/check/_match.rs | 24 +- src/librustc_typeck/check/autoderef.rs | 2 +- src/librustc_typeck/check/callee.rs | 2 +- src/librustc_typeck/check/cast.rs | 2 +- src/librustc_typeck/check/closure.rs | 2 +- src/librustc_typeck/check/coercion.rs | 4 +- src/librustc_typeck/check/demand.rs | 2 +- src/librustc_typeck/check/dropck.rs | 4 +- src/librustc_typeck/check/intrinsic.rs | 2 +- src/librustc_typeck/check/method/confirm.rs | 2 +- src/librustc_typeck/check/method/mod.rs | 42 ++- src/librustc_typeck/check/method/probe.rs | 2 +- src/librustc_typeck/check/method/suggest.rs | 191 +++++------ src/librustc_typeck/check/mod.rs | 143 ++++---- src/librustc_typeck/check/op.rs | 10 +- src/librustc_typeck/coherence/builtin.rs | 4 +- src/librustc_typeck/coherence/mod.rs | 2 +- src/librustc_typeck/coherence/orphan.rs | 2 +- src/librustc_typeck/collect.rs | 12 +- src/librustc_typeck/constrained_type_params.rs | 2 +- src/librustc_typeck/diagnostics.rs | 6 +- src/librustc_typeck/lib.rs | 66 ++-- src/librustc_typeck/outlives/implicit_infer.rs | 2 +- src/librustc_typeck/variance/constraints.rs | 2 +- src/librustc_typeck/variance/terms.rs | 2 +- src/librustdoc/clean/auto_trait.rs | 14 +- src/librustdoc/clean/cfg.rs | 10 +- src/librustdoc/clean/mod.rs | 59 ++-- src/librustdoc/clean/simplify.rs | 2 +- src/librustdoc/html/layout.rs | 6 +- src/librustdoc/html/render.rs | 2 +- src/librustdoc/html/toc.rs | 12 +- src/librustdoc/lib.rs | 2 +- src/librustdoc/markdown.rs | 4 +- src/librustdoc/passes/collect_intra_doc_links.rs | 75 ++--- src/librustdoc/test.rs | 102 +++--- src/librustdoc/visit_ast.rs | 47 ++- src/librustdoc/visit_lib.rs | 2 +- src/libstd/collections/hash/set.rs | 12 +- src/libstd/error.rs | 4 +- src/libstd/f64.rs | 2 +- src/libstd/ffi/c_str.rs | 6 +- src/libstd/ffi/mod.rs | 4 +- src/libstd/ffi/os_str.rs | 2 +- src/libstd/fs.rs | 2 +- src/libstd/io/cursor.rs | 2 +- src/libstd/io/stdio.rs | 4 +- src/libstd/keyword_docs.rs | 2 +- src/libstd/net/addr.rs | 2 +- src/libstd/net/tcp.rs | 4 +- src/libstd/net/udp.rs | 2 +- src/libstd/panic.rs | 2 +- src/libstd/panicking.rs | 2 +- src/libstd/path.rs | 50 +-- src/libstd/primitive_docs.rs | 2 +- src/libstd/process.rs | 2 +- src/libstd/sync/mod.rs | 2 +- src/libstd/sync/mpsc/sync.rs | 2 +- src/libstd/sync/once.rs | 4 +- src/libstd/sys/unix/android.rs | 2 +- src/libstd/sys/unix/ext/net.rs | 2 +- src/libstd/sys/unix/net.rs | 2 +- src/libstd/sys/unix/process/zircon.rs | 2 +- src/libstd/sys/windows/ext/ffi.rs | 2 +- src/libstd/sys/windows/fs.rs | 2 +- src/libstd/sys/windows/os.rs | 2 +- src/libstd/sys/windows/pipe.rs | 10 +- src/libstd/sys_common/gnu/libbacktrace.rs | 2 +- src/libstd/thread/local.rs | 2 +- src/libstd/thread/mod.rs | 10 +- src/libstd/time.rs | 2 +- src/libsyntax/ast.rs | 375 ++++++++++----------- src/libsyntax/attr/mod.rs | 4 +- src/libsyntax/config.rs | 4 +- src/libsyntax/ext/base.rs | 6 +- src/libsyntax/ext/expand.rs | 2 +- src/libsyntax/ext/tt/macro_parser.rs | 8 +- src/libsyntax/ext/tt/macro_rules.rs | 12 +- src/libsyntax/ext/tt/quoted.rs | 12 +- src/libsyntax/feature_gate.rs | 288 ++++++++-------- src/libsyntax/fold.rs | 4 +- src/libsyntax/lib.rs | 2 +- src/libsyntax/parse/lexer/mod.rs | 2 +- src/libsyntax/parse/parser.rs | 24 +- src/libsyntax/parse/token.rs | 2 +- src/libsyntax/print/pp.rs | 2 +- src/libsyntax/ptr.rs | 6 +- src/libsyntax/test.rs | 2 +- src/libsyntax/util/parser.rs | 4 +- src/libsyntax/visit.rs | 4 +- src/libsyntax_ext/deriving/cmp/partial_ord.rs | 2 +- src/libsyntax_ext/deriving/generic/mod.rs | 18 +- src/libsyntax_ext/deriving/generic/ty.rs | 2 +- src/libsyntax_ext/format.rs | 2 +- src/libsyntax_ext/test.rs | 2 +- src/libsyntax_pos/hygiene.rs | 14 +- src/libsyntax_pos/lib.rs | 162 ++++----- src/libsyntax_pos/symbol.rs | 45 +-- src/libterm/lib.rs | 2 +- src/libterm/terminfo/searcher.rs | 4 +- src/libtest/formatters/terse.rs | 2 +- src/libtest/lib.rs | 8 +- src/libtest/stats.rs | 2 +- src/rtstartup/rsbegin.rs | 2 +- .../unreferenced-inline-function.rs | 2 +- src/test/codegen/external-no-mangle-fns.rs | 2 +- src/test/codegen/external-no-mangle-statics.rs | 2 +- src/test/debuginfo/type-names.rs | 2 +- src/test/incremental/hashes/panic_exprs.rs | 2 +- src/test/incremental/hashes/struct_defs.rs | 2 +- src/test/pretty/block-disambig.rs | 2 +- .../reproducible-build/reproducible-build.rs | 2 +- src/test/run-pass/coerce/coerce-unify.rs | 2 +- src/test/run-pass/coerce/coerce-unsize-subtype.rs | 4 +- src/test/run-pass/core-run-destroy.rs | 2 +- src/test/run-pass/drop/dropck-eyepatch.rs | 2 +- src/test/run-pass/drop/dropck_legal_cycles.rs | 2 +- .../loop-no-reinit-needed-post-bot.rs | 2 +- src/test/run-pass/impl-trait/example-calendar.rs | 61 +--- src/test/run-pass/issues/issue-23808.rs | 1 + .../run-pass/issues/issue-24805-dropck-itemless.rs | 2 +- src/test/run-pass/issues/issue-26996.rs | 2 +- src/test/run-pass/issues/issue-27021.rs | 2 +- src/test/run-pass/issues/issue-3563-3.rs | 2 +- src/test/run-pass/issues/issue-49298.rs | 2 +- src/test/run-pass/issues/issue-49955-2.rs | 2 +- ...crlf-line-endings-string-literal-doc-comment.rs | 2 +- ...mel-case-types-non-uppercase-statics-unicode.rs | 2 +- src/test/run-pass/macros/macro-comma-behavior.rs | 2 +- .../packed/packed-struct-optimized-enum.rs | 4 +- .../regions/regions-early-bound-trait-param.rs | 2 +- .../run-pass/simd/simd-intrinsic-generic-cast.rs | 4 +- src/test/run-pass/try-operator-hygiene.rs | 2 +- src/test/run-pass/uniform-paths/basic-nested.rs | 2 +- src/test/run-pass/uniform-paths/macros-nested.rs | 2 +- .../associated-const-no-item.stderr | 6 +- src/test/ui/bogus-tag.stderr | 4 +- src/test/ui/borrowck/two-phase-nonrecv-autoref.rs | 2 +- src/test/ui/coherence/coherence-all-remote.stderr | 2 +- .../ui/coherence/coherence-bigint-param.stderr | 2 +- src/test/ui/coherence/coherence-cow.a.stderr | 2 +- src/test/ui/coherence/coherence-cow.b.stderr | 2 +- src/test/ui/coherence/coherence-cow.c.stderr | 2 +- .../coherence-cross-crate-conflict.stderr | 2 +- .../coherence/coherence-lone-type-parameter.stderr | 2 +- .../coherence/coherence-overlapping-pairs.stderr | 2 +- .../coherence-pair-covered-uncovered-1.stderr | 2 +- .../coherence-pair-covered-uncovered.stderr | 2 +- src/test/ui/coherence/coherence-vec-local-2.stderr | 2 +- src/test/ui/constructor-lifetime-args.rs | 2 +- .../ui/consts/const-eval/const-eval-overflow2.rs | 2 +- .../ui/consts/const-eval/const-eval-overflow2b.rs | 2 +- .../ui/consts/const-eval/const-eval-overflow2c.rs | 2 +- .../dont_promote_unstable_const_fn.stderr | 2 +- src/test/ui/consts/const-pattern-irrefutable.rs | 2 +- src/test/ui/consts/const-typeid-of.stderr | 2 +- src/test/ui/did_you_mean/bad-assoc-pat.stderr | 24 +- .../ui/dont-suggest-private-trait-method.stderr | 6 +- src/test/ui/dropck/dropck-eyepatch.rs | 2 +- src/test/ui/e0119/complex-impl.stderr | 2 +- src/test/ui/e0119/issue-28981.stderr | 2 +- src/test/ui/empty/empty-struct-braces-expr.stderr | 16 +- src/test/ui/error-codes/E0599.stderr | 4 +- src/test/ui/imports/unused.rs | 2 +- src/test/ui/invalid/invalid-path-in-const.stderr | 6 +- src/test/ui/issues/issue-20261.rs | 2 +- src/test/ui/issues/issue-22933-2.stderr | 6 +- src/test/ui/issues/issue-22933-3.stderr | 6 +- src/test/ui/issues/issue-23173.stderr | 24 +- src/test/ui/issues/issue-23217.stderr | 8 +- src/test/ui/issues/issue-27842.stderr | 2 +- src/test/ui/issues/issue-28344.stderr | 12 +- src/test/ui/issues/issue-28586.stderr | 6 +- src/test/ui/issues/issue-28971.stderr | 6 +- src/test/ui/issues/issue-30123.stderr | 6 +- src/test/ui/issues/issue-36744-without-calls.rs | 2 +- src/test/ui/issues/issue-38919.stderr | 6 +- src/test/ui/issues/issue-39559.stderr | 6 +- src/test/ui/issues/issue-3973.stderr | 6 +- src/test/ui/issues/issue-40861.stderr | 2 +- src/test/ui/issues/issue-41974.stderr | 2 +- src/test/ui/issues/issue-42880.stderr | 4 +- src/test/ui/issues/issue-52060.stderr | 2 +- src/test/ui/issues/issue-7950.stderr | 6 +- src/test/ui/lexical-scopes.stderr | 6 +- src/test/ui/lint/lint-unused-imports.rs | 2 +- src/test/ui/namespace/namespace-mix.rs | 2 +- .../ui/nll/issue-21232-partial-init-and-use.rs | 2 +- src/test/ui/no-implicit-prelude-nested.rs | 2 +- src/test/ui/no-implicit-prelude.rs | 2 +- src/test/ui/orphan-check-diagnostics.stderr | 2 +- src/test/ui/parser/assoc-oddities-1.rs | 2 +- src/test/ui/print_type_sizes/generics.rs | 2 +- .../regions-free-region-ordering-incorrect.rs | 18 +- .../regions-free-region-ordering-incorrect.stderr | 32 +- src/test/ui/resolve/issue-5035.rs | 2 +- .../no-double-error.stderr | 6 +- src/test/ui/rfc-2126-extern-absolute-paths/meta.rs | 2 +- .../ui/rust-2018/trait-import-suggestions.stderr | 6 +- .../simd-intrinsic-single-nominal-type.rs | 2 +- .../ui/span/issue-24805-dropck-trait-has-items.rs | 2 +- src/test/ui/traits/trait-item-privacy.stderr | 24 +- src/test/ui/type/type-alias-bounds.rs | 2 +- src/test/ui/ufcs/ufcs-partially-resolved.stderr | 12 +- src/test/ui/unspecified-self-in-trait-ref.stderr | 24 +- src/tools/compiletest/src/errors.rs | 2 +- src/tools/compiletest/src/header.rs | 2 +- 457 files changed, 2341 insertions(+), 2317 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/bootstrap/builder.rs b/src/bootstrap/builder.rs index 98005f93961..b3682850de7 100644 --- a/src/bootstrap/builder.rs +++ b/src/bootstrap/builder.rs @@ -793,7 +793,7 @@ impl<'a> Builder<'a> { } // Set a flag for `check` so that certain build scripts can do less work - // (e.g. not building/requiring LLVM). + // (e.g., not building/requiring LLVM). if cmd == "check" { cargo.env("RUST_CHECK", "1"); } @@ -923,12 +923,12 @@ impl<'a> Builder<'a> { cargo.env("RUSTC_FORCE_UNSTABLE", "1"); // Currently the compiler depends on crates from crates.io, and - // then other crates can depend on the compiler (e.g. proc-macro + // then other crates can depend on the compiler (e.g., proc-macro // crates). Let's say, for example that rustc itself depends on the // bitflags crate. If an external crate then depends on the // bitflags crate as well, we need to make sure they don't // conflict, even if they pick the same version of bitflags. We'll - // want to make sure that e.g. a plugin and rustc each get their + // want to make sure that e.g., a plugin and rustc each get their // own copy of bitflags. // Cargo ensures that this works in general through the -C metadata diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 6108692e43c..35348a34b0b 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -353,7 +353,7 @@ impl Step for Mingw { /// Build the `rust-mingw` installer component. /// /// This contains all the bits and pieces to run the MinGW Windows targets - /// without any extra installed software (e.g. we bundle gcc, libraries, etc). + /// without any extra installed software (e.g., we bundle gcc, libraries, etc). fn run(self, builder: &Builder) -> Option { let host = self.host; diff --git a/src/bootstrap/flags.rs b/src/bootstrap/flags.rs index 1211d485d1c..c49da8fc734 100644 --- a/src/bootstrap/flags.rs +++ b/src/bootstrap/flags.rs @@ -121,11 +121,11 @@ To learn more about a subcommand, run `./x.py -h`" opts.optopt("", "on-fail", "command to run on failure", "CMD"); opts.optflag("", "dry-run", "dry run; don't build anything"); opts.optopt("", "stage", - "stage to build (indicates compiler to use/test, e.g. stage 0 uses the \ + "stage to build (indicates compiler to use/test, e.g., stage 0 uses the \ bootstrap compiler, stage 1 the stage 0 rustc artifacts, etc.)", "N"); opts.optmulti("", "keep-stage", "stage(s) to keep without recompiling \ - (pass multiple times to keep e.g. both stages 0 and 1)", "N"); + (pass multiple times to keep e.g., both stages 0 and 1)", "N"); opts.optopt("", "src", "path to the root of the rust checkout", "DIR"); opts.optopt("j", "jobs", "number of jobs to run in parallel", "JOBS"); opts.optflag("h", "help", "print this help message"); diff --git a/src/bootstrap/job.rs b/src/bootstrap/job.rs index e6ee525ca2e..f7b1c50f0fd 100644 --- a/src/bootstrap/job.rs +++ b/src/bootstrap/job.rs @@ -10,7 +10,7 @@ //! Job management on Windows for bootstrapping //! -//! Most of the time when you're running a build system (e.g. make) you expect +//! Most of the time when you're running a build system (e.g., make) you expect //! Ctrl-C or abnormal termination to actually terminate the entire tree of //! process in play, not just the one at the top. This currently works "by //! default" on Unix platforms because Ctrl-C actually sends a signal to the @@ -162,11 +162,11 @@ pub unsafe fn setup(build: &mut Build) { return } - // If we've got a parent process (e.g. the python script that called us) + // If we've got a parent process (e.g., the python script that called us) // then move ownership of this job object up to them. That way if the python - // script is killed (e.g. via ctrl-c) then we'll all be torn down. + // script is killed (e.g., via ctrl-c) then we'll all be torn down. // - // If we don't have a parent (e.g. this was run directly) then we + // If we don't have a parent (e.g., this was run directly) then we // intentionally leak the job object handle. When our process exits // (normally or abnormally) it will close the handle implicitly, causing all // processes in the job to be cleaned up. @@ -184,7 +184,7 @@ pub unsafe fn setup(build: &mut Build) { // If this failed, well at least we tried! An example of DuplicateHandle // failing in the past has been when the wrong python2 package spawned this - // build system (e.g. the `python2` package in MSYS instead of + // build system (e.g., the `python2` package in MSYS instead of // `mingw-w64-x86_64-python2`. Not sure why it failed, but the "failure // mode" here is that we only clean everything up when the build system // dies, not when the python parent does, so not too bad. diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 2832f5bebdd..2bcccc7b95b 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -38,7 +38,7 @@ //! However, compiletest itself tries to avoid running tests when the artifacts //! that are involved (mainly the compiler) haven't changed. //! -//! When you execute `x.py build`, the steps which are executed are: +//! When you execute `x.py build`, the steps executed are: //! //! * First, the python script is run. This will automatically download the //! stage0 rustc and cargo according to `src/stage0.txt`, or use the cached diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index 448967ef0c2..27ed61d49fe 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -251,7 +251,7 @@ impl Step for Llvm { configure_cmake(builder, target, &mut cfg, false); // FIXME: we don't actually need to build all LLVM tools and all LLVM - // libraries here, e.g. we just want a few components and a few + // libraries here, e.g., we just want a few components and a few // tools. Figure out how to filter them down and only build the right // tools and libs on all platforms. diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index da827356800..eaffc9df1f0 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -971,7 +971,7 @@ impl Step for Compiletest { } if builder.no_std(target) == Some(true) { - // for no_std run-make (e.g. thumb*), + // for no_std run-make (e.g., thumb*), // we need a host compiler which is called by cargo. builder.ensure(compile::Std { compiler, target: compiler.host }); } @@ -1277,7 +1277,7 @@ impl Step for DocTest { /// Run `rustdoc --test` for all documentation in `src/doc`. /// - /// This will run all tests in our markdown documentation (e.g. the book) + /// This will run all tests in our markdown documentation (e.g., the book) /// located in `src/doc`. The `rustdoc` that's run is the one that sits next to /// `compiler`. fn run(self, builder: &Builder) { diff --git a/src/bootstrap/tool.rs b/src/bootstrap/tool.rs index 58c5296beb3..1bd4403a66f 100644 --- a/src/bootstrap/tool.rs +++ b/src/bootstrap/tool.rs @@ -646,7 +646,7 @@ impl<'a> Builder<'a> { self.cargo_out(compiler, tool.get_mode(), *host).join("deps"), ]; - // On MSVC a tool may invoke a C compiler (e.g. compiletest in run-make + // On MSVC a tool may invoke a C compiler (e.g., compiletest in run-make // mode) and that C compiler may need some extra PATH modification. Do // so here. if compiler.host.contains("msvc") { diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index c3a84bf778d..83adcce5c74 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -801,7 +801,7 @@ impl AsMut for Box { * safe.) * - It is in practice very useful to have Box be unconditionally * Unpin because of trait objects, for which the structural auto - * trait functionality does not apply (e.g. Box would + * trait functionality does not apply (e.g., Box would * otherwise not be Unpin). * * Another type with the same semantics as Box but only a conditional diff --git a/src/liballoc/collections/binary_heap.rs b/src/liballoc/collections/binary_heap.rs index 8c36962a299..5dd0ea7d431 100644 --- a/src/liballoc/collections/binary_heap.rs +++ b/src/liballoc/collections/binary_heap.rs @@ -858,7 +858,7 @@ impl BinaryHeap { } } -/// Hole represents a hole in a slice i.e. an index without valid value +/// Hole represents a hole in a slice i.e., an index without valid value /// (because it was moved from or duplicated). /// In drop, `Hole` will restore the slice by filling the hole /// position with the value that was originally removed. diff --git a/src/liballoc/collections/btree/set.rs b/src/liballoc/collections/btree/set.rs index af9a7074e4a..fa74dce2f1f 100644 --- a/src/liballoc/collections/btree/set.rs +++ b/src/liballoc/collections/btree/set.rs @@ -258,7 +258,7 @@ impl BTreeSet { } /// Visits the values representing the difference, - /// i.e. the values that are in `self` but not in `other`, + /// i.e., the values that are in `self` but not in `other`, /// in ascending order. /// /// # Examples @@ -286,7 +286,7 @@ impl BTreeSet { } /// Visits the values representing the symmetric difference, - /// i.e. the values that are in `self` or in `other` but not in both, + /// i.e., the values that are in `self` or in `other` but not in both, /// in ascending order. /// /// # Examples @@ -316,7 +316,7 @@ impl BTreeSet { } /// Visits the values representing the intersection, - /// i.e. the values that are both in `self` and `other`, + /// i.e., the values that are both in `self` and `other`, /// in ascending order. /// /// # Examples @@ -344,7 +344,7 @@ impl BTreeSet { } /// Visits the values representing the union, - /// i.e. all the values in `self` or `other`, without duplicates, + /// i.e., all the values in `self` or `other`, without duplicates, /// in ascending order. /// /// # Examples @@ -455,7 +455,7 @@ impl BTreeSet { } /// Returns `true` if the set is a subset of another, - /// i.e. `other` contains at least all the values in `self`. + /// i.e., `other` contains at least all the values in `self`. /// /// # Examples /// @@ -498,7 +498,7 @@ impl BTreeSet { } /// Returns `true` if the set is a superset of another, - /// i.e. `self` contains at least all the values in `other`. + /// i.e., `self` contains at least all the values in `other`. /// /// # Examples /// diff --git a/src/liballoc/raw_vec.rs b/src/liballoc/raw_vec.rs index e87bf78561c..f4674b32769 100644 --- a/src/liballoc/raw_vec.rs +++ b/src/liballoc/raw_vec.rs @@ -739,7 +739,7 @@ unsafe impl<#[may_dangle] T, A: Alloc> Drop for RawVec { // On 64-bit we just need to check for overflow since trying to allocate // `> isize::MAX` bytes will surely fail. On 32-bit and 16-bit we need to add // an extra guard for this in case we're running on a platform which can use -// all 4GB in user-space. e.g. PAE or x32 +// all 4GB in user-space. e.g., PAE or x32 #[inline] fn alloc_guard(alloc_size: usize) -> Result<(), CollectionAllocErr> { diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index c0a947e7011..52ad30c411a 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -276,7 +276,7 @@ struct RcBox { /// See the [module-level documentation](./index.html) for more details. /// /// The inherent methods of `Rc` are all associated functions, which means -/// that you have to call them as e.g. [`Rc::get_mut(&mut value)`][get_mut] instead of +/// that you have to call them as e.g., [`Rc::get_mut(&mut value)`][get_mut] instead of /// `value.get_mut()`. This avoids conflicts with methods of the inner /// type `T`. /// @@ -1252,7 +1252,7 @@ impl Weak { } /// Return `None` when the pointer is dangling and there is no allocated `RcBox`, - /// i.e. this `Weak` was created by `Weak::new` + /// i.e., this `Weak` was created by `Weak::new` #[inline] fn inner(&self) -> Option<&RcBox> { if is_dangling(self.ptr) { diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 22da9dd6e96..a8e9a2f5a39 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -177,7 +177,7 @@ mod hack { impl [T] { /// Sorts the slice. /// - /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case. + /// This sort is stable (i.e., does not reorder equal elements) and `O(n log n)` worst-case. /// /// When applicable, unstable sorting is preferred because it is generally faster than stable /// sorting and it doesn't allocate auxiliary memory. @@ -211,7 +211,7 @@ impl [T] { /// Sorts the slice with a comparator function. /// - /// This sort is stable (i.e. does not reorder equal elements) and `O(n log n)` worst-case. + /// This sort is stable (i.e., does not reorder equal elements) and `O(n log n)` worst-case. /// /// The comparator function must define a total ordering for the elements in the slice. If /// the ordering is not total, the order of the elements is unspecified. An order is a @@ -264,7 +264,7 @@ impl [T] { /// Sorts the slice with a key extraction function. /// - /// This sort is stable (i.e. does not reorder equal elements) and `O(m n log(m n))` + /// This sort is stable (i.e., does not reorder equal elements) and `O(m n log(m n))` /// worst-case, where the key function is `O(m)`. /// /// When applicable, unstable sorting is preferred because it is generally faster than stable @@ -301,10 +301,10 @@ impl [T] { /// /// During sorting, the key function is called only once per element. /// - /// This sort is stable (i.e. does not reorder equal elements) and `O(m n + n log n)` + /// This sort is stable (i.e., does not reorder equal elements) and `O(m n + n log n)` /// worst-case, where the key function is `O(m)`. /// - /// For simple key functions (e.g. functions that are property accesses or + /// For simple key functions (e.g., functions that are property accesses or /// basic operations), [`sort_by_key`](#method.sort_by_key) is likely to be /// faster. /// diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index 0a397f79103..111459d12a4 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -1121,7 +1121,7 @@ impl Weak { } /// Return `None` when the pointer is dangling and there is no allocated `ArcInner`, - /// i.e. this `Weak` was created by `Weak::new` + /// i.e., this `Weak` was created by `Weak::new` #[inline] fn inner(&self) -> Option<&ArcInner> { if is_dangling(self.ptr) { diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index a50f99b0022..787e4952882 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -484,7 +484,7 @@ fn test_sort_stability() { // create a vector like [(6, 1), (5, 1), (6, 2), ...], // where the first item of each tuple is random, but // the second item represents which occurrence of that - // number this element is, i.e. the second elements + // number this element is, i.e., the second elements // will occur in sorted order. let mut orig: Vec<_> = (0..len) .map(|_| { @@ -502,7 +502,7 @@ fn test_sort_stability() { // This comparison includes the count (the second item // of the tuple), so elements with equal first items // will need to be ordered with increasing - // counts... i.e. exactly asserting that this sort is + // counts... i.e., exactly asserting that this sort is // stable. assert!(v.windows(2).all(|w| w[0] <= w[1])); @@ -1579,7 +1579,7 @@ macro_rules! test { }).join(); // Check that the number of things dropped is exactly - // what we expect (i.e. the contents of `v`). + // what we expect (i.e., the contents of `v`). for (i, c) in DROP_COUNTS.iter().enumerate().take(len) { let count = c.load(Relaxed); assert!(count == 1, diff --git a/src/liballoc/tests/str.rs b/src/liballoc/tests/str.rs index 494b36f8541..683ce2bf112 100644 --- a/src/liballoc/tests/str.rs +++ b/src/liballoc/tests/str.rs @@ -1005,7 +1005,7 @@ fn test_escape_debug() { // Note that there are subtleties with the number of backslashes // on the left- and right-hand sides. In particular, Unicode code points // are usually escaped with two backslashes on the right-hand side, as - // they are escaped. However, when the character is unescaped (e.g. for + // they are escaped. However, when the character is unescaped (e.g., for // printable characters), only a single backslash appears (as the character // itself appears in the debug string). assert_eq!("abc".escape_debug(), "abc"); diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs index ca7c766e413..63af69dda1d 100644 --- a/src/liballoc/vec.rs +++ b/src/liballoc/vec.rs @@ -213,7 +213,7 @@ use raw_vec::RawVec; /// about its design. This ensures that it's as low-overhead as possible in /// the general case, and can be correctly manipulated in primitive ways /// by unsafe code. Note that these guarantees refer to an unqualified `Vec`. -/// If additional type parameters are added (e.g. to support custom allocators), +/// If additional type parameters are added (e.g., to support custom allocators), /// overriding their defaults may change the behavior. /// /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length) diff --git a/src/libcore/alloc.rs b/src/libcore/alloc.rs index 58639808fae..8db7d33bdec 100644 --- a/src/libcore/alloc.rs +++ b/src/libcore/alloc.rs @@ -69,7 +69,7 @@ impl Layout { /// * `align` must be a power of two, /// /// * `size`, when rounded up to the nearest multiple of `align`, - /// must not overflow (i.e. the rounded value must be less than + /// must not overflow (i.e., the rounded value must be less than /// `usize::MAX`). #[stable(feature = "alloc_layout", since = "1.28.0")] #[inline] @@ -177,7 +177,7 @@ impl Layout { /// to ensure that the following address will satisfy `align` /// (measured in bytes). /// - /// E.g. if `self.size()` is 9, then `self.padding_needed_for(4)` + /// e.g., if `self.size()` is 9, then `self.padding_needed_for(4)` /// returns 3, because that is the minimum number of bytes of /// padding required to get a 4-aligned address (assuming that the /// corresponding memory block starts at a 4-aligned address). @@ -455,7 +455,7 @@ pub unsafe trait GlobalAlloc { /// if the caller does not ensure that `layout` has non-zero size. /// /// (Extension subtraits might provide more specific bounds on - /// behavior, e.g. guarantee a sentinel address or a null pointer + /// behavior, e.g., guarantee a sentinel address or a null pointer /// in response to a zero-size allocation request.) /// /// The allocated block of memory may or may not be initialized. @@ -550,10 +550,10 @@ pub unsafe trait GlobalAlloc { /// * `new_size` must be greater than zero. /// /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`, - /// must not overflow (i.e. the rounded value must be less than `usize::MAX`). + /// must not overflow (i.e., the rounded value must be less than `usize::MAX`). /// /// (Extension subtraits might provide more specific bounds on - /// behavior, e.g. guarantee a sentinel address or a null pointer + /// behavior, e.g., guarantee a sentinel address or a null pointer /// in response to a zero-size allocation request.) /// /// # Errors @@ -616,7 +616,7 @@ pub unsafe trait GlobalAlloc { /// whether to return `Err`, or to return `Ok` with some pointer. /// /// * If an `Alloc` implementation chooses to return `Ok` in this -/// case (i.e. the pointer denotes a zero-sized inaccessible block) +/// case (i.e., the pointer denotes a zero-sized inaccessible block) /// then that returned pointer must be considered "currently /// allocated". On such an allocator, *all* methods that take /// currently-allocated pointers as inputs must accept these @@ -651,7 +651,7 @@ pub unsafe trait GlobalAlloc { /// /// * if a layout `k` fits a memory block (denoted by `ptr`) /// currently allocated via an allocator `a`, then it is legal to -/// use that layout to deallocate it, i.e. `a.dealloc(ptr, k);`. +/// use that layout to deallocate it, i.e., `a.dealloc(ptr, k);`. /// /// # Unsafety /// @@ -673,7 +673,7 @@ pub unsafe trait Alloc { // (Note: some existing allocators have unspecified but well-defined // behavior in response to a zero size allocation request ; - // e.g. in C, `malloc` of 0 will either return a null pointer or a + // e.g., in C, `malloc` of 0 will either return a null pointer or a // unique pointer, but will not have arbitrary undefined // behavior. // However in jemalloc for example, @@ -688,7 +688,7 @@ pub unsafe trait Alloc { /// /// The returned block of storage may or may not have its contents /// initialized. (Extension subtraits might restrict this - /// behavior, e.g. to ensure initialization to particular sets of + /// behavior, e.g., to ensure initialization to particular sets of /// bit patterns.) /// /// # Safety @@ -697,7 +697,7 @@ pub unsafe trait Alloc { /// if the caller does not ensure that `layout` has non-zero size. /// /// (Extension subtraits might provide more specific bounds on - /// behavior, e.g. guarantee a sentinel address or a null pointer + /// behavior, e.g., guarantee a sentinel address or a null pointer /// in response to a zero-size allocation request.) /// /// # Errors @@ -803,10 +803,10 @@ pub unsafe trait Alloc { /// * `new_size` must be greater than zero. /// /// * `new_size`, when rounded up to the nearest multiple of `layout.align()`, - /// must not overflow (i.e. the rounded value must be less than `usize::MAX`). + /// must not overflow (i.e., the rounded value must be less than `usize::MAX`). /// /// (Extension subtraits might provide more specific bounds on - /// behavior, e.g. guarantee a sentinel address or a null pointer + /// behavior, e.g., guarantee a sentinel address or a null pointer /// in response to a zero-size allocation request.) /// /// # Errors diff --git a/src/libcore/any.rs b/src/libcore/any.rs index c2113dfd2a0..f521ab994cd 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -126,7 +126,7 @@ impl fmt::Debug for dyn Any { } } -// Ensure that the result of e.g. joining a thread can be printed and +// Ensure that the result of e.g., joining a thread can be printed and // hence used with `unwrap`. May eventually no longer be needed if // dispatch works with upcasting. #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index d8d51f53377..0a16c92928d 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -97,7 +97,7 @@ //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that there is mutation happening -//! "under the hood". This may be because logically the operation is immutable, but e.g. caching +//! "under the hood". This may be because logically the operation is immutable, but e.g., caching //! forces the implementation to perform mutation; or because you must employ mutation to implement //! a trait method that was originally defined to take `&self`. //! @@ -1227,7 +1227,7 @@ impl fmt::Display for Ref<'_, T> { } impl<'b, T: ?Sized> RefMut<'b, T> { - /// Make a new `RefMut` for a component of the borrowed data, e.g. an enum + /// Make a new `RefMut` for a component of the borrowed data, e.g., an enum /// variant. /// /// The `RefCell` is already mutably borrowed, so this cannot fail. diff --git a/src/libcore/char/mod.rs b/src/libcore/char/mod.rs index 7e1313747ee..e07a0f5d712 100644 --- a/src/libcore/char/mod.rs +++ b/src/libcore/char/mod.rs @@ -131,7 +131,7 @@ pub struct EscapeUnicode { state: EscapeUnicodeState, // The index of the next hex digit to be printed (0 if none), - // i.e. the number of remaining hex digits to be printed; + // i.e., the number of remaining hex digits to be printed; // increasing from the least significant digit: 0x543210 hex_digit_idx: usize, } diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 46bb580dcdd..225ea3de9cd 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -13,7 +13,7 @@ //! In Rust, some simple types are "implicitly copyable" and when you //! assign them or pass them as arguments, the receiver will get a copy, //! leaving the original value in place. These types do not require -//! allocation to copy and do not have finalizers (i.e. they do not +//! allocation to copy and do not have finalizers (i.e., they do not //! contain owned boxes or implement [`Drop`]), so the compiler considers //! them cheap and safe to copy. For other types copies must be made //! explicitly, by convention implementing the [`Clone`] trait and calling @@ -93,10 +93,10 @@ /// In addition to the [implementors listed below][impls], /// the following types also implement `Clone`: /// -/// * Function item types (i.e. the distinct types defined for each function) -/// * Function pointer types (e.g. `fn() -> i32`) -/// * Array types, for all sizes, if the item type also implements `Clone` (e.g. `[i32; 123456]`) -/// * Tuple types, if each component also implements `Clone` (e.g. `()`, `(i32, bool)`) +/// * Function item types (i.e., the distinct types defined for each function) +/// * Function pointer types (e.g., `fn() -> i32`) +/// * Array types, for all sizes, if the item type also implements `Clone` (e.g., `[i32; 123456]`) +/// * Tuple types, if each component also implements `Clone` (e.g., `()`, `(i32, bool)`) /// * Closure types, if they capture no value from the environment /// or if all such captured values implement `Clone` themselves. /// Note that variables captured by shared reference always implement `Clone` diff --git a/src/libcore/ffi.rs b/src/libcore/ffi.rs index edeb3b0d368..1dbf03923e1 100644 --- a/src/libcore/ffi.rs +++ b/src/libcore/ffi.rs @@ -18,7 +18,7 @@ use ::fmt; /// /// [`!`]: ../../std/primitive.never.html /// [pointer]: ../../std/primitive.pointer.html -// NB: For LLVM to recognize the void pointer type and by extension +// N.B., for LLVM to recognize the void pointer type and by extension // functions like malloc(), we need to have it represented as i8* in // LLVM bitcode. The enum used here ensures this and prevents misuse // of the "raw" type by only having private variants.. We need two diff --git a/src/libcore/hash/mod.rs b/src/libcore/hash/mod.rs index bbebadd452a..3e59ee1f8e5 100644 --- a/src/libcore/hash/mod.rs +++ b/src/libcore/hash/mod.rs @@ -408,7 +408,7 @@ impl Hasher for &mut H { /// A trait for creating instances of [`Hasher`]. /// -/// A `BuildHasher` is typically used (e.g. by [`HashMap`]) to create +/// A `BuildHasher` is typically used (e.g., by [`HashMap`]) to create /// [`Hasher`]s for each key such that they are hashed independently of one /// another, since [`Hasher`]s contain state. /// diff --git a/src/libcore/hint.rs b/src/libcore/hint.rs index f4e96e67b2c..0bfdd937abd 100644 --- a/src/libcore/hint.rs +++ b/src/libcore/hint.rs @@ -24,7 +24,7 @@ use intrinsics; /// therefore will eliminate all branches that reach to a call to /// `unreachable_unchecked()`. /// -/// Like all instances of UB, if this assumption turns out to be wrong, i.e. the +/// Like all instances of UB, if this assumption turns out to be wrong, i.e., the /// `unreachable_unchecked()` call is actually reachable among all possible /// control flow, the compiler will apply the wrong optimization strategy, and /// may sometimes even corrupt seemingly unrelated code, causing diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index 16f0299c18b..eebb98b5e6d 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -52,7 +52,7 @@ pub use ptr::drop_in_place; extern "rust-intrinsic" { - // NB: These intrinsics take raw pointers because they mutate aliased + // N.B., these intrinsics take raw pointers because they mutate aliased // memory, which is not valid for either `&` or `&mut`. /// Stores a value if the current value is the same as the `old` value. @@ -635,7 +635,7 @@ extern "rust-intrinsic" { /// Tells LLVM that this point in the code is not reachable, enabling /// further optimizations. /// - /// NB: This is very different from the `unreachable!()` macro: Unlike the + /// N.B., this is very different from the `unreachable!()` macro: Unlike the /// macro, which panics when it is executed, it is *undefined behavior* to /// reach code marked with this function. /// diff --git a/src/libcore/iter/iterator.rs b/src/libcore/iter/iterator.rs index 3063cb1a7df..92a4aed4e27 100644 --- a/src/libcore/iter/iterator.rs +++ b/src/libcore/iter/iterator.rs @@ -154,7 +154,7 @@ pub trait Iterator { /// /// `size_hint()` is primarily intended to be used for optimizations such as /// reserving space for the elements of the iterator, but must not be - /// trusted to e.g. omit bounds checks in unsafe code. An incorrect + /// trusted to e.g., omit bounds checks in unsafe code. An incorrect /// implementation of `size_hint()` should not lead to memory safety /// violations. /// diff --git a/src/libcore/iter/traits.rs b/src/libcore/iter/traits.rs index d2c5a3bed28..45e5b614db3 100644 --- a/src/libcore/iter/traits.rs +++ b/src/libcore/iter/traits.rs @@ -770,7 +770,7 @@ pub trait Product: Sized { fn product>(iter: I) -> Self; } -// NB: explicitly use Add and Mul here to inherit overflow checks +// N.B., explicitly use Add and Mul here to inherit overflow checks macro_rules! integer_sum_product { (@impls $zero:expr, $one:expr, #[$attr:meta], $($a:ty)*) => ($( #[$attr] diff --git a/src/libcore/marker.rs b/src/libcore/marker.rs index 23f07773f3f..0d43f927115 100644 --- a/src/libcore/marker.rs +++ b/src/libcore/marker.rs @@ -274,10 +274,10 @@ pub trait Unsize { /// In addition to the [implementors listed below][impls], /// the following types also implement `Copy`: /// -/// * Function item types (i.e. the distinct types defined for each function) -/// * Function pointer types (e.g. `fn() -> i32`) -/// * Array types, for all sizes, if the item type also implements `Copy` (e.g. `[i32; 123456]`) -/// * Tuple types, if each component also implements `Copy` (e.g. `()`, `(i32, bool)`) +/// * Function item types (i.e., the distinct types defined for each function) +/// * Function pointer types (e.g., `fn() -> i32`) +/// * Array types, for all sizes, if the item type also implements `Copy` (e.g., `[i32; 123456]`) +/// * Tuple types, if each component also implements `Copy` (e.g., `()`, `(i32, bool)`) /// * Closure types, if they capture no value from the environment /// or if all such captured values implement `Copy` themselves. /// Note that variables captured by shared reference always implement `Copy` diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index e4b2800ae21..06754f17a6f 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -305,7 +305,7 @@ pub const fn size_of() -> usize { /// Returns the size of the pointed-to value in bytes. /// /// This is usually the same as `size_of::()`. However, when `T` *has* no -/// statically known size, e.g. a slice [`[T]`][slice] or a [trait object], +/// statically known size, e.g., a slice [`[T]`][slice] or a [trait object], /// then `size_of_val` can be used to get the dynamically-known size. /// /// [slice]: ../../std/primitive.slice.html @@ -1119,7 +1119,7 @@ impl MaybeUninit { /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized /// state, otherwise this will immediately cause undefined behavior. // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references - // to uninitialized data (e.g. in `libcore/fmt/float.rs`). We should make + // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make // a final decision about the rules before stabilization. #[unstable(feature = "maybe_uninit", issue = "53491")] #[inline(always)] diff --git a/src/libcore/num/bignum.rs b/src/libcore/num/bignum.rs index 732a02e8c42..2bfb49c0682 100644 --- a/src/libcore/num/bignum.rs +++ b/src/libcore/num/bignum.rs @@ -183,7 +183,7 @@ macro_rules! define_bignum { let nonzero = &digits[..end]; if nonzero.is_empty() { - // There are no non-zero digits, i.e. the number is zero. + // There are no non-zero digits, i.e., the number is zero. return 0; } // This could be optimized with leading_zeros() and bit shifts, but that's diff --git a/src/libcore/num/dec2flt/algorithm.rs b/src/libcore/num/dec2flt/algorithm.rs index ccf3950c2ba..c3a983d0f0e 100644 --- a/src/libcore/num/dec2flt/algorithm.rs +++ b/src/libcore/num/dec2flt/algorithm.rs @@ -61,9 +61,9 @@ mod fpu_precision { /// /// The only field which is relevant for the following code is PC, Precision Control. This /// field determines the precision of the operations performed by the FPU. It can be set to: - /// - 0b00, single precision i.e. 32-bits - /// - 0b10, double precision i.e. 64-bits - /// - 0b11, double extended precision i.e. 80-bits (default state) + /// - 0b00, single precision i.e., 32-bits + /// - 0b10, double precision i.e., 64-bits + /// - 0b11, double extended precision i.e., 80-bits (default state) /// The 0b01 value is reserved and should not be used. pub struct FPUControlWord(u16); diff --git a/src/libcore/num/dec2flt/rawfp.rs b/src/libcore/num/dec2flt/rawfp.rs index 38f4e4687a9..18c30e29c79 100644 --- a/src/libcore/num/dec2flt/rawfp.rs +++ b/src/libcore/num/dec2flt/rawfp.rs @@ -349,7 +349,7 @@ pub fn prev_float(x: T) -> T { } // Find the smallest floating point number strictly larger than the argument. -// This operation is saturating, i.e. next_float(inf) == inf. +// This operation is saturating, i.e., next_float(inf) == inf. // Unlike most code in this module, this function does handle zero, subnormals, and infinities. // However, like all other code here, it does not deal with NaN and negative numbers. pub fn next_float(x: T) -> T { diff --git a/src/libcore/num/flt2dec/mod.rs b/src/libcore/num/flt2dec/mod.rs index d58015beecb..097240e58ae 100644 --- a/src/libcore/num/flt2dec/mod.rs +++ b/src/libcore/num/flt2dec/mod.rs @@ -23,7 +23,7 @@ representation `V = 0.d[0..n-1] * 10^k` such that: - `d[0]` is non-zero. - It's correctly rounded when parsed back: `v - minus < V < v + plus`. - Furthermore it is shortest such one, i.e. there is no representation + Furthermore it is shortest such one, i.e., there is no representation with less than `n` digits that is correctly rounded. - It's closest to the original value: `abs(V - v) <= 10^(k-n) / 2`. Note that @@ -398,7 +398,7 @@ fn determine_sign(sign: Sign, decoded: &FullDecoded, negative: bool) -> &'static /// given number of fractional digits. The result is stored to the supplied parts /// array while utilizing given byte buffer as a scratch. `upper` is currently /// unused but left for the future decision to change the case of non-finite values, -/// i.e. `inf` and `nan`. The first part to be rendered is always a `Part::Sign` +/// i.e., `inf` and `nan`. The first part to be rendered is always a `Part::Sign` /// (which can be an empty string if no sign is rendered). /// /// `format_shortest` should be the underlying digit-generation function. @@ -591,7 +591,7 @@ pub fn to_exact_exp_str<'a, T, F>(mut format_exact: F, v: T, /// given number of fractional digits. The result is stored to the supplied parts /// array while utilizing given byte buffer as a scratch. `upper` is currently /// unused but left for the future decision to change the case of non-finite values, -/// i.e. `inf` and `nan`. The first part to be rendered is always a `Part::Sign` +/// i.e., `inf` and `nan`. The first part to be rendered is always a `Part::Sign` /// (which can be an empty string if no sign is rendered). /// /// `format_exact` should be the underlying digit-generation function. diff --git a/src/libcore/num/flt2dec/strategy/dragon.rs b/src/libcore/num/flt2dec/strategy/dragon.rs index aa6a08cb205..cda0773afbd 100644 --- a/src/libcore/num/flt2dec/strategy/dragon.rs +++ b/src/libcore/num/flt2dec/strategy/dragon.rs @@ -81,11 +81,11 @@ pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp // - followed by `(mant + 2 * plus) * 2^exp` in the original type. // // obviously, `minus` and `plus` cannot be zero. (for infinities, we use out-of-range values.) - // also we assume that at least one digit is generated, i.e. `mant` cannot be zero too. + // also we assume that at least one digit is generated, i.e., `mant` cannot be zero too. // // this also means that any number between `low = (mant - minus) * 2^exp` and // `high = (mant + plus) * 2^exp` will map to this exact floating point number, - // with bounds included when the original mantissa was even (i.e. `!mant_was_odd`). + // with bounds included when the original mantissa was even (i.e., `!mant_was_odd`). assert!(d.mant > 0); assert!(d.minus > 0); @@ -172,7 +172,7 @@ pub fn format_shortest(d: &Decoded, buf: &mut [u8]) -> (/*#digits*/ usize, /*exp // - `high - v = plus / scale * 10^(k-n)` // // assume that `d[0..n-1]` is the shortest representation between `low` and `high`, - // i.e. `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: + // i.e., `d[0..n-1]` satisfies both of the following but `d[0..n-2]` doesn't: // - `low < d[0..n-1] * 10^(k-n) < high` (bijectivity: digits round to `v`); and // - `abs(v / 10^(k-n) - d[0..n-1]) <= 1/2` (the last digit is correct). // @@ -304,7 +304,7 @@ pub fn format_exact(d: &Decoded, buf: &mut [u8], limit: i16) -> (/*#digits*/ usi // rounding up if we stop in the middle of digits // if the following digits are exactly 5000..., check the prior digit and try to - // round to even (i.e. avoid rounding up when the prior digit is even). + // round to even (i.e., avoid rounding up when the prior digit is even). let order = mant.cmp(scale.mul_small(5)); if order == Ordering::Greater || (order == Ordering::Equal && (len == 0 || buf[len-1] & 1 == 1)) { diff --git a/src/libcore/num/flt2dec/strategy/grisu.rs b/src/libcore/num/flt2dec/strategy/grisu.rs index effe073c381..3e76feca885 100644 --- a/src/libcore/num/flt2dec/strategy/grisu.rs +++ b/src/libcore/num/flt2dec/strategy/grisu.rs @@ -242,7 +242,7 @@ pub fn format_shortest_opt(d: &Decoded, // // find the digit length `kappa` between `(minus1, plus1)` as per Theorem 6.2. // Theorem 6.2 can be adopted to exclude `x` by requiring `y mod 10^k < y - x` instead. - // (e.g. `x` = 32000, `y` = 32777; `kappa` = 2 since `y mod 10^3 = 777 < y - x = 777`.) + // (e.g., `x` = 32000, `y` = 32777; `kappa` = 2 since `y mod 10^3 = 777 < y - x = 777`.) // the algorithm relies on the later verification phase to exclude `y`. let delta1 = plus1 - minus1; // let delta1int = (delta1 >> e) as usize; // only for explanation @@ -362,19 +362,19 @@ pub fn format_shortest_opt(d: &Decoded, // proceed, but we then have at least one valid representation known to be closest to // `v + 1 ulp` anyway. we will denote them as TC1 through TC3 for brevity. // - // TC1: `w(n) <= v + 1 ulp`, i.e. this is the last repr that can be the closest one. + // TC1: `w(n) <= v + 1 ulp`, i.e., this is the last repr that can be the closest one. // this is equivalent to `plus1 - w(n) = plus1w(n) >= plus1 - (v + 1 ulp) = plus1v_up`. // combined with TC2 (which checks if `w(n+1)` is valid), this prevents the possible // overflow on the calculation of `plus1w(n)`. // - // TC2: `w(n+1) < minus1`, i.e. the next repr definitely does not round to `v`. + // TC2: `w(n+1) < minus1`, i.e., the next repr definitely does not round to `v`. // this is equivalent to `plus1 - w(n) + 10^kappa = plus1w(n) + 10^kappa > // plus1 - minus1 = threshold`. the left hand side can overflow, but we know // `threshold > plus1v`, so if TC1 is false, `threshold - plus1w(n) > // threshold - (plus1v - 1 ulp) > 1 ulp` and we can safely test if // `threshold - plus1w(n) < 10^kappa` instead. // - // TC3: `abs(w(n) - (v + 1 ulp)) <= abs(w(n+1) - (v + 1 ulp))`, i.e. the next repr is + // TC3: `abs(w(n) - (v + 1 ulp)) <= abs(w(n+1) - (v + 1 ulp))`, i.e., the next repr is // no closer to `v + 1 ulp` than the current repr. given `z(n) = plus1v_up - plus1w(n)`, // this becomes `abs(z(n)) <= abs(z(n+1))`. again assuming that TC1 is false, we have // `z(n) > 0`. we have two cases to consider: @@ -384,7 +384,7 @@ pub fn format_shortest_opt(d: &Decoded, // - when `z(n+1) < 0`: // - TC3a: the precondition is `plus1v_up < plus1w(n) + 10^kappa`. assuming TC2 is // false, `threshold >= plus1w(n) + 10^kappa` so it cannot overflow. - // - TC3b: TC3 becomes `z(n) <= -z(n+1)`, i.e. `plus1v_up - plus1w(n) >= + // - TC3b: TC3 becomes `z(n) <= -z(n+1)`, i.e., `plus1v_up - plus1w(n) >= // plus1w(n+1) - plus1v_up = plus1w(n) + 10^kappa - plus1v_up`. the negated TC1 // gives `plus1v_up > plus1w(n)`, so it cannot overflow or underflow when // combined with TC3a. @@ -414,7 +414,7 @@ pub fn format_shortest_opt(d: &Decoded, // now we have the closest representation to `v` between `plus1` and `minus1`. // this is too liberal, though, so we reject any `w(n)` not between `plus0` and `minus0`, - // i.e. `plus1 - plus1w(n) <= minus0` or `plus1 - plus1w(n) >= plus0`. we utilize the facts + // i.e., `plus1 - plus1w(n) <= minus0` or `plus1 - plus1w(n) >= plus0`. we utilize the facts // that `threshold = plus1 - minus1` and `plus1 - plus0 = minus0 - minus1 = 2 ulp`. if 2 * ulp <= plus1w && plus1w <= threshold - 4 * ulp { Some((buf.len(), exp)) @@ -675,7 +675,7 @@ pub fn format_exact_opt(d: &Decoded, buf: &mut [u8], limit: i16) return Some((len, exp)); } - // otherwise we are doomed (i.e. some values between `v - 1 ulp` and `v + 1 ulp` are + // otherwise we are doomed (i.e., some values between `v - 1 ulp` and `v + 1 ulp` are // rounding down and others are rounding up) and give up. None } diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 7f5d596b220..13b422162f3 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -1544,7 +1544,7 @@ assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true)); concat!("Negates self, overflowing if this is equal to the minimum value. Returns a tuple of the negated version of self along with a boolean indicating whether an overflow -happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the +happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the minimum value will be returned again and `true` will be returned for an overflow happening. # Examples @@ -1621,7 +1621,7 @@ $EndFeature, " concat!("Computes the absolute value of `self`. Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow -happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type +happened. If self is the minimum value (e.g., ", stringify!($SelfT), "::MIN for values of type ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned for an overflow happening. @@ -3617,7 +3617,7 @@ assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, " doc_comment! { concat!("Returns the smallest power of two greater than or equal to `self`. -When return value overflows (i.e. `self > (1 << (N-1))` for type +When return value overflows (i.e., `self > (1 << (N-1))` for type `uN`), it panics in debug mode and return value is wrapped to 0 in release mode (the only situation in which method can return 0). @@ -4827,7 +4827,7 @@ fn from_str_radix(src: &str, radix: u32) -> Result (1 << (N-1))` for type +When return value overflows (i.e., `self > (1 << (N-1))` for type `uN`), overflows to `2^N = 0`. # Examples diff --git a/src/libcore/ops/function.rs b/src/libcore/ops/function.rs index c9591c3f57b..d1be724c326 100644 --- a/src/libcore/ops/function.rs +++ b/src/libcore/ops/function.rs @@ -26,7 +26,7 @@ /// is expected. /// /// Use `Fn` as a bound when you want to accept a parameter of function-like -/// type and need to call it repeatedly and without mutating state (e.g. when +/// type and need to call it repeatedly and without mutating state (e.g., when /// calling it concurrently). If you do not need such strict requirements, use /// [`FnMut`] or [`FnOnce`] as bounds. /// @@ -84,7 +84,7 @@ pub trait Fn : FnMut { /// /// `FnMut` is implemented automatically by closures which take mutable /// references to captured variables, as well as all types that implement -/// [`Fn`], e.g. (safe) [function pointers][] (since `FnMut` is a supertrait of +/// [`Fn`], e.g., (safe) [function pointers][] (since `FnMut` is a supertrait of /// [`Fn`]). Additionally, for any type `F` that implements `FnMut`, `&mut F` /// implements `FnMut`, too. /// @@ -163,7 +163,7 @@ pub trait FnMut : FnOnce { /// implements `FnOnce`, it can only be called once. /// /// `FnOnce` is implemented automatically by closure that might consume captured -/// variables, as well as all types that implement [`FnMut`], e.g. (safe) +/// variables, as well as all types that implement [`FnMut`], e.g., (safe) /// [function pointers][] (since `FnOnce` is a supertrait of [`FnMut`]). /// /// Since both [`Fn`] and [`FnMut`] are subtraits of `FnOnce`, any instance of diff --git a/src/libcore/ops/mod.rs b/src/libcore/ops/mod.rs index edfa6df11ac..785f0733df2 100644 --- a/src/libcore/ops/mod.rs +++ b/src/libcore/ops/mod.rs @@ -27,7 +27,7 @@ //! should have some resemblance to multiplication (and share expected //! properties like associativity). //! -//! Note that the `&&` and `||` operators short-circuit, i.e. they only +//! Note that the `&&` and `||` operators short-circuit, i.e., they only //! evaluate their second operand if it contributes to the result. Since this //! behavior is not enforceable by traits, `&&` and `||` are not supported as //! overloadable operators. diff --git a/src/libcore/option.rs b/src/libcore/option.rs index cf1c77041b9..44d632ece05 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -62,7 +62,7 @@ //! The following example uses [`Option`] to create an optional box of //! [`i32`]. Notice that in order to use the inner [`i32`] value first, the //! `check_optional` function needs to use pattern matching to -//! determine whether the box has a value (i.e. it is [`Some(...)`][`Some`]) or +//! determine whether the box has a value (i.e., it is [`Some(...)`][`Some`]) or //! not ([`None`]). //! //! ``` diff --git a/src/libcore/pin.rs b/src/libcore/pin.rs index 308dd9c79fa..aa5155536c9 100644 --- a/src/libcore/pin.rs +++ b/src/libcore/pin.rs @@ -9,7 +9,7 @@ //! //! In order to prevent objects from moving, they must be pinned //! by wrapping a pointer to the data in the [`Pin`] type. A pointer wrapped -//! in a `Pin` is otherwise equivalent to its normal version, e.g. `Pin>` +//! in a `Pin` is otherwise equivalent to its normal version, e.g., `Pin>` //! and `Box` work the same way except that the first is pinning the value //! of `T` in place. //! diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 8630dd402ef..a2d32e9d68f 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -103,7 +103,7 @@ pub use intrinsics::write_bytes; /// dropped normally. /// /// * It is friendlier to the optimizer to do this over [`ptr::read`] when -/// dropping manually allocated memory (e.g. when writing Box/Rc/Vec), +/// dropping manually allocated memory (e.g., when writing Box/Rc/Vec), /// as the compiler doesn't need to prove that it's sound to elide the /// copy. /// @@ -836,7 +836,7 @@ pub unsafe fn write_unaligned(dst: *mut T, src: T) { /// /// The compiler shouldn't change the relative order or number of volatile /// memory operations. However, volatile memory operations on zero-sized types -/// (e.g. if a zero-sized type is passed to `read_volatile`) are no-ops +/// (e.g., if a zero-sized type is passed to `read_volatile`) are no-ops /// and may be ignored. /// /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf @@ -913,7 +913,7 @@ pub unsafe fn read_volatile(src: *const T) -> T { /// /// The compiler shouldn't change the relative order or number of volatile /// memory operations. However, volatile memory operations on zero-sized types -/// (e.g. if a zero-sized type is passed to `write_volatile`) are no-ops +/// (e.g., if a zero-sized type is passed to `write_volatile`) are no-ops /// and may be ignored. /// /// [c11]: http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf @@ -1035,7 +1035,7 @@ impl *const T { /// Calculates the offset from a pointer. /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1089,7 +1089,7 @@ impl *const T { /// Calculates the offset from a pointer using wrapping arithmetic. /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1253,7 +1253,7 @@ impl *const T { /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`). /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1310,7 +1310,7 @@ impl *const T { /// Calculates the offset from a pointer (convenience for /// `.offset((count as isize).wrapping_neg())`). /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1367,7 +1367,7 @@ impl *const T { /// Calculates the offset from a pointer using wrapping arithmetic. /// (convenience for `.wrapping_offset(count as isize)`) /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1408,7 +1408,7 @@ impl *const T { /// Calculates the offset from a pointer using wrapping arithmetic. /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`) /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1655,7 +1655,7 @@ impl *mut T { /// Calculates the offset from a pointer. /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1708,7 +1708,7 @@ impl *mut T { } /// Calculates the offset from a pointer using wrapping arithmetic. - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1891,7 +1891,7 @@ impl *mut T { /// Calculates the offset from a pointer (convenience for `.offset(count as isize)`). /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -1948,7 +1948,7 @@ impl *mut T { /// Calculates the offset from a pointer (convenience for /// `.offset((count as isize).wrapping_neg())`). /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -2005,7 +2005,7 @@ impl *mut T { /// Calculates the offset from a pointer using wrapping arithmetic. /// (convenience for `.wrapping_offset(count as isize)`) /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -2046,7 +2046,7 @@ impl *mut T { /// Calculates the offset from a pointer using wrapping arithmetic. /// (convenience for `.wrapping_offset((count as isize).wrapping_sub())`) /// - /// `count` is in units of T; e.g. a `count` of 3 represents a pointer + /// `count` is in units of T; e.g., a `count` of 3 represents a pointer /// offset of `3 * size_of::()` bytes. /// /// # Safety @@ -2375,7 +2375,7 @@ pub(crate) unsafe fn align_offset(p: *const T, a: usize) -> usize { fn mod_inv(x: usize, m: usize) -> usize { /// Multiplicative modular inverse table modulo 2⁴ = 16. /// - /// Note, that this table does not contain values where inverse does not exist (i.e. for + /// Note, that this table does not contain values where inverse does not exist (i.e., for /// `0⁻¹ mod 16`, `2⁻¹ mod 16`, etc.) const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15]; /// Modulo for which the `INV_TABLE_MOD_16` is intended. @@ -2398,7 +2398,7 @@ pub(crate) unsafe fn align_offset(p: *const T, a: usize) -> usize { // y = y * (2 - xy) mod n // // Note, that we use wrapping operations here intentionally – the original formula - // uses e.g. subtraction `mod n`. It is entirely fine to do them `mod + // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod // usize::max_value()` instead, because we take the result `mod n` at the end // anyway. inverse = inverse.wrapping_mul( @@ -2887,12 +2887,12 @@ pub struct NonNull { } /// `NonNull` pointers are not `Send` because the data they reference may be aliased. -// NB: This impl is unnecessary, but should provide better error messages. +// N.B., this impl is unnecessary, but should provide better error messages. #[stable(feature = "nonnull", since = "1.25.0")] impl !Send for NonNull { } /// `NonNull` pointers are not `Sync` because the data they reference may be aliased. -// NB: This impl is unnecessary, but should provide better error messages. +// N.B., this impl is unnecessary, but should provide better error messages. #[stable(feature = "nonnull", since = "1.25.0")] impl !Sync for NonNull { } diff --git a/src/libcore/raw.rs b/src/libcore/raw.rs index 3d4bccb4f9d..4f1af8bf110 100644 --- a/src/libcore/raw.rs +++ b/src/libcore/raw.rs @@ -24,7 +24,7 @@ /// `Box`. /// /// `TraitObject` is guaranteed to match layouts, but it is not the -/// type of trait objects (e.g. the fields are not directly accessible +/// type of trait objects (e.g., the fields are not directly accessible /// on a `&SomeTrait`) nor does it control that layout (changing the /// definition will not change the layout of a `&SomeTrait`). It is /// only designed to be used by unsafe code that needs to manipulate diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 5b57dcabb8d..59c11b27329 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Slice management and manipulation +//! Slice management and manipulation. //! //! For more details see [`std::slice`]. //! @@ -1151,7 +1151,7 @@ impl [T] { /// /// # Examples /// - /// Print the slice split once by numbers divisible by 3 (i.e. `[10, 40]`, + /// Print the slice split once by numbers divisible by 3 (i.e., `[10, 40]`, /// `[20, 60, 50]`): /// /// ``` @@ -1215,7 +1215,7 @@ impl [T] { /// # Examples /// /// Print the slice split once, starting from the end, by numbers divisible - /// by 3 (i.e. `[50]`, `[10, 40, 30, 20]`): + /// by 3 (i.e., `[50]`, `[10, 40, 30, 20]`): /// /// ``` /// let v = [10, 40, 30, 20, 60, 50]; @@ -1471,8 +1471,8 @@ impl [T] { /// Sorts the slice, but may not preserve the order of equal elements. /// - /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate), - /// and `O(n log n)` worst-case. + /// This sort is unstable (i.e., may reorder equal elements), in-place + /// (i.e., does not allocate), and `O(n log n)` worst-case. /// /// # Current implementation /// @@ -1482,7 +1482,7 @@ impl [T] { /// randomization to avoid degenerate cases, but with a fixed seed to always provide /// deterministic behavior. /// - /// It is typically faster than stable sorting, except in a few special cases, e.g. when the + /// It is typically faster than stable sorting, except in a few special cases, e.g., when the /// slice consists of several concatenated sorted sequences. /// /// # Examples @@ -1506,8 +1506,8 @@ impl [T] { /// Sorts the slice with a comparator function, but may not preserve the order of equal /// elements. /// - /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate), - /// and `O(n log n)` worst-case. + /// This sort is unstable (i.e., may reorder equal elements), in-place + /// (i.e., does not allocate), and `O(n log n)` worst-case. /// /// The comparator function must define a total ordering for the elements in the slice. If /// the ordering is not total, the order of the elements is unspecified. An order is a @@ -1533,7 +1533,7 @@ impl [T] { /// randomization to avoid degenerate cases, but with a fixed seed to always provide /// deterministic behavior. /// - /// It is typically faster than stable sorting, except in a few special cases, e.g. when the + /// It is typically faster than stable sorting, except in a few special cases, e.g., when the /// slice consists of several concatenated sorted sequences. /// /// # Examples @@ -1560,8 +1560,9 @@ impl [T] { /// Sorts the slice with a key extraction function, but may not preserve the order of equal /// elements. /// - /// This sort is unstable (i.e. may reorder equal elements), in-place (i.e. does not allocate), - /// and `O(m n log(m n))` worst-case, where the key function is `O(m)`. + /// This sort is unstable (i.e., may reorder equal elements), in-place + /// (i.e., does not allocate), and `O(m n log(m n))` worst-case, where the key function is + /// `O(m)`. /// /// # Current implementation /// @@ -2458,13 +2459,13 @@ impl SliceIndex<[T]> for usize { #[inline] fn index(self, slice: &[T]) -> &T { - // NB: use intrinsic indexing + // N.B., use intrinsic indexing &(*slice)[self] } #[inline] fn index_mut(self, slice: &mut [T]) -> &mut T { - // NB: use intrinsic indexing + // N.B., use intrinsic indexing &mut (*slice)[self] } } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index 6c953d1b9a0..4a22d929fed 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -482,7 +482,7 @@ fn utf8_first_byte(byte: u8, width: u32) -> u32 { (byte & (0x7F >> width)) as u3 #[inline] fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { (ch << 6) | (byte & CONT_MASK) as u32 } -/// Checks whether the byte is a UTF-8 continuation byte (i.e. starts with the +/// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the /// bits `10`). #[inline] fn utf8_is_cont_byte(byte: u8) -> bool { (byte & !CONT_MASK) == TAG_CONT_U8 } diff --git a/src/libcore/str/pattern.rs b/src/libcore/str/pattern.rs index 1c974533e10..2059160ddfe 100644 --- a/src/libcore/str/pattern.rs +++ b/src/libcore/str/pattern.rs @@ -397,7 +397,7 @@ unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> { let found_char = index - shift; if let Some(slice) = haystack.get(found_char..(found_char + self.utf8_size)) { if slice == &self.utf8_encoded[0..self.utf8_size] { - // move finger to before the character found (i.e. at its start index) + // move finger to before the character found (i.e., at its start index) self.finger_back = found_char; return Some((self.finger_back, self.finger_back + self.utf8_size)); } @@ -1016,7 +1016,7 @@ struct TwoWaySearcher { It can be proven that the following is an equivalent definition of a local period for a factorization (u, v): any positive integer r such that x[i] == x[i+r] for all i such that |u| - r <= i <= |u| - 1 and such that both x[i] and x[i+r] are - defined. (i.e. i > 0 and i + r < |x|). + defined. (i.e., i > 0 and i + r < |x|). Using the above reformulation, it is easy to prove that diff --git a/src/libcore/task/wake.rs b/src/libcore/task/wake.rs index c0ce7255d62..8ea7abce67b 100644 --- a/src/libcore/task/wake.rs +++ b/src/libcore/task/wake.rs @@ -227,7 +227,7 @@ pub unsafe trait UnsafeWake: Send + Sync { /// # Unsafety /// /// This function is unsafe to call because it's asserting the `UnsafeWake` - /// value is in a consistent state, i.e. hasn't been dropped. + /// value is in a consistent state, i.e., hasn't been dropped. unsafe fn clone_raw(&self) -> Waker; /// Drops this instance of `UnsafeWake`, deallocating resources @@ -249,7 +249,7 @@ pub unsafe trait UnsafeWake: Send + Sync { /// # Unsafety /// /// This function is unsafe to call because it's asserting the `UnsafeWake` - /// value is in a consistent state, i.e. hasn't been dropped. + /// value is in a consistent state, i.e., hasn't been dropped. unsafe fn drop_raw(&self); /// Indicates that the associated task is ready to make progress and should @@ -266,7 +266,7 @@ pub unsafe trait UnsafeWake: Send + Sync { /// # Unsafety /// /// This function is unsafe to call because it's asserting the `UnsafeWake` - /// value is in a consistent state, i.e. hasn't been dropped. + /// value is in a consistent state, i.e., hasn't been dropped. unsafe fn wake(&self); /// Indicates that the associated task is ready to make progress and should @@ -286,7 +286,7 @@ pub unsafe trait UnsafeWake: Send + Sync { /// # Unsafety /// /// This function is unsafe to call because it's asserting the `UnsafeWake` - /// value is in a consistent state, i.e. hasn't been dropped, and that the + /// value is in a consistent state, i.e., hasn't been dropped, and that the /// `UnsafeWake` hasn't moved from the thread on which it was created. unsafe fn wake_local(&self) { self.wake() diff --git a/src/libcore/tests/num/dec2flt/mod.rs b/src/libcore/tests/num/dec2flt/mod.rs index 17b2f59cd4d..879a41b4b77 100644 --- a/src/libcore/tests/num/dec2flt/mod.rs +++ b/src/libcore/tests/num/dec2flt/mod.rs @@ -17,7 +17,7 @@ mod rawfp; // Take a float literal, turn it into a string in various ways (that are all trusted // to be correct) and see if those strings are parsed back to the value of the literal. -// Requires a *polymorphic literal*, i.e. one that can serve as f64 as well as f32. +// Requires a *polymorphic literal*, i.e., one that can serve as f64 as well as f32. macro_rules! test_literal { ($x: expr) => ({ let x32: f32 = $x; diff --git a/src/libcore/tests/num/flt2dec/random.rs b/src/libcore/tests/num/flt2dec/random.rs index ab619093d9d..95dfcb522e0 100644 --- a/src/libcore/tests/num/flt2dec/random.rs +++ b/src/libcore/tests/num/flt2dec/random.rs @@ -99,7 +99,7 @@ pub fn f32_exhaustive_equivalence_test(f: F, g: G, k: usize) // this is of course very stressful (and thus should be behind an `#[ignore]` attribute), // but with `-C opt-level=3 -C lto` this only takes about an hour or so. - // iterate from 0x0000_0001 to 0x7f7f_ffff, i.e. all finite ranges + // iterate from 0x0000_0001 to 0x7f7f_ffff, i.e., all finite ranges let (npassed, nignored) = iterate("f32_exhaustive_equivalence_test", k, 0x7f7f_ffff, f, g, |i: usize| { diff --git a/src/libcore/time.rs b/src/libcore/time.rs index 938e97503de..475bb721f23 100644 --- a/src/libcore/time.rs +++ b/src/libcore/time.rs @@ -216,7 +216,7 @@ impl Duration { /// /// This method does **not** return the length of the duration when /// represented by milliseconds. The returned number always represents a - /// fractional portion of a second (i.e. it is less than one thousand). + /// fractional portion of a second (i.e., it is less than one thousand). /// /// # Examples /// @@ -235,7 +235,7 @@ impl Duration { /// /// This method does **not** return the length of the duration when /// represented by microseconds. The returned number always represents a - /// fractional portion of a second (i.e. it is less than one million). + /// fractional portion of a second (i.e., it is less than one million). /// /// # Examples /// @@ -254,7 +254,7 @@ impl Duration { /// /// This method does **not** return the length of the duration when /// represented by nanoseconds. The returned number always represents a - /// fractional portion of a second (i.e. it is less than one billion). + /// fractional portion of a second (i.e., it is less than one billion). /// /// # Examples /// diff --git a/src/libgraphviz/lib.rs b/src/libgraphviz/lib.rs index 396b0366074..e3cf959beb8 100644 --- a/src/libgraphviz/lib.rs +++ b/src/libgraphviz/lib.rs @@ -10,7 +10,7 @@ //! Generate files suitable for use with [Graphviz](http://www.graphviz.org/) //! -//! The `render` function generates output (e.g. an `output.dot` file) for +//! The `render` function generates output (e.g., an `output.dot` file) for //! use with [Graphviz](http://www.graphviz.org/) by walking a labeled //! graph. (Graphviz can then automatically lay out the nodes and edges //! of the graph, and also optionally render the graph as an image or @@ -25,7 +25,7 @@ //! expressiveness of the [DOT language]( //! http://www.graphviz.org/doc/info/lang.html). For example, there are //! many [attributes](http://www.graphviz.org/content/attrs) related to -//! providing layout hints (e.g. left-to-right versus top-down, which +//! providing layout hints (e.g., left-to-right versus top-down, which //! algorithm to use, etc). The current intention of this library is to //! emit a human-readable .dot file with very regular structure suitable //! for easy post-processing. @@ -373,7 +373,7 @@ impl Style { // implement a Labelling service) that I have encountered is that it // makes it impossible to use types outside of the current crate // directly as Nodes/Edges; you need to wrap them in newtype'd -// structs. See e.g. the `No` and `Ed` structs in the examples. (In +// structs. See e.g., the `No` and `Ed` structs in the examples. (In // practice clients using a graph in some other crate would need to // provide some sort of adapter shim over the graph anyway to // interface with this library). @@ -400,7 +400,7 @@ impl<'a> Id<'a> { /// The caller must ensure that the input conforms to an /// identifier format: it must be a non-empty string made up of /// alphanumeric or underscore characters, not beginning with a - /// digit (i.e. the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`). + /// digit (i.e., the regular expression `[a-zA-Z_][a-zA-Z_0-9]*`). /// /// (Note: this format is a strict subset of the `ID` format /// defined by the DOT language. This function may change in the diff --git a/src/libpanic_unwind/dwarf/mod.rs b/src/libpanic_unwind/dwarf/mod.rs index 3ff250ff659..c9ae87ade28 100644 --- a/src/libpanic_unwind/dwarf/mod.rs +++ b/src/libpanic_unwind/dwarf/mod.rs @@ -32,7 +32,7 @@ impl DwarfReader { DwarfReader { ptr } } - // DWARF streams are packed, so e.g. a u32 would not necessarily be aligned + // DWARF streams are packed, so e.g., a u32 would not necessarily be aligned // on a 4-byte boundary. This may cause problems on platforms with strict // alignment requirements. By wrapping data in a "packed" struct, we are // telling the backend to generate "misalignment-safe" code. diff --git a/src/libpanic_unwind/gcc.rs b/src/libpanic_unwind/gcc.rs index 11ebcf5c01e..441058c8d74 100644 --- a/src/libpanic_unwind/gcc.rs +++ b/src/libpanic_unwind/gcc.rs @@ -25,7 +25,7 @@ //! //! In both phases the unwinder walks stack frames from top to bottom using //! information from the stack frame unwind sections of the current process's -//! modules ("module" here refers to an OS module, i.e. an executable or a +//! modules ("module" here refers to an OS module, i.e., an executable or a //! dynamic library). //! //! For each stack frame, it invokes the associated "personality routine", whose @@ -296,7 +296,7 @@ unsafe extern "C" fn rust_eh_unwind_resume(panic_ctx: *mut u8) -> ! { // Each module's image contains a frame unwind info section (usually // ".eh_frame"). When a module is loaded/unloaded into the process, the // unwinder must be informed about the location of this section in memory. The -// methods of achieving that vary by the platform. On some (e.g. Linux), the +// methods of achieving that vary by the platform. On some (e.g., Linux), the // unwinder can discover unwind info sections on its own (by dynamically // enumerating currently loaded modules via the dl_iterate_phdr() API and // finding their ".eh_frame" sections); Others, like Windows, require modules diff --git a/src/libpanic_unwind/seh.rs b/src/libpanic_unwind/seh.rs index 832a0aff71b..9d24079d91e 100644 --- a/src/libpanic_unwind/seh.rs +++ b/src/libpanic_unwind/seh.rs @@ -12,7 +12,7 @@ //! //! On Windows (currently only on MSVC), the default exception handling //! mechanism is Structured Exception Handling (SEH). This is quite different -//! than Dwarf-based exception handling (e.g. what other unix platforms use) in +//! than Dwarf-based exception handling (e.g., what other unix platforms use) in //! terms of compiler internals, so LLVM is required to have a good deal of //! extra support for SEH. //! @@ -304,7 +304,7 @@ pub unsafe fn cleanup(payload: [u64; 2]) -> Box { }) } -// This is required by the compiler to exist (e.g. it's a lang item), but +// This is required by the compiler to exist (e.g., it's a lang item), but // it's never actually called by the compiler because __C_specific_handler // or _except_handler3 is the personality function that is always used. // Hence this is just an aborting stub. diff --git a/src/libproc_macro/bridge/client.rs b/src/libproc_macro/bridge/client.rs index ed27df44962..f5e12713e4e 100644 --- a/src/libproc_macro/bridge/client.rs +++ b/src/libproc_macro/bridge/client.rs @@ -262,7 +262,7 @@ enum BridgeState<'a> { Connected(Bridge<'a>), /// Access to the bridge is being exclusively acquired - /// (e.g. during `BridgeState::with`). + /// (e.g., during `BridgeState::with`). InUse, } @@ -283,7 +283,7 @@ impl BridgeState<'_> { /// The state will be restored after `f` exits, even /// by panic, including modifications made to it by `f`. /// - /// NB: while `f` is running, the thread-local state + /// N.B., while `f` is running, the thread-local state /// is `BridgeState::InUse`. fn with(f: impl FnOnce(&mut BridgeState) -> R) -> R { BRIDGE_STATE.with(|state| { @@ -333,7 +333,7 @@ impl Bridge<'_> { /// which may be using a different `proc_macro` from the one /// used by the server, but can be interacted with compatibly. /// -/// NB: `F` must have FFI-friendly memory layout (e.g. a pointer). +/// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer). /// The call ABI of function pointers used for `F` doesn't /// need to match between server and client, since it's only /// passed between them and (eventually) called by the client. diff --git a/src/libproc_macro/bridge/mod.rs b/src/libproc_macro/bridge/mod.rs index f03c63fc04c..edb4d3fbdaa 100644 --- a/src/libproc_macro/bridge/mod.rs +++ b/src/libproc_macro/bridge/mod.rs @@ -14,7 +14,7 @@ //! Serialization (with C ABI buffers) and unique integer handles are employed //! to allow safely interfacing between two copies of `proc_macro` built //! (from the same source) by different compilers with potentially mismatching -//! Rust ABIs (e.g. stage0/bin/rustc vs stage1/bin/rustc during bootstrap). +//! Rust ABIs (e.g., stage0/bin/rustc vs stage1/bin/rustc during bootstrap). #![deny(unsafe_code)] diff --git a/src/libproc_macro/bridge/scoped_cell.rs b/src/libproc_macro/bridge/scoped_cell.rs index 51d1fece79b..c86d5fc309a 100644 --- a/src/libproc_macro/bridge/scoped_cell.rs +++ b/src/libproc_macro/bridge/scoped_cell.rs @@ -19,7 +19,7 @@ pub trait ApplyL<'a> { type Out; } -/// Type lambda taking a lifetime, i.e. `Lifetime -> Type`. +/// Type lambda taking a lifetime, i.e., `Lifetime -> Type`. pub trait LambdaL: for<'a> ApplyL<'a> {} impl ApplyL<'a>> LambdaL for T {} diff --git a/src/libproc_macro/bridge/server.rs b/src/libproc_macro/bridge/server.rs index f500b17d1ca..0c1d4f7cc50 100644 --- a/src/libproc_macro/bridge/server.rs +++ b/src/libproc_macro/bridge/server.rs @@ -16,7 +16,7 @@ use super::*; use super::client::HandleStore; /// Declare an associated item of one of the traits below, optionally -/// adjusting it (i.e. adding bounds to types and default bodies to methods). +/// adjusting it (i.e., adding bounds to types and default bodies to methods). macro_rules! associated_item { (type TokenStream) => (type TokenStream: 'static + Clone;); diff --git a/src/libproc_macro/lib.rs b/src/libproc_macro/lib.rs index 32c81302931..f2b85832dac 100644 --- a/src/libproc_macro/lib.rs +++ b/src/libproc_macro/lib.rs @@ -110,7 +110,7 @@ impl FromStr for TokenStream { } } -// NB: the bridge only provides `to_string`, implement `fmt::Display` +// N.B., the bridge only provides `to_string`, implement `fmt::Display` // based on it (the reverse of the usual relationship between the two). #[stable(feature = "proc_macro_lib", since = "1.15.0")] impl ToString for TokenStream { @@ -196,7 +196,7 @@ pub mod token_stream { use {bridge, Group, Ident, Literal, Punct, TokenTree, TokenStream}; /// An iterator over `TokenStream`'s `TokenTree`s. - /// The iteration is "shallow", e.g. the iterator doesn't recurse into delimited groups, + /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups, /// and returns whole groups as token trees. #[derive(Clone)] #[stable(feature = "proc_macro_lib2", since = "1.29.0")] @@ -426,7 +426,7 @@ impl PartialEq for SourceFile { #[unstable(feature = "proc_macro_span", issue = "54725")] impl Eq for SourceFile {} -/// A single token or a delimited sequence of token trees (e.g. `[1, (), ..]`). +/// A single token or a delimited sequence of token trees (e.g., `[1, (), ..]`). #[stable(feature = "proc_macro_lib2", since = "1.29.0")] #[derive(Clone)] pub enum TokenTree { @@ -533,7 +533,7 @@ impl From for TokenTree { } } -// NB: the bridge only provides `to_string`, implement `fmt::Display` +// N.B., the bridge only provides `to_string`, implement `fmt::Display` // based on it (the reverse of the usual relationship between the two). #[stable(feature = "proc_macro_lib", since = "1.15.0")] impl ToString for TokenTree { @@ -663,7 +663,7 @@ impl Group { } } -// NB: the bridge only provides `to_string`, implement `fmt::Display` +// N.B., the bridge only provides `to_string`, implement `fmt::Display` // based on it (the reverse of the usual relationship between the two). #[stable(feature = "proc_macro_lib", since = "1.15.0")] impl ToString for Group { @@ -711,10 +711,10 @@ impl !Sync for Punct {} #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub enum Spacing { - /// E.g. `+` is `Alone` in `+ =`, `+ident` or `+()`. + /// e.g., `+` is `Alone` in `+ =`, `+ident` or `+()`. #[stable(feature = "proc_macro_lib2", since = "1.29.0")] Alone, - /// E.g. `+` is `Joint` in `+=` or `'#`. + /// e.g., `+` is `Joint` in `+=` or `'#`. /// Additionally, single quote `'` can join with identifiers to form lifetimes `'ident`. #[stable(feature = "proc_macro_lib2", since = "1.29.0")] Joint, @@ -765,7 +765,7 @@ impl Punct { } } -// NB: the bridge only provides `to_string`, implement `fmt::Display` +// N.B., the bridge only provides `to_string`, implement `fmt::Display` // based on it (the reverse of the usual relationship between the two). #[stable(feature = "proc_macro_lib", since = "1.15.0")] impl ToString for Punct { @@ -860,7 +860,7 @@ impl Ident { } } -// NB: the bridge only provides `to_string`, implement `fmt::Display` +// N.B., the bridge only provides `to_string`, implement `fmt::Display` // based on it (the reverse of the usual relationship between the two). #[stable(feature = "proc_macro_lib", since = "1.15.0")] impl ToString for Ident { @@ -1110,7 +1110,7 @@ impl Literal { } } -// NB: the bridge only provides `to_string`, implement `fmt::Display` +// N.B., the bridge only provides `to_string`, implement `fmt::Display` // based on it (the reverse of the usual relationship between the two). #[stable(feature = "proc_macro_lib", since = "1.15.0")] impl ToString for Literal { diff --git a/src/librustc/cfg/construct.rs b/src/librustc/cfg/construct.rs index 457f33f8bd7..c5d6ce24c5d 100644 --- a/src/librustc/cfg/construct.rs +++ b/src/librustc/cfg/construct.rs @@ -379,7 +379,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { } hir::ExprKind::Index(ref l, ref r) | - hir::ExprKind::Binary(_, ref l, ref r) => { // NB: && and || handled earlier + hir::ExprKind::Binary(_, ref l, ref r) => { // N.B., && and || handled earlier self.straightline(expr, pred, [l, r].iter().map(|&e| &**e)) } diff --git a/src/librustc/dep_graph/dep_node.rs b/src/librustc/dep_graph/dep_node.rs index dd46dd3fd64..f0c6196412a 100644 --- a/src/librustc/dep_graph/dep_node.rs +++ b/src/librustc/dep_graph/dep_node.rs @@ -17,7 +17,7 @@ //! fully identify a dependency node, even across multiple compilation sessions. //! In other words, the value of the fingerprint does not depend on anything //! that is specific to a given compilation session, like an unpredictable -//! interning key (e.g. NodeId, DefId, Symbol) or the numeric value of a +//! interning key (e.g., NodeId, DefId, Symbol) or the numeric value of a //! pointer. The concept behind this could be compared to how git commit hashes //! uniquely identify a given commit and has a few advantages: //! @@ -28,7 +28,7 @@ //! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to //! implement `Copy`, `Sync`, `Send`, `Freeze`, etc. //! * Since we just have a bit pattern, `DepNode` can be mapped from disk into -//! memory without any post-processing (e.g. "abomination-style" pointer +//! memory without any post-processing (e.g., "abomination-style" pointer //! reconstruction). //! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that //! refer to things that do not exist anymore. In previous implementations @@ -81,7 +81,7 @@ use ty::{TyCtxt, FnSig, Instance, InstanceDef, use ty::subst::Substs; // erase!() just makes tokens go away. It's used to specify which macro argument -// is repeated (i.e. which sub-expression of the macro we are in) but don't need +// is repeated (i.e., which sub-expression of the macro we are in) but don't need // to actually use any of the arguments. macro_rules! erase { ($x:tt) => ({}) diff --git a/src/librustc/diagnostics.rs b/src/librustc/diagnostics.rs index 96590c1fc72..3dc6f761ec9 100644 --- a/src/librustc/diagnostics.rs +++ b/src/librustc/diagnostics.rs @@ -47,7 +47,7 @@ trait Foo where Self: Sized { We cannot create an object of type `Box` or `&Foo` since in this case `Self` would not be `Sized`. -Generally, `Self : Sized` is used to indicate that the trait should not be used +Generally, `Self: Sized` is used to indicate that the trait should not be used as a trait object. If the trait comes from your own crate, consider removing this restriction. @@ -217,9 +217,9 @@ trait Trait { ``` If this is not an option, consider replacing the type parameter with another -trait object (e.g. if `T: OtherTrait`, use `on: Box`). If the number -of types you intend to feed to this method is limited, consider manually listing -out the methods of different types. +trait object (e.g., if `T: OtherTrait`, use `on: Box`). If the +number of types you intend to feed to this method is limited, consider manually +listing out the methods of different types. ### Method has no receiver @@ -642,7 +642,7 @@ struct Foo; // error: duplicate lang item found: `arc` ``` Lang items are already implemented in the standard library. Unless you are -writing a free-standing application (e.g. a kernel), you do not need to provide +writing a free-standing application (e.g., a kernel), you do not need to provide them yourself. You can build a free-standing crate by adding `#![no_std]` to the crate @@ -699,7 +699,7 @@ This error appears when the curly braces contain an identifier which doesn't match with any of the type parameters or the string `Self`. This might happen if you misspelled a type parameter, or if you intended to use literal curly braces. If it is the latter, escape the curly braces with a second curly brace -of the same type; e.g. a literal `{` is `{{`. +of the same type; e.g., a literal `{` is `{{`. "##, E0231: r##" @@ -832,7 +832,7 @@ extern "C" { E0271: r##" This is because of a type mismatch between the associated type of some -trait (e.g. `T::Bar`, where `T` implements `trait Quux { type Bar; }`) +trait (e.g., `T::Bar`, where `T` implements `trait Quux { type Bar; }`) and another type `U` that is required to be equal to `T::Bar`, but is not. Examples follow. @@ -1622,7 +1622,7 @@ representation of enums isn't strictly defined in Rust, and this attribute won't work on enums. `#[repr(simd)]` will give a struct consisting of a homogeneous series of machine -types (i.e. `u8`, `i32`, etc) a representation that permits vectorization via +types (i.e., `u8`, `i32`, etc) a representation that permits vectorization via SIMD. This doesn't make much sense for enums since they don't consist of a single list of data. "##, diff --git a/src/librustc/hir/def.rs b/src/librustc/hir/def.rs index 50922ee601d..fb3c3dec7c2 100644 --- a/src/librustc/hir/def.rs +++ b/src/librustc/hir/def.rs @@ -46,7 +46,7 @@ pub enum NonMacroAttrKind { pub enum Def { // Type namespace Mod(DefId), - Struct(DefId), // DefId refers to NodeId of the struct itself + Struct(DefId), // `DefId` refers to `NodeId` of the struct itself Union(DefId), Enum(DefId), Variant(DefId), @@ -63,27 +63,27 @@ pub enum Def { PrimTy(hir::PrimTy), TyParam(DefId), SelfTy(Option /* trait */, Option /* impl */), - ToolMod, // e.g. `rustfmt` in `#[rustfmt::skip]` + ToolMod, // e.g., `rustfmt` in `#[rustfmt::skip]` // Value namespace Fn(DefId), Const(DefId), Static(DefId, bool /* is_mutbl */), - StructCtor(DefId, CtorKind), // DefId refers to NodeId of the struct's constructor - VariantCtor(DefId, CtorKind), // DefId refers to the enum variant - SelfCtor(DefId /* impl */), // DefId refers to the impl + StructCtor(DefId, CtorKind), // `DefId` refers to `NodeId` of the struct's constructor + VariantCtor(DefId, CtorKind), // `DefId` refers to the enum variant + SelfCtor(DefId /* impl */), // `DefId` refers to the impl Method(DefId), AssociatedConst(DefId), Local(ast::NodeId), - Upvar(ast::NodeId, // node id of closed over local - usize, // index in the freevars list of the closure + Upvar(ast::NodeId, // `NodeId` of closed over local + usize, // index in the `freevars` list of the closure ast::NodeId), // expr node that creates the closure Label(ast::NodeId), // Macro namespace Macro(DefId, MacroKind), - NonMacroAttr(NonMacroAttrKind), // e.g. `#[inline]` or `#[rustfmt::skip]` + NonMacroAttr(NonMacroAttrKind), // e.g., `#[inline]` or `#[rustfmt::skip]` // Both namespaces Err, @@ -170,6 +170,7 @@ impl PerNS { impl ::std::ops::Index for PerNS { type Output = T; + fn index(&self, ns: Namespace) -> &T { match ns { ValueNS => &self.value_ns, @@ -238,6 +239,7 @@ impl CtorKind { ast::VariantData::Struct(..) => CtorKind::Fictive, } } + pub fn from_hir(vdata: &hir::VariantData) -> CtorKind { match *vdata { hir::VariantData::Tuple(..) => CtorKind::Fn, diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index d9963f23a15..f7e2c7036f6 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -131,7 +131,7 @@ impl<'this, 'tcx> NestedVisitorMap<'this, 'tcx> { /// Each method of the Visitor trait is a hook to be potentially /// overridden. Each method's default implementation recursively visits /// the substructure of the input via the corresponding `walk` method; -/// e.g. the `visit_mod` method by default calls `intravisit::walk_mod`. +/// e.g., the `visit_mod` method by default calls `intravisit::walk_mod`. /// /// Note that this visitor does NOT visit nested items by default /// (this is why the module is called `intravisit`, to distinguish it @@ -493,7 +493,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { item.id) } ItemKind::Mod(ref module) => { - // visit_mod() takes care of visiting the Item's NodeId + // `visit_mod()` takes care of visiting the `Item`'s `NodeId`. visitor.visit_mod(module, item.span, item.id) } ItemKind::ForeignMod(ref foreign_module) => { @@ -518,7 +518,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item) { } ItemKind::Enum(ref enum_definition, ref type_parameters) => { visitor.visit_generics(type_parameters); - // visit_enum_def() takes care of visiting the Item's NodeId + // `visit_enum_def()` takes care of visiting the `Item`'s `NodeId`. visitor.visit_enum_def(enum_definition, type_parameters, item.id, item.span) } ItemKind::Impl( @@ -877,7 +877,7 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai } pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: &'v TraitItemRef) { - // NB: Deliberately force a compilation error if/when new fields are added. + // N.B., deliberately force a compilation error if/when new fields are added. let TraitItemRef { id, ident, ref kind, span: _, ref defaultness } = *trait_item_ref; visitor.visit_nested_trait_item(id); visitor.visit_ident(ident); @@ -886,7 +886,7 @@ pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: } pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem) { - // NB: Deliberately force a compilation error if/when new fields are added. + // N.B., deliberately force a compilation error if/when new fields are added. let ImplItem { id: _, hir_id: _, @@ -932,7 +932,7 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt } pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) { - // NB: Deliberately force a compilation error if/when new fields are added. + // N.B., deliberately force a compilation error if/when new fields are added. let ImplItemRef { id, ident, ref kind, span: _, ref vis, ref defaultness } = *impl_item_ref; visitor.visit_nested_impl_item(id); visitor.visit_ident(ident); diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index a485af0a5ee..6fd0ccb49b6 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -82,7 +82,7 @@ const HIR_ID_COUNTER_LOCKED: u32 = 0xFFFFFFFF; pub struct LoweringContext<'a> { crate_root: Option<&'static str>, - // Use to assign ids to hir nodes that do not directly correspond to an ast node + // Used to assign ids to HIR nodes that do not directly correspond to an AST node. sess: &'a Session, cstore: &'a dyn CrateStore, @@ -114,10 +114,10 @@ pub struct LoweringContext<'a> { anonymous_lifetime_mode: AnonymousLifetimeMode, // Used to create lifetime definitions from in-band lifetime usages. - // e.g. `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8` + // e.g., `fn foo(x: &'x u8) -> &'x u8` to `fn foo<'x>(x: &'x u8) -> &'x u8` // When a named lifetime is encountered in a function or impl header and // has not been defined - // (i.e. it doesn't appear in the in_scope_lifetimes list), it is added + // (i.e., it doesn't appear in the in_scope_lifetimes list), it is added // to this list. The results of this list are then added to the list of // lifetime definitions in the corresponding impl or function generics. lifetimes_to_define: Vec<(Span, ParamName)>, @@ -149,7 +149,7 @@ pub trait Resolver { is_value: bool, ) -> hir::Path; - /// Obtain the resolution for a node id + /// Obtain the resolution for a node-id. fn get_resolution(&mut self, id: NodeId) -> Option; /// Obtain the possible resolutions for the given `use` statement. @@ -159,8 +159,8 @@ pub trait Resolver { /// This should only return `None` during testing. fn definitions(&mut self) -> &mut Definitions; - /// Given suffix ["b","c","d"], creates a HIR path for `[::crate_root]::b::c::d` and resolves - /// it based on `is_value`. + /// Given suffix `["b", "c", "d"]`, creates a HIR path for `[::crate_root]::b::c::d` and + /// resolves it based on `is_value`. fn resolve_str_path( &mut self, span: Span, @@ -185,7 +185,7 @@ enum ImplTraitContext<'a> { /// /// We optionally store a `DefId` for the parent item here so we can look up necessary /// information later. It is `None` when no information about the context should be stored, - /// e.g. for consts and statics. + /// e.g., for consts and statics. Existential(Option), /// `impl Trait` is not accepted in this position. @@ -358,8 +358,8 @@ impl<'a> LoweringContext<'a> { fn lower_crate(mut self, c: &Crate) -> hir::Crate { /// Full-crate AST visitor that inserts into a fresh /// `LoweringContext` any information that may be - /// needed from arbitrary locations in the crate. - /// E.g. The number of lifetime generic parameters + /// needed from arbitrary locations in the crate, + /// e.g., the number of lifetime generic parameters /// declared for every type and trait definition. struct MiscCollector<'lcx, 'interner: 'lcx> { lctx: &'lcx mut LoweringContext<'interner>, @@ -512,7 +512,7 @@ impl<'a> LoweringContext<'a> { debug ); } - // Always allocate the first HirId for the owner itself + // Always allocate the first `HirId` for the owner itself. self.lower_node_id_with_owner(owner, owner) } @@ -536,7 +536,7 @@ impl<'a> LoweringContext<'a> { let existing_hir_id = self.node_id_to_hir_id[ast_node_id]; if existing_hir_id == hir::DUMMY_HIR_ID { - // Generate a new HirId + // Generate a new `HirId`. let hir_id = alloc_hir_id(self); self.node_id_to_hir_id[ast_node_id] = hir_id; LoweredNodeId { @@ -573,12 +573,12 @@ impl<'a> LoweringContext<'a> { ret } - /// This method allocates a new HirId for the given NodeId and stores it in - /// the LoweringContext's NodeId => HirId map. - /// Take care not to call this method if the resulting HirId is then not + /// This method allocates a new `HirId` for the given `NodeId` and stores it in + /// the `LoweringContext`'s `NodeId => HirId` map. + /// Take care not to call this method if the resulting `HirId` is then not /// actually used in the HIR, as that would trigger an assertion in the - /// HirIdValidator later on, which makes sure that all NodeIds got mapped - /// properly. Calling the method twice with the same NodeId is fine though. + /// `HirIdValidator` later on, which makes sure that all `NodeId`s got mapped + /// properly. Calling the method twice with the same `NodeId` is fine though. fn lower_node_id(&mut self, ast_node_id: NodeId) -> LoweredNodeId { self.lower_node_id_generic(ast_node_id, |this| { let &mut (def_index, ref mut local_id_counter) = @@ -743,7 +743,7 @@ impl<'a> LoweringContext<'a> { ), }; - // Add a definition for the in-band lifetime def + // Add a definition for the in-band lifetime def. self.resolver.definitions().create_def_with_parent( parent_id.index, def_node_id, @@ -1067,7 +1067,7 @@ impl<'a> LoweringContext<'a> { fn lower_attr(&mut self, attr: &Attribute) -> Attribute { // Note that we explicitly do not walk the path. Since we don't really // lower attributes (we use the AST version) there is nowhere to keep - // the HirIds. We don't actually need HIR version of attributes anyway. + // the `HirId`s. We don't actually need HIR version of attributes anyway. Attribute { id: attr.id, style: attr.style, @@ -1246,7 +1246,7 @@ impl<'a> LoweringContext<'a> { } ImplTraitContext::Universal(in_band_ty_params) => { self.lower_node_id(def_node_id); - // Add a definition for the in-band Param + // Add a definition for the in-band `Param`. let def_index = self .resolver .definitions() @@ -1257,7 +1257,7 @@ impl<'a> LoweringContext<'a> { bounds, ImplTraitContext::Universal(in_band_ty_params), ); - // Set the name to `impl Bound1 + Bound2` + // Set the name to `impl Bound1 + Bound2`. let ident = Ident::from_str(&pprust::ty_to_string(t)).with_span_pos(span); in_band_ty_params.push(hir::GenericParam { id: def_node_id, @@ -1365,7 +1365,7 @@ impl<'a> LoweringContext<'a> { impl_trait_fn: fn_def_id, }); let exist_ty_id = lctx.lower_node_id(exist_ty_node_id); - // Generate an `existential type Foo: Trait;` declaration + // Generate an `existential type Foo: Trait;` declaration. trace!("creating existential type with id {:#?}", exist_ty_id); trace!("exist ty def index: {:#?}", exist_ty_def_index); @@ -1384,7 +1384,7 @@ impl<'a> LoweringContext<'a> { // does not actually exist in the AST. lctx.items.insert(exist_ty_id.node_id, exist_ty_item); - // `impl Trait` now just becomes `Foo<'a, 'b, ..>` + // `impl Trait` now just becomes `Foo<'a, 'b, ..>`. hir::TyKind::Def(hir::ItemId { id: exist_ty_id.node_id }, lifetimes) }) } @@ -1397,7 +1397,7 @@ impl<'a> LoweringContext<'a> { ) -> (HirVec, HirVec) { // This visitor walks over impl trait bounds and creates defs for all lifetimes which // appear in the bounds, excluding lifetimes that are created within the bounds. - // e.g. 'a, 'b, but not 'c in `impl for<'c> SomeTrait<'a, 'b, 'c>` + // E.g., `'a`, `'b`, but not `'c` in `impl for<'c> SomeTrait<'a, 'b, 'c>`. struct ImplTraitLifetimeCollector<'r, 'a: 'r> { context: &'r mut LoweringContext<'a>, parent: DefIndex, @@ -1429,7 +1429,7 @@ impl<'a> LoweringContext<'a> { } fn visit_ty(&mut self, t: &'v hir::Ty) { - // Don't collect elided lifetimes used inside of `fn()` syntax + // Don't collect elided lifetimes used inside of `fn()` syntax. if let hir::TyKind::BareFn(_) = t.node { let old_collect_elided_lifetimes = self.collect_elided_lifetimes; self.collect_elided_lifetimes = false; @@ -1459,10 +1459,10 @@ impl<'a> LoweringContext<'a> { } fn visit_generic_param(&mut self, param: &'v hir::GenericParam) { - // Record the introduction of 'a in `for<'a> ...` + // Record the introduction of 'a in `for<'a> ...`. if let hir::GenericParamKind::Lifetime { .. } = param.kind { // Introduce lifetimes one at a time so that we can handle - // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>` + // cases like `fn foo<'d>() -> impl for<'a, 'b: 'a, 'c: 'b + 'd>`. let lt_name = hir::LifetimeName::Param(param.name); self.currently_bound_lifetimes.push(lt_name); } @@ -1475,7 +1475,7 @@ impl<'a> LoweringContext<'a> { hir::LifetimeName::Implicit | hir::LifetimeName::Underscore => { if self.collect_elided_lifetimes { // Use `'_` for both implicit and underscore lifetimes in - // `abstract type Foo<'_>: SomeTrait<'_>;` + // `abstract type Foo<'_>: SomeTrait<'_>;`. hir::LifetimeName::Underscore } else { return; @@ -1648,7 +1648,7 @@ impl<'a> LoweringContext<'a> { { ParenthesizedGenericArgs::Ok } - // Avoid duplicated errors + // Avoid duplicated errors. Def::Err => ParenthesizedGenericArgs::Ok, // An error Def::Struct(..) @@ -1689,7 +1689,7 @@ impl<'a> LoweringContext<'a> { }); // Simple case, either no projections, or only fully-qualified. - // E.g. `std::mem::size_of` or `::Item`. + // E.g., `std::mem::size_of` or `::Item`. if resolution.unresolved_segments() == 0 { return hir::QPath::Resolved(qself, path); } @@ -1697,11 +1697,11 @@ impl<'a> LoweringContext<'a> { // Create the innermost type that we're projecting from. let mut ty = if path.segments.is_empty() { // If the base path is empty that means there exists a - // syntactical `Self`, e.g. `&i32` in `<&i32>::clone`. + // syntactical `Self`, e.g., `&i32` in `<&i32>::clone`. qself.expect("missing QSelf for ::...") } else { // Otherwise, the base path is an implicit `Self` type path, - // e.g. `Vec` in `Vec::new` or `::Item` in + // e.g., `Vec` in `Vec::new` or `::Item` in // `::Item::default`. let new_id = self.next_id(); P(self.ty_path(new_id, p.span, hir::QPath::Resolved(qself, path))) @@ -1709,7 +1709,7 @@ impl<'a> LoweringContext<'a> { // Anything after the base path are associated "extensions", // out of which all but the last one are associated types, - // e.g. for `std::vec::Vec::::IntoIter::Item::clone`: + // e.g., for `std::vec::Vec::::IntoIter::Item::clone`: // * base path is `std::vec::Vec` // * "extensions" are `IntoIter`, `Item` and `clone` // * type nodes are: @@ -1739,7 +1739,7 @@ impl<'a> LoweringContext<'a> { ty = P(self.ty_path(new_id, p.span, qpath)); } - // Should've returned in the for loop above. + // We should've returned in the for loop above. span_bug!( p.span, "lower_qpath: no final extension segment in {}..{}", @@ -1838,11 +1838,11 @@ impl<'a> LoweringContext<'a> { let no_bindings = generic_args.bindings.is_empty(); let (incl_angl_brckt, insertion_span, suggestion) = if no_ty_args && no_bindings { // If there are no (non-implicit) generic args or associated-type - // bindings, our suggestion includes the angle brackets + // bindings, our suggestion includes the angle brackets. (true, path_span.shrink_to_hi(), format!("<{}>", anon_lt_suggestion)) } else { // Otherwise—sorry, this is kind of gross—we need to infer the - // place to splice in the `'_, ` from the generics that do exist + // place to splice in the `'_, ` from the generics that do exist. let first_generic_span = first_generic_span .expect("already checked that type args or bindings exist"); (false, first_generic_span.shrink_to_lo(), format!("{}, ", anon_lt_suggestion)) @@ -2096,14 +2096,15 @@ impl<'a> LoweringContext<'a> { return_impl_trait_id: NodeId, ) -> hir::FunctionRetTy { // Get lifetimes used in the input arguments to the function. Our output type must also - // have the same lifetime. FIXME(cramertj) multiple different lifetimes are not allowed - // because `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither - // is a subset of the other. We really want some new lifetime that is a subset of all input - // lifetimes, but that doesn't exist at the moment. + // have the same lifetime. + // FIXME(cramertj): multiple different lifetimes are not allowed because + // `impl Trait + 'a + 'b` doesn't allow for capture `'a` and `'b` where neither is a subset + // of the other. We really want some new lifetime that is a subset of all input lifetimes, + // but that doesn't exist at the moment. struct AsyncFnLifetimeCollector<'r, 'a: 'r> { context: &'r mut LoweringContext<'a>, - // Lifetimes bound by HRTB + // Lifetimes bound by HRTB. currently_bound_lifetimes: Vec, // Whether to count elided lifetimes. // Disabled inside of `Fn` or `fn` syntax. @@ -2133,7 +2134,7 @@ impl<'a> LoweringContext<'a> { } fn visit_ty(&mut self, t: &'v hir::Ty) { - // Don't collect elided lifetimes used inside of `fn()` syntax + // Don't collect elided lifetimes used inside of `fn()` syntax. if let &hir::TyKind::BareFn(_) = &t.node { let old_collect_elided_lifetimes = self.collect_elided_lifetimes; self.collect_elided_lifetimes = false; @@ -2424,7 +2425,7 @@ impl<'a> LoweringContext<'a> { GenericParamKind::Type { ref default, .. } => { // Don't expose `Self` (recovered "keyword used as ident" parse error). // `rustc::ty` expects `Self` to be only used for a trait's `Self`. - // Instead, use gensym("Self") to create a distinct name that looks the same. + // Instead, use `gensym("Self")` to create a distinct name that looks the same. let ident = if param.ident.name == keywords::SelfUpper.name() { param.ident.gensym() } else { @@ -2467,7 +2468,7 @@ impl<'a> LoweringContext<'a> { -> hir::Generics { // Collect `?Trait` bounds in where clause and move them to parameter definitions. - // FIXME: This could probably be done with less rightward drift. Also looks like two control + // FIXME: this could probably be done with less rightward drift. Also looks like two control // paths where report_error is called are also the only paths that advance to after // the match statement, so the error reporting could probably just be moved there. let mut add_bounds: NodeMap> = Default::default(); @@ -2563,7 +2564,7 @@ impl<'a> LoweringContext<'a> { .iter() .filter_map(|bound| match *bound { // Ignore `?Trait` bounds. - // Tthey were copied into type parameters already. + // They were copied into type parameters already. GenericBound::Trait(_, TraitBoundModifier::Maybe) => None, _ => Some(this.lower_param_bound( bound, @@ -2662,7 +2663,7 @@ impl<'a> LoweringContext<'a> { id: self.lower_node_id(f.id).node_id, ident: match f.ident { Some(ident) => ident, - // FIXME(jseyfried) positional field hygiene + // FIXME(jseyfried): positional field hygiene None => Ident::new(Symbol::intern(&index.to_string()), f.span), }, vis: self.lower_visibility(&f.vis, None), @@ -2946,7 +2947,7 @@ impl<'a> LoweringContext<'a> { } // [1] `defaultness.has_value()` is never called for an `impl`, always `true` in order to - // not cause an assertion failure inside the `lower_defaultness` function + // not cause an assertion failure inside the `lower_defaultness` function. } fn lower_use_tree( @@ -3190,7 +3191,7 @@ impl<'a> LoweringContext<'a> { /// Paths like the visibility path in `pub(super) use foo::{bar, baz}` are repeated /// many times in the HIR tree; for each occurrence, we need to assign distinct - /// node-ids. (See e.g. #56128.) + /// node-ids. (See e.g., #56128.) fn renumber_segment_ids(&mut self, path: &P) -> P { debug!("renumber_segment_ids(path = {:?})", path); let mut path = path.clone(); @@ -3780,7 +3781,7 @@ impl<'a> LoweringContext<'a> { let else_opt = else_opt.as_ref().map(|els| { match els.node { ExprKind::IfLet(..) => { - // wrap the if-let expr in a block + // Wrap the `if let` expr in a block. let span = els.span; let els = P(self.lower_expr(els)); let LoweredNodeId { node_id, hir_id } = self.next_id(); @@ -3871,7 +3872,7 @@ impl<'a> LoweringContext<'a> { let fn_decl = self.lower_fn_decl(&outer_decl, None, false, None); self.with_new_scopes(|this| { - // FIXME(cramertj) allow `async` non-`move` closures with + // FIXME(cramertj): allow `async` non-`move` closures with arguments. if capture_clause == CaptureBy::Ref && !decl.inputs.is_empty() { @@ -3883,13 +3884,13 @@ impl<'a> LoweringContext<'a> { are not currently supported", ) .help("consider using `let` statements to manually capture \ - variables by reference before entering an \ - `async move` closure") + variables by reference before entering an \ + `async move` closure") .emit(); } // Transform `async |x: u8| -> X { ... }` into - // `|x: u8| future_from_generator(|| -> X { ... })` + // `|x: u8| future_from_generator(|| -> X { ... })`. let body_id = this.lower_body(Some(&outer_decl), |this| { let async_ret_ty = if let FunctionRetTy::Ty(ty) = &decl.output { Some(&**ty) @@ -3972,7 +3973,7 @@ impl<'a> LoweringContext<'a> { ExprKind::Index(ref el, ref er) => { hir::ExprKind::Index(P(self.lower_expr(el)), P(self.lower_expr(er))) } - // Desugar `..=` to `std::ops::RangeInclusive::new(, )` + // Desugar `..=` into `std::ops::RangeInclusive::new(, )`. ExprKind::Range(Some(ref e1), Some(ref e2), RangeLimits::Closed) => { let id = self.next_id(); let e1 = self.lower_expr(e1); @@ -4106,11 +4107,11 @@ impl<'a> LoweringContext<'a> { ), ExprKind::Paren(ref ex) => { let mut ex = self.lower_expr(ex); - // include parens in span, but only if it is a super-span. + // Include parens in span, but only if it is a super-span. if e.span.contains(ex.span) { ex.span = e.span; } - // merge attributes into the inner expression. + // Merge attributes into the inner expression. let mut attrs = e.attrs.clone(); attrs.extend::>(ex.attrs.into()); ex.attrs = attrs; @@ -4128,8 +4129,8 @@ impl<'a> LoweringContext<'a> { hir::ExprKind::Yield(P(expr)) } - // Desugar ExprIfLet - // From: `if let = []` + // Desugar `ExprIfLet` + // from: `if let = []` ExprKind::IfLet(ref pats, ref sub_expr, ref body, ref else_opt) => { // to: // @@ -4173,8 +4174,8 @@ impl<'a> LoweringContext<'a> { ) } - // Desugar ExprWhileLet - // From: `[opt_ident]: while let = ` + // Desugar `ExprWhileLet` + // from: `[opt_ident]: while let = ` ExprKind::WhileLet(ref pats, ref sub_expr, ref body, opt_label) => { // to: // @@ -4223,12 +4224,12 @@ impl<'a> LoweringContext<'a> { self.lower_label(opt_label), hir::LoopSource::WhileLet, ); - // add attributes to the outer returned expr node + // Add attributes to the outer returned expr node. loop_expr } - // Desugar ExprForLoop - // From: `[opt_ident]: for in ` + // Desugar `ExprForLoop` + // from: `[opt_ident]: for in ` ExprKind::ForLoop(ref pat, ref head, ref body, opt_label) => { // to: // @@ -4386,21 +4387,21 @@ impl<'a> LoweringContext<'a> { )); // `{ let _result = ...; _result }` - // underscore prevents an unused_variables lint if the head diverges + // Underscore prevents an `unused_variables` lint if the head diverges. let result_ident = self.str_to_ident("_result"); let (let_stmt, let_stmt_binding) = self.stmt_let(e.span, false, result_ident, match_expr); let result = P(self.expr_ident(e.span, result_ident, let_stmt_binding)); let block = P(self.block_all(e.span, hir_vec![let_stmt], Some(result))); - // add the attributes to the outer returned expr node + // Add the attributes to the outer returned expr node. return self.expr_block(block, e.attrs.clone()); } - // Desugar ExprKind::Try - // From: `?` + // Desugar `ExprKind::Try` + // from: `?` ExprKind::Try(ref sub_expr) => { - // to: + // into: // // match Try::into_result() { // Ok(val) => #[allow(unreachable_code)] val, @@ -4414,7 +4415,7 @@ impl<'a> LoweringContext<'a> { let unstable_span = self.allow_internal_unstable(CompilerDesugaringKind::QuestionMark, e.span); - // Try::into_result() + // `Try::into_result()` let discr = { // expand let sub_expr = self.lower_expr(sub_expr); @@ -4425,9 +4426,9 @@ impl<'a> LoweringContext<'a> { P(self.expr_call(e.span, path, hir_vec![sub_expr])) }; - // #[allow(unreachable_code)] + // `#[allow(unreachable_code)]` let attr = { - // allow(unreachable_code) + // `allow(unreachable_code)` let allow = { let allow_ident = Ident::from_str("allow").with_span_pos(e.span); let uc_ident = Ident::from_str("unreachable_code").with_span_pos(e.span); @@ -4438,7 +4439,7 @@ impl<'a> LoweringContext<'a> { }; let attrs = vec![attr]; - // Ok(val) => #[allow(unreachable_code)] val, + // `Ok(val) => #[allow(unreachable_code)] val,` let ok_arm = { let val_ident = self.str_to_ident("val"); let val_pat = self.pat_ident(e.span, val_ident); @@ -4453,8 +4454,8 @@ impl<'a> LoweringContext<'a> { self.arm(hir_vec![ok_pat], val_expr) }; - // Err(err) => #[allow(unreachable_code)] - // return Try::from_error(From::from(err)), + // `Err(err) => #[allow(unreachable_code)] + // return Try::from_error(From::from(err)),` let err_arm = { let err_ident = self.str_to_ident("err"); let err_local = self.pat_ident(e.span, err_ident); @@ -5014,7 +5015,7 @@ impl<'a> LoweringContext<'a> { /// error, depending on the mode. fn elided_path_lifetimes(&mut self, span: Span, count: usize) -> P<[hir::Lifetime]> { match self.anonymous_lifetime_mode { - // NB. We intentionally ignore the create-parameter mode here + // N.B., We intentionally ignore the create-parameter mode here // and instead "pass through" to resolve-lifetimes, which will then // report an error. This is because we don't want to support // impl elision for deprecated forms like diff --git a/src/librustc/hir/map/blocks.rs b/src/librustc/hir/map/blocks.rs index 1ab1c7d3fc5..40904eaa5db 100644 --- a/src/librustc/hir/map/blocks.rs +++ b/src/librustc/hir/map/blocks.rs @@ -13,7 +13,7 @@ //! it captures a common set of attributes that all "function-like //! things" (represented by `FnLike` instances) share. For example, //! all `FnLike` instances have a type signature (be it explicit or -//! inferred). And all `FnLike` instances have a body, i.e. the code +//! inferred). And all `FnLike` instances have a body, i.e., the code //! that is run when the function-like thing it represents is invoked. //! //! With the above abstraction in place, one can treat the program @@ -34,7 +34,7 @@ use syntax_pos::Span; /// More specifically, it is one of either: /// /// - A function item, -/// - A closure expr (i.e. an ExprKind::Closure), or +/// - A closure expr (i.e., an ExprKind::Closure), or /// - The default implementation for a trait method. /// /// To construct one, use the `Code::from_node` function. diff --git a/src/librustc/hir/map/definitions.rs b/src/librustc/hir/map/definitions.rs index eb9bd183fd9..d5031efae57 100644 --- a/src/librustc/hir/map/definitions.rs +++ b/src/librustc/hir/map/definitions.rs @@ -150,10 +150,9 @@ impl Decodable for DefPathTable { } } - /// The definition table containing node definitions. -/// It holds the DefPathTable for local DefIds/DefPaths and it also stores a -/// mapping from NodeIds to local DefIds. +/// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a +/// mapping from `NodeId`s to local `DefId`s. #[derive(Clone, Default)] pub struct Definitions { table: DefPathTable, diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 99c92e1e31d..b98e279aef4 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -286,9 +286,7 @@ impl<'hir> Map<'hir> { match node { Node::Item(item) => { - let def_id = || { - self.local_def_id(item.id) - }; + let def_id = || self.local_def_id(item.id); match item.node { ItemKind::Static(_, m, _) => Some(Def::Static(def_id(), m == MutMutable)), @@ -383,7 +381,7 @@ impl<'hir> Map<'hir> { pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem { self.read(id.node_id); - // NB: intentionally bypass `self.forest.krate()` so that we + // N.B., intentionally bypass `self.forest.krate()` so that we // do not trigger a read of the whole krate here self.forest.krate.trait_item(id) } @@ -391,7 +389,7 @@ impl<'hir> Map<'hir> { pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem { self.read(id.node_id); - // NB: intentionally bypass `self.forest.krate()` so that we + // N.B., intentionally bypass `self.forest.krate()` so that we // do not trigger a read of the whole krate here self.forest.krate.impl_item(id) } @@ -399,7 +397,7 @@ impl<'hir> Map<'hir> { pub fn body(&self, id: BodyId) -> &'hir Body { self.read(id.node_id); - // NB: intentionally bypass `self.forest.krate()` so that we + // N.B., intentionally bypass `self.forest.krate()` so that we // do not trigger a read of the whole krate here self.forest.krate.body(id) } @@ -413,7 +411,7 @@ impl<'hir> Map<'hir> { } /// Returns the `NodeId` that corresponds to the definition of - /// which this is the body of, i.e. a `fn`, `const` or `static` + /// which this is the body of, i.e., a `fn`, `const` or `static` /// item (possibly associated), a closure, or a `hir::AnonConst`. pub fn body_owner(&self, BodyId { node_id }: BodyId) -> NodeId { let parent = self.get_parent_node(node_id); @@ -484,7 +482,7 @@ impl<'hir> Map<'hir> { pub fn trait_impls(&self, trait_did: DefId) -> &'hir [NodeId] { self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls)); - // NB: intentionally bypass `self.forest.krate()` so that we + // N.B., intentionally bypass `self.forest.krate()` so that we // do not trigger a read of the whole krate here self.forest.krate.trait_impls.get(&trait_did).map_or(&[], |xs| &xs[..]) } @@ -492,7 +490,7 @@ impl<'hir> Map<'hir> { pub fn trait_auto_impl(&self, trait_did: DefId) -> Option { self.dep_graph.read(DepNode::new_no_params(DepKind::AllLocalTraitImpls)); - // NB: intentionally bypass `self.forest.krate()` so that we + // N.B., intentionally bypass `self.forest.krate()` so that we // do not trigger a read of the whole krate here self.forest.krate.trait_auto_impl.get(&trait_did).cloned() } @@ -565,14 +563,14 @@ impl<'hir> Map<'hir> { result } - /// Similar to get_parent, returns the parent node id or id if there is no - /// parent. Note that the parent may be CRATE_NODE_ID, which is not itself + /// Similar to `get_parent`; returns the parent node-id, or own `id` if there is + /// no parent. Note that the parent may be `CRATE_NODE_ID`, which is not itself /// present in the map -- so passing the return value of get_parent_node to /// get may actually panic. /// This function returns the immediate parent in the AST, whereas get_parent /// returns the enclosing item. Note that this might not be the actual parent /// node in the AST - some kinds of nodes are not in the map and these will - /// never appear as the parent_node. So you can always walk the parent_nodes + /// never appear as the parent_node. So you can always walk the `parent_nodes` /// from a node to the root of the ast (unless you get the same id back here /// that can happen if the id is not in the map itself or is just weird). pub fn get_parent_node(&self, id: NodeId) -> NodeId { @@ -608,7 +606,7 @@ impl<'hir> Map<'hir> { /// If there is some error when walking the parents (e.g., a node does not /// have a parent in the map or a node can't be found), then we return the - /// last good node id we found. Note that reaching the crate root (id == 0), + /// last good node id we found. Note that reaching the crate root (`id == 0`), /// is not an error, since items in the crate module have the crate root as /// parent. fn walk_parent_nodes(&self, @@ -644,7 +642,7 @@ impl<'hir> Map<'hir> { } } - /// Retrieve the NodeId for `id`'s enclosing method, unless there's a + /// Retrieve the `NodeId` for `id`'s enclosing method, unless there's a /// `while` or `loop` before reaching it, as block tail returns are not /// available in them. /// @@ -691,7 +689,7 @@ impl<'hir> Map<'hir> { self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok() } - /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no + /// Retrieve the `NodeId` for `id`'s parent item, or `id` itself if no /// parent item is in this map. The "parent item" is the closest parent node /// in the HIR which is recorded by the map and is an item, either an item /// in a module, trait, or impl. @@ -708,13 +706,13 @@ impl<'hir> Map<'hir> { } } - /// Returns the DefId of `id`'s nearest module parent, or `id` itself if no + /// Returns the `DefId` of `id`'s nearest module parent, or `id` itself if no /// module parent is in this map. pub fn get_module_parent(&self, id: NodeId) -> DefId { self.local_def_id(self.get_module_parent_node(id)) } - /// Returns the NodeId of `id`'s nearest module parent, or `id` itself if no + /// Returns the `NodeId` of `id`'s nearest module parent, or `id` itself if no /// module parent is in this map. pub fn get_module_parent_node(&self, id: NodeId) -> NodeId { match self.walk_parent_nodes(id, |node| match *node { @@ -727,7 +725,7 @@ impl<'hir> Map<'hir> { } /// Returns the nearest enclosing scope. A scope is an item or block. - /// FIXME it is not clear to me that all items qualify as scopes - statics + /// FIXME: it is not clear to me that all items qualify as scopes -- statics /// and associated types probably shouldn't, for example. Behavior in this /// regard should be expected to be highly unstable. pub fn get_enclosing_scope(&self, id: NodeId) -> Option { diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 85bf257df23..156d55b9e2f 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -8,7 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// The Rust HIR. +// HIR datatypes. See the [rustc guide] for more info. +//! +//! [rustc guide]: https://rust-lang.github.io/rustc-guide/hir.html pub use self::BlockCheckMode::*; pub use self::CaptureClause::*; @@ -71,7 +73,7 @@ pub mod print; /// A HirId uniquely identifies a node in the HIR of the current crate. It is /// composed of the `owner`, which is the DefIndex of the directly enclosing -/// hir::Item, hir::TraitItem, or hir::ImplItem (i.e. the closest "item-like"), +/// hir::Item, hir::TraitItem, or hir::ImplItem (i.e., the closest "item-like"), /// and the `local_id` which is unique within the given owner. /// /// This two-level structure makes for more stable values: One can move an item @@ -181,7 +183,7 @@ pub enum ParamName { Plain(Ident), /// Synthetic name generated when user elided a lifetime in an impl header, - /// e.g. the lifetimes in cases like these: + /// e.g., the lifetimes in cases like these: /// /// impl Foo for &u32 /// impl Foo<'_> for u32 @@ -197,7 +199,7 @@ pub enum ParamName { /// Indicates an illegal name was given and an error has been /// repored (so we should squelch other derived errors). Occurs - /// when e.g. `'_` is used in the wrong place. + /// when e.g., `'_` is used in the wrong place. Error, } @@ -222,7 +224,7 @@ pub enum LifetimeName { /// User-given names or fresh (synthetic) names. Param(ParamName), - /// User typed nothing. e.g. the lifetime in `&u32`. + /// User typed nothing. e.g., the lifetime in `&u32`. Implicit, /// Indicates an error during lowering (usually `'_` in wrong place) @@ -351,7 +353,7 @@ pub struct PathSegment { /// Whether to infer remaining type parameters, if any. /// This only applies to expression and pattern paths, and /// out of those only the segments with no type parameters - /// to begin with, e.g. `Vec::new` is `>::new::<..>`. + /// to begin with, e.g., `Vec::new` is `>::new::<..>`. pub infer_types: bool, } @@ -388,7 +390,7 @@ impl PathSegment { } // FIXME: hack required because you can't create a static - // GenericArgs, so you can't just return a &GenericArgs. + // `GenericArgs`, so you can't just return a `&GenericArgs`. pub fn with_generic_args(&self, f: F) -> R where F: FnOnce(&GenericArgs) -> R { @@ -514,17 +516,17 @@ pub type GenericBounds = HirVec; #[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)] pub enum LifetimeParamKind { - // Indicates that the lifetime definition was explicitly declared, like: - // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }` + // Indicates that the lifetime definition was explicitly declared (e.g., in + // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`). Explicit, // Indicates that the lifetime definition was synthetically added - // as a result of an in-band lifetime usage like: - // `fn foo(x: &'a u8) -> &'a u8 { x }` + // as a result of an in-band lifetime usage (e.g., in + // `fn foo(x: &'a u8) -> &'a u8 { x }`). InBand, - // Indication that the lifetime was elided like both cases here: - // `fn foo(x: &u8) -> &'_ u8 { x }` + // Indication that the lifetime was elided (e.g., in both cases in + // `fn foo(x: &u8) -> &'_ u8 { x }`). Elided, // Indication that the lifetime name was somehow in error. @@ -533,7 +535,7 @@ pub enum LifetimeParamKind { #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericParamKind { - /// A lifetime definition, eg `'a: 'b + 'c + 'd`. + /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). Lifetime { kind: LifetimeParamKind, }, @@ -637,11 +639,11 @@ impl WhereClause { /// A single predicate in a `where` clause #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum WherePredicate { - /// A type binding, eg `for<'c> Foo: Send+Clone+'c` + /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`). BoundPredicate(WhereBoundPredicate), - /// A lifetime predicate, e.g. `'a: 'b+'c` + /// A lifetime predicate (e.g., `'a: 'b + 'c`). RegionPredicate(WhereRegionPredicate), - /// An equality predicate (unsupported) + /// An equality predicate (unsupported). EqPredicate(WhereEqPredicate), } @@ -667,7 +669,7 @@ pub struct WhereBoundPredicate { pub bounds: GenericBounds, } -/// A lifetime predicate, e.g. `'a: 'b+'c` +/// A lifetime predicate, e.g., `'a: 'b+'c` #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereRegionPredicate { pub span: Span, @@ -675,7 +677,7 @@ pub struct WhereRegionPredicate { pub bounds: GenericBounds, } -/// An equality predicate (unsupported), e.g. `T=int` +/// An equality predicate (unsupported), e.g., `T=int` #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereEqPredicate { pub id: NodeId, @@ -697,7 +699,7 @@ pub struct Crate { pub span: Span, pub exported_macros: HirVec, - // NB: We use a BTreeMap here so that `visit_all_items` iterates + // N.B., we use a BTreeMap here so that `visit_all_items` iterates // over the ids in increasing order. In principle it should not // matter what order we visit things in, but in *practice* it // does, because it can affect the order in which errors are @@ -932,11 +934,11 @@ pub enum PatKind { /// A fresh binding `ref mut binding @ OPT_SUBPATTERN`. /// The `NodeId` is the canonical ID for the variable being bound, - /// e.g. in `Ok(x) | Err(x)`, both `x` use the same canonical ID, + /// e.g., in `Ok(x) | Err(x)`, both `x` use the same canonical ID, /// which is the pattern ID of the first `x`. Binding(BindingAnnotation, NodeId, Ident, Option>), - /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`. + /// A struct or struct variant pattern, e.g., `Variant {x, y, ..}`. /// The `bool` is `true` in the presence of a `..`. Struct(QPath, HirVec>, bool), @@ -954,11 +956,11 @@ pub enum PatKind { Tuple(HirVec>, Option), /// A `box` pattern Box(P), - /// A reference pattern, e.g. `&mut (a, b)` + /// A reference pattern, e.g., `&mut (a, b)` Ref(P, Mutability), /// A literal Lit(P), - /// A range pattern, e.g. `1...2` or `1..2` + /// A range pattern, e.g., `1...2` or `1..2` Range(P, P, RangeEnd), /// `[a, b, ..i, y, z]` is represented as: /// `PatKind::Slice(box [a, b], Some(i), box [y, z])` @@ -1319,8 +1321,8 @@ pub enum BodyOwnerKind { /// A constant (expression) that's not an item or associated item, /// but needs its own `DefId` for type-checking, const-eval, etc. -/// These are usually found nested inside types (e.g. array lengths) -/// or expressions (e.g. repeat counts), and also used to define +/// These are usually found nested inside types (e.g., array lengths) +/// or expressions (e.g., repeat counts), and also used to define /// explicit discriminant values for enum variants. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Debug)] pub struct AnonConst { @@ -1541,12 +1543,12 @@ pub enum QPath { /// Path to a definition, optionally "fully-qualified" with a `Self` /// type, if the path points to an associated item in a trait. /// - /// E.g. an unqualified path like `Clone::clone` has `None` for `Self`, + /// e.g., an unqualified path like `Clone::clone` has `None` for `Self`, /// while ` as Clone>::clone` has `Some(Vec)` for `Self`, /// even though they both have the same two-segment `Clone::clone` `Path`. Resolved(Option>, P), - /// Type-related paths, e.g. `::default` or `::Output`. + /// Type-related paths, e.g., `::default` or `::Output`. /// Will be resolved by type-checking to an associated item. /// /// UFCS source paths can desugar into this, with `Vec::new` turning into @@ -1633,7 +1635,7 @@ pub enum CaptureClause { CaptureByRef, } -// NB: If you change this, you'll probably want to change the corresponding +// N.B., if you change this, you'll probably want to change the corresponding // type structure in middle/ty.rs as well. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct MutTy { @@ -1792,14 +1794,14 @@ pub enum TyKind { Ptr(MutTy), /// A reference (`&'a T` or `&'a mut T`) Rptr(Lifetime, MutTy), - /// A bare function (e.g. `fn(usize) -> bool`) + /// A bare function (e.g., `fn(usize) -> bool`) BareFn(P), /// The never type (`!`) Never, /// A tuple (`(A, B, C, D,...)`) Tup(HirVec), /// A path to a type definition (`module::module::...::Type`), or an - /// associated type, e.g. ` as Trait>::Type` or `::Target`. + /// associated type, e.g., ` as Trait>::Type` or `::Target`. /// /// Type parameters may be stored in each `PathSegment`. Path(QPath), @@ -1814,7 +1816,7 @@ pub enum TyKind { TraitObject(HirVec, Lifetime), /// Unused for now Typeof(AnonConst), - /// TyKind::Infer means the type should be inferred instead of it having been + /// `TyKind::Infer` means the type should be inferred instead of it having been /// specified. This can appear anywhere in a type. Infer, /// Placeholder for a type that has failed to be defined. @@ -2017,7 +2019,7 @@ pub struct VariantKind { pub name: Name, pub attrs: HirVec, pub data: VariantData, - /// Explicit discriminant, eg `Foo = 1` + /// Explicit discriminant, e.g., `Foo = 1` pub disr_expr: Option, } @@ -2025,15 +2027,15 @@ pub type Variant = Spanned; #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum UseKind { - /// One import, e.g. `use foo::bar` or `use foo::bar as baz`. + /// One import, e.g., `use foo::bar` or `use foo::bar as baz`. /// Also produced for each element of a list `use`, e.g. // `use foo::{a, b}` lowers to `use foo::a; use foo::b;`. Single, - /// Glob import, e.g. `use foo::*`. + /// Glob import, e.g., `use foo::*`. Glob, - /// Degenerate list import, e.g. `use foo::{a, b}` produces + /// Degenerate list import, e.g., `use foo::{a, b}` produces /// an additional `use foo::{}` for performing checks such as /// unstable feature gating. May be removed in the future. ListStem, @@ -2196,7 +2198,7 @@ pub struct FnHeader { pub enum ItemKind { /// An `extern crate` item, with optional *original* crate name if the crate was renamed. /// - /// E.g. `extern crate foo` or `extern crate foo_bar as foo` + /// e.g., `extern crate foo` or `extern crate foo_bar as foo` ExternCrate(Option), /// `use foo::bar::*;` or `use foo::bar::baz as quux;` @@ -2218,15 +2220,15 @@ pub enum ItemKind { ForeignMod(ForeignMod), /// Module-level inline assembly (from global_asm!) GlobalAsm(P), - /// A type alias, e.g. `type Foo = Bar` + /// A type alias, e.g., `type Foo = Bar` Ty(P, Generics), - /// An existential type definition, e.g. `existential type Foo: Bar;` + /// An existential type definition, e.g., `existential type Foo: Bar;` Existential(ExistTy), - /// An enum definition, e.g. `enum Foo {C, D}` + /// An enum definition, e.g., `enum Foo {C, D}` Enum(EnumDef, Generics), - /// A struct definition, e.g. `struct Foo {x: A}` + /// A struct definition, e.g., `struct Foo {x: A}` Struct(VariantData, Generics), - /// A union definition, e.g. `union Foo {x: A, y: B}` + /// A union definition, e.g., `union Foo {x: A, y: B}` Union(VariantData, Generics), /// Represents a Trait Declaration Trait(IsAuto, Unsafety, Generics, GenericBounds, HirVec), diff --git a/src/librustc/hir/pat_util.rs b/src/librustc/hir/pat_util.rs index 8a714a5fbd8..d6816d3b81b 100644 --- a/src/librustc/hir/pat_util.rs +++ b/src/librustc/hir/pat_util.rs @@ -101,7 +101,7 @@ impl hir::Pat { } /// Checks if the pattern contains any patterns that bind something to - /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`. + /// an ident, e.g., `foo`, or `Foo(foo)` or `foo @ Bar(..)`. pub fn contains_bindings(&self) -> bool { let mut contains_bindings = false; self.walk(|p| { @@ -116,7 +116,7 @@ impl hir::Pat { } /// Checks if the pattern contains any patterns that bind something to - /// an ident or wildcard, e.g. `foo`, or `Foo(_)`, `foo @ Bar(..)`, + /// an ident or wildcard, e.g., `foo`, or `Foo(_)`, `foo @ Bar(..)`, pub fn contains_bindings_or_wild(&self) -> bool { let mut contains_bindings = false; self.walk(|p| { diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 484722f8c13..a24f2fa4bc6 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -2448,8 +2448,8 @@ fn bin_op_to_assoc_op(op: hir::BinOpKind) -> AssocOp { } } -/// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any -/// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and +/// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any +/// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not. fn contains_exterior_struct_lit(value: &hir::Expr) -> bool { match value.node { diff --git a/src/librustc/ich/hcx.rs b/src/librustc/ich/hcx.rs index 7c623a1874e..2e56308daf7 100644 --- a/src/librustc/ich/hcx.rs +++ b/src/librustc/ich/hcx.rs @@ -45,7 +45,7 @@ fn compute_ignored_attr_names() -> FxHashSet { /// This is the context state available during incr. comp. hashing. It contains /// enough information to transform DefIds and HirIds into stable DefPaths (i.e. /// a reference to the TyCtxt) and it holds a few caches for speeding up various -/// things (e.g. each DefId/DefPath is only hashed once). +/// things (e.g., each DefId/DefPath is only hashed once). #[derive(Clone)] pub struct StableHashingContext<'a> { sess: &'a Session, diff --git a/src/librustc/infer/combine.rs b/src/librustc/infer/combine.rs index f13210926a7..f124623becd 100644 --- a/src/librustc/infer/combine.rs +++ b/src/librustc/infer/combine.rs @@ -371,7 +371,7 @@ impl<'cx, 'gcx, 'tcx> TypeRelation<'cx, 'gcx, 'tcx> for Generalizer<'cx, 'gcx, ' if self.ambient_variance == ty::Variance::Invariant { // Avoid fetching the variance if we are in an invariant // context; no need, and it can induce dependency cycles - // (e.g. #41849). + // (e.g., #41849). relate::relate_substs(self, None, a_subst, b_subst) } else { let opt_variances = self.tcx().variances_of(item_def_id); diff --git a/src/librustc/infer/equate.rs b/src/librustc/infer/equate.rs index c7b5ddb8341..27faa4587f3 100644 --- a/src/librustc/infer/equate.rs +++ b/src/librustc/infer/equate.rs @@ -47,9 +47,9 @@ impl<'combine, 'infcx, 'gcx, 'tcx> TypeRelation<'infcx, 'gcx, 'tcx> b_subst: &'tcx Substs<'tcx>) -> RelateResult<'tcx, &'tcx Substs<'tcx>> { - // NB: Once we are equating types, we don't care about + // N.B., once we are equating types, we don't care about // variance, so don't try to lookup the variance here. This - // also avoids some cycles (e.g. #41849) since looking up + // also avoids some cycles (e.g., #41849) since looking up // variance requires computing types which can require // performing trait matching (which then performs equality // unification). diff --git a/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs b/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs index 38363be4827..df0dcbed30a 100644 --- a/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs +++ b/src/librustc/infer/error_reporting/nice_region_error/find_anon_type.rs @@ -30,7 +30,7 @@ impl<'a, 'gcx, 'tcx> NiceRegionError<'a, 'gcx, 'tcx> { /// { x.push(y); } /// ``` /// The function returns the nested type corresponding to the anonymous region - /// for e.g. `&u8` and Vec<`&u8`. + /// for e.g., `&u8` and Vec<`&u8`. pub(super) fn find_anon_type( &self, region: Region<'tcx>, @@ -97,7 +97,7 @@ struct FindNestedTypeVisitor<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { // associated with the anonymous region we are looking for. bound_region: ty::BoundRegion, // The type where the anonymous lifetime appears - // for e.g. Vec<`&u8`> and <`&u8`> + // for e.g., Vec<`&u8`> and <`&u8`> found_type: Option<&'gcx hir::Ty>, current_index: ty::DebruijnIndex, } diff --git a/src/librustc/infer/higher_ranked/mod.rs b/src/librustc/infer/higher_ranked/mod.rs index cf91b858076..c8cd11c8198 100644 --- a/src/librustc/infer/higher_ranked/mod.rs +++ b/src/librustc/infer/higher_ranked/mod.rs @@ -542,7 +542,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { /// Pops the placeholder regions found in `placeholder_map` from the region /// inference context. Whenever you create placeholder regions via /// `replace_bound_vars_with_placeholders`, they must be popped before you - /// commit the enclosing snapshot (if you do not commit, e.g. within a + /// commit the enclosing snapshot (if you do not commit, e.g., within a /// probe or as a result of an error, then this is not necessary, as /// popping happens as part of the rollback). /// diff --git a/src/librustc/infer/mod.rs b/src/librustc/infer/mod.rs index d8beae45b0a..b1a13354b7c 100644 --- a/src/librustc/infer/mod.rs +++ b/src/librustc/infer/mod.rs @@ -219,7 +219,7 @@ pub struct InferCtxt<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { /// `UniverseIndex::root()` but grows from there as we enter /// universal quantifiers. /// - /// NB: At present, we exclude the universal quantifiers on the + /// N.B., at present, we exclude the universal quantifiers on the /// item we are type-checking, and just consider those names as /// part of the root universe. So this would only get incremented /// when we enter into a higher-ranked (`for<..>`) type or trait @@ -732,7 +732,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { region_obligations_snapshot: self.region_obligations.borrow().len(), universe: self.universe(), was_in_snapshot: in_snapshot, - // Borrow tables "in progress" (i.e. during typeck) + // Borrow tables "in progress" (i.e., during typeck) // to ban writes from within a snapshot to them. _in_progress_tables: self.in_progress_tables.map(|tables| tables.borrow()), } @@ -1047,7 +1047,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { // type parameter definition. The substitutions are // for actual parameters that may be referred to by // the default of this type parameter, if it exists. - // E.g. `struct Foo(...);` when + // e.g., `struct Foo(...);` when // used in a path such as `Foo::::new()` will // use an inference variable for `C` with `[T, U]` // as the substitutions for the default, `(T, U)`. @@ -1261,7 +1261,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { * Where possible, replaces type/int/float variables in * `value` with their final value. Note that region variables * are unaffected. If a type variable has not been unified, it - * is left as is. This is an idempotent operation that does + * is left as is. This is an idempotent operation that does * not affect inference state in any way and so you can do it * at will. */ @@ -1298,7 +1298,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { /*! * Attempts to resolve all type/region variables in * `value`. Region inference must have been run already (e.g., - * by calling `resolve_regions_and_report_errors`). If some + * by calling `resolve_regions_and_report_errors`). If some * variable was never unified, an `Err` results. * * This method is idempotent, but it not typically not invoked @@ -1331,7 +1331,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { let actual_ty = self.resolve_type_vars_if_possible(&actual_ty); debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty); - // Don't report an error if actual type is Error. + // Don't report an error if actual type is `Error`. if actual_ty.references_error() { return self.tcx.sess.diagnostic().struct_dummy(); } diff --git a/src/librustc/infer/nll_relate/mod.rs b/src/librustc/infer/nll_relate/mod.rs index 972ba16f7e2..773c7129722 100644 --- a/src/librustc/infer/nll_relate/mod.rs +++ b/src/librustc/infer/nll_relate/mod.rs @@ -15,7 +15,7 @@ //! //! Here are the key differences: //! -//! - This code may choose to bypass some checks (e.g. the occurs check) +//! - This code may choose to bypass some checks (e.g., the occurs check) //! in the case where we know that there are no unbound type inference //! variables. This is the case for NLL, because at NLL time types are fully //! inferred up-to regions. @@ -97,7 +97,7 @@ pub trait TypeRelatingDelegate<'tcx> { /// region that is instantiated existentially. This creates an /// inference variable, typically. /// - /// So e.g. if you have `for<'a> fn(..) <: for<'b> fn(..)`, then + /// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then /// we will invoke this method to instantiate `'a` with an /// inference variable (though `'b` would be instantiated first, /// as a placeholder). @@ -107,7 +107,7 @@ pub trait TypeRelatingDelegate<'tcx> { /// higher-ranked region that is instantiated universally. /// This creates a new region placeholder, typically. /// - /// So e.g. if you have `for<'a> fn(..) <: for<'b> fn(..)`, then + /// So e.g., if you have `for<'a> fn(..) <: for<'b> fn(..)`, then /// we will invoke this method to instantiate `'b` with a /// placeholder region. fn next_placeholder_region(&mut self, placeholder: ty::PlaceholderRegion) -> ty::Region<'tcx>; diff --git a/src/librustc/infer/opaque_types/mod.rs b/src/librustc/infer/opaque_types/mod.rs index 09053118f69..44c5fe5acaa 100644 --- a/src/librustc/infer/opaque_types/mod.rs +++ b/src/librustc/infer/opaque_types/mod.rs @@ -761,7 +761,7 @@ impl<'a, 'gcx, 'tcx> Instantiator<'a, 'gcx, 'tcx> { ); // Use the same type variable if the exact same Opaque appears more - // than once in the return type (e.g. if it's passed to a type alias). + // than once in the return type (e.g., if it's passed to a type alias). if let Some(opaque_defn) = self.opaque_types.get(&def_id) { return opaque_defn.concrete_ty; } @@ -783,7 +783,7 @@ impl<'a, 'gcx, 'tcx> Instantiator<'a, 'gcx, 'tcx> { ); // make sure that we are in fact defining the *entire* type - // e.g. `existential type Foo: Bar;` needs to be + // e.g., `existential type Foo: Bar;` needs to be // defined by a function like `fn foo() -> Foo`. debug!( "instantiate_opaque_types: param_env: {:#?}", diff --git a/src/librustc/infer/outlives/obligations.rs b/src/librustc/infer/outlives/obligations.rs index 502a5828f3e..7b21a6992a7 100644 --- a/src/librustc/infer/outlives/obligations.rs +++ b/src/librustc/infer/outlives/obligations.rs @@ -408,7 +408,7 @@ where // Remove outlives bounds that we get from the environment but // which are also deducable from the trait. This arises (cc - // #55756) in cases where you have e.g. `>::Item: + // #55756) in cases where you have e.g., `>::Item: // 'a` in the environment but `trait Foo<'b> { type Item: 'b // }` in the trait definition. approx_env_bounds.retain(|bound| { diff --git a/src/librustc/infer/region_constraints/mod.rs b/src/librustc/infer/region_constraints/mod.rs index af1b6964b81..9cac73dfab0 100644 --- a/src/librustc/infer/region_constraints/mod.rs +++ b/src/librustc/infer/region_constraints/mod.rs @@ -60,7 +60,7 @@ pub struct RegionConstraintCollector<'tcx> { /// which can never be rolled back. undo_log: Vec>, - /// The number of open snapshots, i.e. those that haven't been committed or + /// The number of open snapshots, i.e., those that haven't been committed or /// rolled back. num_open_snapshots: usize, @@ -607,7 +607,7 @@ impl<'tcx> RegionConstraintCollector<'tcx> { // never overwrite an existing (constraint, origin) - only insert one if it isn't // present in the map yet. This prevents origins from outside the snapshot being - // replaced with "less informative" origins e.g. during calls to `can_eq` + // replaced with "less informative" origins e.g., during calls to `can_eq` let in_snapshot = self.in_snapshot(); let undo_log = &mut self.undo_log; self.data.constraints.entry(constraint).or_insert_with(|| { diff --git a/src/librustc/infer/type_variable.rs b/src/librustc/infer/type_variable.rs index 5624961ea6e..b7aac23b955 100644 --- a/src/librustc/infer/type_variable.rs +++ b/src/librustc/infer/type_variable.rs @@ -175,7 +175,7 @@ impl<'tcx> TypeVariableTable<'tcx> { /// Creates a new type variable. /// /// - `diverging`: indicates if this is a "diverging" type - /// variable, e.g. one created as the type of a `return` + /// variable, e.g., one created as the type of a `return` /// expression. The code in this module doesn't care if a /// variable is diverging, but the main Rust type-checker will /// sometimes "unify" such variables with the `!` or `()` types. diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index ddb0c5bf22a..4324cfc7b5f 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -119,7 +119,7 @@ extern crate test; #[macro_use] mod macros; -// NB: This module needs to be declared first so diagnostics are +// N.B., this module needs to be declared first so diagnostics are // registered before they are used. pub mod diagnostics; diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 22f2023eefb..a09d167f217 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -174,7 +174,7 @@ declare_lint! { declare_lint! { pub LEGACY_DIRECTORY_OWNERSHIP, Deny, - "non-inline, non-`#[path]` modules (e.g. `mod foo;`) were erroneously allowed in some files \ + "non-inline, non-`#[path]` modules (e.g., `mod foo;`) were erroneously allowed in some files \ not named `mod.rs`" } @@ -366,7 +366,7 @@ pub mod parser { } /// Does nothing as a lint pass, but registers some `Lint`s -/// which are used by other parts of the compiler. +/// that are used by other parts of the compiler. #[derive(Copy, Clone)] pub struct HardwiredLints; diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index c633c0fb036..449f8e0a2db 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -1270,7 +1270,7 @@ pub fn check_ast_crate( // // Rustdoc runs everybody-loops before the early lints and removes // function bodies, so it's totally possible for linted - // node ids to not exist (e.g. macros defined within functions for the + // node ids to not exist (e.g., macros defined within functions for the // unused_macro lint) anymore. So we only run this check // when we're not in rustdoc mode. (see issue #47639) if !sess.opts.actually_rustdoc { diff --git a/src/librustc/lint/levels.rs b/src/librustc/lint/levels.rs index cfb9f04c4c6..06e3e0bab4f 100644 --- a/src/librustc/lint/levels.rs +++ b/src/librustc/lint/levels.rs @@ -66,7 +66,7 @@ impl LintLevelSets { for &(ref lint_name, level) in &sess.opts.lint_opts { store.check_lint_name_cmdline(sess, &lint_name, level); - // If the cap is less than this specified level, e.g. if we've got + // If the cap is less than this specified level, e.g., if we've got // `--cap-lints allow` but we've also got `-D foo` then we ignore // this specification as the lint cap will set it to allow anyway. let level = cmp::min(level, self.lint_cap); @@ -191,7 +191,7 @@ impl<'a> LintLevelsBuilder<'a> { /// * It'll validate all lint-related attributes in `attrs` /// * It'll mark all lint-related attributes as used /// * Lint levels will be updated based on the attributes provided - /// * Lint attributes are validated, e.g. a #[forbid] can't be switched to + /// * Lint attributes are validated, e.g., a #[forbid] can't be switched to /// #[allow] /// /// Don't forget to call `pop`! diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index f54fdf8b468..7a8aa7e362a 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -67,7 +67,7 @@ pub struct Lint { /// `declare_lint!()` invocations to follow the convention of upper-case /// statics without repeating the name. /// - /// The name is written with underscores, e.g. "unused_imports". + /// The name is written with underscores, e.g., "unused_imports". /// On the command line, underscores become dashes. pub name: &'static str, @@ -76,7 +76,7 @@ pub struct Lint { /// Description of the lint or the issue it detects. /// - /// e.g. "imports that are never used" + /// e.g., "imports that are never used" pub desc: &'static str, /// Starting at the given edition, default to the given lint level. If this is `None`, then use @@ -173,7 +173,7 @@ pub type LintArray = Vec<&'static Lint>; pub trait LintPass { /// Get descriptions of the lints this `LintPass` object can emit. /// - /// NB: there is no enforcement that the object only emits lints it registered. + /// N.B., there is no enforcement that the object only emits lints it registered. /// And some `rustc` internal `LintPass`es register lints to be emitted by other /// parts of the compiler. If you want enforced access restrictions for your /// `Lint`, make it a private `static` item in its own module. diff --git a/src/librustc/middle/cstore.rs b/src/librustc/middle/cstore.rs index 4720bb29549..c7f93512cd8 100644 --- a/src/librustc/middle/cstore.rs +++ b/src/librustc/middle/cstore.rs @@ -59,7 +59,7 @@ pub enum DepKind { /// A dependency that is only used for its macros. MacrosOnly, /// A dependency that is always injected into the dependency list and so - /// doesn't need to be linked to an rlib, e.g. the injected allocator. + /// doesn't need to be linked to an rlib, e.g., the injected allocator. Implicit, /// A dependency that is required by an rlib version of this crate. /// Ordinary `extern crate`s result in `Explicit` dependencies. diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 807d5a31143..934d7c12be5 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -311,7 +311,7 @@ fn has_allow_dead_code_or_lang_attr(tcx: TyCtxt<'_, '_, '_>, let cg_attrs = tcx.codegen_fn_attrs(def_id); // #[used], #[no_mangle], #[export_name], etc also keeps the item alive - // forcefully, e.g. for placing it in a specific section. + // forcefully, e.g., for placing it in a specific section. if cg_attrs.contains_extern_indicator() || cg_attrs.flags.contains(CodegenFnAttrFlags::USED) { return true; diff --git a/src/librustc/middle/dependency_format.rs b/src/librustc/middle/dependency_format.rs index 549a848a39d..5e75f119aef 100644 --- a/src/librustc/middle/dependency_format.rs +++ b/src/librustc/middle/dependency_format.rs @@ -201,7 +201,7 @@ fn calculate_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // static libraries. // // If the crate hasn't been included yet and it's not actually required - // (e.g. it's an allocator) then we skip it here as well. + // (e.g., it's an allocator) then we skip it here as well. for &cnum in tcx.crates().iter() { let src = tcx.used_crate_source(cnum); if src.dylib.is_none() && @@ -306,7 +306,7 @@ fn attempt_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option EntryPointType { match item.node { @@ -98,7 +98,7 @@ fn entry_point_type(item: &Item, at_root: bool) -> EntryPointType { EntryPointType::MainAttr } else if item.name == "main" { if at_root { - // This is a top-level function so can be 'main' + // This is a top-level function so can be 'main'. EntryPointType::MainNamed } else { EntryPointType::OtherMain diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 32e23a67bdc..f1bc37d03e5 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -813,7 +813,7 @@ impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> { self.consume_expr(&arm.body); } - /// Walks a pat that occurs in isolation (i.e. top-level of fn + /// Walks a pat that occurs in isolation (i.e., top-level of fn /// arg or let binding. *Not* a match arm or nested pat.) fn walk_irrefutable_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat) { let mut mode = Unknown; @@ -851,7 +851,7 @@ impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> { } /// The core driver for walking a pattern; `match_mode` must be - /// established up front, e.g. via `determine_pat_move_mode` (see + /// established up front, e.g., via `determine_pat_move_mode` (see /// also `walk_irrefutable_pat` for patterns that stand alone). fn walk_pat(&mut self, cmt_discr: mc::cmt<'tcx>, pat: &hir::Pat, match_mode: MatchMode) { debug!("walk_pat(cmt_discr={:?}, pat={:?})", cmt_discr, pat); diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index f0f8124c076..23ec24d71d2 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -13,9 +13,9 @@ // Language items are items that represent concepts intrinsic to the language // itself. Examples are: // -// * Traits that specify "kinds"; e.g. "Sync", "Send". +// * Traits that specify "kinds"; e.g., "Sync", "Send". // -// * Traits that represent operators; e.g. "Add", "Sub", "Index". +// * Traits that represent operators; e.g., "Add", "Sub", "Index". // // * Functions called by the compiler itself. diff --git a/src/librustc/middle/lib_features.rs b/src/librustc/middle/lib_features.rs index a33ef10a27b..8934c7ebb2a 100644 --- a/src/librustc/middle/lib_features.rs +++ b/src/librustc/middle/lib_features.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Detecting lib features (i.e. features that are not lang features). +// Detecting lib features (i.e., features that are not lang features). // -// These are declared using stability attributes (e.g. `#[stable (..)]` +// These are declared using stability attributes (e.g., `#[stable (..)]` // and `#[unstable (..)]`), but are not declared in one single location // (unlike lang features), which means we need to collect them instead. @@ -61,7 +61,7 @@ impl<'a, 'tcx> LibFeatureCollector<'a, 'tcx> { fn extract(&self, attr: &Attribute) -> Option<(Symbol, Option, Span)> { let stab_attrs = vec!["stable", "unstable", "rustc_const_unstable"]; - // Find a stability attribute (i.e. `#[stable (..)]`, `#[unstable (..)]`, + // Find a stability attribute (i.e., `#[stable (..)]`, `#[unstable (..)]`, // `#[rustc_const_unstable (..)]`). if let Some(stab_attr) = stab_attrs.iter().find(|stab_attr| { attr.check_name(stab_attr) diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index b7cea975e0a..e576951417f 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -554,7 +554,7 @@ struct RWUTable { /// 65 bits of data into 32; in the uncommon cases, it expands the 65 bits /// in 96. /// - /// More compact representations are possible -- e.g. use only 2 bits per + /// More compact representations are possible -- e.g., use only 2 bits per /// packed `RWU` and make the secondary table a HashMap that maps from /// indices to `RWU`s -- but this one strikes a good balance between size /// and speed. diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index c8fd75a6ec9..a04914e9774 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -127,7 +127,7 @@ pub enum PointerKind<'tcx> { } // We use the term "interior" to mean "something reachable from the -// base without a pointer dereference", e.g. a field +// base without a pointer dereference", e.g., a field #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub enum InteriorKind { InteriorField(FieldIndex), @@ -153,8 +153,8 @@ impl Hash for FieldIndex { #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] pub enum InteriorOffsetKind { - Index, // e.g. `array_expr[index_expr]` - Pattern, // e.g. `fn foo([_, a, _, _]: [A; 4]) { ... }` + Index, // e.g., `array_expr[index_expr]` + Pattern, // e.g., `fn foo([_, a, _, _]: [A; 4]) { ... }` } #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] @@ -961,7 +961,7 @@ impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> { debug!("cat_rvalue_node: promotable = {:?}", promotable); - // Always promote `[T; 0]` (even when e.g. borrowed mutably). + // Always promote `[T; 0]` (even when e.g., borrowed mutably). let promotable = match expr_ty.sty { ty::Array(_, len) if len.assert_usize(self.tcx) == Some(0) => true, _ => promotable, diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 0a4ddf8b572..9977faf5b2c 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -84,7 +84,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, /// (D9.): DestructionScope for temporaries created during M8. /// (R10.): Remainder scope for block `'b:`, stmt 1 (let y = ...). /// (D11.): DestructionScope for temporaries and bindings from block `'b:`. -/// (D12.): DestructionScope for temporaries created during M1 (e.g. f()). +/// (D12.): DestructionScope for temporaries created during M1 (e.g., f()). /// ``` /// /// Note that while the above picture shows the destruction scopes @@ -155,7 +155,7 @@ pub enum ScopeData { /// everything after that first `let`. (If you want a scope that /// includes EXPR_1 as well, then do not use `Scope::Remainder`, /// but instead another `Scope` that encompasses the whole block, -/// e.g. `Scope::Node`. +/// e.g., `Scope::Node`. /// /// * the subscope with `first_statement_index == 1` is scope of `c`, /// and thus does not include EXPR_2, but covers the `...`. @@ -172,7 +172,7 @@ static_assert!(ASSERT_SCOPE_DATA: mem::size_of::() == 4); impl Scope { /// Returns a item-local id associated with this scope. /// - /// NB: likely to be replaced as API is refined; e.g. pnkfelix + /// N.B., likely to be replaced as API is refined; e.g., pnkfelix /// anticipates `fn entry_node_id` and `fn each_exit_node_id`. pub fn item_local_id(&self) -> hir::ItemLocalId { self.id @@ -770,10 +770,10 @@ fn resolve_block<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, blk: // }, other_argument()); // // Each of the statements within the block is a terminating - // scope, and thus a temporary (e.g. the result of calling + // scope, and thus a temporary (e.g., the result of calling // `bar()` in the initializer expression for `let inner = ...;`) // will be cleaned up immediately after its corresponding - // statement (i.e. `let inner = ...;`) executes. + // statement (i.e., `let inner = ...;`) executes. // // On the other hand, temporaries associated with evaluating the // tail expression for the block are assigned lifetimes so that @@ -984,7 +984,7 @@ fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, // As an exception to the normal rules governing temporary // lifetimes, initializers in a let have a temporary lifetime - // of the enclosing block. This means that e.g. a program + // of the enclosing block. This means that e.g., a program // like the following is legal: // // let ref x = HashMap::new(); @@ -1183,7 +1183,7 @@ fn resolve_local<'a, 'tcx>(visitor: &mut RegionResolutionVisitor<'a, 'tcx>, loop { // Note: give all the expressions matching `ET` with the // extended temporary lifetime, not just the innermost rvalue, - // because in codegen if we must compile e.g. `*rvalue()` + // because in codegen if we must compile e.g., `*rvalue()` // into a temporary, we request the temporary scope of the // outer expression. visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope); @@ -1281,7 +1281,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> { // according to rvalue lifetime semantics, using the same // syntactical rules used for let initializers. // - // E.g. in `let x = &f();`, the temporary holding the result from + // e.g., in `let x = &f();`, the temporary holding the result from // the `f()` call lives for the entirety of the surrounding block. // // Similarly, `const X: ... = &f();` would have the result of `f()` @@ -1292,7 +1292,7 @@ impl<'a, 'tcx> Visitor<'tcx> for RegionResolutionVisitor<'a, 'tcx> { // // However, `const Y: ... = g(&f());`, like `let y = g(&f());`, // would *not* let the `f()` temporary escape into an outer scope - // (i.e. `'static`), which means that after `g` returns, it drops, + // (i.e., `'static`), which means that after `g` returns, it drops, // and all the associated destruction scope rules apply. self.cx.var_parent = None; resolve_local(self, None, Some(&body.value)); diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 54d8d169288..571f718f905 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -303,14 +303,14 @@ enum Scope<'a> { /// Lifetimes introduced by a fn are scoped to the call-site for that fn, /// if this is a fn body, otherwise the original definitions are used. /// Unspecified lifetimes are inferred, unless an elision scope is nested, - /// e.g. `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`. + /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`. Body { id: hir::BodyId, s: ScopeRef<'a>, }, /// A scope which either determines unspecified lifetimes or errors - /// on them (e.g. due to ambiguity). For more details, see `Elide`. + /// on them (e.g., due to ambiguity). For more details, see `Elide`. Elision { elide: Elide, s: ScopeRef<'a>, @@ -622,13 +622,13 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { LifetimeName::Implicit => { // If the user does not write *anything*, we // use the object lifetime defaulting - // rules. So e.g. `Box` becomes + // rules. So e.g., `Box` becomes // `Box`. self.resolve_object_lifetime_default(lifetime) } LifetimeName::Underscore => { // If the user writes `'_`, we use the *ordinary* elision - // rules. So the `'_` in e.g. `Box` will be + // rules. So the `'_` in e.g., `Box` will be // resolved the same as the `'_` in `&'_ Foo`. // // cc #48468 @@ -1699,7 +1699,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { { insert_late_bound_lifetimes(self.map, decl, generics); - // Find the start of nested early scopes, e.g. in methods. + // Find the start of nested early scopes, e.g., in methods. let mut index = 0; if let Some(parent_id) = parent_id { let parent = self.tcx.hir().expect_item(parent_id); diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index 52a81d9a1c0..ab379c910f7 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -14,9 +14,10 @@ pub use self::StabilityLevel::*; use lint; +use hir::{self, Item, Generics, StructField, Variant, HirId}; use hir::def::Def; use hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE}; -use ty::{self, TyCtxt}; +use hir::intravisit::{self, Visitor, NestedVisitorMap}; use middle::privacy::AccessLevels; use session::{DiagnosticMessageId, Session}; use syntax::symbol::Symbol; @@ -25,12 +26,9 @@ use syntax::ast; use syntax::ast::{NodeId, Attribute}; use syntax::feature_gate::{GateIssue, emit_feature_err}; use syntax::attr::{self, Stability, Deprecation}; +use ty::{self, TyCtxt}; use util::nodemap::{FxHashSet, FxHashMap}; -use hir; -use hir::{Item, Generics, StructField, Variant, HirId}; -use hir::intravisit::{self, Visitor, NestedVisitorMap}; - use std::mem::replace; use std::cmp::Ordering; @@ -474,10 +472,10 @@ pub fn check_unstable_api_usage<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { } /// Check whether an item marked with `deprecated(since="X")` is currently -/// deprecated (i.e. whether X is not greater than the current rustc version). +/// deprecated (i.e., whether X is not greater than the current rustc version). pub fn deprecation_in_effect(since: &str) -> bool { fn parse_version(ver: &str) -> Vec { - // We ignore non-integer components of the version (e.g. "nightly"). + // We ignore non-integer components of the version (e.g., "nightly"). ver.split(|c| c == '.' || c == '-').flat_map(|s| s.parse()).collect() } @@ -518,7 +516,7 @@ pub enum EvalResult { } impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { - // (See issue #38412) + // See issue #38412. fn skip_stability_check_due_to_privacy(self, mut def_id: DefId) -> bool { // Check if `def_id` is a trait method. match self.describe_def(def_id) { @@ -528,8 +526,8 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container { // Trait methods do not declare visibility (even // for visibility info in cstore). Use containing - // trait instead, so methods of pub traits are - // themselves considered pub. + // trait instead, so methods of `pub` traits are + // themselves considered `pub`. def_id = trait_def_id; } } @@ -539,10 +537,10 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { let visibility = self.visibility(def_id); match visibility { - // must check stability for pub items. + // Must check stability for `pub` items. ty::Visibility::Public => false, - // these are not visible outside crate; therefore + // These are not visible outside crate; therefore // stability markers are irrelevant, if even present. ty::Visibility::Restricted(..) | ty::Visibility::Invisible => true, @@ -628,7 +626,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { return EvalResult::Allow; } - // Issue 38412: private items lack stability markers. + // Issue #38412: private items lack stability markers. if self.skip_stability_check_due_to_privacy(def_id) { return EvalResult::Allow; } @@ -644,7 +642,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // crates also pulled in from crates.io. We want to ideally be // able to compile everything without requiring upstream // modifications, so in the case that this looks like a - // rustc_private crate (e.g. a compiler crate) and we also have + // `rustc_private` crate (e.g., a compiler crate) and we also have // the `-Z force-unstable-if-unmarked` flag present (we're // compiling a compiler crate), then let this missing feature // annotation slide. @@ -794,7 +792,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { } } -/// Given the list of enabled features that were not language features (i.e. that +/// Given the list of enabled features that were not language features (i.e., that /// were expected to be library features), and the list of features used from /// libraries, identify activated features that don't exist and error about them. pub fn check_unused_or_stable_features<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { diff --git a/src/librustc/mir/interpret/error.rs b/src/librustc/mir/interpret/error.rs index 503e0abdbf3..289f693df24 100644 --- a/src/librustc/mir/interpret/error.rs +++ b/src/librustc/mir/interpret/error.rs @@ -378,7 +378,7 @@ impl<'tcx, O> EvalErrorKind<'tcx, O> { "tried to read from foreign (extern) static", InvalidPointerMath => "attempted to do invalid arithmetic on pointers that would leak base addresses, \ - e.g. comparing pointers into different allocations", + e.g., comparing pointers into different allocations", ReadUndefBytes(_) => "attempted to read undefined bytes", DeadLocal => diff --git a/src/librustc/mir/mod.rs b/src/librustc/mir/mod.rs index 2d503de25f7..b7a42952075 100644 --- a/src/librustc/mir/mod.rs +++ b/src/librustc/mir/mod.rs @@ -556,7 +556,7 @@ pub enum BorrowKind { /// Data is mutable and not aliasable. Mut { /// True if this borrow arose from method-call auto-ref - /// (i.e. `adjustment::Adjust::Borrow`) + /// (i.e., `adjustment::Adjust::Borrow`) allow_two_phase_borrow: bool, }, } @@ -692,7 +692,7 @@ mod binding_form_impl { /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`. /// /// It is used to improve diagnostics when such temporaries are -/// involved in borrow_check errors, e.g. explanations of where the +/// involved in borrow_check errors, e.g., explanations of where the /// temporaries come from, when their destructors are run, and/or how /// one might revise the code to satisfy the borrow checker's rules. #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] @@ -701,7 +701,7 @@ pub struct BlockTailInfo { /// expression is ignored by the block's expression context. /// /// Examples include `{ ...; tail };` and `let _ = { ...; tail };` - /// but not e.g. `let _x = { ...; tail };` + /// but not e.g., `let _x = { ...; tail };` pub tail_result_is_ignored: bool, } @@ -756,7 +756,7 @@ pub struct LocalDecl<'tcx> { pub ty: Ty<'tcx>, /// If the user manually ascribed a type to this variable, - /// e.g. via `let x: T`, then we carry that type here. The MIR + /// e.g., via `let x: T`, then we carry that type here. The MIR /// borrow checker needs this information since it can affect /// region inference. pub user_ty: UserTypeProjections<'tcx>, @@ -767,7 +767,7 @@ pub struct LocalDecl<'tcx> { /// to generate better debuginfo. pub name: Option, - /// The *syntactic* (i.e. not visibility) source scope the local is defined + /// The *syntactic* (i.e., not visibility) source scope the local is defined /// in. If the local was defined in a let-statement, this /// is *within* the let-statement, rather than outside /// of it. @@ -1745,7 +1745,7 @@ pub enum StatementKind<'tcx> { Assign(Place<'tcx>, Box>), /// This represents all the reading that a pattern match may do - /// (e.g. inspecting constants and discriminant values), and the + /// (e.g., inspecting constants and discriminant values), and the /// kind of pattern it comes from. This is in order to adapt potential /// error messages to these specific patterns. FakeRead(FakeReadCause, Place<'tcx>), @@ -2180,7 +2180,7 @@ pub enum Rvalue<'tcx> { /// Read the discriminant of an ADT. /// - /// Undefined (i.e. no effort is made to make it defined, but there’s no reason why it cannot + /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot /// be defined to return, say, a 0) if ADT is not an enum. Discriminant(Place<'tcx>), @@ -2222,7 +2222,7 @@ pub enum AggregateKind<'tcx> { /// The second field is the variant index. It's equal to 0 for struct /// and union expressions. The fourth field is /// active field number and is present only for union expressions - /// -- e.g. for a union expression `SomeUnion { c: .. }`, the + /// -- e.g., for a union expression `SomeUnion { c: .. }`, the /// active field index would identity the field `c` Adt( &'tcx AdtDef, diff --git a/src/librustc/mir/mono.rs b/src/librustc/mir/mono.rs index ff2bf3d7807..c96cbd40efa 100644 --- a/src/librustc/mir/mono.rs +++ b/src/librustc/mir/mono.rs @@ -272,7 +272,7 @@ impl<'a, 'gcx: 'tcx, 'tcx: 'a> CodegenUnitNameBuilder<'a, 'gcx, 'tcx> { /// /// The '.' before `` makes sure that names with a special /// suffix can never collide with a name built out of regular Rust - /// identifiers (e.g. module paths). + /// identifiers (e.g., module paths). pub fn build_cgu_name(&mut self, cnum: CrateNum, components: I, diff --git a/src/librustc/mir/traversal.rs b/src/librustc/mir/traversal.rs index f3a0b7de903..4424ba0a4f7 100644 --- a/src/librustc/mir/traversal.rs +++ b/src/librustc/mir/traversal.rs @@ -253,7 +253,7 @@ impl<'a, 'tcx> Iterator for Postorder<'a, 'tcx> { /// ``` /// /// A reverse postorder traversal of this graph is either `A B C D` or `A C B D` -/// Note that for a graph containing no loops (i.e. A DAG), this is equivalent to +/// Note that for a graph containing no loops (i.e., A DAG), this is equivalent to /// a topological sort. /// /// Construction of a `ReversePostorder` traversal requires doing a full diff --git a/src/librustc/mir/visit.rs b/src/librustc/mir/visit.rs index d40d85a1937..237f6bc9c7b 100644 --- a/src/librustc/mir/visit.rs +++ b/src/librustc/mir/visit.rs @@ -33,7 +33,7 @@ use syntax_pos::Span; // in that circumstance. // // For the most part, we do not destructure things external to the -// MIR, e.g. types, spans, etc, but simply visit them and stop. This +// MIR, e.g., types, spans, etc, but simply visit them and stop. This // avoids duplication with other visitors like `TypeFoldable`. // // ## Updating @@ -997,7 +997,7 @@ pub enum NonMutatingUseContext<'tcx> { ShallowBorrow(Region<'tcx>), /// Unique borrow. UniqueBorrow(Region<'tcx>), - /// Used as base for another place, e.g. `x` in `x.y`. Will not mutate the place. + /// Used as base for another place, e.g., `x` in `x.y`. Will not mutate the place. /// For example, the projection `x.y` is not marked as a mutation in these cases: /// /// z = x.y; @@ -1020,7 +1020,7 @@ pub enum MutatingUseContext<'tcx> { Drop, /// Mutable borrow. Borrow(Region<'tcx>), - /// Used as base for another place, e.g. `x` in `x.y`. Could potentially mutate the place. + /// Used as base for another place, e.g., `x` in `x.y`. Could potentially mutate the place. /// For example, the projection `x.y` is marked as a mutation in these cases: /// /// x.y = ...; diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index f1ddcda823e..51855ff6cc8 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -1280,7 +1280,7 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED], "if set, exclude the pass number when dumping MIR (used in tests)"), mir_emit_retag: bool = (false, parse_bool, [TRACKED], - "emit Retagging MIR statements, interpreted e.g. by miri; implies -Zmir-opt-level=0"), + "emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0"), perf_stats: bool = (false, parse_bool, [UNTRACKED], "print some performance-related statistics"), hir_stats: bool = (false, parse_bool, [UNTRACKED], @@ -1532,7 +1532,7 @@ impl RustcOptGroup { // adds extra rustc-specific metadata to each option; such metadata // is exposed by . The public // functions below ending with `_u` are the functions that return -// *unstable* options, i.e. options that are only enabled when the +// *unstable* options, i.e., options that are only enabled when the // user also passes the `-Z unstable-options` debugging flag. mod opt { // The `fn opt_u` etc below are written so that we can use them @@ -2380,7 +2380,7 @@ impl fmt::Display for CrateType { /// tracking are hashed into a single value that determines whether the /// incremental compilation cache can be re-used or not. This hashing is done /// via the DepTrackingHash trait defined below, since the standard Hash -/// implementation might not be suitable (e.g. arguments are stored in a Vec, +/// implementation might not be suitable (e.g., arguments are stored in a Vec, /// the hash of which is order dependent, but we might not want the order of /// arguments to make a difference for the hash). /// diff --git a/src/librustc/session/filesearch.rs b/src/librustc/session/filesearch.rs index e686a1d1275..8159c65a8bc 100644 --- a/src/librustc/session/filesearch.rs +++ b/src/librustc/session/filesearch.rs @@ -176,7 +176,7 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> { // of the directory where librustc is located, rather than where the rustc // binary is. // If --libdir is set during configuration to the value other than - // "lib" (i.e. non-default), this value is used (see issue #16552). + // "lib" (i.e., non-default), this value is used (see issue #16552). #[cfg(target_pointer_width = "64")] const PRIMARY_LIB_DIR: &str = "lib64"; diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 293cd0c7c54..d1dd745add9 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -586,7 +586,7 @@ impl Session { // either return `No` or `ThinLocal`. // If processing command line options determined that we're incompatible - // with ThinLTO (e.g. `-C lto --emit llvm-ir`) then return that option. + // with ThinLTO (e.g., `-C lto --emit llvm-ir`) then return that option. if self.opts.cli_forced_thinlto_off { return config::Lto::No; } diff --git a/src/librustc/traits/auto_trait.rs b/src/librustc/traits/auto_trait.rs index a0237348ea6..fff77816e75 100644 --- a/src/librustc/traits/auto_trait.rs +++ b/src/librustc/traits/auto_trait.rs @@ -138,7 +138,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { // the first evaluate_predicates call. // // The problem is this: most of rustc, including SelectionContext and traits::project, - // are designed to work with a concrete usage of a type (e.g. Vec + // are designed to work with a concrete usage of a type (e.g., Vec // fn() { Vec }. This information will generally never change - given // the 'T' in fn() { ... }, we'll never know anything else about 'T'. // If we're unable to prove that 'T' implements a particular trait, we're done - @@ -289,7 +289,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { // // One additional consideration is supertrait bounds. Normally, a ParamEnv is only ever // constructed once for a given type. As part of the construction process, the ParamEnv will - // have any supertrait bounds normalized - e.g. if we have a type 'struct Foo', the + // have any supertrait bounds normalized - e.g., if we have a type 'struct Foo', the // ParamEnv will contain 'T: Copy' and 'T: Clone', since 'Copy: Clone'. When we construct our // own ParamEnv, we need to do this ourselves, through traits::elaborate_predicates, or else // SelectionContext will choke on the missing predicates. However, this should never show up in @@ -343,7 +343,7 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { match &result { &Ok(Some(ref vtable)) => { - // If we see an explicit negative impl (e.g. 'impl !Send for MyStruct'), + // If we see an explicit negative impl (e.g., 'impl !Send for MyStruct'), // we immediately bail out, since it's impossible for us to continue. match vtable { Vtable::VtableImpl(VtableImplData { impl_def_id, .. }) => { @@ -432,11 +432,11 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> { // If we put both of these predicates in our computed ParamEnv, we'll // confuse SelectionContext, since it will (correctly) view both as being applicable. // - // To solve this, we pick the 'more strict' lifetime bound - i.e. the HRTB + // To solve this, we pick the 'more strict' lifetime bound - i.e., the HRTB // Our end goal is to generate a user-visible description of the conditions // under which a type implements an auto trait. A trait predicate involving // a HRTB means that the type needs to work with any choice of lifetime, - // not just one specific lifetime (e.g. 'static). + // not just one specific lifetime (e.g., 'static). fn add_user_pred<'c>( &self, user_computed_preds: &mut FxHashSet>, diff --git a/src/librustc/traits/coherence.rs b/src/librustc/traits/coherence.rs index 4bf8ba0d6d1..f10f523e2b4 100644 --- a/src/librustc/traits/coherence.rs +++ b/src/librustc/traits/coherence.rs @@ -256,12 +256,12 @@ pub fn orphan_check<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, /// The current rule is that a trait-ref orphan checks in a crate C: /// /// 1. Order the parameters in the trait-ref in subst order - Self first, -/// others linearly (e.g. `>` is U < V < W). +/// others linearly (e.g., `>` is U < V < W). /// 2. Of these type parameters, there is at least one type parameter /// in which, walking the type as a tree, you can reach a type local /// to C where all types in-between are fundamental types. Call the /// first such parameter the "local key parameter". -/// - e.g. `Box` is OK, because you can visit LocalType +/// - e.g., `Box` is OK, because you can visit LocalType /// going through `Box`, which is fundamental. /// - similarly, `FundamentalPair, Box>` is OK for /// the same reason. @@ -269,7 +269,7 @@ pub fn orphan_check<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, /// not local), `Vec` is bad, because `Vec<->` is between /// the local type and the type parameter. /// 3. Every type parameter before the local key parameter is fully known in C. -/// - e.g. `impl T: Trait` is bad, because `T` might be +/// - e.g., `impl T: Trait` is bad, because `T` might be /// an unknown type. /// - but `impl LocalType: Trait` is OK, because `LocalType` /// occurs before `T`. @@ -277,7 +277,7 @@ pub fn orphan_check<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, /// through the parameter's type tree, must appear only as a subtree of /// a type local to C, with only fundamental types between the type /// local to C and the local key parameter. -/// - e.g. `Vec>>` (or equivalently `Box>>`) +/// - e.g., `Vec>>` (or equivalently `Box>>`) /// 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 @@ -288,7 +288,7 @@ pub fn orphan_check<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, /// /// The orphan rules actually serve several different purposes: /// -/// 1. They enable link-safety - i.e. 2 mutually-unknowing crates (where +/// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where /// every type local to one crate is unknown in the other) can't implement /// the same trait-ref. This follows because it can be seen that no such /// type can orphan-check in 2 such crates. diff --git a/src/librustc/traits/error_reporting.rs b/src/librustc/traits/error_reporting.rs index 80634aa3066..4ef4f457105 100644 --- a/src/librustc/traits/error_reporting.rs +++ b/src/librustc/traits/error_reporting.rs @@ -128,7 +128,7 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> { } } - // returns if `cond` not occurring implies that `error` does not occur - i.e. that + // returns if `cond` not occurring implies that `error` does not occur - i.e., that // `error` occurring implies that `cond` occurs. fn error_implies(&self, cond: &ty::Predicate<'tcx>, diff --git a/src/librustc/traits/mod.rs b/src/librustc/traits/mod.rs index ab2fa68ab5f..b259ee011da 100644 --- a/src/librustc/traits/mod.rs +++ b/src/librustc/traits/mod.rs @@ -8,34 +8,46 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Trait Resolution. See [rustc guide] for more info on how this works. +//! Trait Resolution. See the [rustc guide] for more information on how this works. //! //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html -pub use self::SelectionError::*; -pub use self::FulfillmentErrorCode::*; -pub use self::Vtable::*; -pub use self::ObligationCauseCode::*; +#[allow(dead_code)] +pub mod auto_trait; +mod coherence; +pub mod error_reporting; +mod engine; +mod fulfill; +mod project; +mod object_safety; +mod on_unimplemented; +mod select; +mod specialize; +mod structural_impls; +pub mod codegen; +mod util; +pub mod query; use chalk_engine; use hir; use hir::def_id::DefId; -use infer::SuppressRegionErrors; +use infer::{InferCtxt, SuppressRegionErrors}; use infer::outlives::env::OutlivesEnvironment; use middle::region; use mir::interpret::ErrorHandled; +use rustc_data_structures::sync::Lrc; +use syntax::ast; +use syntax_pos::{Span, DUMMY_SP}; use ty::subst::Substs; use ty::{self, AdtKind, List, Ty, TyCtxt, GenericParamDefKind, ToPredicate}; use ty::error::{ExpectedFound, TypeError}; use ty::fold::{TypeFolder, TypeFoldable, TypeVisitor}; -use infer::{InferCtxt}; use util::common::ErrorReported; -use rustc_data_structures::sync::Lrc; -use std::fmt::Debug; -use std::rc::Rc; -use syntax::ast; -use syntax_pos::{Span, DUMMY_SP}; +pub use self::SelectionError::*; +pub use self::FulfillmentErrorCode::*; +pub use self::Vtable::*; +pub use self::ObligationCauseCode::*; pub use self::coherence::{orphan_check, overlapping_impls, OrphanCheckErr, OverlapResult}; pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation}; @@ -51,25 +63,13 @@ pub use self::specialize::{OverlapError, specialization_graph, translate_substs} pub use self::specialize::find_associated_item; pub use self::engine::{TraitEngine, TraitEngineExt}; pub use self::util::{elaborate_predicates, elaborate_trait_ref, elaborate_trait_refs}; -pub use self::util::{supertraits, supertrait_def_ids, Supertraits, SupertraitDefIds}; -pub use self::util::transitive_bounds; - -#[allow(dead_code)] -pub mod auto_trait; -mod coherence; -pub mod error_reporting; -mod engine; -mod fulfill; -mod project; -mod object_safety; -mod on_unimplemented; -mod select; -mod specialize; -mod structural_impls; -pub mod codegen; -mod util; +pub use self::util::{supertraits, supertrait_def_ids, transitive_bounds, + Supertraits, SupertraitDefIds}; -pub mod query; +pub use self::ObligationCauseCode::*; +pub use self::FulfillmentErrorCode::*; +pub use self::SelectionError::*; +pub use self::Vtable::*; // Whether to enable bug compatibility with issue #43355 #[derive(Copy, Clone, PartialEq, Eq, Debug)] @@ -91,7 +91,7 @@ pub enum TraitQueryMode { Canonical, } -/// An `Obligation` represents some trait reference (e.g. `int:Eq`) for +/// An `Obligation` represents some trait reference (e.g., `int:Eq`) for /// which the vtable must be found. The process of finding a vtable is /// called "resolving" the `Obligation`. This process consists of /// either identifying an `impl` (e.g., `impl Eq for int`) that @@ -955,7 +955,7 @@ fn substitute_normalize_and_test_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx /// Given a trait `trait_ref`, iterates the vtable entries /// that come from `trait_ref`, including its supertraits. -#[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait. +#[inline] // FIXME(#35870): avoid closures being unexported due to `impl Trait`. fn vtable_methods<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_ref: ty::PolyTraitRef<'tcx>) diff --git a/src/librustc/traits/object_safety.rs b/src/librustc/traits/object_safety.rs index 2909daf22b3..4b2f817cfa9 100644 --- a/src/librustc/traits/object_safety.rs +++ b/src/librustc/traits/object_safety.rs @@ -36,7 +36,7 @@ pub enum ObjectSafetyViolation { SizedSelf, /// Supertrait reference references `Self` an in illegal location - /// (e.g. `trait Foo : Bar`) + /// (e.g., `trait Foo : Bar`) SupertraitSelf, /// Method has something illegal @@ -81,7 +81,7 @@ pub enum MethodViolationCode { /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self` ReferencesSelf, - /// e.g. `fn foo(&self) where Self: Clone` + /// e.g., `fn foo(&self) where Self: Clone` WhereClauseReferencesSelf(Span), /// e.g., `fn foo()` @@ -343,7 +343,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { } }; - // e.g. Rc<()> + // e.g., Rc<()> let unit_receiver_ty = self.receiver_for_self_ty( receiver_ty, self.mk_unit(), method.def_id ); @@ -357,7 +357,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { trait_def_id, self.mk_region(ty::ReStatic) ); - // e.g. Rc + // e.g., Rc let trait_object_receiver = self.receiver_for_self_ty( receiver_ty, trait_object_ty, method.def_id ); @@ -376,7 +376,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { } /// performs a type substitution to produce the version of receiver_ty when `Self = self_ty` - /// e.g. for receiver_ty = `Rc` and self_ty = `Foo`, returns `Rc` + /// e.g., for receiver_ty = `Rc` and self_ty = `Foo`, returns `Rc` fn receiver_for_self_ty( self, receiver_ty: Ty<'tcx>, self_ty: Ty<'tcx>, method_def_id: DefId ) -> Ty<'tcx> { @@ -451,7 +451,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { /// /// The only case where the receiver is not dispatchable, but is still a valid receiver /// type (just not object-safe), is when there is more than one level of pointer indirection. - /// e.g. `self: &&Self`, `self: &Rc`, `self: Box>`. In these cases, there + /// e.g., `self: &&Self`, `self: &Rc`, `self: Box>`. In these cases, there /// is no way, or at least no inexpensive way, to coerce the receiver from the version where /// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type /// contained by the trait object, because the object that needs to be coerced is behind diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs index 1d3d66e82f1..5717a76f1cf 100644 --- a/src/librustc/traits/project.rs +++ b/src/librustc/traits/project.rs @@ -70,7 +70,7 @@ pub enum Reveal { /// be observable directly by the user, `Reveal::All` /// should not be used by checks which may expose /// type equality or type contents to the user. - /// There are some exceptions, e.g. around OIBITS and + /// There are some exceptions, e.g., around OIBITS and /// transmute-checking, which expose some details, but /// not the whole concrete type of the `impl Trait`. All, @@ -608,7 +608,7 @@ fn opt_normalize_projection_type<'a, 'b, 'gcx, 'tcx>( // created (and hence the new ones will quickly be // discarded as duplicated). But when doing trait // evaluation this is not the case, and dropping the trait - // evaluations can causes ICEs (e.g. #43132). + // evaluations can causes ICEs (e.g., #43132). debug!("opt_normalize_projection_type: \ found normalized ty `{:?}`", ty); @@ -1589,7 +1589,7 @@ fn assoc_ty_def<'cx, 'gcx, 'tcx>( /// When working with a fulfillment context, the derived obligations of each /// projection cache entry will be registered on the fulfillcx, so any users /// that can wait for a fulfillcx fixed point need not care about this. However, -/// users that don't wait for a fixed point (e.g. trait evaluation) have to +/// users that don't wait for a fixed point (e.g., trait evaluation) have to /// resolve the obligations themselves to make sure the projected result is /// ok and avoid issues like #43132. /// @@ -1637,7 +1637,7 @@ enum ProjectionCacheEntry<'tcx> { NormalizedTy(NormalizedTy<'tcx>), } -// NB: intentionally not Clone +// N.B., intentionally not Clone pub struct ProjectionCacheSnapshot { snapshot: Snapshot, } diff --git a/src/librustc/traits/select.rs b/src/librustc/traits/select.rs index fb4c9f3bad7..c438542106c 100644 --- a/src/librustc/traits/select.rs +++ b/src/librustc/traits/select.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! See [rustc guide] for more info on how this works. +//! Candidate selection. See the [rustc guide] for more information on how this works. //! //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/resolution.html#selection @@ -69,10 +69,10 @@ pub struct SelectionContext<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> { /// require themselves. freshener: TypeFreshener<'cx, 'gcx, 'tcx>, - /// If true, indicates that the evaluation should be conservative + /// If `true`, indicates that the evaluation should be conservative /// and consider the possibility of types outside this crate. /// This comes up primarily when resolving ambiguity. Imagine - /// there is some trait reference `$0 : Bar` where `$0` is an + /// there is some trait reference `$0: Bar` where `$0` is an /// inference variable. If `intercrate` is true, then we can never /// say for sure that this reference is not implemented, even if /// there are *no impls at all for `Bar`*, because `$0` could be @@ -80,7 +80,7 @@ pub struct SelectionContext<'cx, 'gcx: 'cx + 'tcx, 'tcx: 'cx> { /// `Bar`. This is the suitable mode for coherence. Elsewhere, /// though, we set this to false, because we are only interested /// in types that the user could actually have written --- in - /// other words, we consider `$0 : Bar` to be unimplemented if + /// other words, we consider `$0: Bar` to be unimplemented if /// there is no type that the user could *actually name* that /// would satisfy it. This avoids crippling inference, basically. intercrate: Option, @@ -1170,7 +1170,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { // // The selection process begins by examining all in-scope impls, // caller obligations, and so forth and assembling a list of - // candidates. See [rustc guide] for more details. + // candidates. See the [rustc guide] for more details. // // [rustc guide]: // https://rust-lang.github.io/rustc-guide/traits/resolution.html#candidate-assembly @@ -1615,7 +1615,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { }; if obligation.predicate.skip_binder().self_ty().is_ty_var() { - // Self is a type variable (e.g. `_: AsRef`). + // Self is a type variable (e.g., `_: AsRef`). // // This is somewhat problematic, as the current scheme can't really // handle it turning to be a projection. This does end up as truly @@ -1664,7 +1664,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { self.assemble_candidates_for_unsizing(obligation, &mut candidates); } else { if lang_items.clone_trait() == Some(def_id) { - // Same builtin conditions as `Copy`, i.e. every type which has builtin support + // Same builtin conditions as `Copy`, i.e., every type which has builtin support // for `Copy` also has builtin support for `Clone`, + tuples and arrays of `Clone` // types have builtin support for `Clone`. let clone_conditions = self.copy_clone_conditions(obligation); @@ -2023,7 +2023,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { { candidates.vec.push(ImplCandidate(impl_def_id)); - // NB: we can safely drop the placeholder map + // N.B., we can safely drop the placeholder map // since we are in a probe. mem::drop(placeholder_map); } @@ -2069,7 +2069,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { // that this obligation holds. That could be a // where-clause or, in the case of an object type, // it could be that the object type lists the - // trait (e.g. `Foo+Send : Send`). See + // trait (e.g., `Foo+Send : Send`). See // `compile-fail/typeck-default-trait-impl-send-param.rs` // for an example of a test case that exercises // this path. @@ -2097,7 +2097,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { ); self.probe(|this, _snapshot| { - // the code below doesn't care about regions, and the + // The code below doesn't care about regions, and the // self-ty here doesn't escape this probe, so just erase // any LBR. let self_ty = this.tcx().erase_late_bound_regions(&obligation.self_ty()); @@ -2145,7 +2145,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { .count(); if upcast_trait_refs > 1 { - // can be upcast in many ways; need more type information + // Can be upcast in many ways; need more type information. candidates.ambiguous = true; } else if upcast_trait_refs == 1 { candidates.vec.push(ObjectCandidate); @@ -2197,8 +2197,8 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { (&ty::Dynamic(ref data_a, ..), &ty::Dynamic(ref data_b, ..)) => { // Upcasts permit two things: // - // 1. Dropping builtin bounds, e.g. `Foo+Send` to `Foo` - // 2. Tightening the region bound, e.g. `Foo+'a` to `Foo+'b` if `'a : 'b` + // 1. Dropping builtin bounds, e.g., `Foo+Send` to `Foo` + // 2. Tightening the region bound, e.g., `Foo+'a` to `Foo+'b` if `'a : 'b` // // Note that neither of these changes requires any // change at runtime. Eventually this will be @@ -2354,7 +2354,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { ImplCandidate(other_def) => { // See if we can toss out `victim` based on specialization. // This requires us to know *for sure* that the `other` impl applies - // i.e. EvaluatedToOk: + // i.e., EvaluatedToOk: if other.evaluation == EvaluatedToOk { match victim.candidate { ImplCandidate(victim_def) => { @@ -2717,7 +2717,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { // // Confirmation unifies the output type parameters of the trait // with the values found in the obligation, possibly yielding a - // type error. See [rustc guide] for more details. + // type error. See the [rustc guide] for more details. // // [rustc guide]: // https://rust-lang.github.io/rustc-guide/traits/resolution.html#confirmation @@ -3003,7 +3003,7 @@ impl<'cx, 'gcx, 'tcx> SelectionContext<'cx, 'gcx, 'tcx> { // are sufficient to determine the impl substs, without // relying on projections in the impl-trait-ref. // - // e.g. `impl> Foo<::T> for V` + // e.g., `impl> Foo<::T> for V` impl_obligations.append(&mut substs.obligations); VtableImplData { diff --git a/src/librustc/traits/specialize/mod.rs b/src/librustc/traits/specialize/mod.rs index 50d2179c412..96bb545f25c 100644 --- a/src/librustc/traits/specialize/mod.rs +++ b/src/librustc/traits/specialize/mod.rs @@ -19,22 +19,21 @@ //! //! [rustc guide]: https://rust-lang.github.io/rustc-guide/traits/specialization.html -use super::{SelectionContext, FulfillmentContext}; -use super::util::impl_trait_ref_and_oblig; +pub mod specialization_graph; -use rustc_data_structures::fx::FxHashSet; use hir::def_id::DefId; use infer::{InferCtxt, InferOk}; -use ty::subst::{Subst, Substs}; +use lint; +use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::sync::Lrc; +use syntax_pos::DUMMY_SP; use traits::{self, ObligationCause, TraitEngine}; use traits::select::IntercrateAmbiguityCause; use ty::{self, TyCtxt, TypeFoldable}; -use syntax_pos::DUMMY_SP; -use rustc_data_structures::sync::Lrc; - -use lint; +use ty::subst::{Subst, Substs}; -pub mod specialization_graph; +use super::{SelectionContext, FulfillmentContext}; +use super::util::impl_trait_ref_and_oblig; /// Information pertinent to an overlapping impl error. pub struct OverlapError { @@ -184,7 +183,7 @@ pub(super) fn specializes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // // See RFC 1210 for more details and justification. - // Currently we do not allow e.g. a negative impl to specialize a positive one + // Currently we do not allow e.g., a negative impl to specialize a positive one if tcx.impl_polarity(impl1_def_id) != tcx.impl_polarity(impl2_def_id) { return false; } @@ -295,17 +294,18 @@ fn fulfill_implication<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>, } // Query provider for `specialization_graph_of`. -pub(super) fn specialization_graph_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - trait_id: DefId) - -> Lrc { +pub(super) fn specialization_graph_provider<'a, 'tcx>( + tcx: TyCtxt<'a, 'tcx, 'tcx>, + trait_id: DefId, +) -> Lrc { let mut sg = specialization_graph::Graph::new(); let mut trait_impls = tcx.all_impls(trait_id); // The coherence checking implementation seems to rely on impls being // iterated over (roughly) in definition order, so we are sorting by - // negated CrateNum (so remote definitions are visited first) and then - // by a flattened version of the DefIndex. + // negated `CrateNum` (so remote definitions are visited first) and then + // by a flattened version of the `DefIndex`. trait_impls.sort_unstable_by_key(|def_id| { (-(def_id.krate.as_u32() as i64), def_id.index.address_space().index(), diff --git a/src/librustc/traits/specialize/specialization_graph.rs b/src/librustc/traits/specialize/specialization_graph.rs index db0302f3a90..22221e0a3d9 100644 --- a/src/librustc/traits/specialize/specialization_graph.rs +++ b/src/librustc/traits/specialize/specialization_graph.rs @@ -29,7 +29,7 @@ use util::nodemap::{DefIdMap, FxHashMap}; /// /// The graph provides two key services: /// -/// - Construction, which implicitly checks for overlapping impls (i.e., impls +/// - Construction. This implicitly checks for overlapping impls (i.e., impls /// that overlap but where neither specializes the other -- an artifact of the /// simple "chain" rule. /// @@ -39,11 +39,11 @@ use util::nodemap::{DefIdMap, FxHashMap}; /// has at most one parent. #[derive(RustcEncodable, RustcDecodable)] pub struct Graph { - // all impls have a parent; the "root" impls have as their parent the def_id - // of the trait + // All impls have a parent; the "root" impls have as their parent the `def_id` + // of the trait. parent: DefIdMap, - // the "root" impls are found by looking up the trait's def_id. + // The "root" impls are found by looking up the trait's def_id. children: DefIdMap, } @@ -81,7 +81,7 @@ enum Inserted { } impl<'a, 'gcx, 'tcx> Children { - /// Insert an impl into this set of children without comparing to any existing impls + /// Insert an impl into this set of children without comparing to any existing impls. fn insert_blindly(&mut self, tcx: TyCtxt<'a, 'gcx, 'tcx>, impl_def_id: DefId) { @@ -144,13 +144,13 @@ impl<'a, 'gcx, 'tcx> Children { ); let overlap_error = |overlap: traits::coherence::OverlapResult<'_>| { - // overlap, but no specialization; error out + // Found overlap, but no specialization; error out. let trait_ref = overlap.impl_header.trait_ref.unwrap(); let self_ty = trait_ref.self_ty(); OverlapError { with_impl: possible_sibling, trait_desc: trait_ref.to_string(), - // only report the Self type if it has at least + // Only report the `Self` type if it has at least // some outer concrete shell; otherwise, it's // not adding much information. self_desc: if self_ty.has_concrete_skeleton() { @@ -189,7 +189,7 @@ impl<'a, 'gcx, 'tcx> Children { debug!("descending as child of TraitRef {:?}", tcx.impl_trait_ref(possible_sibling).unwrap()); - // the impl specializes possible_sibling + // The impl specializes `possible_sibling`. return Ok(Inserted::ShouldRecurseOn(possible_sibling)); } else if ge && !le { debug!("placing as parent of TraitRef {:?}", @@ -216,7 +216,7 @@ impl<'a, 'gcx, 'tcx> Children { return Ok(Inserted::ReplaceChildren(replace_children)); } - // no overlap with any potential siblings, so add as a new sibling + // No overlap with any potential siblings, so add as a new sibling. debug!("placing as new sibling"); self.insert_blindly(tcx, impl_def_id); Ok(Inserted::BecameNewSibling(last_lint)) @@ -256,7 +256,7 @@ impl<'a, 'gcx, 'tcx> Graph { debug!("insert({:?}): inserting TraitRef {:?} into specialization graph", impl_def_id, trait_ref); - // if the reference itself contains an earlier error (e.g., due to a + // If the reference itself contains an earlier error (e.g., due to a // resolution failure), then we just insert the impl at the top level of // the graph and claim that there's no overlap (in order to suppress // bogus errors). @@ -275,7 +275,7 @@ impl<'a, 'gcx, 'tcx> Graph { let mut last_lint = None; let simplified = fast_reject::simplify_type(tcx, trait_ref.self_ty(), false); - // Descend the specialization tree, where `parent` is the current parent node + // Descend the specialization tree, where `parent` is the current parent node. loop { use self::Inserted::*; @@ -313,7 +313,7 @@ impl<'a, 'gcx, 'tcx> Graph { siblings.insert_blindly(tcx, impl_def_id); } - // Set G's parent to N and N's parent to P + // Set G's parent to N and N's parent to P. for &grand_child_to_be in &grand_children_to_be { self.parent.insert(grand_child_to_be, impl_def_id); } @@ -429,7 +429,8 @@ impl NodeItem { impl<'a, 'gcx, 'tcx> Ancestors { /// Search the items from the given ancestors, returning each definition /// with the given name and the given kind. - #[inline] // FIXME(#35870) Avoid closures being unexported due to impl Trait. + // FIXME(#35870): avoid closures being unexported due to `impl Trait`. + #[inline] pub fn defs( self, tcx: TyCtxt<'a, 'gcx, 'tcx>, diff --git a/src/librustc/traits/util.rs b/src/librustc/traits/util.rs index 6d3fc0d4fe4..80d8a1d6e5c 100644 --- a/src/librustc/traits/util.rs +++ b/src/librustc/traits/util.rs @@ -9,12 +9,11 @@ // except according to those terms. use hir::def_id::DefId; -use ty::subst::{Kind, Subst, Substs}; +use traits::specialize::specialization_graph::NodeItem; use ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef}; use ty::outlives::Component; +use ty::subst::{Kind, Subst}; use util::nodemap::FxHashSet; -use hir::{self}; -use traits::specialize::specialization_graph::NodeItem; use super::{Obligation, ObligationCause, PredicateObligation, SelectionContext, Normalized}; diff --git a/src/librustc/ty/adjustment.rs b/src/librustc/ty/adjustment.rs index 83521c5f724..d91ae7e120f 100644 --- a/src/librustc/ty/adjustment.rs +++ b/src/librustc/ty/adjustment.rs @@ -83,7 +83,7 @@ pub enum Adjust<'tcx> { /// Take the address and produce either a `&` or `*` pointer. Borrow(AutoBorrow<'tcx>), - /// Unsize a pointer/reference value, e.g. `&[T; n]` to + /// Unsize a pointer/reference value, e.g., `&[T; n]` to /// `&[T]`. Note that the source could be a thin or fat pointer. /// This will do things like convert thin pointers to fat /// pointers, or convert structs containing thin pointers to diff --git a/src/librustc/ty/codec.rs b/src/librustc/ty/codec.rs index 8738f574148..5ad7d247fe4 100644 --- a/src/librustc/ty/codec.rs +++ b/src/librustc/ty/codec.rs @@ -92,7 +92,7 @@ pub fn encode_with_shorthand(encoder: &mut E, let leb128_bits = len * 7; // Check that the shorthand is a not longer than the - // full encoding itself, i.e. it's an obvious win. + // full encoding itself, i.e., it's an obvious win. if leb128_bits >= 64 || (shorthand as u64) < (1 << leb128_bits) { cache(encoder).insert(value.clone(), shorthand); } diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index 818b3a31c12..a3db3a02aad 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -587,7 +587,7 @@ impl<'tcx> TypeckTables<'tcx> { // auto-ref. The type returned by this function does not consider such // adjustments. See `expr_ty_adjusted()` instead. // - // NB (2): This type doesn't provide type parameter substitutions; e.g. if you + // NB (2): This type doesn't provide type parameter substitutions; e.g., if you // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" // instead of "fn(ty) -> T with T = isize". pub fn expr_ty(&self, expr: &hir::Expr) -> Ty<'tcx> { @@ -1654,7 +1654,7 @@ impl<'gcx: 'tcx, 'tcx> GlobalCtxt<'gcx> { /// For Ty, None can be returned if either the type interner doesn't /// contain the TyKind key or if the address of the interned /// pointer differs. The latter case is possible if a primitive type, -/// e.g. `()` or `u8`, was interned in a different context. +/// e.g., `()` or `u8`, was interned in a different context. pub trait Lift<'tcx>: fmt::Debug { type Lifted: fmt::Debug + 'tcx; fn lift_to_tcx<'a, 'gcx>(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Option; @@ -2232,7 +2232,7 @@ impl<'tcx, T: 'tcx+?Sized> Clone for Interned<'tcx, T> { } impl<'tcx, T: 'tcx+?Sized> Copy for Interned<'tcx, T> {} -// NB: An Interned compares and hashes as a sty. +// N.B., an `Interned` compares and hashes as a sty. impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { self.0.sty == other.0.sty @@ -2253,7 +2253,7 @@ impl<'tcx: 'lcx, 'lcx> Borrow> for Interned<'tcx, TyS<'tcx>> { } } -// NB: An Interned> compares and hashes as its elements. +// N.B., an `Interned>` compares and hashes as its elements. impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { fn eq(&self, other: &Interned<'tcx, List>) -> bool { self.0[..] == other.0[..] @@ -2464,7 +2464,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { /// Given a closure signature `sig`, returns an equivalent `fn` /// type with the same signature. Detuples and so forth -- so - /// e.g. if we have a sig with `Fn<(u32, i32)>` then you would get + /// e.g., if we have a sig with `Fn<(u32, i32)>` then you would get /// a `fn(u32, i32)`. pub fn coerce_closure_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { let converted_sig = sig.map_bound(|s| { @@ -2869,11 +2869,11 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { } pub fn lint_hir_note>(self, - lint: &'static Lint, - hir_id: HirId, - span: S, - msg: &str, - note: &str) { + lint: &'static Lint, + hir_id: HirId, + span: S, + msg: &str, + note: &str) { let mut err = self.struct_span_lint_hir(lint, hir_id, span.into(), msg); err.note(note); err.emit() @@ -3016,9 +3016,9 @@ impl InternIteratorElement for Result { } pub fn provide(providers: &mut ty::query::Providers<'_>) { - // FIXME(#44234) - almost all of these queries have no sub-queries and + // FIXME(#44234): almost all of these queries have no sub-queries and // therefore no actual inputs, they're just reading tables calculated in - // resolve! Does this work? Unsure! That's what the issue is about + // resolve! Does this work? Unsure! That's what the issue is about. providers.in_scope_traits_map = |tcx, id| tcx.gcx.trait_map.get(&id).cloned(); providers.module_exports = |tcx, id| tcx.gcx.export_map.get(&id).cloned(); providers.crate_name = |tcx, id| { diff --git a/src/librustc/ty/erase_regions.rs b/src/librustc/ty/erase_regions.rs index f53e634a044..a361ad057c7 100644 --- a/src/librustc/ty/erase_regions.rs +++ b/src/librustc/ty/erase_regions.rs @@ -19,7 +19,7 @@ pub(super) fn provide(providers: &mut ty::query::Providers<'_>) { } fn erase_regions_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - // NB: use `super_fold_with` here. If we used `fold_with`, it + // N.B., use `super_fold_with` here. If we used `fold_with`, it // could invoke the `erase_regions_ty` query recursively. ty.super_fold_with(&mut RegionEraserVisitor { tcx }) } diff --git a/src/librustc/ty/fast_reject.rs b/src/librustc/ty/fast_reject.rs index 8304e363815..7005e14c26c 100644 --- a/src/librustc/ty/fast_reject.rs +++ b/src/librustc/ty/fast_reject.rs @@ -110,7 +110,7 @@ pub fn simplify_type<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, // anything. when lazy normalization happens, this // will change. It would still be nice to have a way // to deal with known-not-to-unify-with-anything - // projections (e.g. the likes of <__S as Encoder>::Error). + // projections (e.g., the likes of <__S as Encoder>::Error). Some(ParameterSimplifiedType) } else { None diff --git a/src/librustc/ty/fold.rs b/src/librustc/ty/fold.rs index 20f64597b78..a40e1df14f8 100644 --- a/src/librustc/ty/fold.rs +++ b/src/librustc/ty/fold.rs @@ -887,7 +887,7 @@ struct LateBoundRegionsCollector { /// If true, we only want regions that are known to be /// "constrained" when you equate this type with another type. In - /// particular, if you have e.g. `&'a u32` and `&'b u32`, equating + /// particular, if you have e.g., `&'a u32` and `&'b u32`, equating /// them constraints `'a == 'b`. But if you have `<&'a u32 as /// Trait>::Foo` and `<&'b u32 as Trait>::Foo`, normalizing those /// types may mean that `'a` and `'b` don't appear in the results, diff --git a/src/librustc/ty/item_path.rs b/src/librustc/ty/item_path.rs index e24f9094dd2..a39eb004fd7 100644 --- a/src/librustc/ty/item_path.rs +++ b/src/librustc/ty/item_path.rs @@ -317,7 +317,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // Unclear if there is any value in distinguishing these. // Probably eventually (and maybe we would even want - // finer-grained distinctions, e.g. between enum/struct). + // finer-grained distinctions, e.g., between enum/struct). data @ DefPathData::Misc | data @ DefPathData::TypeNs(..) | data @ DefPathData::Trait(..) | diff --git a/src/librustc/ty/layout.rs b/src/librustc/ty/layout.rs index 5406495226d..87d745e5cea 100644 --- a/src/librustc/ty/layout.rs +++ b/src/librustc/ty/layout.rs @@ -248,7 +248,7 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> { AlwaysSized, /// A univariant, the last field of which may be coerced to unsized. MaybeUnsized, - /// A univariant, but with a prefix of an arbitrary size & alignment (e.g. enum tag). + /// A univariant, but with a prefix of an arbitrary size & alignment (e.g., enum tag). Prefixed(Size, Align), } @@ -748,7 +748,7 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> { // A variant is absent if it's uninhabited and only has ZST fields. // Present uninhabited variants only require space for their fields, - // but *not* an encoding of the discriminant (e.g. a tag value). + // but *not* an encoding of the discriminant (e.g., a tag value). // See issue #49298 for more details on the need to leave space // for non-ZST uninhabited data (mostly partial initialization). let absent = |fields: &[TyLayout<'_>]| { @@ -1252,7 +1252,7 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> { }).collect(); session::VariantInfo { - name: n.map(|n|n.to_string()), + name: n.map(|n| n.to_string()), kind: if layout.is_unsized() { session::SizeKind::Min } else { @@ -1311,7 +1311,7 @@ impl<'a, 'tcx> LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> { } } -/// Type size "skeleton", i.e. the only information determining a type's size. +/// Type size "skeleton", i.e., the only information determining a type's size. /// While this is conservative, (aside from constant sizes, only pointers, /// newtypes thereof and null pointer optimized enums are allowed), it is /// enough to statically check common use cases of transmute. @@ -1522,7 +1522,7 @@ impl<'a, 'tcx> LayoutOf for LayoutCx<'tcx, TyCtxt<'a, 'tcx, 'tcx>> { details }; - // NB: This recording is normally disabled; when enabled, it + // N.B., this recording is normally disabled; when enabled, it // can however trigger recursive invocations of `layout_of`. // Therefore, we execute it *after* the main query has // completed, to avoid problems around recursive structures @@ -1549,7 +1549,7 @@ impl<'a, 'tcx> LayoutOf for LayoutCx<'tcx, ty::query::TyCtxtAt<'a, 'tcx, 'tcx>> details }; - // NB: This recording is normally disabled; when enabled, it + // N.B., this recording is normally disabled; when enabled, it // can however trigger recursive invocations of `layout_of`. // Therefore, we execute it *after* the main query has // completed, to avoid problems around recursive structures @@ -1660,7 +1660,7 @@ impl<'a, 'tcx, C> TyLayoutMethods<'tcx, C> for Ty<'tcx> assert!(i < this.fields.count()); // Reuse the fat *T type as its own thin pointer data field. - // This provides information about e.g. DST struct pointees + // This provides information about e.g., DST struct pointees // (which may have no non-DST form), and will work as long // as the `Abi` or `FieldPlacement` is checked by users. if i == 0 { diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 7c819941173..a1fc949137d 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -125,7 +125,7 @@ mod sty; /// The complete set of all analyses described in this module. This is /// produced by the driver and fed to codegen and later passes. /// -/// NB: These contents are being migrated into queries using the +/// N.B., these contents are being migrated into queries using the /// *on-demand* infrastructure. #[derive(Clone)] pub struct CrateAnalysis { @@ -505,15 +505,15 @@ pub struct TyS<'tcx> { /// by some sub-binder. /// /// So, for a type without any late-bound things, like `u32`, this - /// will be INNERMOST, because that is the innermost binder that + /// will be *innermost*, because that is the innermost binder that /// captures nothing. But for a type `&'D u32`, where `'D` is a - /// late-bound region with debruijn index D, this would be D+1 -- - /// the binder itself does not capture D, but D is captured by an - /// inner binder. + /// late-bound region with debruijn index `D`, this would be `D + 1` + /// -- the binder itself does not capture `D`, but `D` is captured + /// by an inner binder. /// - /// We call this concept an "exclusive" binder D (because all + /// We call this concept an "exclusive" binder `D` because all /// debruijn indices within the type are contained within `0..D` - /// (exclusive)). + /// (exclusive). outer_exclusive_binder: ty::DebruijnIndex, } @@ -900,10 +900,10 @@ pub struct GenericParamCount { } /// Information about the formal type/lifetime parameters associated -/// with an item or method. Analogous to hir::Generics. +/// with an item or method. Analogous to `hir::Generics`. /// -/// The ordering of parameters is the same as in Subst (excluding child generics): -/// Self (optionally), Lifetime params..., Type params... +/// The ordering of parameters is the same as in `Subst` (excluding child generics): +/// `Self` (optionally), `Lifetime` params..., `Type` params... #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct Generics { pub parent: Option, @@ -1681,7 +1681,7 @@ impl<'tcx> ParamEnv<'tcx> { /// pair it with the empty environment. This improves caching and is generally /// invisible. /// - /// NB: We preserve the environment when type-checking because it + /// N.B., we preserve the environment when type-checking because it /// is possible for the user to have wacky where-clauses like /// `where Box: Copy`, which are clearly never /// satisfiable. We generally want to behave as if they were true, @@ -1778,8 +1778,8 @@ bitflags! { #[derive(Debug)] pub struct VariantDef { - /// The variant's DefId. If this is a tuple-like struct, - /// this is the DefId of the struct's ctor. + /// The variant's `DefId`. If this is a tuple-like struct, + /// this is the `DefId` of the struct's ctor. pub did: DefId, pub name: Name, // struct's name if this is a struct pub discr: VariantDiscr, @@ -1798,7 +1798,7 @@ impl<'a, 'gcx, 'tcx> VariantDef { /// /// Note that we *could* use the constructor DefId, because the constructor attributes /// redirect to the base attributes, but compiling a small crate requires - /// loading the AdtDefs for all the structs in the universe (e.g. coherence for any + /// loading the AdtDefs for all the structs in the universe (e.g., coherence for any /// built-in trait), and we do not want to load attributes twice. /// /// If someone speeds up attribute loading to not be a performance concern, they can @@ -1847,7 +1847,7 @@ impl_stable_hash_for!(struct VariantDef { #[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub enum VariantDiscr { - /// Explicit value for this variant, i.e. `X = 123`. + /// Explicit value for this variant, i.e., `X = 123`. /// The `DefId` corresponds to the embedded constant. Explicit(DefId), @@ -1865,9 +1865,9 @@ pub struct FieldDef { pub vis: Visibility, } -/// The definition of an abstract data type - a struct or enum. +/// The definition of an abstract data type -- a struct or enum. /// -/// These are all interned (by intern_adt_def) into the adt_defs +/// These are all interned (by `intern_adt_def`) into the `adt_defs` /// table. pub struct AdtDef { pub did: DefId, @@ -2367,7 +2367,7 @@ impl<'a, 'gcx, 'tcx> AdtDef { /// Self would prevent its containing ADT from being Sized. /// /// Due to normalization being eager, this applies even if - /// the associated type is behind a pointer, e.g. issue #31299. + /// the associated type is behind a pointer, e.g., issue #31299. pub fn sized_constraint(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>) -> &'tcx [Ty<'tcx>] { match tcx.try_adt_sized_constraint(DUMMY_SP, self.did) { Ok(tys) => tys, diff --git a/src/librustc/ty/query/mod.rs b/src/librustc/ty/query/mod.rs index 699c2d111c6..5cd06fb8a52 100644 --- a/src/librustc/ty/query/mod.rs +++ b/src/librustc/ty/query/mod.rs @@ -166,21 +166,21 @@ define_queries! { <'tcx> ) -> Result, NoSolution>, /// True if this is a const fn, use the `is_const_fn` to know whether your crate actually - /// sees it as const fn (e.g. the const-fn-ness might be unstable and you might not have + /// sees it as const fn (e.g., the const-fn-ness might be unstable and you might not have /// the feature gate active) /// - /// DO NOT CALL MANUALLY, it is only meant to cache the base data for the `is_const_fn` - /// function + /// **Do not call this function manually.** It is only meant to cache the base data for the + /// `is_const_fn` function. [] fn is_const_fn_raw: IsConstFn(DefId) -> bool, /// Returns true if calls to the function may be promoted /// - /// This is either because the function is e.g. a tuple-struct or tuple-variant constructor, - /// or because it has the `#[rustc_promotable]` attribute. The attribute should be removed - /// in the future in favour of some form of check which figures out whether the function - /// does not inspect the bits of any of its arguments (so is essentially just a constructor - /// function) + /// This is either because the function is e.g., a tuple-struct or tuple-variant + /// constructor, or because it has the `#[rustc_promotable]` attribute. The attribute should + /// be removed in the future in favour of some form of check which figures out whether the + /// function does not inspect the bits of any of its arguments (so is essentially just a + /// constructor function). [] fn is_promotable_const_fn: IsPromotableConstFn(DefId) -> bool, /// True if this is a foreign item (i.e., linked via `extern { ... }`). @@ -539,7 +539,7 @@ define_queries! { <'tcx> [] fn all_crate_nums: all_crate_nums_node(CrateNum) -> Lrc>, /// A vector of every trait accessible in the whole crate - /// (i.e. including those from subcrates). This is used only for + /// (i.e., including those from subcrates). This is used only for /// error reporting. [] fn all_traits: all_traits_node(CrateNum) -> Lrc>, }, diff --git a/src/librustc/ty/relate.rs b/src/librustc/ty/relate.rs index 1b64a686794..7ad4fd58273 100644 --- a/src/librustc/ty/relate.rs +++ b/src/librustc/ty/relate.rs @@ -8,10 +8,11 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Generalized type relating mechanism. A type relation R relates a -//! pair of values (A, B). A and B are usually types or regions but -//! can be other things. Examples of type relations are subtyping, -//! type equality, etc. +//! Generalized type relating mechanism. +//! +//! A type relation `R` relates a pair of values `(A, B)`. `A and B` are usually +//! types or regions but can be other things. Examples of type relations are +//! subtyping, type equality, etc. use hir::def_id::DefId; use mir::interpret::ConstValue; diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs index d861fb36781..f757f48e987 100644 --- a/src/librustc/ty/sty.rs +++ b/src/librustc/ty/sty.rs @@ -8,8 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! This module contains TyKind and its major components +//! This module contains `TyKind` and its major components. +use hir; use hir::def_id::DefId; use infer::canonical::Canonical; use mir::interpret::ConstValue; @@ -30,9 +31,6 @@ use syntax::ast::{self, Ident}; use syntax::symbol::{keywords, InternedString}; use serialize; - -use hir; - use self::InferTy::*; use self::TyKind::*; @@ -91,7 +89,7 @@ impl BoundRegion { } } -/// N.B., If you change this, you'll probably want to change the corresponding +/// N.B., if you change this, you'll probably want to change the corresponding /// AST structure in `libsyntax/ast.rs` as well. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)] pub enum TyKind<'tcx> { @@ -531,11 +529,11 @@ impl<'tcx> UpvarSubsts<'tcx> { #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, RustcEncodable, RustcDecodable)] pub enum ExistentialPredicate<'tcx> { - /// e.g. Iterator + /// e.g., Iterator Trait(ExistentialTraitRef<'tcx>), - /// e.g. Iterator::Item = T + /// e.g., Iterator::Item = T Projection(ExistentialProjection<'tcx>), - /// e.g. Send + /// e.g., Send AutoTrait(DefId), } @@ -784,7 +782,7 @@ impl<'tcx> PolyExistentialTraitRef<'tcx> { /// Binder`). Note that when we instantiate, /// erase, or otherwise "discharge" these bound vars, we change the /// type from `Binder` to just `T` (see -/// e.g. `liberate_late_bound_regions`). +/// e.g., `liberate_late_bound_regions`). #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)] pub struct Binder(T); @@ -1099,12 +1097,12 @@ pub type Region<'tcx> = &'tcx RegionKind; /// with some concrete region before being used. There are 2 kind of /// bound regions: early-bound, which are bound in an item's Generics, /// and are substituted by a Substs, and late-bound, which are part of -/// higher-ranked types (e.g. `for<'a> fn(&'a ())`) and are substituted by +/// higher-ranked types (e.g., `for<'a> fn(&'a ())`) and are substituted by /// the likes of `liberate_late_bound_regions`. The distinction exists /// because higher-ranked lifetimes aren't supported in all places. See [1][2]. /// /// Unlike Param-s, bound regions are not supposed to exist "in the wild" -/// outside their binder, e.g. in types passed to type inference, and +/// outside their binder, e.g., in types passed to type inference, and /// should first be substituted (by placeholder regions, free regions, /// or region variables). /// @@ -1160,7 +1158,7 @@ pub enum RegionKind { ReFree(FreeRegion), /// A concrete region naming some statically determined scope - /// (e.g. an expression or sequence of statements) within the + /// (e.g., an expression or sequence of statements) within the /// current function. ReScope(region::Scope), @@ -1324,7 +1322,7 @@ impl<'a, 'tcx, 'gcx> PolyExistentialProjection<'tcx> { impl DebruijnIndex { /// Returns the resulting index when this value is moved into - /// `amount` number of new binders. So e.g. if you had + /// `amount` number of new binders. So e.g., if you had /// /// for<'a> fn(&'a x) /// @@ -1332,7 +1330,7 @@ impl DebruijnIndex { /// /// for<'a> fn(for<'b> fn(&'a x)) /// - /// you would need to shift the index for `'a` into 1 new binder. + /// you would need to shift the index for `'a` into a new binder. #[must_use] pub fn shifted_in(self, amount: u32) -> DebruijnIndex { DebruijnIndex::from_u32(self.as_u32() + amount) @@ -1809,10 +1807,10 @@ impl<'a, 'gcx, 'tcx> TyS<'tcx> { } } - /// Returns the type and mutability of *ty. + /// Returns the type and mutability of `*ty`. /// /// The parameter `explicit` indicates if this is an *explicit* dereference. - /// Some types---notably unsafe ptrs---can only be dereferenced explicitly. + /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly. pub fn builtin_deref(&self, explicit: bool) -> Option> { match self.sty { Adt(def, _) if def.is_box() => { diff --git a/src/librustc/ty/subst.rs b/src/librustc/ty/subst.rs index 34252039898..cda281e053a 100644 --- a/src/librustc/ty/subst.rs +++ b/src/librustc/ty/subst.rs @@ -316,10 +316,10 @@ impl<'a, 'gcx, 'tcx> Substs<'tcx> { } /// Transform from substitutions for a child of `source_ancestor` - /// (e.g. a trait or impl) to substitutions for the same child + /// (e.g., a trait or impl) to substitutions for the same child /// in a different item, with `target_substs` as the base for /// the target impl/trait, with the source child-specific - /// parameters (e.g. method parameters) on top of that base. + /// parameters (e.g., method parameters) on top of that base. pub fn rebase_onto(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, source_ancestor: DefId, target_substs: &Substs<'tcx>) diff --git a/src/librustc/ty/util.rs b/src/librustc/ty/util.rs index 2b9bd91e48a..f9ce228a30c 100644 --- a/src/librustc/ty/util.rs +++ b/src/librustc/ty/util.rs @@ -344,7 +344,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { /// themselves. This should really be a unique type; `FreshTy(0)` is a /// popular choice. /// - /// NB: in some cases, particularly around higher-ranked bounds, + /// N.B., in some cases, particularly around higher-ranked bounds, /// this function returns a kind of conservative approximation. /// That is, all regions returned by this function are definitely /// required, but there may be other region bounds that are not @@ -451,9 +451,9 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // destructor will not access borrowed data, // even if such data is otherwise reachable. // - // Such access can be in plain sight (e.g. dereferencing + // Such access can be in plain sight (e.g., dereferencing // `*foo.0` of `Foo<'a>(&'a u32)`) or indirectly hidden - // (e.g. calling `foo.0.clone()` of `Foo`). + // (e.g., calling `foo.0.clone()` of `Foo`). if self.has_attr(dtor, "unsafe_destructor_blind_to_params") { debug!("destructor_constraint({:?}) - blind", def.did); return vec![]; @@ -656,7 +656,7 @@ impl<'a, 'tcx> ty::TyS<'tcx> { /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely /// non-copy and *might* have a destructor attached; if it returns - /// `false`, then `ty` definitely has no destructor (i.e. no drop glue). + /// `false`, then `ty` definitely has no destructor (i.e., no drop glue). /// /// (Note that this implies that if `ty` has a destructor attached, /// then `needs_drop` will definitely return `true` for `ty`.) diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index c6ba20de0d3..68e197849b0 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -342,7 +342,7 @@ pub trait MemoizationMap { /// If `key` is present in the map, return the value, /// otherwise invoke `op` and store the value in the map. /// - /// NB: if the receiver is a `DepTrackingMap`, special care is + /// N.B., if the receiver is a `DepTrackingMap`, special care is /// needed in the `op` to ensure that the correct edges are /// added into the dep graph. See the `DepTrackingMap` impl for /// more details! diff --git a/src/librustc_apfloat/ieee.rs b/src/librustc_apfloat/ieee.rs index 2ad83fc93ef..60ddac1abfd 100644 --- a/src/librustc_apfloat/ieee.rs +++ b/src/librustc_apfloat/ieee.rs @@ -926,7 +926,7 @@ impl Float for IeeeFloat { // In case MSB resides at the left-hand side of radix point, shift the // mantissa right by some amount to make sure the MSB reside right before - // the radix point (i.e. "MSB . rest-significant-bits"). + // the radix point (i.e., "MSB . rest-significant-bits"). if omsb > S::PRECISION { let bits = omsb - S::PRECISION; loss = sig::shift_right(&mut wide_sig, &mut self.exp, bits).combine(loss); @@ -2674,7 +2674,7 @@ mod sig { // In case MSB resides at the left-hand side of radix point, shift the // mantissa right by some amount to make sure the MSB reside right before - // the radix point (i.e. "MSB . rest-significant-bits"). + // the radix point (i.e., "MSB . rest-significant-bits"). // // Note that the result is not normalized when "omsb < precision". So, the // caller needs to call IeeeFloat::normalize() if normalized value is diff --git a/src/librustc_apfloat/lib.rs b/src/librustc_apfloat/lib.rs index 69c9f385409..c9019171601 100644 --- a/src/librustc_apfloat/lib.rs +++ b/src/librustc_apfloat/lib.rs @@ -26,8 +26,8 @@ //! Comments have been preserved where possible, only slightly adapted. //! //! Instead of keeping a pointer to a configuration struct and inspecting it -//! dynamically on every operation, types (e.g. `ieee::Double`), traits -//! (e.g. `ieee::Semantics`) and associated constants are employed for +//! dynamically on every operation, types (e.g., `ieee::Double`), traits +//! (e.g., `ieee::Semantics`) and associated constants are employed for //! increased type safety and performance. //! //! On-heap bigints are replaced everywhere (except in decimal conversion), @@ -179,7 +179,7 @@ pub struct ParseError(pub &'static str); /// implemented operations. Currently implemented operations are add, subtract, /// multiply, divide, fused-multiply-add, conversion-to-float, /// conversion-to-integer and conversion-from-integer. New rounding modes -/// (e.g. away from zero) can be added with three or four lines of code. +/// (e.g., away from zero) can be added with three or four lines of code. /// /// Four formats are built-in: IEEE single precision, double precision, /// quadruple precision, and x87 80-bit extended double (when operating with @@ -589,7 +589,7 @@ pub trait Float pub trait FloatConvert: Float { /// Convert a value of one floating point type to another. /// The return value corresponds to the IEEE754 exceptions. *loses_info - /// records whether the transformation lost information, i.e. whether + /// records whether the transformation lost information, i.e., whether /// converting the result back to the original type will produce the /// original value (this is almost the same as return value==Status::OK, /// but there are edge cases where this is not so). diff --git a/src/librustc_apfloat/ppc.rs b/src/librustc_apfloat/ppc.rs index e662088e82f..aaf6b29a99e 100644 --- a/src/librustc_apfloat/ppc.rs +++ b/src/librustc_apfloat/ppc.rs @@ -288,7 +288,7 @@ where // \ / // Normal // - // e.g. NaN * NaN = NaN + // e.g., NaN * NaN = NaN // Zero * Inf = NaN // Normal * Zero = Zero // Normal * Inf = Inf diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs index 1a9672aa6ce..7ed4d4910d7 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs @@ -286,7 +286,7 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { lp); } None => { - // This can occur with e.g. `*foo() = 5`. In such + // This can occur with e.g., `*foo() = 5`. In such // cases, there is no need to check for conflicts // with moves etc, just ignore. } diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 3a0d252137c..cb1200f462f 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -217,7 +217,7 @@ fn build_borrowck_dataflow_data<'a, 'c, 'tcx, F>(this: &mut BorrowckCtxt<'a, 'tc } /// Accessor for introspective clients inspecting `AnalysisData` and -/// the `BorrowckCtxt` itself , e.g. the flowgraph visualizer. +/// the `BorrowckCtxt` itself , e.g., the flowgraph visualizer. pub fn build_borrowck_dataflow_data_for_fn<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, body_id: hir::BodyId, diff --git a/src/librustc_borrowck/dataflow.rs b/src/librustc_borrowck/dataflow.rs index 99df0fa5e47..d12c22109c6 100644 --- a/src/librustc_borrowck/dataflow.rs +++ b/src/librustc_borrowck/dataflow.rs @@ -71,7 +71,7 @@ pub struct DataFlowContext<'a, 'tcx: 'a, O> { scope_kills: Vec, /// bits killed as we exit the cfg node directly; if it is jumped - /// over, e.g. via `break`, the kills are not reflected in the + /// over, e.g., via `break`, the kills are not reflected in the /// jump's effects. Updated by `add_kill(KillFrom::Execution)`. action_kills: Vec, @@ -172,7 +172,7 @@ fn build_local_id_to_index(body: Option<&hir::Body>, let mut index = FxHashMap::default(); // FIXME(#15020) Would it be better to fold formals from decl - // into cfg itself? i.e. introduce a fn-based flow-graph in + // into cfg itself? i.e., introduce a fn-based flow-graph in // addition to the current block-based flow-graph, rather than // have to put traversals like this here? if let Some(body) = body { @@ -430,7 +430,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { for offset in 0..usize_bits { let bit = 1 << offset; if (word & bit) != 0 { - // NB: we round up the total number of bits + // N.B., we round up the total number of bits // that we store in any given bit set so that // it is an even multiple of usize::BITS. This // means that there may be some stray bits at diff --git a/src/librustc_codegen_llvm/abi.rs b/src/librustc_codegen_llvm/abi.rs index 5b6d157043d..b8954dee794 100644 --- a/src/librustc_codegen_llvm/abi.rs +++ b/src/librustc_codegen_llvm/abi.rs @@ -185,7 +185,7 @@ pub trait ArgTypeExt<'ll, 'tcx> { impl ArgTypeExt<'ll, 'tcx> for ArgType<'tcx, Ty<'tcx>> { /// Get the LLVM type for a place of the original Rust type of - /// this argument/return, i.e. the result of `type_of::type_of`. + /// this argument/return, i.e., the result of `type_of::type_of`. fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type { self.layout.llvm_type(cx) } diff --git a/src/librustc_codegen_llvm/attributes.rs b/src/librustc_codegen_llvm/attributes.rs index 38ab1302cfa..ffe5e123f9b 100644 --- a/src/librustc_codegen_llvm/attributes.rs +++ b/src/librustc_codegen_llvm/attributes.rs @@ -71,7 +71,7 @@ pub fn set_optimize_for_size(val: &'ll Value, optimize: bool) { Attribute::OptimizeForSize.toggle_llfn(Function, val, optimize); } -/// Tell LLVM if this function should be 'naked', i.e. skip the epilogue and prologue. +/// Tell LLVM if this function should be 'naked', i.e., skip the epilogue and prologue. #[inline] pub fn naked(val: &'ll Value, is_naked: bool) { Attribute::Naked.toggle_llfn(Function, val, is_naked); @@ -147,7 +147,7 @@ pub fn non_lazy_bind(sess: &Session, llfn: &'ll Value) { } } -/// Composite function which sets LLVM attributes for function depending on its AST (#[attribute]) +/// Composite function which sets LLVM attributes for function depending on its AST (`#[attribute]`) /// attributes. pub fn from_fn_attrs( cx: &CodegenCx<'ll, '_>, diff --git a/src/librustc_codegen_llvm/back/link.rs b/src/librustc_codegen_llvm/back/link.rs index 68da14570e4..9e100a1427f 100644 --- a/src/librustc_codegen_llvm/back/link.rs +++ b/src/librustc_codegen_llvm/back/link.rs @@ -994,7 +994,7 @@ fn link_args(cmd: &mut dyn Linker, // // The rationale behind this ordering is that those items lower down in the // list can't depend on items higher up in the list. For example nothing can - // depend on what we just generated (e.g. that'd be a circular dependency). + // depend on what we just generated (e.g., that'd be a circular dependency). // Upstream rust libraries are not allowed to depend on our local native // libraries as that would violate the structure of the DAG, in that // scenario they are required to link to them as well in a shared fashion. @@ -1003,7 +1003,7 @@ fn link_args(cmd: &mut dyn Linker, // well, but they also can't depend on what we just started to add to the // link line. And finally upstream native libraries can't depend on anything // in this DAG so far because they're only dylibs and dylibs can only depend - // on other dylibs (e.g. other native deps). + // on other dylibs (e.g., other native deps). add_local_native_libraries(cmd, sess, codegen_results); add_upstream_rust_crates(cmd, sess, codegen_results, crate_type, tmpdir); add_upstream_native_libraries(cmd, sess, codegen_results, crate_type); @@ -1205,7 +1205,7 @@ fn add_upstream_rust_crates(cmd: &mut dyn Linker, // compiler-builtins are always placed last to ensure that they're // linked correctly. // We must always link the `compiler_builtins` crate statically. Even if it - // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic` + // was already "included" in a dylib (e.g., `libstd` when `-C prefer-dynamic` // is used) if let Some(cnum) = compiler_builtins { add_static_crate(cmd, sess, codegen_results, tmpdir, crate_type, cnum); @@ -1385,7 +1385,7 @@ fn add_upstream_rust_crates(cmd: &mut dyn Linker, // because a `dylib` can be reused as an intermediate artifact. // // Note, though, that we don't want to include the whole of a - // compiler-builtins crate (e.g. compiler-rt) because it'll get + // compiler-builtins crate (e.g., compiler-rt) because it'll get // repeatedly linked anyway. if crate_type == config::CrateType::Dylib && codegen_results.crate_info.compiler_builtins != Some(cnum) { diff --git a/src/librustc_codegen_llvm/back/write.rs b/src/librustc_codegen_llvm/back/write.rs index 2ddbd0c299a..78a3b6907a6 100644 --- a/src/librustc_codegen_llvm/back/write.rs +++ b/src/librustc_codegen_llvm/back/write.rs @@ -782,7 +782,7 @@ fn create_msvc_imps( } // The x86 ABI seems to require that leading underscores are added to symbol // names, so we need an extra underscore on 32-bit. There's also a leading - // '\x01' here which disables LLVM's symbol mangling (e.g. no extra + // '\x01' here which disables LLVM's symbol mangling (e.g., no extra // underscores added in front). let prefix = if cgcx.target_pointer_width == "32" { "\x01__imp__" diff --git a/src/librustc_codegen_llvm/common.rs b/src/librustc_codegen_llvm/common.rs index fd13421835c..55f286eb0be 100644 --- a/src/librustc_codegen_llvm/common.rs +++ b/src/librustc_codegen_llvm/common.rs @@ -63,7 +63,7 @@ pub use context::CodegenCx; /// /// Each `Block` may contain an instance of this, indicating whether the block /// is part of a landing pad or not. This is used to make decision about whether -/// to emit `invoke` instructions (e.g. in a landing pad we don't continue to +/// to emit `invoke` instructions (e.g., in a landing pad we don't continue to /// use `invoke`) and also about various function call metadata. /// /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is diff --git a/src/librustc_codegen_llvm/consts.rs b/src/librustc_codegen_llvm/consts.rs index a4baa332fe2..086fb1f5a93 100644 --- a/src/librustc_codegen_llvm/consts.rs +++ b/src/librustc_codegen_llvm/consts.rs @@ -295,7 +295,7 @@ impl CodegenCx<'ll, 'tcx> { self.tcx.sess.opts.cg.prefer_dynamic)); if needs_dll_storage_attr { - // This item is external but not foreign, i.e. it originates from an external Rust + // This item is external but not foreign, i.e., it originates from an external Rust // crate. Since we don't know whether this crate will be linked dynamically or // statically in the final application, we always mark such symbols as 'dllimport'. // If final linkage happens to be static, we rely on compiler-emitted __imp_ stubs @@ -426,7 +426,7 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> { // // By default a global's alignment can be freely increased. // This allows LLVM to generate more performant instructions - // e.g. using load-aligned into a SIMD register. + // e.g., using load-aligned into a SIMD register. // // However, on macOS 10.10 or below, the dynamic linker does not // respect any alignment given on the TLS (radar 24221680). diff --git a/src/librustc_codegen_llvm/context.rs b/src/librustc_codegen_llvm/context.rs index 564e424cf6c..6c90937de3f 100644 --- a/src/librustc_codegen_llvm/context.rs +++ b/src/librustc_codegen_llvm/context.rs @@ -233,7 +233,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { // they're not available to be linked against. This poses a few problems // for the compiler, some of which are somewhat fundamental, but we use // the `use_dll_storage_attrs` variable below to attach the `dllexport` - // attribute to all LLVM functions that are exported e.g. they're + // attribute to all LLVM functions that are exported e.g., they're // already tagged with external linkage). This is suboptimal for a few // reasons: // diff --git a/src/librustc_codegen_llvm/debuginfo/doc.rs b/src/librustc_codegen_llvm/debuginfo/doc.rs index ce0476b07eb..5e2476e0918 100644 --- a/src/librustc_codegen_llvm/debuginfo/doc.rs +++ b/src/librustc_codegen_llvm/debuginfo/doc.rs @@ -166,7 +166,7 @@ //! //! (3) Tuple-, pointer and function types are structurally identified, which //! means that they are equivalent if their component types are equivalent -//! (i.e. (i32, i32) is the same regardless in which crate it is used). +//! (i.e., (i32, i32) is the same regardless in which crate it is used). //! //! This algorithm also provides a stable ID for types that are defined in one //! crate but instantiated from metadata within another crate. We just have to diff --git a/src/librustc_codegen_llvm/debuginfo/metadata.rs b/src/librustc_codegen_llvm/debuginfo/metadata.rs index 5a1c62e2536..d263b4e1237 100644 --- a/src/librustc_codegen_llvm/debuginfo/metadata.rs +++ b/src/librustc_codegen_llvm/debuginfo/metadata.rs @@ -509,7 +509,7 @@ pub fn type_metadata( }, None => { // The Ty is not in the TypeMap but maybe we have already seen - // an equivalent type (e.g. only differing in region arguments). + // an equivalent type (e.g., only differing in region arguments). // In order to find out, generate the unique type id and look // that up. let unique_type_id = type_map.get_unique_type_id_of_type(cx, t); diff --git a/src/librustc_codegen_llvm/debuginfo/mod.rs b/src/librustc_codegen_llvm/debuginfo/mod.rs index e54e180224e..5b65b1fdda6 100644 --- a/src/librustc_codegen_llvm/debuginfo/mod.rs +++ b/src/librustc_codegen_llvm/debuginfo/mod.rs @@ -488,7 +488,7 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> { ); // Only "class" methods are generally understood by LLVM, - // so avoid methods on other types (e.g. `<*mut T>::null`). + // so avoid methods on other types (e.g., `<*mut T>::null`). match impl_self_ty.sty { ty::Adt(def, ..) if !def.is_box() => { Some(type_metadata(cx, impl_self_ty, syntax_pos::DUMMY_SP)) diff --git a/src/librustc_codegen_llvm/debuginfo/type_names.rs b/src/librustc_codegen_llvm/debuginfo/type_names.rs index 60545f9e193..2e827cc6d06 100644 --- a/src/librustc_codegen_llvm/debuginfo/type_names.rs +++ b/src/librustc_codegen_llvm/debuginfo/type_names.rs @@ -19,9 +19,9 @@ use rustc_codegen_ssa::traits::*; use rustc::hir; // Compute the name of the type as it should be stored in debuginfo. Does not do -// any caching, i.e. calling the function twice with the same type will also do +// any caching, i.e., calling the function twice with the same type will also do // the work twice. The `qualified` parameter only affects the first level of the -// type name, further levels (i.e. type parameters) are always fully qualified. +// type name, further levels (i.e., type parameters) are always fully qualified. pub fn compute_debuginfo_type_name<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, t: Ty<'tcx>, qualified: bool) diff --git a/src/librustc_codegen_llvm/debuginfo/utils.rs b/src/librustc_codegen_llvm/debuginfo/utils.rs index 89262beb356..4b6ef30b138 100644 --- a/src/librustc_codegen_llvm/debuginfo/utils.rs +++ b/src/librustc_codegen_llvm/debuginfo/utils.rs @@ -26,7 +26,7 @@ use syntax_pos::{self, Span}; pub fn is_node_local_to_unit(cx: &CodegenCx, def_id: DefId) -> bool { // The is_local_to_unit flag indicates whether a function is local to the - // current compilation unit (i.e. if it is *static* in the C-sense). The + // current compilation unit (i.e., if it is *static* in the C-sense). The // *reachable* set should provide a good approximation of this, as it // contains everything that might leak out of the current crate (by being // externally visible or by being inlined into something externally diff --git a/src/librustc_codegen_llvm/intrinsic.rs b/src/librustc_codegen_llvm/intrinsic.rs index 313aa175106..59608b11939 100644 --- a/src/librustc_codegen_llvm/intrinsic.rs +++ b/src/librustc_codegen_llvm/intrinsic.rs @@ -732,7 +732,7 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> { // We found a tuple that needs squishing! So // run over the tuple and load each field. // - // This assumes the type is "simple", i.e. no + // This assumes the type is "simple", i.e., no // destructors, and the contents are SIMD // etc. assert!(!bx.type_needs_drop(arg.layout.ty)); @@ -997,7 +997,7 @@ fn codegen_msvc_try( } // Definition of the standard "try" function for Rust using the GNU-like model -// of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke +// of exceptions (e.g., the normal semantics of LLVM's landingpad and invoke // instructions). // // This codegen is a little surprising because we always call a shim diff --git a/src/librustc_codegen_llvm/llvm/mod.rs b/src/librustc_codegen_llvm/llvm/mod.rs index fbd5192a63f..3764c122dea 100644 --- a/src/librustc_codegen_llvm/llvm/mod.rs +++ b/src/librustc_codegen_llvm/llvm/mod.rs @@ -125,7 +125,7 @@ pub fn SetFunctionCallConv(fn_: &'a Value, cc: CallConv) { // example happen for generics when using multiple codegen units. This function simply uses the // value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the // function. -// For more details on COMDAT sections see e.g. http://www.airs.com/blog/archives/52 +// For more details on COMDAT sections see e.g., http://www.airs.com/blog/archives/52 pub fn SetUniqueComdat(llmod: &Module, val: &'a Value) { unsafe { LLVMRustSetComdat(llmod, val, LLVMGetValueName(val)); diff --git a/src/librustc_codegen_llvm/mono_item.rs b/src/librustc_codegen_llvm/mono_item.rs index 9b2d17d65ca..1d5bcc4ba39 100644 --- a/src/librustc_codegen_llvm/mono_item.rs +++ b/src/librustc_codegen_llvm/mono_item.rs @@ -63,7 +63,7 @@ impl PreDefineMethods<'tcx> for CodegenCx<'ll, 'tcx> { llvm::SetUniqueComdat(self.llmod, lldecl); } - // If we're compiling the compiler-builtins crate, e.g. the equivalent of + // If we're compiling the compiler-builtins crate, e.g., the equivalent of // compiler-rt, then we want to implicitly compile everything with hidden // visibility as we're going to link this object all over the place but // don't want the symbols to get exported. diff --git a/src/librustc_codegen_llvm/type_.rs b/src/librustc_codegen_llvm/type_.rs index b100b677803..313ab1f974f 100644 --- a/src/librustc_codegen_llvm/type_.rs +++ b/src/librustc_codegen_llvm/type_.rs @@ -255,7 +255,7 @@ impl Type { } } - // Creates an integer type with the given number of bits, e.g. i24 + // Creates an integer type with the given number of bits, e.g., i24 pub fn ix_llcx( llcx: &llvm::Context, num_bits: u64 diff --git a/src/librustc_codegen_llvm/type_of.rs b/src/librustc_codegen_llvm/type_of.rs index 15b5bdeb44d..52b560c6625 100644 --- a/src/librustc_codegen_llvm/type_of.rs +++ b/src/librustc_codegen_llvm/type_of.rs @@ -15,8 +15,8 @@ use rustc::ty::{self, Ty, TypeFoldable}; use rustc::ty::layout::{self, Align, LayoutOf, Size, TyLayout}; use rustc_target::abi::FloatTy; use rustc_mir::monomorphize::item::DefPathBasedNames; -use type_::Type; use rustc_codegen_ssa::traits::*; +use type_::Type; use std::fmt::Write; @@ -84,10 +84,10 @@ fn uncached_llvm_type<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, let packed = false; match name { None => { - cx.type_struct( &[fill], packed) + cx.type_struct(&[fill], packed) } Some(ref name) => { - let llty = cx.type_named_struct( name); + let llty = cx.type_named_struct(name); cx.set_struct_body(llty, &[fill], packed); llty } @@ -236,7 +236,7 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> { } } - /// Get the LLVM type corresponding to a Rust type, i.e. `rustc::ty::Ty`. + /// Get the LLVM type corresponding to a Rust type, i.e., `rustc::ty::Ty`. /// The pointee type of the pointer in `PlaceRef` is always this type. /// For sized types, it is also the right LLVM type for an `alloca` /// containing a value of that type, and most immediates (except `bool`). @@ -470,9 +470,9 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyLayout<'tcx> { // (according to its type), or null (which the // niche field's scalar validity range encodes). // This allows using `dereferenceable_or_null` - // for e.g. `Option<&T>`, and this will continue + // for e.g., `Option<&T>`, and this will continue // to work as long as we don't start using more - // niches than just null (e.g. the first page + // niches than just null (e.g., the first page // of the address space, or unaligned pointers). if self.fields.offset(0) == offset { Some(self.for_variant(cx, dataful_variant)) diff --git a/src/librustc_codegen_ssa/back/linker.rs b/src/librustc_codegen_ssa/back/linker.rs index f3cc344254f..2f92c427f65 100644 --- a/src/librustc_codegen_ssa/back/linker.rs +++ b/src/librustc_codegen_ssa/back/linker.rs @@ -107,7 +107,7 @@ impl LinkerInfo { /// This trait is the total list of requirements needed by `back::link` and /// represents the meaning of each option being passed down. This trait is then /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an -/// MSVC linker (e.g. `link.exe`) is being used. +/// MSVC linker (e.g., `link.exe`) is being used. pub trait Linker { fn link_dylib(&mut self, lib: &str); fn link_rust_dylib(&mut self, lib: &str, path: &Path); diff --git a/src/librustc_codegen_ssa/back/symbol_export.rs b/src/librustc_codegen_ssa/back/symbol_export.rs index 84b17e31dd4..a17a00ddb29 100644 --- a/src/librustc_codegen_ssa/back/symbol_export.rs +++ b/src/librustc_codegen_ssa/back/symbol_export.rs @@ -85,7 +85,7 @@ fn reachable_non_generics_provider<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // categories: // // 1. Those that are included statically via a static library - // 2. Those included otherwise (e.g. dynamically or via a framework) + // 2. Those included otherwise (e.g., dynamically or via a framework) // // Although our LLVM module is not literally emitting code for the // statically included symbols, it's an export of our library which diff --git a/src/librustc_codegen_ssa/base.rs b/src/librustc_codegen_ssa/base.rs index 76d699d1736..8a5b8bd2bab 100644 --- a/src/librustc_codegen_ssa/base.rs +++ b/src/librustc_codegen_ssa/base.rs @@ -268,7 +268,7 @@ pub fn coerce_unsized_into<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>( let (base, info) = match bx.load_operand(src).val { OperandValue::Pair(base, info) => { // fat-ptr to fat-ptr unsize preserves the vtable - // i.e. &'a fmt::Debug+Send => &'a fmt::Debug + // i.e., &'a fmt::Debug+Send => &'a fmt::Debug // So we need to pointercast the base to ensure // the types match up. let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR); diff --git a/src/librustc_codegen_ssa/common.rs b/src/librustc_codegen_ssa/common.rs index 8c53129abc3..70b7729b78b 100644 --- a/src/librustc_codegen_ssa/common.rs +++ b/src/librustc_codegen_ssa/common.rs @@ -158,7 +158,7 @@ pub fn langcall(tcx: TyCtxt, } // To avoid UB from LLVM, these two functions mask RHS with an -// appropriate mask unconditionally (i.e. the fallback behavior for +// appropriate mask unconditionally (i.e., the fallback behavior for // all shifts). For 32- and 64-bit types, this matches the semantics // of Java. (See related discussion on #1877 and #10183.) diff --git a/src/librustc_codegen_ssa/lib.rs b/src/librustc_codegen_ssa/lib.rs index 24ede4db6e3..d0cdb8924df 100644 --- a/src/librustc_codegen_ssa/lib.rs +++ b/src/librustc_codegen_ssa/lib.rs @@ -61,7 +61,7 @@ use rustc_data_structures::svh::Svh; use rustc::middle::cstore::{LibSource, CrateSource, NativeLibrary}; use syntax_pos::symbol::Symbol; -// NB: This module needs to be declared first so diagnostics are +// N.B., this module needs to be declared first so diagnostics are // registered before they are used. mod diagnostics; diff --git a/src/librustc_codegen_ssa/mir/analyze.rs b/src/librustc_codegen_ssa/mir/analyze.rs index c7e2c76c3e5..81da7f5fb5c 100644 --- a/src/librustc_codegen_ssa/mir/analyze.rs +++ b/src/librustc_codegen_ssa/mir/analyze.rs @@ -43,7 +43,7 @@ pub fn non_ssa_locals<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>( // These sorts of types require an alloca. Note that // is_llvm_immediate() may *still* be true, particularly // for newtypes, but we currently force some types - // (e.g. structs) into an alloca unconditionally, just so + // (e.g., structs) into an alloca unconditionally, just so // that we don't have to deal with having two pathways // (gep vs extractvalue etc). analyzer.not_ssa(mir::Local::new(index)); @@ -227,9 +227,9 @@ impl<'mir, 'a: 'mir, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> Visitor<'tcx> PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) | PlaceContext::NonMutatingUse(NonMutatingUseContext::Move) => { - // Reads from uninitialized variables (e.g. in dead code, after + // Reads from uninitialized variables (e.g., in dead code, after // optimizations) require locals to be in (uninitialized) memory. - // NB: there can be uninitialized reads of a local visited after + // N.B., there can be uninitialized reads of a local visited after // an assignment to that local, if they happen on disjoint paths. let ssa_read = match self.first_assignment(local) { Some(assignment_location) => { diff --git a/src/librustc_codegen_ssa/mir/mod.rs b/src/librustc_codegen_ssa/mir/mod.rs index a992364959e..750de1c660c 100644 --- a/src/librustc_codegen_ssa/mir/mod.rs +++ b/src/librustc_codegen_ssa/mir/mod.rs @@ -467,7 +467,7 @@ fn arg_local_refs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>( }; if Some(local) == mir.spread_arg { - // This argument (e.g. the last argument in the "rust-call" ABI) + // This argument (e.g., the last argument in the "rust-call" ABI) // is a tuple that was spread at the ABI level and now we have // to reconstruct it into a tuple local variable, from multiple // individual LLVM function arguments. @@ -614,7 +614,7 @@ fn arg_local_refs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>( // because that's what the llvm.dbg.declare intrinsic expects. // FIXME(eddyb) this shouldn't be necessary but SROA seems to - // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it + // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e., it // doesn't actually strip the offset when splitting the closure // environment into its components so it ends up out of bounds. // (cuviper) It seems to be fine without the alloca on LLVM 6 and later. diff --git a/src/librustc_codegen_ssa/mir/place.rs b/src/librustc_codegen_ssa/mir/place.rs index 1aba53255e7..90aa9f6cbc7 100644 --- a/src/librustc_codegen_ssa/mir/place.rs +++ b/src/librustc_codegen_ssa/mir/place.rs @@ -229,9 +229,9 @@ impl<'a, 'tcx: 'a, V: CodegenObject> PlaceRef<'tcx, V> { layout::Variants::Tagged { ref tag, .. } => { let signed = match tag.value { // We use `i1` for bytes that are always `0` or `1`, - // e.g. `#[repr(i8)] enum E { A, B }`, but we can't + // e.g., `#[repr(i8)] enum E { A, B }`, but we can't // let LLVM interpret the `i1` as signed, because - // then `i1 1` (i.e. E::B) is effectively `i8 -1`. + // then `i1 1` (i.e., E::B) is effectively `i8 -1`. layout::Int(_, signed) => !tag.is_bool() && signed, _ => false }; diff --git a/src/librustc_codegen_ssa/mir/rvalue.rs b/src/librustc_codegen_ssa/mir/rvalue.rs index dc7b1ec37b2..c932ffd1c1b 100644 --- a/src/librustc_codegen_ssa/mir/rvalue.rs +++ b/src/librustc_codegen_ssa/mir/rvalue.rs @@ -319,9 +319,9 @@ impl<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { if let layout::Abi::Scalar(ref scalar) = operand.layout.abi { if let layout::Int(_, s) = scalar.value { // We use `i1` for bytes that are always `0` or `1`, - // e.g. `#[repr(i8)] enum E { A, B }`, but we can't + // e.g., `#[repr(i8)] enum E { A, B }`, but we can't // let LLVM interpret the `i1` as signed, because - // then `i1 1` (i.e. E::B) is effectively `i8 -1`. + // then `i1 1` (i.e., E::B) is effectively `i8 -1`. signed = !scalar.is_bool() && s; let er = scalar.valid_range_exclusive(bx.cx()); diff --git a/src/librustc_codegen_ssa/traits/declare.rs b/src/librustc_codegen_ssa/traits/declare.rs index f9a29652843..611e5f758a7 100644 --- a/src/librustc_codegen_ssa/traits/declare.rs +++ b/src/librustc_codegen_ssa/traits/declare.rs @@ -41,7 +41,7 @@ pub trait DeclareMethods<'tcx>: BackendTypes { /// Use this function when you intend to define a global. This function will /// return None if the name already has a definition associated with it. In that /// case an error should be reported to the user, because it usually happens due - /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes). + /// to user’s fault (e.g., misuse of #[no_mangle] or #[export_name] attributes). fn define_global(&self, name: &str, ty: Self::Type) -> Option; /// Declare a private global diff --git a/src/librustc_codegen_ssa/traits/type_.rs b/src/librustc_codegen_ssa/traits/type_.rs index 1d31bdfa9f0..ed53c8fffa7 100644 --- a/src/librustc_codegen_ssa/traits/type_.rs +++ b/src/librustc_codegen_ssa/traits/type_.rs @@ -32,7 +32,7 @@ pub trait BaseTypeMethods<'tcx>: Backend<'tcx> { fn type_i64(&self) -> Self::Type; fn type_i128(&self) -> Self::Type; - // Creates an integer type with the given number of bits, e.g. i24 + // Creates an integer type with the given number of bits, e.g., i24 fn type_ix(&self, num_bits: u64) -> Self::Type; fn type_isize(&self) -> Self::Type; diff --git a/src/librustc_codegen_utils/symbol_names.rs b/src/librustc_codegen_utils/symbol_names.rs index 305c718ff06..d5b95e77b1a 100644 --- a/src/librustc_codegen_utils/symbol_names.rs +++ b/src/librustc_codegen_utils/symbol_names.rs @@ -71,7 +71,7 @@ //! order to also avoid inter-crate conflicts two more measures are taken: //! //! - The name of the crate containing the symbol is prepended to the symbol -//! name, i.e. symbols are "crate qualified". For example, a function `foo` in +//! name, i.e., symbols are "crate qualified". For example, a function `foo` in //! module `bar` in crate `baz` would get a symbol name like //! `baz::bar::foo::{hash}` instead of just `bar::foo::{hash}`. This avoids //! simple conflicts between functions from different crates. diff --git a/src/librustc_data_structures/obligation_forest/mod.rs b/src/librustc_data_structures/obligation_forest/mod.rs index c211d888df1..2a1958357e0 100644 --- a/src/librustc_data_structures/obligation_forest/mod.rs +++ b/src/librustc_data_structures/obligation_forest/mod.rs @@ -531,7 +531,7 @@ impl ObligationForest { /// indices. Cannot be used during a transaction. /// /// Beforehand, all nodes must be marked as `Done` and no cycles - /// on these nodes may be present. This is done by e.g. `process_cycles`. + /// on these nodes may be present. This is done by e.g., `process_cycles`. #[inline(never)] fn compress(&mut self, do_completed: DoCompleted) -> Option> { let nodes_len = self.nodes.len(); diff --git a/src/librustc_data_structures/owning_ref/mod.rs b/src/librustc_data_structures/owning_ref/mod.rs index 27c2f8b718a..0b126e5c572 100644 --- a/src/librustc_data_structures/owning_ref/mod.rs +++ b/src/librustc_data_structures/owning_ref/mod.rs @@ -215,7 +215,7 @@ fn main() { ## Mutable reference When the owned container implements `DerefMut`, it is also possible to make -a _mutable owning reference_. (E.g. with `Box`, `RefMut`, `MutexGuard`) +a _mutable owning reference_. (e.g., with `Box`, `RefMut`, `MutexGuard`) ``` extern crate owning_ref; @@ -452,7 +452,7 @@ impl OwningRef { /// use owning_ref::{OwningRef, Erased}; /// /// fn main() { - /// // NB: Using the concrete types here for explicitness. + /// // N.B., using the concrete types here for explicitness. /// // For less verbose code type aliases like `BoxRef` are provided. /// /// let owning_ref_a: OwningRef, [i32; 4]> @@ -722,7 +722,7 @@ impl OwningRefMut { /// use owning_ref::{OwningRefMut, Erased}; /// /// fn main() { - /// // NB: Using the concrete types here for explicitness. + /// // N.B., using the concrete types here for explicitness. /// // For less verbose code type aliases like `BoxRef` are provided. /// /// let owning_ref_mut_a: OwningRefMut, [i32; 4]> @@ -1124,8 +1124,8 @@ impl ToHandleMut for RefCell { unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { (*x).borrow_mut() } } -// NB: Implementing ToHandle{,Mut} for Mutex and RwLock requires a decision -// about which handle creation to use (i.e. read() vs try_read()) as well as +// N.B., implementing ToHandle{,Mut} for Mutex and RwLock requires a decision +// about which handle creation to use (i.e., read() vs try_read()) as well as // what to do with error results. /// Typedef of a owning reference that uses a `Box` as the owner. diff --git a/src/librustc_data_structures/thin_vec.rs b/src/librustc_data_structures/thin_vec.rs index 546686b46b8..5b7ea161b28 100644 --- a/src/librustc_data_structures/thin_vec.rs +++ b/src/librustc_data_structures/thin_vec.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/// A vector type optimized for cases where this size is usually 0 (c.f. `SmallVector`). +/// A vector type optimized for cases where this size is usually 0 (cf. `SmallVector`). /// The `Option>` wrapping allows us to represent a zero sized vector with `None`, /// which uses only a single (null) pointer. #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Debug)] diff --git a/src/librustc_data_structures/transitive_relation.rs b/src/librustc_data_structures/transitive_relation.rs index fd5dfab9e61..250dad8136e 100644 --- a/src/librustc_data_structures/transitive_relation.rs +++ b/src/librustc_data_structures/transitive_relation.rs @@ -304,7 +304,7 @@ impl TransitiveRelation { /// /// The intuition is that this moves "one step up" through a lattice /// (where the relation is encoding the `<=` relation for the lattice). - /// So e.g. if the relation is `->` and we have + /// So e.g., if the relation is `->` and we have /// /// ``` /// a -> b -> d -> f diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 2a1a3b481b3..f2edcdc1bac 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -9,15 +9,9 @@ // except according to those terms. use rustc::dep_graph::DepGraph; -use rustc::hir::{self, map as hir_map}; +use rustc::hir; use rustc::hir::lowering::lower_crate; -use rustc_data_structures::fingerprint::Fingerprint; -use rustc_data_structures::stable_hasher::StableHasher; -use rustc_mir as mir; -use rustc::session::{CompileResult, CrateDisambiguator, Session}; -use rustc::session::CompileIncomplete; -use rustc::session::config::{self, Input, OutputFilenames, OutputType}; -use rustc::session::search_paths::PathKind; +use rustc::hir::map as hir_map; use rustc::lint; use rustc::middle::{self, reachable, resolve_lifetime, stability}; use rustc::middle::privacy::AccessLevels; @@ -25,20 +19,37 @@ use rustc::ty::{self, AllArenas, Resolutions, TyCtxt}; use rustc::traits; use rustc::util::common::{install_panic_hook, time, ErrorReported}; use rustc::util::profiling::ProfileCategory; +use rustc::session::{CompileResult, CrateDisambiguator, Session}; +use rustc::session::CompileIncomplete; +use rustc::session::config::{self, Input, OutputFilenames, OutputType}; +use rustc::session::search_paths::PathKind; use rustc_allocator as allocator; use rustc_borrowck as borrowck; +use rustc_codegen_utils::codegen_backend::CodegenBackend; +use rustc_data_structures::fingerprint::Fingerprint; +use rustc_data_structures::stable_hasher::StableHasher; +use rustc_data_structures::sync::{self, Lrc, Lock}; use rustc_incremental; -use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas}; use rustc_metadata::creader::CrateLoader; use rustc_metadata::cstore::{self, CStore}; +use rustc_mir as mir; +use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion}; +use rustc_plugin as plugin; +use rustc_plugin::registry::Registry; +use rustc_privacy; +use rustc_resolve::{MakeGlobMap, Resolver, ResolverArenas}; use rustc_traits; -use rustc_codegen_utils::codegen_backend::CodegenBackend; use rustc_typeck as typeck; -use rustc_privacy; -use rustc_plugin::registry::Registry; -use rustc_plugin as plugin; -use rustc_passes::{self, ast_validation, hir_stats, loops, rvalue_promotion}; -use super::Compilation; +use syntax::{self, ast, attr, diagnostics, visit}; +use syntax::early_buffered_lints::BufferedEarlyLint; +use syntax::ext::base::ExtCtxt; +use syntax::fold::Folder; +use syntax::parse::{self, PResult}; +use syntax::util::node_count::NodeCounter; +use syntax::util::lev_distance::find_best_match_for_name; +use syntax::symbol::Symbol; +use syntax_pos::{FileName, hygiene}; +use syntax_ext; use serialize::json; @@ -49,23 +60,12 @@ use std::fs; use std::io::{self, Write}; use std::iter; use std::path::{Path, PathBuf}; -use rustc_data_structures::sync::{self, Lrc, Lock}; use std::sync::mpsc; -use syntax::{self, ast, attr, diagnostics, visit}; -use syntax::early_buffered_lints::BufferedEarlyLint; -use syntax::ext::base::ExtCtxt; -use syntax::fold::Folder; -use syntax::parse::{self, PResult}; -use syntax::util::node_count::NodeCounter; -use syntax::util::lev_distance::find_best_match_for_name; -use syntax::symbol::Symbol; -use syntax_pos::{FileName, hygiene}; -use syntax_ext; -use proc_macro_decls; use pretty::ReplaceBodyWithLoop; - +use proc_macro_decls; use profile; +use super::Compilation; #[cfg(not(parallel_queries))] pub fn spawn_thread_pool R + sync::Send, R: sync::Send>( diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index b89c4262024..b41b0d081ce 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -8,25 +8,21 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! The various pretty print routines. +//! The various pretty-printing routines. -pub use self::UserIdentifiedItem::*; -pub use self::PpSourceMode::*; -pub use self::PpMode::*; -use self::NodesMatchingUII::*; - -use {abort_on_err, driver}; - -use rustc::ty::{self, TyCtxt, Resolutions, AllArenas}; use rustc::cfg; use rustc::cfg::graphviz::LabelledCFG; +use rustc::hir; +use rustc::hir::map as hir_map; +use rustc::hir::map::blocks; +use rustc::hir::print as pprust_hir; use rustc::session::Session; use rustc::session::config::{Input, OutputFilenames}; +use rustc::ty::{self, TyCtxt, Resolutions, AllArenas}; use rustc_borrowck as borrowck; use rustc_borrowck::graphviz as borrowck_dot; use rustc_data_structures::thin_vec::ThinVec; use rustc_metadata::cstore::CStore; - use rustc_mir::util::{write_mir_pretty, write_mir_graphviz}; use syntax::ast::{self, BlockCheckMode}; @@ -47,10 +43,11 @@ use std::path::Path; use std::str::FromStr; use std::mem; -use rustc::hir::map as hir_map; -use rustc::hir::map::blocks; -use rustc::hir; -use rustc::hir::print as pprust_hir; +pub use self::UserIdentifiedItem::*; +pub use self::PpSourceMode::*; +pub use self::PpMode::*; +use self::NodesMatchingUII::*; +use {abort_on_err, driver}; #[derive(Copy, Clone, PartialEq, Debug)] pub enum PpSourceMode { diff --git a/src/librustc_driver/test.rs b/src/librustc_driver/test.rs index 77bd05cf919..f9d49f03ee0 100644 --- a/src/librustc_driver/test.rs +++ b/src/librustc_driver/test.rs @@ -10,13 +10,11 @@ //! # Standalone Tests for the Inference Module -use std::path::PathBuf; -use std::sync::mpsc; - use driver; use errors; use errors::emitter::Emitter; use errors::{DiagnosticBuilder, Level}; +use rustc::hir; use rustc::hir::map as hir_map; use rustc::infer::outlives::env::OutlivesEnvironment; use rustc::infer::type_variable::TypeVariableOrigin; @@ -40,7 +38,8 @@ use syntax::source_map::{FileName, FilePathMapping, SourceMap}; use syntax::symbol::Symbol; use syntax_pos::DUMMY_SP; -use rustc::hir; +use std::path::PathBuf; +use std::sync::mpsc; struct Env<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> { infcx: &'a infer::InferCtxt<'a, 'gcx, 'tcx>, @@ -155,7 +154,7 @@ fn test_env_with_pool( let arenas = ty::AllArenas::new(); let hir_map = hir_map::map_crate(&sess, &cstore, &mut hir_forest, &defs); - // run just enough stuff to build a tcx: + // Run just enough stuff to build a tcx. let (tx, _rx) = mpsc::channel(); let outputs = OutputFilenames { out_directory: PathBuf::new(), @@ -228,8 +227,8 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { } pub fn create_simple_region_hierarchy(&mut self) { - // creates a region hierarchy where 1 is root, 10 and 11 are - // children of 1, etc + // Creates a region hierarchy where 1 is root, 10 and 11 are + // children of 1, etc. let dscope = region::Scope { id: hir::ItemLocalId::from_u32(1), @@ -434,7 +433,7 @@ impl<'a, 'gcx, 'tcx> Env<'a, 'gcx, 'tcx> { obligations, value: (), }) => { - // None of these tests should require nested obligations: + // None of these tests should require nested obligations. assert!(obligations.is_empty()); } Err(ref e) => { @@ -476,7 +475,7 @@ fn contravariant_region_ptr_err() { env.assert_eq(t_rptr1, t_rptr1); env.assert_eq(t_rptr10, t_rptr10); - // will cause an error when regions are resolved + // This will cause an error when regions are resolved. env.make_subtype(t_rptr10, t_rptr1); }) } @@ -487,7 +486,7 @@ fn sub_free_bound_false() { //! //! fn(&'a isize) <: for<'b> fn(&'b isize) //! - //! does NOT hold. + //! *does not* hold. test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| { env.create_simple_region_hierarchy(); @@ -506,7 +505,7 @@ fn sub_bound_free_true() { //! //! for<'a> fn(&'a isize) <: fn(&'b isize) //! - //! DOES hold. + //! *does* hold. test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| { env.create_simple_region_hierarchy(); @@ -578,11 +577,11 @@ fn subst_ty_renumber_bound() { fn subst_ty_renumber_some_bounds() { test_env(EMPTY_SOURCE_STR, errors(&[]), |env| { // Situation: - // Theta = [A -> &'a foo] + // `Theta = [A -> &'a foo]` let t_rptr_bound1 = env.t_rptr_late_bound(1); - // t_source = (A, fn(A)) + // `t_source = (A, fn(A))` let t_source = { let t_param = env.t_param(0); env.t_pair(t_param, env.t_fn(&[t_param], env.t_nil())) @@ -591,9 +590,9 @@ fn subst_ty_renumber_some_bounds() { let substs = env.infcx.tcx.intern_substs(&[t_rptr_bound1.into()]); let t_substituted = t_source.subst(env.infcx.tcx, substs); - // t_expected = (&'a isize, fn(&'a isize)) + // `t_expected = (&'a isize, fn(&'a isize))` // - // but not that the Debruijn index is different in the different cases. + // However, note that the Debruijn index is different in the different cases. let t_expected = { let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, d2()); env.t_pair(t_rptr_bound1, env.t_fn(&[t_rptr_bound2], env.t_nil())) @@ -613,7 +612,7 @@ fn subst_ty_renumber_some_bounds() { fn escaping() { test_env(EMPTY_SOURCE_STR, errors(&[]), |mut env| { // Situation: - // Theta = [A -> &'a foo] + // `Theta = [A -> &'a foo]` env.create_simple_region_hierarchy(); assert!(!env.t_nil().has_escaping_bound_vars()); @@ -627,7 +626,7 @@ fn escaping() { let t_rptr_bound2 = env.t_rptr_late_bound_with_debruijn(1, d2()); assert!(t_rptr_bound2.has_escaping_bound_vars()); - // t_fn = fn(A) + // `t_fn = fn(A)` let t_param = env.t_param(0); assert!(!t_param.has_escaping_bound_vars()); let t_fn = env.t_fn(&[t_param], env.t_nil()); @@ -642,7 +641,7 @@ fn subst_region_renumber_region() { test_env(EMPTY_SOURCE_STR, errors(&[]), |env| { let re_bound1 = env.re_late_bound_with_debruijn(1, d1()); - // type t_source<'a> = fn(&'a isize) + // `type t_source<'a> = fn(&'a isize)` let t_source = { let re_early = env.re_early_bound(0, "'a"); env.t_fn(&[env.t_rptr(re_early)], env.t_nil()) @@ -651,7 +650,7 @@ fn subst_region_renumber_region() { let substs = env.infcx.tcx.intern_substs(&[re_bound1.into()]); let t_substituted = t_source.subst(env.infcx.tcx, substs); - // t_expected = fn(&'a isize) + // `t_expected = fn(&'a isize)` // // but not that the Debruijn index is different in the different cases. let t_expected = { diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs index 55a4a63c8f3..e17663c41e5 100644 --- a/src/librustc_incremental/persist/dirty_clean.rs +++ b/src/librustc_incremental/persist/dirty_clean.rs @@ -78,7 +78,7 @@ const BASE_IMPL: &[&str] = &[ ]; /// DepNodes for MirValidated/Optimized, which is relevant in "executable" -/// code, i.e. functions+methods +/// code, i.e., functions+methods const BASE_MIR: &[&str] = &[ label_strs::MirOptimized, label_strs::MirValidated, @@ -364,16 +364,16 @@ impl<'a, 'tcx> DirtyCleanVisitor<'a, 'tcx> { // Module-level inline assembly (from global_asm!) HirItem::GlobalAsm(..) => ("ItemGlobalAsm", LABELS_HIR_ONLY), - // A type alias, e.g. `type Foo = Bar` + // A type alias, e.g., `type Foo = Bar` HirItem::Ty(..) => ("ItemTy", LABELS_HIR_ONLY), - // An enum definition, e.g. `enum Foo {C, D}` + // An enum definition, e.g., `enum Foo {C, D}` HirItem::Enum(..) => ("ItemEnum", LABELS_ADT), - // A struct definition, e.g. `struct Foo {x: A}` + // A struct definition, e.g., `struct Foo {x: A}` HirItem::Struct(..) => ("ItemStruct", LABELS_ADT), - // A union definition, e.g. `union Foo {x: A, y: B}` + // A union definition, e.g., `union Foo {x: A, y: B}` HirItem::Union(..) => ("ItemUnion", LABELS_ADT), // Represents a Trait Declaration diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index 9d3dc97552f..e0e790e9f23 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -1573,7 +1573,7 @@ impl EarlyLintPass for KeywordIdents { } } - // no new keywords yet for 2018 edition and beyond + // There are no new keywords yet for the 2018 edition and beyond. // However, `await` is a "false" keyword in the 2018 edition, // and can only be used if the `async_await` feature is enabled. // Otherwise, we emit an error. diff --git a/src/librustc_lint/lib.rs b/src/librustc_lint/lib.rs index 4d709d574c4..b1e44ea761c 100644 --- a/src/librustc_lint/lib.rs +++ b/src/librustc_lint/lib.rs @@ -8,14 +8,14 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Lints in the Rust compiler. +//! # Lints in the Rust compiler //! //! This currently only contains the definitions and implementations //! of most of the lints that `rustc` supports directly, it does not //! contain the infrastructure for defining/registering lints. That is //! available in `rustc::lint` and `rustc_plugin` respectively. //! -//! # Note +//! ## Note //! //! This API is completely unstable and subject to change. @@ -40,6 +40,12 @@ extern crate rustc_target; extern crate syntax_pos; extern crate rustc_data_structures; +mod diagnostics; +mod nonstandard_style; +pub mod builtin; +mod types; +mod unused; + use rustc::lint; use rustc::lint::{LateContext, LateLintPass, LintPass, LintArray}; use rustc::lint::builtin::{ @@ -54,19 +60,13 @@ use rustc::util; use rustc::hir; use syntax::ast; +use syntax::edition::Edition; use syntax_pos::Span; use session::Session; -use syntax::edition::Edition; use lint::LintId; use lint::FutureIncompatibleInfo; -mod diagnostics; -mod nonstandard_style; -pub mod builtin; -mod types; -mod unused; - use nonstandard_style::*; use builtin::*; use types::*; @@ -212,8 +212,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { // and include the full URL, sort items in ascending order of issue numbers. // - Later, change lint to error // - Eventually, remove lint - store.register_future_incompatible(sess, - vec![ + store.register_future_incompatible(sess, vec![ FutureIncompatibleInfo { id: LintId::of(PRIVATE_IN_PUBLIC), reference: "issue #34537 ", @@ -333,7 +332,7 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { }, ]); - // Register renamed and removed lints + // Register renamed and removed lints. store.register_renamed("single_use_lifetime", "single_use_lifetimes"); store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths"); store.register_renamed("bare_trait_object", "bare_trait_objects"); @@ -344,10 +343,10 @@ pub fn register_builtins(store: &mut lint::LintStore, sess: Option<&Session>) { store.register_removed("unsigned_negation", "replaced by negate_unsigned feature gate"); store.register_removed("negate_unsigned", "cast a signed value instead"); store.register_removed("raw_pointer_derive", "using derive with raw pointers is ok"); - // Register lint group aliases + // Register lint group aliases. store.register_group_alias("nonstandard_style", "bad_style"); - // This was renamed to raw_pointer_derive, which was then removed, - // so it is also considered removed + // This was renamed to `raw_pointer_derive`, which was then removed, + // so it is also considered removed. store.register_removed("raw_pointer_deriving", "using derive with raw pointers is ok"); store.register_removed("drop_with_repr_extern", "drop flags have been removed"); store.register_removed("fat_ptr_transmutes", "was accidentally removed back in 2014"); diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs index 33250475d10..13be50ef01f 100644 --- a/src/librustc_lint/nonstandard_style.rs +++ b/src/librustc_lint/nonstandard_style.rs @@ -8,19 +8,17 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use rustc::hir::{self, GenericParamKind, PatKind}; use rustc::hir::def::Def; +use rustc::hir::intravisit::FnKind; use rustc::ty; +use rustc_target::spec::abi::Abi; use lint::{LateContext, LintContext, LintArray}; use lint::{LintPass, LateLintPass}; - -use rustc_target::spec::abi::Abi; use syntax::ast; use syntax::attr; use syntax_pos::Span; -use rustc::hir::{self, GenericParamKind, PatKind}; -use rustc::hir::intravisit::FnKind; - #[derive(PartialEq)] pub enum MethodLateContext { TraitAutoImpl, diff --git a/src/librustc_llvm/lib.rs b/src/librustc_llvm/lib.rs index 1c48d844739..10f35e5598b 100644 --- a/src/librustc_llvm/lib.rs +++ b/src/librustc_llvm/lib.rs @@ -22,7 +22,7 @@ extern crate rustc_cratesio_shim; // NOTE: This crate only exists to allow linking on mingw targets. /// Initialize targets enabled by the build script via `cfg(llvm_component = "...")`. -/// NB: this function can't be moved to `rustc_codegen_llvm` because of the `cfg`s. +/// N.B., this function can't be moved to `rustc_codegen_llvm` because of the `cfg`s. pub fn initialize_available_targets() { macro_rules! init_target( ($cfg:meta, $($method:ident),*) => { { diff --git a/src/librustc_metadata/cstore.rs b/src/librustc_metadata/cstore.rs index 2be9883d03d..f650db5aafa 100644 --- a/src/librustc_metadata/cstore.rs +++ b/src/librustc_metadata/cstore.rs @@ -56,7 +56,7 @@ pub struct CrateMetadata { /// Original name of the crate. pub name: Symbol, - /// Name of the crate as imported. I.e. if imported with + /// Name of the crate as imported. I.e., if imported with /// `extern crate foo as bar;` this will be `bar`. pub imported_name: Symbol, diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index d0fa63a6163..da2ba392c5e 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -307,7 +307,7 @@ pub fn provide<'tcx>(providers: &mut Providers<'tcx>) { Lrc::new(link_args::collect(tcx)) }, - // Returns a map from a sufficiently visible external item (i.e. an + // Returns a map from a sufficiently visible external item (i.e., an // external item that is visible from at least one local module) to a // sufficiently visible parent (considering modules that re-export the // external item to be parents). diff --git a/src/librustc_metadata/locator.rs b/src/librustc_metadata/locator.rs index d4e51693d7e..1f298f6d2d3 100644 --- a/src/librustc_metadata/locator.rs +++ b/src/librustc_metadata/locator.rs @@ -661,7 +661,7 @@ impl<'a> Context<'a> { // Ok so at this point we've determined that `(lib, kind)` above is // a candidate crate to load, and that `slot` is either none (this // is the first crate of its kind) or if some the previous path has - // the exact same hash (e.g. it's the exact same crate). + // the exact same hash (e.g., it's the exact same crate). // // In principle these two candidate crates are exactly the same so // we can choose either of them to link. As a stupidly gross hack, diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs index fc3af6cf2e7..1ae3f0a12bd 100644 --- a/src/librustc_metadata/schema.rs +++ b/src/librustc_metadata/schema.rs @@ -40,7 +40,7 @@ pub fn rustc_version() -> String { } /// Metadata encoding version. -/// NB: increment this if you change the format of metadata such that +/// N.B., increment this if you change the format of metadata such that /// the rustc version can't be found to compare with `rustc_version()`. pub const METADATA_VERSION: u8 = 4; diff --git a/src/librustc_mir/borrow_check/error_reporting.rs b/src/librustc_mir/borrow_check/error_reporting.rs index b8d0c0b348f..598c2f810be 100644 --- a/src/librustc_mir/borrow_check/error_reporting.rs +++ b/src/librustc_mir/borrow_check/error_reporting.rs @@ -1249,7 +1249,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { /// (part of) a non-`mut` local that occurs potentially after that /// local has already been initialized. `place` is the path being /// assigned; `err_place` is a place providing a reason why - /// `place` is not mutable (e.g. the non-`mut` local `x` in an + /// `place` is not mutable (e.g., the non-`mut` local `x` in an /// assignment to `x.f`). pub(super) fn report_illegal_reassignment( &mut self, diff --git a/src/librustc_mir/borrow_check/mod.rs b/src/librustc_mir/borrow_check/mod.rs index 14c366b7628..e3029c6a19d 100644 --- a/src/librustc_mir/borrow_check/mod.rs +++ b/src/librustc_mir/borrow_check/mod.rs @@ -1526,7 +1526,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { // ancestors; dataflow recurs on children when parents // move (to support partial (re)inits). // - // (I.e. querying parents breaks scenario 7; but may want + // (I.e., querying parents breaks scenario 7; but may want // to do such a query based on partial-init feature-gate.) } } @@ -1562,7 +1562,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { // // (Distinct from handling of scenarios 1+2+4 above because // `place` does not interfere with suffixes of its prefixes, - // e.g. `a.b.c` does not interfere with `a.b.d`) + // e.g., `a.b.c` does not interfere with `a.b.d`) // // This code covers scenario 1. @@ -1735,7 +1735,7 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { // // This does not use check_if_path_or_subpath_is_moved, // because we want to *allow* reinitializations of fields: - // e.g. want to allow + // e.g., want to allow // // `let mut s = ...; drop(s.x); s.x=Val;` // @@ -2166,7 +2166,7 @@ enum Overlap { /// `u.a.x` and `a.b.y` are. Arbitrary, /// The places have the same type, and are either completely disjoint - /// or equal - i.e. they can't "partially" overlap as can occur with + /// or equal - i.e., they can't "partially" overlap as can occur with /// unions. This is the "base case" on which we recur for extensions /// of the place. EqualOrDisjoint, diff --git a/src/librustc_mir/borrow_check/move_errors.rs b/src/librustc_mir/borrow_check/move_errors.rs index 1811333e445..db60017185a 100644 --- a/src/librustc_mir/borrow_check/move_errors.rs +++ b/src/librustc_mir/borrow_check/move_errors.rs @@ -40,7 +40,7 @@ use util::borrowck_errors::{BorrowckErrors, Origin}; #[derive(Debug)] enum GroupedMoveError<'tcx> { // Place expression can't be moved from, - // e.g. match x[0] { s => (), } where x: &[String] + // e.g., match x[0] { s => (), } where x: &[String] MovesFromPlace { original_path: Place<'tcx>, span: Span, @@ -49,7 +49,7 @@ enum GroupedMoveError<'tcx> { binds_to: Vec, }, // Part of a value expression can't be moved from, - // e.g. match &String::new() { &x => (), } + // e.g., match &String::new() { &x => (), } MovesFromValue { original_path: Place<'tcx>, span: Span, diff --git a/src/librustc_mir/borrow_check/nll/constraints/mod.rs b/src/librustc_mir/borrow_check/nll/constraints/mod.rs index a873af8333a..bfac33b34c7 100644 --- a/src/librustc_mir/borrow_check/nll/constraints/mod.rs +++ b/src/librustc_mir/borrow_check/nll/constraints/mod.rs @@ -40,7 +40,7 @@ impl ConstraintSet { /// Constructs a "normal" graph from the constraint set; the graph makes it /// easy to find the constraints affecting a particular region. /// - /// NB: This graph contains a "frozen" view of the current + /// N.B., this graph contains a "frozen" view of the current /// constraints. any new constraints added to the `ConstraintSet` /// after the graph is built will not be present in the graph. crate fn graph(&self, num_region_vars: usize) -> graph::NormalConstraintGraph { diff --git a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs index 5cd3d5fbc73..0c0504b7b31 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/error_reporting/var_name.rs @@ -95,7 +95,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { /// Search the argument types for one that references fr (which should be a free region). /// Returns Some(_) with the index of the input if one is found. /// - /// NB: In the case of a closure, the index is indexing into the signature as seen by the + /// N.B., in the case of a closure, the index is indexing into the signature as seen by the /// user - in particular, index 0 is not the implicit self parameter. crate fn get_argument_index_for_region( &self, 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 fbde699264b..cbd1e666284 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/mod.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/mod.rs @@ -119,7 +119,7 @@ struct RegionDefinition<'tcx> { external_name: Option>, } -/// NB: The variants in `Cause` are intentionally ordered. Lower +/// N.B., the variants in `Cause` are intentionally ordered. Lower /// values are preferred when it comes to error messages. Do not /// reorder willy nilly. #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)] @@ -657,7 +657,7 @@ impl<'tcx> RegionInferenceContext<'tcx> { .buffer(errors_buffer); } else { // FIXME. We should handle this case better. It - // indicates that we have e.g. some region variable + // indicates that we have e.g., some region variable // whose value is like `'a+'b` where `'a` and `'b` are // distinct unrelated univesal regions that are not // known to outlive one another. It'd be nice to have 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 c7512f4b67f..4f5829f3406 100644 --- a/src/librustc_mir/borrow_check/nll/region_infer/values.rs +++ b/src/librustc_mir/borrow_check/nll/region_infer/values.rs @@ -313,7 +313,7 @@ impl RegionValues { self.points.insert_all_into_row(r); } - /// Add all elements in `r_from` to `r_to` (because e.g. `r_to: + /// Add all elements in `r_from` to `r_to` (because e.g., `r_to: /// r_from`). crate fn add_region(&mut self, r_to: N, r_from: N) -> bool { self.points.union_rows(r_from, r_to) diff --git a/src/librustc_mir/borrow_check/nll/type_check/input_output.rs b/src/librustc_mir/borrow_check/nll/type_check/input_output.rs index 85ea39e538f..bb890e65b53 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/input_output.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/input_output.rs @@ -40,7 +40,7 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> { // If the user explicitly annotated the input types, extract // those. // - // e.g. `|x: FxHashMap<_, &'static u32>| ...` + // e.g., `|x: FxHashMap<_, &'static u32>| ...` let user_provided_sig; if !self.tcx().is_closure(self.mir_def_id) { user_provided_sig = None; @@ -50,7 +50,7 @@ impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> { None => None, Some(user_provided_poly_sig) => { // Instantiate the canonicalized variables from - // user-provided signature (e.g. the `_` in the code + // user-provided signature (e.g., the `_` in the code // above) with fresh variables. let (poly_sig, _) = self.infcx.instantiate_canonical_with_fresh_inference_vars( mir.span, diff --git a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs index 4b39d58cd96..320422c9d33 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/liveness/local_use_map.rs @@ -23,7 +23,7 @@ crate struct LocalUseMap<'me> { liveness_map: &'me NllLivenessMap, /// Head of a linked list of **definitions** of each variable -- - /// definition in this context means assignment, e.g. `x` is + /// definition in this context means assignment, e.g., `x` is /// defined in `x = y` but not `y`; that first def is the head of /// a linked list that lets you enumerate all places the variable /// is assigned. diff --git a/src/librustc_mir/borrow_check/nll/type_check/mod.rs b/src/librustc_mir/borrow_check/nll/type_check/mod.rs index 33346a584e5..4807abe2bdd 100644 --- a/src/librustc_mir/borrow_check/nll/type_check/mod.rs +++ b/src/librustc_mir/borrow_check/nll/type_check/mod.rs @@ -9,6 +9,7 @@ // except according to those terms. //! This pass type-checks the MIR to ensure it is not broken. + #![allow(unreachable_code)] use borrow_check::borrow_set::BorrowSet; diff --git a/src/librustc_mir/borrow_check/places_conflict.rs b/src/librustc_mir/borrow_check/places_conflict.rs index 715d6e0c0d1..eeac915cff3 100644 --- a/src/librustc_mir/borrow_check/places_conflict.rs +++ b/src/librustc_mir/borrow_check/places_conflict.rs @@ -128,10 +128,10 @@ fn place_components_conflict<'gcx, 'tcx>( // // There is no *easy* way of comparing the fields // further on, because they might have different types - // (e.g. borrows of `u.a.0` and `u.b.y` where `.0` and + // (e.g., borrows of `u.a.0` and `u.b.y` where `.0` and // `.y` come from different structs). // - // We could try to do some things here - e.g. count + // We could try to do some things here - e.g., count // dereferences - but that's probably not a good // idea, at least for now, so just give up and // report a conflict. This is unsafe code anyway so @@ -175,14 +175,14 @@ fn place_components_conflict<'gcx, 'tcx>( // borrowed place (at least in MIR as it is // currently.) // - // e.g. a (mutable) borrow of `a[5]` while we read the + // e.g., a (mutable) borrow of `a[5]` while we read the // array length of `a`. debug!("borrow_conflicts_with_place: implicit field"); return false; } (ProjectionElem::Deref, _, Shallow(None)) => { - // e.g. a borrow of `*x.y` while we shallowly access `x.y` or some + // e.g., a borrow of `*x.y` while we shallowly access `x.y` or some // prefix thereof - the shallow access can't touch anything behind // the pointer. debug!("borrow_conflicts_with_place: shallow access behind ptr"); @@ -216,7 +216,7 @@ fn place_components_conflict<'gcx, 'tcx>( | (ProjectionElem::Downcast { .. }, _, _) => { // Recursive case. This can still be disjoint on a // further iteration if this a shallow access and - // there's a deref later on, e.g. a borrow + // there's a deref later on, e.g., a borrow // of `*x.y` while accessing `x`. } } @@ -251,7 +251,7 @@ fn place_components_conflict<'gcx, 'tcx>( /// the place `a` with a "next" pointer to `a.b`). Created by /// `unroll_place`. /// -/// NB: This particular impl strategy is not the most obvious. It was +/// N.B., this particular impl strategy is not the most obvious. It was /// chosen because it makes a measurable difference to NLL /// performance, as this code (`borrow_conflicts_with_place`) is somewhat hot. struct PlaceComponents<'p, 'tcx: 'p> { @@ -277,7 +277,7 @@ impl<'p, 'tcx> PlaceComponents<'p, 'tcx> { /// Iterator over components; see `PlaceComponents::iter` for more /// information. /// -/// NB: This is not a *true* Rust iterator -- the code above just +/// N.B., this is not a *true* Rust iterator -- the code above just /// manually invokes `next`. This is because we (sometimes) want to /// keep executing even after `None` has been returned. struct PlaceComponentsIter<'p, 'tcx: 'p> { @@ -384,13 +384,13 @@ fn place_element_conflict<'a, 'gcx: 'tcx, 'tcx>( (Place::Projection(pi1), Place::Projection(pi2)) => { match (&pi1.elem, &pi2.elem) { (ProjectionElem::Deref, ProjectionElem::Deref) => { - // derefs (e.g. `*x` vs. `*x`) - recur. + // derefs (e.g., `*x` vs. `*x`) - recur. debug!("place_element_conflict: DISJOINT-OR-EQ-DEREF"); Overlap::EqualOrDisjoint } (ProjectionElem::Field(f1, _), ProjectionElem::Field(f2, _)) => { if f1 == f2 { - // same field (e.g. `a.y` vs. `a.y`) - recur. + // same field (e.g., `a.y` vs. `a.y`) - recur. debug!("place_element_conflict: DISJOINT-OR-EQ-FIELD"); Overlap::EqualOrDisjoint } else { diff --git a/src/librustc_mir/borrow_check/prefixes.rs b/src/librustc_mir/borrow_check/prefixes.rs index 7d583b4f541..b759e0416e5 100644 --- a/src/librustc_mir/borrow_check/prefixes.rs +++ b/src/librustc_mir/borrow_check/prefixes.rs @@ -91,7 +91,7 @@ impl<'cx, 'gcx, 'tcx> Iterator for Prefixes<'cx, 'gcx, 'tcx> { // Post-processing `place`: Enqueue any remaining // work. Also, `place` may not be a prefix itself, but - // may hold one further down (e.g. we never return + // may hold one further down (e.g., we never return // downcasts here, but may return a base of a downcast). 'cursor: loop { diff --git a/src/librustc_mir/build/block.rs b/src/librustc_mir/build/block.rs index 2ef71617b7c..4df8d66e2fb 100644 --- a/src/librustc_mir/build/block.rs +++ b/src/librustc_mir/build/block.rs @@ -117,7 +117,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { }; this.block_context.push(BlockFrame::Statement { ignores_expr_result }); - // Enter the remainder scope, i.e. the bindings' destruction scope. + // Enter the remainder scope, i.e., the bindings' destruction scope. this.push_scope((remainder_scope, source_info)); let_scope_stack.push(remainder_scope); diff --git a/src/librustc_mir/build/expr/as_rvalue.rs b/src/librustc_mir/build/expr/as_rvalue.rs index 18ce7ae4907..a476165462a 100644 --- a/src/librustc_mir/build/expr/as_rvalue.rs +++ b/src/librustc_mir/build/expr/as_rvalue.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! See docs in build/expr/mod.rs +//! See docs in `build/expr/mod.rs`. use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::Idx; diff --git a/src/librustc_mir/build/expr/into.rs b/src/librustc_mir/build/expr/into.rs index 8eb46a04839..0e7305e076e 100644 --- a/src/librustc_mir/build/expr/into.rs +++ b/src/librustc_mir/build/expr/into.rs @@ -414,7 +414,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { // must be handled above or else we get an // infinite loop in the builder; see - // e.g. `ExprKind::VarRef` above + // e.g., `ExprKind::VarRef` above Category::Place => false, _ => true, diff --git a/src/librustc_mir/build/expr/stmt.rs b/src/librustc_mir/build/expr/stmt.rs index 45235b31539..0e9f81bbe95 100644 --- a/src/librustc_mir/build/expr/stmt.rs +++ b/src/librustc_mir/build/expr/stmt.rs @@ -16,7 +16,7 @@ use rustc::mir::*; impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Builds a block of MIR statements to evaluate the HAIR `expr`. /// If the original expression was an AST statement, - /// (e.g. `some().code(&here());`) then `opt_stmt_span` is the + /// (e.g., `some().code(&here());`) then `opt_stmt_span` is the /// span of that statement (including its semicolon, if any). /// Diagnostics use this span (which may be larger than that of /// `expr`) to identify when statement temporaries are dropped. diff --git a/src/librustc_mir/build/into.rs b/src/librustc_mir/build/into.rs index 9c8d0b2aeb9..3e57c4acb42 100644 --- a/src/librustc_mir/build/into.rs +++ b/src/librustc_mir/build/into.rs @@ -11,7 +11,7 @@ //! In general, there are a number of things for which it's convenient //! to just call `builder.into` and have it emit its result into a //! given location. This is basically for expressions or things that can be -//! wrapped up as expressions (e.g. blocks). To make this ergonomic, we use this +//! wrapped up as expressions (e.g., blocks). To make this ergonomic, we use this //! latter `EvalInto` trait. use build::{BlockAnd, Builder}; diff --git a/src/librustc_mir/build/matches/mod.rs b/src/librustc_mir/build/matches/mod.rs index 243b702060a..7e7c0b15555 100644 --- a/src/librustc_mir/build/matches/mod.rs +++ b/src/librustc_mir/build/matches/mod.rs @@ -111,7 +111,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { // pattern, which means there may be more than one candidate // *per arm*. These candidates are kept sorted such that the // highest priority candidate comes first in the list. - // (i.e. same order as in source) + // (i.e., same order as in source) let candidates: Vec<_> = arms.iter() .enumerate() @@ -1384,7 +1384,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { // Tricky business: For `ref id` and `ref mut id` // patterns, we want `id` within the guard to // correspond to a temp of type `& &T` or `& &mut - // T` (i.e. a "borrow of a borrow") that is + // T` (i.e., a "borrow of a borrow") that is // implicitly dereferenced. // // To borrow a borrow, we need that inner borrow diff --git a/src/librustc_mir/build/misc.rs b/src/librustc_mir/build/misc.rs index 9405f43c056..3ac7bd3fc68 100644 --- a/src/librustc_mir/build/misc.rs +++ b/src/librustc_mir/build/misc.rs @@ -22,7 +22,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { /// Add a new temporary value of type `ty` storing the result of /// evaluating `expr`. /// - /// NB: **No cleanup is scheduled for this temporary.** You should + /// N.B., **No cleanup is scheduled for this temporary.** You should /// call `schedule_drop` once the temporary is initialized. pub fn temp(&mut self, ty: Ty<'tcx>, span: Span) -> Place<'tcx> { let temp = self.local_decls.push(LocalDecl::new_temp(ty, span)); diff --git a/src/librustc_mir/build/scope.rs b/src/librustc_mir/build/scope.rs index 7388d11ed6c..8c948766314 100644 --- a/src/librustc_mir/build/scope.rs +++ b/src/librustc_mir/build/scope.rs @@ -152,7 +152,7 @@ struct DropData<'tcx> { pub(crate) struct CachedBlock { /// The cached block for the cleanups-on-diverge path. This block /// contains code to run the current drop and all the preceding - /// drops (i.e. those having lower index in Drop’s Scope drop + /// drops (i.e., those having lower index in Drop’s Scope drop /// array) unwind: Option, @@ -182,7 +182,7 @@ pub struct BreakableScope<'tcx> { /// Block to branch into when the loop or block terminates (either by being `break`-en out /// from, or by having its condition to become false) pub break_block: BasicBlock, - /// The destination of the loop/block expression itself (i.e. where to put the result of a + /// The destination of the loop/block expression itself (i.e., where to put the result of a /// `break` expression) pub break_destination: Place<'tcx>, } @@ -737,7 +737,7 @@ impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> { // // Note that this code iterates scopes from the inner-most to the outer-most, // invalidating caches of each scope visited. This way bare minimum of the - // caches gets invalidated. i.e. if a new drop is added into the middle scope, the + // caches gets invalidated. i.e., if a new drop is added into the middle scope, the // cache of outer scpoe stays intact. scope.invalidate_cache(!needs_drop, this_scope); if this_scope { diff --git a/src/librustc_mir/dataflow/at_location.rs b/src/librustc_mir/dataflow/at_location.rs index d815bfedc37..52eae581528 100644 --- a/src/librustc_mir/dataflow/at_location.rs +++ b/src/librustc_mir/dataflow/at_location.rs @@ -67,7 +67,7 @@ pub trait FlowsAtLocation { /// effects at any point in the control-flow graph by starting with /// the state at the start of the basic block (`reset_to_entry_of`) /// and then replaying the effects of statements and terminators -/// (e.g. via `reconstruct_statement_effect` and +/// (e.g., via `reconstruct_statement_effect` and /// `reconstruct_terminator_effect`; don't forget to call /// `apply_local_effect`). pub struct FlowAtLocation diff --git a/src/librustc_mir/dataflow/impls/borrows.rs b/src/librustc_mir/dataflow/impls/borrows.rs index 3a9e4fc9e4a..5e78ef03c2c 100644 --- a/src/librustc_mir/dataflow/impls/borrows.rs +++ b/src/librustc_mir/dataflow/impls/borrows.rs @@ -267,7 +267,7 @@ impl<'a, 'gcx, 'tcx> BitDenotation for Borrows<'a, 'gcx, 'tcx> { Place::Local(..) | Place::Static(..) => {} // okay Place::Projection(..) => { // ... can assign into projections, - // e.g. `box (&mut _)`. Current + // e.g., `box (&mut _)`. Current // conservative solution: force // immediate activation here. sets.gen(*index); diff --git a/src/librustc_mir/dataflow/impls/mod.rs b/src/librustc_mir/dataflow/impls/mod.rs index efdf9c33023..c29a855b1d2 100644 --- a/src/librustc_mir/dataflow/impls/mod.rs +++ b/src/librustc_mir/dataflow/impls/mod.rs @@ -488,7 +488,7 @@ impl<'a, 'gcx, 'tcx> BitDenotation for EverInitializedPlaces<'a, 'gcx, 'tcx> { // // FIXME(#46525): We *need* to do this for StorageLive as well as // StorageDead, because lifetimes of match bindings with guards are - // weird - i.e. this code + // weird - i.e., this code // // ``` // fn main() { diff --git a/src/librustc_mir/dataflow/mod.rs b/src/librustc_mir/dataflow/mod.rs index c19145636e6..bd842669a1f 100644 --- a/src/librustc_mir/dataflow/mod.rs +++ b/src/librustc_mir/dataflow/mod.rs @@ -290,7 +290,7 @@ impl<'a, 'tcx: 'a, BD> DataflowBuilder<'a, 'tcx, BD> where BD: BitDenotation /// It abstracts over the FlowState and also completely hides the /// underlying flow analysis results, because it needs to handle cases /// where we are combining the results of *multiple* flow analyses -/// (e.g. borrows + inits + uninits). +/// (e.g., borrows + inits + uninits). pub(crate) trait DataflowResultsConsumer<'a, 'tcx: 'a> { type FlowState: FlowsAtLocation; @@ -553,7 +553,7 @@ impl AllSets { /// Parameterization for the precise form of data flow that is used. /// `InitialFlow` handles initializing the bitvectors before any /// code is inspected by the analysis. Analyses that need more nuanced -/// initialization (e.g. they need to consult the results of some other +/// initialization (e.g., they need to consult the results of some other /// dataflow analysis to set up the initial bitvectors) should not /// implement this. pub trait InitialFlow { @@ -592,7 +592,7 @@ pub trait BitDenotation: BitSetOperator { /// A name describing the dataflow analysis that this /// BitDenotation is supporting. The name should be something - /// suitable for plugging in as part of a filename e.g. avoid + /// suitable for plugging in as part of a filename e.g., avoid /// space-characters or other things that tend to look bad on a /// file system, like slashes or periods. It is also better for /// the name to be reasonably short, again because it will be @@ -739,7 +739,7 @@ impl<'a, 'tcx: 'a, D> DataflowAnalysis<'a, 'tcx, D> where D: BitDenotation /// To reflect this, the `propagate_call_return` method of the /// `BitDenotation` mutates `in_out` when propagating `in_out` via /// a call terminator; such mutation is performed *last*, to - /// ensure its side-effects do not leak elsewhere (e.g. into + /// ensure its side-effects do not leak elsewhere (e.g., into /// unwind target). fn propagate_bits_into_graph_successors_of( &mut self, diff --git a/src/librustc_mir/dataflow/move_paths/abs_domain.rs b/src/librustc_mir/dataflow/move_paths/abs_domain.rs index 4d20857bc2e..186e5f5f5f0 100644 --- a/src/librustc_mir/dataflow/move_paths/abs_domain.rs +++ b/src/librustc_mir/dataflow/move_paths/abs_domain.rs @@ -10,7 +10,7 @@ //! The move-analysis portion of borrowck needs to work in an abstract //! domain of lifted Places. Most of the Place variants fall into a -//! one-to-one mapping between the concrete and abstract (e.g. a +//! one-to-one mapping between the concrete and abstract (e.g., a //! field-deref on a local-variable, `x.field`, has the same meaning //! in both domains). Indexed-Projections are the exception: `a[x]` //! needs to be treated as mapping to the same move path as `a[y]` as diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs index a772f446730..a1471adac60 100644 --- a/src/librustc_mir/hair/cx/expr.rs +++ b/src/librustc_mir/hair/cx/expr.rs @@ -181,7 +181,7 @@ fn apply_adjustment<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, // To ensure that both implicit and explicit coercions are // handled the same way, we insert an extra layer of indirection here. - // For explicit casts (e.g. 'foo as *const T'), the source of the 'Use' + // For explicit casts (e.g., 'foo as *const T'), the source of the 'Use' // will be an ExprKind::Hair with the appropriate cast expression. Here, // we make our Use source the generated Cast from the original coercion. // @@ -1212,7 +1212,7 @@ fn capture_freevar<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, } } -/// Converts a list of named fields (i.e. for struct-like struct/enum ADTs) into FieldExprRef. +/// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef. fn field_refs<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, fields: &'tcx [hir::Field]) -> Vec> { diff --git a/src/librustc_mir/hair/pattern/_match.rs b/src/librustc_mir/hair/pattern/_match.rs index 5db7b6ceb5d..e80ef38a617 100644 --- a/src/librustc_mir/hair/pattern/_match.rs +++ b/src/librustc_mir/hair/pattern/_match.rs @@ -29,9 +29,9 @@ /// /// If we have this predicate, then we can easily compute both exhaustiveness of an /// entire set of patterns and the individual usefulness of each one. -/// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e. adding a wildcard +/// (a) the set of patterns is exhaustive iff `U(P, _)` is false (i.e., adding a wildcard /// match doesn't increase the number of values we're matching) -/// (b) a pattern `p_i` is not useful if `U(P[0..=(i-1), p_i)` is false (i.e. adding a +/// (b) a pattern `p_i` is not useful if `U(P[0..=(i-1), p_i)` is false (i.e., adding a /// pattern to those that have come before it doesn't increase the number of values /// we're matching). /// @@ -90,17 +90,17 @@ /// /// The algorithm for computing `U` /// ------------------------------- -/// The algorithm is inductive (on the number of columns: i.e. components of tuple patterns). +/// The algorithm is inductive (on the number of columns: i.e., components of tuple patterns). /// That means we're going to check the components from left-to-right, so the algorithm /// operates principally on the first component of the matrix and new pattern `p_{m + 1}`. /// This algorithm is realised in the `is_useful` function. /// -/// Base case. (`n = 0`, i.e. an empty tuple pattern) -/// - If `P` already contains an empty pattern (i.e. if the number of patterns `m > 0`), +/// Base case. (`n = 0`, i.e., an empty tuple pattern) +/// - If `P` already contains an empty pattern (i.e., if the number of patterns `m > 0`), /// then `U(P, p_{m + 1})` is false. /// - Otherwise, `P` must be empty, so `U(P, p_{m + 1})` is true. /// -/// Inductive step. (`n > 0`, i.e. whether there's at least one column +/// Inductive step. (`n > 0`, i.e., whether there's at least one column /// [which may then be expanded into further columns later]) /// We're going to match on the new pattern, `p_{m + 1}`. /// - If `p_{m + 1} == c(r_1, .., r_a)`, then we have a constructor pattern. @@ -113,7 +113,7 @@ /// + All the constructors of the first component of the type exist within /// all the rows (after having expanded OR-patterns). In this case: /// `U(P, p_{m + 1}) := ∨(k ϵ constructors) U(S(k, P), S(k, p_{m + 1}))` -/// I.e. the pattern `p_{m + 1}` is only useful when all the constructors are +/// I.e., the pattern `p_{m + 1}` is only useful when all the constructors are /// present *if* its later components are useful for the respective constructors /// covered by `p_{m + 1}` (usually a single constructor, but all in the case of `_`). /// + Some constructors are not present in the existing rows (after having expanded @@ -156,14 +156,14 @@ /// - When we're testing for usefulness of a pattern and the pattern's first component is a /// wildcard. /// + If all the constructors appear in the matrix, we have a slight complication. By default, -/// the behaviour (i.e. a disjunction over specialised matrices for each constructor) is +/// the behaviour (i.e., a disjunction over specialised matrices for each constructor) is /// invalid, because we want a disjunction over every *integer* in each range, not just a /// disjunction over every range. This is a bit more tricky to deal with: essentially we need /// to form equivalence classes of subranges of the constructor range for which the behaviour /// of the matrix `P` and new pattern `p_{m + 1}` are the same. This is described in more /// detail in `split_grouped_constructors`. /// + If some constructors are missing from the matrix, it turns out we don't need to do -/// anything special (because we know none of the integers are actually wildcards: i.e. we +/// anything special (because we know none of the integers are actually wildcards: i.e., we /// can't span wildcards using ranges). use self::Constructor::*; @@ -371,7 +371,7 @@ impl<'a, 'tcx> MatchCheckCtxt<'a, 'tcx> { #[derive(Clone, Debug, PartialEq)] pub enum Constructor<'tcx> { /// The constructor of all patterns that don't vary by constructor, - /// e.g. struct patterns and fixed-length arrays. + /// e.g., struct patterns and fixed-length arrays. Single, /// Enum variants. Variant(DefId), @@ -488,7 +488,7 @@ impl<'tcx> Witness<'tcx> { /// patterns expanded by the specialization step. /// /// When a pattern P is discovered to be useful, this function is used bottom-up - /// to reconstruct a complete witness, e.g. a pattern P' that covers a subset + /// to reconstruct a complete witness, e.g., a pattern P' that covers a subset /// of values, V, where each value in that set is not covered by any previously /// used patterns and is covered by the pattern P'. Examples: /// @@ -763,7 +763,7 @@ fn max_slice_length<'p, 'a: 'p, 'tcx: 'a, I>( /// straightforward. See `signed_bias` for details. /// /// `IntRange` is never used to encode an empty range or a "range" that wraps -/// around the (offset) space: i.e. `range.lo <= range.hi`. +/// around the (offset) space: i.e., `range.lo <= range.hi`. #[derive(Clone)] struct IntRange<'tcx> { pub range: RangeInclusive, @@ -854,7 +854,7 @@ impl<'tcx> IntRange<'tcx> { } /// Return a collection of ranges that spans the values covered by `ranges`, subtracted - /// by the values covered by `self`: i.e. `ranges \ self` (in set notation). + /// by the values covered by `self`: i.e., `ranges \ self` (in set notation). fn subtract_from(self, tcx: TyCtxt<'_, 'tcx, 'tcx>, ranges: Vec>) @@ -1122,7 +1122,7 @@ pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, // // There are 2 ways we can report a witness here. // Commonly, we can report all the "free" - // constructors as witnesses, e.g. if we have: + // constructors as witnesses, e.g., if we have: // // ``` // enum Direction { N, S, E, W } @@ -1137,7 +1137,7 @@ pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, // 1) If the user is matching against a non-exhaustive // enum, there is no point in enumerating all possible // variants, because the user can't actually match - // against them himself, e.g. in an example like: + // against them himself, e.g., in an example like: // ``` // let err: io::ErrorKind = ...; // match err { @@ -1151,7 +1151,7 @@ pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, // case). // // 2) If the user didn't actually specify a constructor - // in this arm, e.g. in + // in this arm, e.g., in // ``` // let x: (Direction, Direction, bool) = ...; // let (_, _, false) = x; @@ -1197,7 +1197,7 @@ pub fn is_useful<'p, 'a: 'p, 'tcx: 'a>(cx: &mut MatchCheckCtxt<'a, 'tcx>, } } -/// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e. `is_useful` applied +/// A shorthand for the `U(S(c, P), S(c, q))` operation from the paper. I.e., `is_useful` applied /// to the specialised version of both the pattern matrix `P` and the new pattern `q`. fn is_useful_specialized<'p, 'a:'p, 'tcx: 'a>( cx: &mut MatchCheckCtxt<'a, 'tcx>, @@ -1413,7 +1413,7 @@ fn should_treat_range_exhaustively(tcx: TyCtxt<'_, 'tcx, 'tcx>, ctor: &Construct /// the groups (the ranges). Thus we need to split the groups up. Splitting them up naïvely would /// mean creating a separate constructor for every single value in the range, which is clearly /// impractical. However, observe that for some ranges of integers, the specialisation will be -/// identical across all values in that range (i.e. there are equivalence classes of ranges of +/// identical across all values in that range (i.e., there are equivalence classes of ranges of /// constructors based on their `is_useful_specialized` outcome). These classes are grouped by /// the patterns that apply to them (in the matrix `P`). We can split the range whenever the /// patterns that apply to that range (specifically: the patterns that *intersect* with that range) @@ -1422,7 +1422,7 @@ fn should_treat_range_exhaustively(tcx: TyCtxt<'_, 'tcx, 'tcx>, ctor: &Construct /// the group of intersecting patterns changes (using the method described below). /// And voilà! We're testing precisely those ranges that we need to, without any exhaustive matching /// on actual integers. The nice thing about this is that the number of subranges is linear in the -/// number of rows in the matrix (i.e. the number of cases in the `match` statement), so we don't +/// number of rows in the matrix (i.e., the number of cases in the `match` statement), so we don't /// need to be worried about matching over gargantuan ranges. /// /// Essentially, given the first column of a matrix representing ranges, looking like the following: diff --git a/src/librustc_mir/hair/pattern/check_match.rs b/src/librustc_mir/hair/pattern/check_match.rs index 4d38d207c47..9fb3a09e3c1 100644 --- a/src/librustc_mir/hair/pattern/check_match.rs +++ b/src/librustc_mir/hair/pattern/check_match.rs @@ -188,7 +188,7 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { // Third, perform some lints. for pat in &arm.pats { - check_for_bindings_named_the_same_as_variants(self, pat); + check_for_bindings_named_same_as_variants(self, pat); } } @@ -309,7 +309,7 @@ impl<'a, 'tcx> MatchVisitor<'a, 'tcx> { } } -fn check_for_bindings_named_the_same_as_variants(cx: &MatchVisitor, pat: &Pat) { +fn check_for_bindings_named_same_as_variants(cx: &MatchVisitor, pat: &Pat) { pat.walk(|p| { if let PatKind::Binding(_, _, ident, None) = p.node { if let Some(&bm) = cx.tables.pat_binding_modes().get(p.hir_id) { diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs index 5d2f7ec507b..d695a64f62a 100644 --- a/src/librustc_mir/hair/pattern/mod.rs +++ b/src/librustc_mir/hair/pattern/mod.rs @@ -228,7 +228,7 @@ pub enum PatternKind<'tcx> { /// matches against a slice, checking the length and extracting elements. /// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty. - /// e.g. `&[ref xs..]`. + /// e.g., `&[ref xs..]`. Slice { prefix: Vec>, slice: Option>, diff --git a/src/librustc_mir/interpret/machine.rs b/src/librustc_mir/interpret/machine.rs index f43cfb90fc4..4c7aa887045 100644 --- a/src/librustc_mir/interpret/machine.rs +++ b/src/librustc_mir/interpret/machine.rs @@ -81,7 +81,7 @@ pub trait Machine<'a, 'mir, 'tcx>: Sized { type FrameExtra; /// Extra data stored in memory. A reference to this is available when `AllocExtra` - /// gets initialized, so you can e.g. have an `Rc` here if there is global state you + /// gets initialized, so you can e.g., have an `Rc` here if there is global state you /// need access to in the `AllocExtra` hooks. type MemoryExtra: Default; diff --git a/src/librustc_mir/interpret/memory.rs b/src/librustc_mir/interpret/memory.rs index 97d7e1586b8..e32abb92e21 100644 --- a/src/librustc_mir/interpret/memory.rs +++ b/src/librustc_mir/interpret/memory.rs @@ -55,7 +55,7 @@ impl MayLeak for MemoryKind { } // `Memory` has to depend on the `Machine` because some of its operations -// (e.g. `get`) call a `Machine` hook. +// (e.g., `get`) call a `Machine` hook. pub struct Memory<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> { /// Allocations local to this instance of the miri engine. The kind /// helps ensure that the same mechanism is used for allocation and diff --git a/src/librustc_mir/interpret/place.rs b/src/librustc_mir/interpret/place.rs index 164a9680c79..bae670bf2b4 100644 --- a/src/librustc_mir/interpret/place.rs +++ b/src/librustc_mir/interpret/place.rs @@ -35,7 +35,7 @@ pub struct MemPlace { pub align: Align, /// Metadata for unsized places. Interpretation is up to the type. /// Must not be present for sized types, but can be missing for unsized types - /// (e.g. `extern type`). + /// (e.g., `extern type`). pub meta: Option>, } @@ -236,7 +236,7 @@ impl<'tcx, Tag> MPlaceTy<'tcx, Tag> { } } else { // Go through the layout. There are lots of types that support a length, - // e.g. SIMD types. + // e.g., SIMD types. match self.layout.fields { layout::FieldPlacement::Array { count, .. } => Ok(count), _ => bug!("len not supported on sized type {:?}", self.layout.ty), @@ -908,7 +908,7 @@ where // a fake pointer? Are we even called for ZST? // We need the layout of the local. We can NOT use the layout we got, - // that might e.g. be an inner field of a struct with `Scalar` layout, + // that might e.g., be an inner field of a struct with `Scalar` layout, // that has different alignment than the outer field. let local_layout = self.layout_of_local(&self.stack[frame], local)?; let ptr = self.allocate(local_layout, MemoryKind::Stack)?; diff --git a/src/librustc_mir/interpret/step.rs b/src/librustc_mir/interpret/step.rs index 84cc5127f38..a6835e4f167 100644 --- a/src/librustc_mir/interpret/step.rs +++ b/src/librustc_mir/interpret/step.rs @@ -18,7 +18,7 @@ use rustc::mir::interpret::{EvalResult, Scalar, PointerArithmetic}; use super::{EvalContext, Machine}; -/// Classify whether an operator is "left-homogeneous", i.e. the LHS has the +/// Classify whether an operator is "left-homogeneous", i.e., the LHS has the /// same type as the result. #[inline] fn binop_left_homogeneous(op: mir::BinOp) -> bool { @@ -31,7 +31,7 @@ fn binop_left_homogeneous(op: mir::BinOp) -> bool { false, } } -/// Classify whether an operator is "right-homogeneous", i.e. the RHS has the +/// Classify whether an operator is "right-homogeneous", i.e., the RHS has the /// same type as the LHS. #[inline] fn binop_right_homogeneous(op: mir::BinOp) -> bool { @@ -85,7 +85,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> use rustc::mir::StatementKind::*; - // Some statements (e.g. box) push new stack frames. + // Some statements (e.g., box) push new stack frames. // We have to record the stack frame number *before* executing the statement. let frame_idx = self.cur_frame(); self.tcx.span = stmt.source_info.span; diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs index 300f3d639b5..4a672f195d2 100644 --- a/src/librustc_mir/interpret/terminator.rs +++ b/src/librustc_mir/interpret/terminator.rs @@ -252,7 +252,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> return err!(FunctionAbiMismatch(caller_abi, Abi::RustIntrinsic)); } // The intrinsic itself cannot diverge, so if we got here without a return - // place... (can happen e.g. for transmute returning `!`) + // place... (can happen e.g., for transmute returning `!`) let dest = match dest { Some(dest) => dest, None => return err!(Unreachable) diff --git a/src/librustc_mir/interpret/validity.rs b/src/librustc_mir/interpret/validity.rs index d98d05bc01b..4f1737354ca 100644 --- a/src/librustc_mir/interpret/validity.rs +++ b/src/librustc_mir/interpret/validity.rs @@ -408,7 +408,7 @@ impl<'rt, 'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> // Check if we have encountered this pointer+layout combination // before. Proceed recursively even for integer pointers, no // reason to skip them! They are (recursively) valid for some ZST, - // but not for others (e.g. `!` is a ZST). + // but not for others (e.g., `!` is a ZST). let op = place.into(); if ref_tracking.seen.insert(op) { trace!("Recursing below ptr {:#?}", *op); @@ -548,7 +548,7 @@ impl<'rt, 'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> // NOTE: Keep this in sync with the handling of integer and float // types above, in `visit_primitive`. // In run-time mode, we accept pointers in here. This is actually more - // permissive than a per-element check would be, e.g. we accept + // permissive than a per-element check would be, e.g., we accept // an &[u8] that contains a pointer even though bytewise checking would // reject it. However, that's good: We don't inherently want // to reject those pointers, we just do not have the machinery to diff --git a/src/librustc_mir/interpret/visitor.rs b/src/librustc_mir/interpret/visitor.rs index 81e56f3115d..4773f5627d7 100644 --- a/src/librustc_mir/interpret/visitor.rs +++ b/src/librustc_mir/interpret/visitor.rs @@ -272,7 +272,7 @@ macro_rules! make_value_visitor { // is very relevant for `NonNull` and similar structs: We need to visit them // at their scalar layout *before* descending into their fields. // FIXME: We could avoid some redundant checks here. For newtypes wrapping - // scalars, we do the same check on every "level" (e.g. first we check + // scalars, we do the same check on every "level" (e.g., first we check // MyNewtype and then the scalar in there). match v.layout().abi { layout::Abi::Uninhabited => { diff --git a/src/librustc_mir/lints.rs b/src/librustc_mir/lints.rs index 232468fefe2..775431e5cbd 100644 --- a/src/librustc_mir/lints.rs +++ b/src/librustc_mir/lints.rs @@ -39,11 +39,11 @@ fn check_fn_for_unconditional_recursion(tcx: TyCtxt<'a, 'tcx, 'tcx>, //FIXME(#54444) rewrite this lint to use the dataflow framework // Walk through this function (say `f`) looking to see if - // every possible path references itself, i.e. the function is + // every possible path references itself, i.e., the function is // called recursively unconditionally. This is done by trying // to find a path from the entry node to the exit node that // *doesn't* call `f` by traversing from the entry while - // pretending that calls of `f` are sinks (i.e. ignoring any + // pretending that calls of `f` are sinks (i.e., ignoring any // exit edges from them). // // NB. this has an edge case with non-returning statements, @@ -62,7 +62,7 @@ fn check_fn_for_unconditional_recursion(tcx: TyCtxt<'a, 'tcx, 'tcx>, // considers this to be an error for two reasons, (a) it is // easier to implement, and (b) it seems rare to actually want // to have behaviour like the above, rather than - // e.g. accidentally recursing after an assert. + // e.g., accidentally recursing after an assert. let basic_blocks = mir.basic_blocks(); let mut reachable_without_self_call_queue = vec![mir::START_BLOCK]; @@ -135,7 +135,7 @@ fn check_fn_for_unconditional_recursion(tcx: TyCtxt<'a, 'tcx, 'tcx>, } // Check the number of self calls because a function that - // doesn't return (e.g. calls a `-> !` function or `loop { /* + // doesn't return (e.g., calls a `-> !` function or `loop { /* // no break */ }`) shouldn't be linted unless it actually // recurs. if !reached_exit_without_self_call && !self_call_locations.is_empty() { diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 7890b926948..c962a2416f5 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -821,7 +821,7 @@ fn should_monomorphize_locally<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: /// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair /// `(SomeStruct, SomeTrait)`. /// -/// Finally, there is also the case of custom unsizing coercions, e.g. for +/// Finally, there is also the case of custom unsizing coercions, e.g., for /// smart pointers such as `Rc` and `Arc`. fn find_vtable_types_for_unsizing<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, source_ty: Ty<'tcx>, diff --git a/src/librustc_mir/monomorphize/partitioning.rs b/src/librustc_mir/monomorphize/partitioning.rs index efe6f6dd6fe..00974d4a5b2 100644 --- a/src/librustc_mir/monomorphize/partitioning.rs +++ b/src/librustc_mir/monomorphize/partitioning.rs @@ -51,7 +51,7 @@ //! //! - There are two codegen units for every source-level module: //! - One for "stable", that is non-generic, code -//! - One for more "volatile" code, i.e. monomorphized instances of functions +//! - One for more "volatile" code, i.e., monomorphized instances of functions //! defined in that module //! //! In order to see why this heuristic makes sense, let's take a look at when a diff --git a/src/librustc_mir/transform/check_unsafety.rs b/src/librustc_mir/transform/check_unsafety.rs index 660892c0a5f..6af29b74c1c 100644 --- a/src/librustc_mir/transform/check_unsafety.rs +++ b/src/librustc_mir/transform/check_unsafety.rs @@ -497,7 +497,7 @@ fn unsafety_check_result<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) { debug!("unsafety_violations({:?})", def_id); - // NB: this borrow is valid because all the consumers of + // N.B., this borrow is valid because all the consumers of // `mir_built` force this. let mir = &tcx.mir_built(def_id).borrow(); diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 5e00dea5a05..acae03f7f94 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -289,7 +289,7 @@ impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> { })?; Some((res, span)) }, - // We could get more projections by using e.g. `operand_projection`, + // We could get more projections by using e.g., `operand_projection`, // but we do not even have the stack frame set up properly so // an `Index` projection would throw us off-track. _ => None, diff --git a/src/librustc_mir/transform/inline.rs b/src/librustc_mir/transform/inline.rs index 0348ea5b819..afe0066df1f 100644 --- a/src/librustc_mir/transform/inline.rs +++ b/src/librustc_mir/transform/inline.rs @@ -575,10 +575,10 @@ impl<'a, 'tcx> Inliner<'a, 'tcx> { // The `tmp0`, `tmp1`, and `tmp2` in our example abonve. let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| { - // This is e.g. `tuple_tmp.0` in our example above. + // This is e.g., `tuple_tmp.0` in our example above. let tuple_field = Operand::Move(tuple.clone().field(Field::new(i), ty)); - // Spill to a local to make e.g. `tmp0`. + // Spill to a local to make e.g., `tmp0`. self.create_temp_if_necessary(tuple_field, callsite, caller_mir) }); diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index c5add626078..7f8dfc111a4 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -123,7 +123,7 @@ impl<'tcx> Visitor<'tcx> for TempCollector<'tcx> { } } else if let TempState::Defined { ref mut uses, .. } = *temp { // We always allow borrows, even mutable ones, as we need - // to promote mutable borrows of some ZSTs e.g. `&mut []`. + // to promote mutable borrows of some ZSTs e.g., `&mut []`. let allowed_use = context.is_borrow() || context.is_nonmutating_use(); debug!("visit_local: allowed_use={:?}", allowed_use); if allowed_use { diff --git a/src/librustc_mir/transform/qualify_consts.rs b/src/librustc_mir/transform/qualify_consts.rs index 034096fe889..5f08dee8728 100644 --- a/src/librustc_mir/transform/qualify_consts.rs +++ b/src/librustc_mir/transform/qualify_consts.rs @@ -17,6 +17,8 @@ use rustc_data_structures::bit_set::BitSet; use rustc_data_structures::indexed_vec::IndexVec; use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::sync::Lrc; +use rustc_target::spec::abi::Abi; use rustc::hir; use rustc::hir::def_id::DefId; use rustc::mir::interpret::ConstValue; @@ -28,13 +30,12 @@ use rustc::mir::*; use rustc::mir::traversal::ReversePostorder; use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext}; use rustc::middle::lang_items; -use rustc_target::spec::abi::Abi; +use rustc::session::config::nightly_options; use syntax::ast::LitKind; use syntax::feature_gate::{UnstableFeatures, feature_err, emit_feature_err, GateIssue}; use syntax_pos::{Span, DUMMY_SP}; use std::fmt; -use rustc_data_structures::sync::Lrc; use std::usize; use transform::{MirPass, MirSource}; @@ -639,7 +640,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { self.add(qualif); // Just in case the type is more specific than - // the definition, e.g. impl associated const + // the definition, e.g., impl associated const // with type parameters, take it into account. self.qualif.restrict(constant.literal.ty, self.tcx, self.param_env); } @@ -952,10 +953,10 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { } } _ => { - // in normal functions we only care about promotion + // In normal functions we only care about promotion. if self.mode == Mode::Fn { - // never promote const fn calls of - // functions without #[rustc_promotable] + // Never promote const fn calls of + // functions without `#[rustc_promotable]`. if self.tcx.is_promotable_const_fn(def_id) { is_const_fn = true; is_promotable_const_fn = true; @@ -963,19 +964,19 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { is_const_fn = true; } } else { - // stable const fn or unstable const fns with their feature gate + // stable const fns or unstable const fns with their feature gate // active if self.tcx.is_const_fn(def_id) { is_const_fn = true; } else if self.is_const_panic_fn(def_id) { - // check the const_panic feature gate + // Check the const_panic feature gate. // FIXME: cannot allow this inside `allow_internal_unstable` // because that would make `panic!` insta stable in constants, - // since the macro is marked with the attr + // since the macro is marked with the attribute. if self.tcx.features().const_panic { is_const_fn = true; } else { - // don't allow panics in constants without the feature gate + // Don't allow panics in constants without the feature gate. emit_feature_err( &self.tcx.sess.parse_sess, "const_panic", @@ -984,25 +985,28 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { &format!("panicking in {}s is unstable", self.mode), ); } - } else if let Some(feat) = self.tcx.is_unstable_const_fn(def_id) { - // check `#[unstable]` const fns or `#[rustc_const_unstable]` - // functions without the feature gate active in this crate to - // report a better error message than the one below + } else if let Some(feature) + = self.tcx.is_unstable_const_fn(def_id) { + // Check `#[unstable]` const fns or `#[rustc_const_unstable]` + // functions without the feature gate active in this crate in + // order to report a better error message than the one below. if self.span.allows_unstable() { - // `allow_internal_unstable` can make such calls stable + // `allow_internal_unstable` can make such calls stable. is_const_fn = true; } else { let mut err = self.tcx.sess.struct_span_err(self.span, &format!("`{}` is not yet stable as a const fn", self.tcx.item_path_str(def_id))); - help!(&mut err, - "in Nightly builds, add `#![feature({})]` \ - to the crate attributes to enable", - feat); + if nightly_options::is_nightly_build() { + help!(&mut err, + "add `#![feature({})]` to the \ + crate attributes to enable", + feature); + } err.emit(); } } else { - // FIXME(#24111) Remove this check when const fn stabilizes + // FIXME(#24111): remove this check when const fn stabilizes. let (msg, note) = if let UnstableFeatures::Disallow = self.tcx.sess.opts.unstable_features { (format!("calls in {}s are limited to \ @@ -1081,7 +1085,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { // we care about constness, not promotability. // If we checked for promotability, we'd miss out on // the results of function calls (which are never promoted - // in runtime code) + // in runtime code). // This is not a problem, because the argument explicitly // requests constness, in contrast to regular promotion // which happens even without the user requesting it. @@ -1098,7 +1102,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { }); } - // non-const fn calls. + // non-const fn calls if !is_const_fn { self.qualif = Qualif::NOT_CONST; if self.mode != Mode::Fn { @@ -1131,7 +1135,7 @@ impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> { // Deny *any* live drops anywhere other than functions. if self.mode != Mode::Fn { - // HACK(eddyb) Emulate a bit of dataflow analysis, + // HACK(eddyb): emulate a bit of dataflow analysis, // conservatively, that drop elaboration will do. let needs_drop = if let Place::Local(local) = *place { if self.local_qualif[local].map_or(true, |q| q.contains(Qualif::NEEDS_DROP)) { @@ -1259,7 +1263,7 @@ pub fn provide(providers: &mut Providers) { fn mir_const_qualif<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> (u8, Lrc>) { - // NB: This `borrow()` is guaranteed to be valid (i.e., the value + // N.B., this `borrow()` is guaranteed to be valid (i.e., the value // cannot yet be stolen), because `mir_validated()`, which steals // from `mir_const(), forces this query to execute before // performing the steal. diff --git a/src/librustc_mir/transform/remove_noop_landing_pads.rs b/src/librustc_mir/transform/remove_noop_landing_pads.rs index a31d12baed2..81b010e7dce 100644 --- a/src/librustc_mir/transform/remove_noop_landing_pads.rs +++ b/src/librustc_mir/transform/remove_noop_landing_pads.rs @@ -58,7 +58,7 @@ impl RemoveNoopLandingPads { } StatementKind::Assign(Place::Local(_), box Rvalue::Use(_)) => { - // Writing to a local (e.g. a drop flag) does not + // Writing to a local (e.g., a drop flag) does not // turn a landing pad to a non-nop } diff --git a/src/librustc_mir/util/elaborate_drops.rs b/src/librustc_mir/util/elaborate_drops.rs index 2c7f337b3b1..4f381e0a3d2 100644 --- a/src/librustc_mir/util/elaborate_drops.rs +++ b/src/librustc_mir/util/elaborate_drops.rs @@ -24,8 +24,8 @@ use std::u32; #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum DropFlagState { - Present, // i.e. initialized - Absent, // i.e. deinitialized or "moved" + Present, // i.e., initialized + Absent, // i.e., deinitialized or "moved" } impl DropFlagState { diff --git a/src/librustc_mir/util/liveness.rs b/src/librustc_mir/util/liveness.rs index 22cc8ead478..22554acc6ad 100644 --- a/src/librustc_mir/util/liveness.rs +++ b/src/librustc_mir/util/liveness.rs @@ -29,7 +29,7 @@ //! ``` //! //! This means that users of this analysis still have to check whether -//! pre-existing references can be used to access the value (e.g. at movable +//! pre-existing references can be used to access the value (e.g., at movable //! generator yield points, all pre-existing references are invalidated, so this //! doesn't matter). diff --git a/src/librustc_passes/ast_validation.rs b/src/librustc_passes/ast_validation.rs index b878a330ab6..9a35721e3e1 100644 --- a/src/librustc_passes/ast_validation.rs +++ b/src/librustc_passes/ast_validation.rs @@ -404,7 +404,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } } ItemKind::Mod(_) => { - // Ensure that `path` attributes on modules are recorded as used (c.f. #35584). + // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584). attr::first_attr_value_str_by_name(&item.attrs, "path"); if attr::contains_name(&item.attrs, "warn_directory_ownership") { let lint = lint::builtin::LEGACY_DIRECTORY_OWNERSHIP; @@ -529,7 +529,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } } -// Bans nested `impl Trait`, e.g. `impl Into`. +// Bans nested `impl Trait`, e.g., `impl Into`. // Nested `impl Trait` _is_ allowed in associated type position, // e.g `impl Iterator` struct NestedImplTraitVisitor<'a> { diff --git a/src/librustc_passes/rvalue_promotion.rs b/src/librustc_passes/rvalue_promotion.rs index b41a04e354d..bfe8b677a5e 100644 --- a/src/librustc_passes/rvalue_promotion.rs +++ b/src/librustc_passes/rvalue_promotion.rs @@ -383,7 +383,7 @@ fn check_expr_kind<'a, 'tcx>( NotPromotable }; // Just in case the type is more specific than the definition, - // e.g. impl associated const with type parameters, check it. + // e.g., impl associated const with type parameters, check it. // Also, trait associated consts are relaxed by this. promotable | v.type_promotability(node_ty) } diff --git a/src/librustc_plugin/load.rs b/src/librustc_plugin/load.rs index bf59165a9c4..ad55672fb47 100644 --- a/src/librustc_plugin/load.rs +++ b/src/librustc_plugin/load.rs @@ -144,7 +144,7 @@ impl<'a> PluginLoader<'a> { // Intentionally leak the dynamic library. We can't ever unload it // since the library can make things that will live arbitrarily long - // (e.g. an @-box cycle or a thread). + // (e.g., an @-box cycle or a thread). mem::forget(lib); registrar diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index ccdcfe322b1..86e3b231fc7 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -23,8 +23,7 @@ extern crate rustc_typeck; extern crate syntax_pos; extern crate rustc_data_structures; -use rustc::hir::{self, PatKind}; -use hir::Node; +use rustc::hir::{self, Node, PatKind}; use rustc::hir::def::Def; use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; @@ -36,14 +35,14 @@ use rustc::ty::fold::TypeVisitor; use rustc::ty::query::Providers; use rustc::ty::subst::UnpackedKind; use rustc::util::nodemap::NodeSet; +use rustc_data_structures::fx::FxHashSet; +use rustc_data_structures::sync::Lrc; use syntax::ast::{self, CRATE_NODE_ID, Ident}; use syntax::symbol::keywords; use syntax_pos::Span; use std::cmp; use std::mem::replace; -use rustc_data_structures::fx::FxHashSet; -use rustc_data_structures::sync::Lrc; mod diagnostics; @@ -74,11 +73,11 @@ impl<'a, 'tcx> Visitor<'tcx> for PubRestrictedVisitor<'a, 'tcx> { struct EmbargoVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, - // Accessibility levels for reachable nodes + // Accessibility levels for reachable nodes. access_levels: AccessLevels, - // Previous accessibility level, None means unreachable + // Previous accessibility level; `None` means unreachable. prev_level: Option, - // Have something changed in the level map? + // Has something changed in the level map? changed: bool, } @@ -117,10 +116,10 @@ impl<'a, 'tcx> EmbargoVisitor<'a, 'tcx> { self.access_levels.map.get(&id).cloned() } - // Updates node level and returns the updated level + // Updates node level and returns the updated level. fn update(&mut self, id: ast::NodeId, level: Option) -> Option { let old_level = self.get(id); - // Accessibility levels can only grow + // Accessibility levels can only grow. if level > old_level { self.access_levels.map.insert(id, level.unwrap()); self.changed = true; @@ -149,16 +148,16 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item) { let inherited_item_level = match item.node { - // Impls inherit level from their types and traits + // Impls inherit level from their types and traits. hir::ItemKind::Impl(..) => { let def_id = self.tcx.hir().local_def_id(item.id); cmp::min(self.item_ty_level(def_id), self.impl_trait_level(def_id)) } - // Foreign mods inherit level from parents + // Foreign modules inherit level from parents. hir::ItemKind::ForeignMod(..) => { self.prev_level } - // Other `pub` items inherit levels from parents + // Other `pub` items inherit levels from parents. hir::ItemKind::Const(..) | hir::ItemKind::Enum(..) | hir::ItemKind::ExternCrate(..) | hir::ItemKind::GlobalAsm(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Mod(..) | hir::ItemKind::Static(..) | hir::ItemKind::Struct(..) | @@ -169,10 +168,10 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { } }; - // Update level of the item itself + // Update level of the item itself. let item_level = self.update(item.id, inherited_item_level); - // Update levels of nested things + // Update levels of nested things. match item.node { hir::ItemKind::Enum(ref def, _) => { for variant in &def.variants { @@ -240,23 +239,23 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { // reachability level through interfaces and children. let orig_level = replace(&mut self.prev_level, item_level); - // Mark all items in interfaces of reachable items as reachable + // Mark all items in interfaces of reachable items as reachable. match item.node { - // The interface is empty + // The interface is empty. hir::ItemKind::ExternCrate(..) => {} - // All nested items are checked by visit_item + // All nested items are checked by `visit_item`. hir::ItemKind::Mod(..) => {} - // Re-exports are handled in visit_mod + // Re-exports are handled in `visit_mod`. hir::ItemKind::Use(..) => {} - // The interface is empty + // The interface is empty. hir::ItemKind::GlobalAsm(..) => {} hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => { if item_level.is_some() { - // Reach the (potentially private) type and the API being exposed + // Reach the (potentially private) type and the API being exposed. self.reach(item.id).ty().predicates(); } } - // Visit everything + // Visit everything. hir::ItemKind::Const(..) | hir::ItemKind::Static(..) | hir::ItemKind::Existential(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Ty(..) => { @@ -286,7 +285,7 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { self.reach(item.id).generics().predicates(); } } - // Visit everything except for private impl items + // Visit everything except for private impl items. hir::ItemKind::Impl(.., ref trait_ref, _, ref impl_item_refs) => { if item_level.is_some() { self.reach(item.id).generics().predicates().impl_trait_ref(); @@ -300,7 +299,7 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { } } - // Visit everything, but enum variants have their own levels + // Visit everything, but enum variants have their own levels. hir::ItemKind::Enum(ref def, _) => { if item_level.is_some() { self.reach(item.id).generics().predicates(); @@ -316,7 +315,7 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { } } } - // Visit everything, but foreign items have their own levels + // Visit everything, but foreign items have their own levels. hir::ItemKind::ForeignMod(ref foreign_mod) => { for foreign_item in &foreign_mod.items { if self.get(foreign_item.id).is_some() { @@ -324,7 +323,7 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { } } } - // Visit everything except for private fields + // Visit everything except for private fields. hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { if item_level.is_some() { @@ -348,7 +347,7 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { // Blocks can have public items, for example impls, but they always // start as completely private regardless of publicity of a function, - // constant, type, field, etc. in which this block resides + // constant, type, field, etc., in which this block resides. intravisit::walk_block(self, b); self.prev_level = orig_level; @@ -524,10 +523,10 @@ struct NamePrivacyVisitor<'a, 'tcx: 'a> { impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> { // Checks that a field in a struct constructor (expression or pattern) is accessible. fn check_field(&mut self, - use_ctxt: Span, // Syntax context of the field name at the use site - span: Span, // Span of the field pattern, e.g. `x: 0` - def: &'tcx ty::AdtDef, // Definition of the struct or enum - field: &'tcx ty::FieldDef) { // Definition of the field + use_ctxt: Span, // syntax context of the field name at the use site + span: Span, // span of the field pattern, e.g., `x: 0` + def: &'tcx ty::AdtDef, // definition of the struct or enum + field: &'tcx ty::FieldDef) { // definition of the field let ident = Ident::new(keywords::Invalid.name(), use_ctxt); let def_id = self.tcx.adjust_ident(ident, def.did, self.current_item).1; if !def.is_enum() && !field.vis.is_accessible_from(def_id, self.tcx) { @@ -539,8 +538,8 @@ impl<'a, 'tcx> NamePrivacyVisitor<'a, 'tcx> { } } -// Set the correct TypeckTables for the given `item_id` (or an empty table if -// there is no TypeckTables for the item). +// Set the correct `TypeckTables` for the given `item_id` (or an empty table if +// there is no `TypeckTables` for the item). fn update_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item_id: ast::NodeId, tables: &mut &'a ty::TypeckTables<'tcx>, @@ -710,7 +709,7 @@ impl<'a, 'tcx> TypePrivacyVisitor<'a, 'tcx> { self.def_id_visibility(did).is_accessible_from(self.current_item, self.tcx) } - // Take node ID of an expression or pattern and check its type for privacy. + // Take node-id of an expression or pattern and check its type for privacy. fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool { self.span = span; if self.tables.node_id_to_type(id).visit_with(self) { @@ -862,7 +861,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { intravisit::walk_qpath(self, qpath, id, span); } - // Check types of patterns + // Check types of patterns. fn visit_pat(&mut self, pattern: &'tcx hir::Pat) { if self.check_expr_pat_type(pattern.hir_id, pattern.span) { // Do not check nested patterns if the error already happened. @@ -883,7 +882,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { intravisit::walk_local(self, local); } - // Check types in item interfaces + // Check types in item interfaces. fn visit_item(&mut self, item: &'tcx hir::Item) { let orig_current_item = self.current_item; let orig_tables = update_tables(self.tcx, @@ -1015,18 +1014,18 @@ struct ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, access_levels: &'a AccessLevels, in_variant: bool, - // set of errors produced by this obsolete visitor + // Set of errors produced by this obsolete visitor. old_error_set: NodeSet, } struct ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b: 'a, 'tcx: 'b> { inner: &'a ObsoleteVisiblePrivateTypesVisitor<'b, 'tcx>, - /// whether the type refers to private types. + /// Whether the type refers to private types. contains_private: bool, - /// whether we've recurred at all (i.e. if we're pointing at the - /// first type on which visit_ty was called). + /// Whether we've recurred at all (i.e., if we're pointing at the + /// first type on which `visit_ty` was called). at_outer_type: bool, - // whether that first type is a public path. + /// Whether that first type is a public path. outer_type_is_public_path: bool, } @@ -1041,7 +1040,7 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // it's in this crate... if let Some(node_id) = self.tcx.hir().as_local_node_id(did) { // .. and it corresponds to a private type in the AST (this returns - // None for type parameters) + // `None` for type parameters). match self.tcx.hir().find(node_id) { Some(Node::Item(ref item)) => !item.vis.node.is_pub(), Some(_) | None => false, @@ -1053,7 +1052,7 @@ impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { fn trait_is_public(&self, trait_id: ast::NodeId) -> bool { // FIXME: this would preferably be using `exported_items`, but all - // traits are exported currently (see `EmbargoVisitor.exported_trait`) + // traits are exported currently (see `EmbargoVisitor.exported_trait`). self.access_levels.is_public(trait_id) } @@ -1079,8 +1078,7 @@ impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = ty.node { if self.inner.path_is_private_type(path) { self.contains_private = true; - // found what we're looking for so let's stop - // working. + // Found what we're looking for, so let's stop working. return } } @@ -1093,7 +1091,7 @@ impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a intravisit::walk_ty(self, ty) } - // don't want to recurse into [, .. expr] + // Don't want to recurse into `[, .. expr]`. fn visit_expr(&mut self, _: &hir::Expr) {} } @@ -1106,7 +1104,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { fn visit_item(&mut self, item: &'tcx hir::Item) { match item.node { - // contents of a private mod can be re-exported, so we need + // Contents of a private mod can be re-exported, so we need // to check internals. hir::ItemKind::Mod(_) => {} @@ -1124,19 +1122,19 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } } - // impls need some special handling to try to offer useful + // Impls need some special handling to try to offer useful // error messages without (too many) false positives - // (i.e. we could just return here to not check them at + // (i.e., we could just return here to not check them at // all, or some worse estimation of whether an impl is // publicly visible). hir::ItemKind::Impl(.., ref g, ref trait_ref, ref self_, ref impl_item_refs) => { // `impl [... for] Private` is never visible. let self_contains_private; - // impl [... for] Public<...>, but not `impl [... for] - // Vec` or `(Public,)` etc. + // `impl [... for] Public<...>`, but not `impl [... for] + // Vec` or `(Public,)`, etc. let self_is_public_path; - // check the properties of the Self type: + // Check the properties of the `Self` type: { let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor { inner: self, @@ -1149,7 +1147,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { self_is_public_path = visitor.outer_type_is_public_path; } - // miscellaneous info about the impl + // Miscellaneous info about the impl: // `true` iff this is `impl Private for ...`. let not_private_trait = @@ -1242,7 +1240,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } } } else if trait_ref.is_none() && self_is_public_path { - // impl Public { ... }. Any public static + // `impl Public { ... }`. Any public static // methods will be visible as `Public::foo`. let mut found_pub_static = false; for impl_item_ref in impl_item_refs { @@ -1272,7 +1270,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // we're introducing a new name. hir::ItemKind::Ty(..) => return, - // not at all public, so we don't care + // Not at all public, so we don't care. _ if !self.item_is_public(&item.id, &item.vis) => { return; } @@ -1282,7 +1280,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // We've carefully constructed it so that if we're here, then // any `visit_ty`'s will be called on things that are in - // public signatures, i.e. things that we're interested in for + // public signatures, i.e., things that we're interested in for // this visitor. intravisit::walk_item(self, item); } @@ -1340,7 +1338,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { } } - // we don't need to introspect into these at all: an + // We don't need to introspect into these at all: an // expression/block context can't possibly contain exported things. // (Making them no-ops stops us from traversing the whole AST without // having to be super careful about our `walk_...` calls above.) @@ -1359,9 +1357,9 @@ struct SearchInterfaceForPrivateItemsVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx>, item_def_id: DefId, span: Span, - /// The visitor checks that each component type is at least this visible + /// The visitor checks that each component type is at least this visible. required_visibility: ty::Visibility, - /// The visibility of the least visible component that has been visited + /// The visibility of the least visible component that has been visited. min_visibility: ty::Visibility, has_pub_restricted: bool, has_old_errors: bool, @@ -1384,7 +1382,7 @@ impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> { } fn predicates(&mut self) -> &mut Self { - // NB: We use `explicit_predicates_of` and not `predicates_of` + // N.B., we use `explicit_predicates_of` and not `predicates_of` // because we don't want to report privacy errors due to where // clauses that the compiler inferred. We only want to // consider the ones that the user wrote. This is important @@ -1429,7 +1427,7 @@ impl<'a, 'tcx: 'a> SearchInterfaceForPrivateItemsVisitor<'a, 'tcx> { } fn check_trait_ref(&mut self, trait_ref: ty::TraitRef<'tcx>) { - // Non-local means public (private items can't leave their crate, modulo bugs) + // Non-local means public (private items can't leave their crate, modulo bugs). if let Some(node_id) = self.tcx.hir().as_local_node_id(trait_ref.def_id) { let item = self.tcx.hir().expect_item(node_id); let vis = ty::Visibility::from_hir(&item.vis, node_id, self.tcx); @@ -1478,7 +1476,7 @@ impl<'a, 'tcx: 'a> TypeVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<' }; if let Some(def_id) = ty_def_id { - // Non-local means public (private items can't leave their crate, modulo bugs) + // Non-local means public (private items can't leave their crate, modulo bugs). if let Some(node_id) = self.tcx.hir().as_local_node_id(def_id) { let hir_vis = match self.tcx.hir().find(node_id) { Some(Node::Item(item)) => &item.vis, @@ -1579,30 +1577,29 @@ impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> let item_visibility = ty::Visibility::from_hir(&item.vis, item.id, tcx); match item.node { - // Crates are always public + // Crates are always public. hir::ItemKind::ExternCrate(..) => {} - // All nested items are checked by visit_item + // All nested items are checked by `visit_item`. hir::ItemKind::Mod(..) => {} - // Checked in resolve + // Checked in resolve. hir::ItemKind::Use(..) => {} - // No subitems + // No subitems. hir::ItemKind::GlobalAsm(..) => {} hir::ItemKind::Existential(hir::ExistTy { impl_trait_fn: Some(_), .. }) => { // Check the traits being exposed, as they're separate, - // e.g. `impl Iterator` has two predicates, + // e.g., `impl Iterator` has two predicates, // `X: Iterator` and `::Item == T`, // where `X` is the `impl Iterator` itself, // stored in `predicates_of`, not in the `Ty` itself. - self.check(item.id, item_visibility).predicates(); } - // Subitems of these items have inherited publicity + // Subitems of these items have inherited publicity. hir::ItemKind::Const(..) | hir::ItemKind::Static(..) | hir::ItemKind::Fn(..) | hir::ItemKind::Existential(..) | hir::ItemKind::Ty(..) => { self.check(item.id, item_visibility).generics().predicates().ty(); - // Recurse for e.g. `impl Trait` (see `visit_ty`). + // Recurse for e.g., `impl Trait` (see `visit_ty`). self.inner_visibility = item_visibility; intravisit::walk_item(self, item); } @@ -1634,14 +1631,14 @@ impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> } } } - // Subitems of foreign modules have their own publicity + // Subitems of foreign modules have their own publicity. hir::ItemKind::ForeignMod(ref foreign_mod) => { for foreign_item in &foreign_mod.items { let vis = ty::Visibility::from_hir(&foreign_item.vis, item.id, tcx); self.check(foreign_item.id, vis).generics().predicates().ty(); } } - // Subitems of structs and unions have their own publicity + // Subitems of structs and unions have their own publicity. hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { self.check(item.id, item_visibility).generics().predicates(); @@ -1652,7 +1649,7 @@ impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> } } // An inherent impl is public when its type is public - // Subitems of inherent impls have their own publicity + // Subitems of inherent impls have their own publicity. hir::ItemKind::Impl(.., None, _, ref impl_item_refs) => { let ty_vis = self.check(item.id, ty::Visibility::Invisible).ty().min_visibility; @@ -1665,13 +1662,13 @@ impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type; check.generics().predicates().ty(); - // Recurse for e.g. `impl Trait` (see `visit_ty`). + // Recurse for e.g., `impl Trait` (see `visit_ty`). self.inner_visibility = impl_item_vis; intravisit::walk_impl_item(self, impl_item); } } // A trait impl is public when both its type and its trait are public - // Subitems of trait impls have inherited publicity + // Subitems of trait impls have inherited publicity. hir::ItemKind::Impl(.., Some(_), _, ref impl_item_refs) => { let vis = self.check(item.id, ty::Visibility::Invisible) .ty().impl_trait_ref().min_visibility; @@ -1682,7 +1679,7 @@ impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> check.in_assoc_ty = impl_item_ref.kind == hir::AssociatedItemKind::Type; check.generics().predicates().ty(); - // Recurse for e.g. `impl Trait` (see `visit_ty`). + // Recurse for e.g., `impl Trait` (see `visit_ty`). self.inner_visibility = vis; intravisit::walk_impl_item(self, impl_item); } @@ -1691,12 +1688,12 @@ impl<'a, 'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> } fn visit_impl_item(&mut self, _impl_item: &'tcx hir::ImplItem) { - // handled in `visit_item` above + // Handled in `visit_item` above. } - // Don't recurse into expressions in array sizes or const initializers + // Don't recurse into expressions in array sizes or const initializers. fn visit_expr(&mut self, _: &'tcx hir::Expr) {} - // Don't recurse into patterns in function arguments + // Don't recurse into patterns in function arguments. fn visit_pat(&mut self, _: &'tcx hir::Pat) {} } @@ -1778,7 +1775,7 @@ fn privacy_access_levels<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, pub_restricted_visitor.has_pub_restricted }; - // Check for private types and traits in public interfaces + // Check for private types and traits in public interfaces. let mut visitor = PrivateItemsInPublicInterfacesVisitor { tcx, has_pub_restricted, diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 389be3f758e..ebd2c87fa46 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -84,7 +84,7 @@ use rustc_data_structures::sync::Lrc; use resolve_imports::{ImportDirective, ImportDirectiveSubclass, NameResolution, ImportResolver}; use macros::{InvocationData, LegacyBinding, ParentScope}; -// NB: This module needs to be declared first so diagnostics are +// N.B., this module needs to be declared first so diagnostics are // registered before they are used. mod diagnostics; mod error_reporting; @@ -638,7 +638,7 @@ impl<'a> PathSource<'a> { // A minimal representation of a path segment. We use this in resolve because // we synthesize 'path segments' which don't have the rest of an AST or HIR -// PathSegment. +// `PathSegment`. #[derive(Clone, Copy, Debug)] pub struct Segment { ident: Ident, @@ -2608,7 +2608,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { result } - /// This is called to resolve a trait reference from an `impl` (i.e. `impl Trait for Foo`) + /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`) fn with_optional_trait_ref(&mut self, opt_trait_ref: Option<&TraitRef>, f: F) -> T where F: FnOnce(&mut Resolver, Option) -> T { @@ -2890,7 +2890,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { self.resolve_pattern(&pattern, PatternSource::Match, &mut bindings_list); } - // This has to happen *after* we determine which pat_idents are variants + // This has to happen *after* we determine which pat_idents are variants. self.check_consistent_bindings(&arm.pats); if let Some(ast::Guard::If(ref expr)) = arm.guard { @@ -3032,8 +3032,8 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { Def::StructCtor(..) | Def::VariantCtor(..) | Def::Const(..) | Def::Static(..) => { // This is unambiguously a fresh binding, either syntactically - // (e.g. `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves - // to something unusable as a pattern (e.g. constructor function), + // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves + // to something unusable as a pattern (e.g., constructor function), // but we still conservatively report an error, see // issues/33118#issuecomment-233962221 for one reason why. resolve_error( @@ -3209,9 +3209,9 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { for (sp, variant_path, enum_path) in enum_candidates { if sp.is_dummy() { let msg = format!("there is an enum variant `{}`, \ - try using `{}`?", - variant_path, - enum_path); + try using `{}`?", + variant_path, + enum_path); err.help(&msg); } else { err.span_suggestion_with_applicability( @@ -3263,7 +3263,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { let mut levenshtein_worked = false; - // Try Levenshtein. + // Try Levenshtein algorithm. if let Some(candidate) = this.lookup_typo_candidate(path, ns, is_expected, span) { err.span_label(ident_span, format!("did you mean `{}`?", candidate)); levenshtein_worked = true; @@ -4325,7 +4325,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { for pat in pats { this.resolve_pattern(pat, PatternSource::WhileLet, &mut bindings_list); } - // This has to happen *after* we determine which pat_idents are variants + // This has to happen *after* we determine which pat_idents are variants. this.check_consistent_bindings(pats); this.visit_block(block); this.ribs[ValueNS].pop(); @@ -4611,7 +4611,7 @@ impl<'a, 'crateloader: 'a> Resolver<'a, 'crateloader> { /// When name resolution fails, this method can be used to look up candidate /// entities with the expected name. It allows filtering them using the /// supplied predicate (which should be used to only accept the types of - /// definitions expected e.g. traits). The lookup spans across all crates. + /// definitions expected e.g., traits). The lookup spans across all crates. /// /// NOTE: The method does not look into imports, but this is not a problem, /// since we report the definitions (thus, the de-aliased imports). diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index 39c4fc587cc..3f57c74c2c3 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -359,7 +359,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> { } } else { // Not only attributes, but anything in macro namespace can result in - // `Def::NonMacroAttr` definition (e.g. `inline!()`), so we must report + // `Def::NonMacroAttr` definition (e.g., `inline!()`), so we must report // an error for those cases. let msg = format!("expected a macro, found {}", def.kind_name()); self.session.span_err(path.span, &msg); @@ -436,7 +436,7 @@ impl<'a, 'cl> Resolver<'a, 'cl> { // Resolve an identifier in lexical scope. // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during // expansion and import resolution (perhaps they can be merged in the future). - // The function is used for resolving initial segments of macro paths (e.g. `foo` in + // The function is used for resolving initial segments of macro paths (e.g., `foo` in // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition. crate fn early_resolve_ident_in_lexical_scope( &mut self, diff --git a/src/librustc_resolve/resolve_imports.rs b/src/librustc_resolve/resolve_imports.rs index 36b6b5296f0..f130895e236 100644 --- a/src/librustc_resolve/resolve_imports.rs +++ b/src/librustc_resolve/resolve_imports.rs @@ -430,7 +430,7 @@ impl<'a, 'crateloader> Resolver<'a, 'crateloader> { crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>) -> &'a NameBinding<'a> { let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) || - // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE` + // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE` !directive.is_glob() && binding.is_extern_crate() { directive.vis.get() } else { @@ -1011,7 +1011,7 @@ impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> { NameBindingKind::Import { binding, .. } => { match binding.kind { // Never suggest the name that has binding error - // i.e. the name that cannot be previously resolved + // i.e., the name that cannot be previously resolved NameBindingKind::Def(Def::Err, _) => return None, _ => Some(&i.name), } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index 85ffd3eb1c2..e0acc150ee3 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -110,7 +110,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { } } - // Returns path to the compilation output (e.g. libfoo-12345678.rmeta) + // Returns path to the compilation output (e.g., libfoo-12345678.rmeta) pub fn compilation_output(&self, crate_name: &str) -> PathBuf { let sess = &self.tcx.sess; // Save-analysis is emitted per whole session, not per each crate type diff --git a/src/librustc_target/abi/call/mod.rs b/src/librustc_target/abi/call/mod.rs index 489bb37fc26..1c3763c6e37 100644 --- a/src/librustc_target/abi/call/mod.rs +++ b/src/librustc_target/abi/call/mod.rs @@ -164,7 +164,7 @@ impl Reg { } /// An argument passed entirely registers with the -/// same kind (e.g. HFA / HVA on PPC64 and AArch64). +/// same kind (e.g., HFA / HVA on PPC64 and AArch64). #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct Uniform { pub unit: Reg, @@ -173,7 +173,7 @@ pub struct Uniform { /// * equal to `unit.size` (one scalar/vector) /// * a multiple of `unit.size` (an array of scalar/vectors) /// * if `unit.kind` is `Integer`, the last element - /// can be shorter, i.e. `{ i64, i64, i32 }` for + /// can be shorter, i.e., `{ i64, i64, i32 }` for /// 64-bit integers with a total size of 20 bytes pub total: Size, } diff --git a/src/librustc_target/abi/call/s390x.rs b/src/librustc_target/abi/call/s390x.rs index d6d8ea71918..fe1c8751792 100644 --- a/src/librustc_target/abi/call/s390x.rs +++ b/src/librustc_target/abi/call/s390x.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// FIXME: The assumes we're using the non-vector ABI, i.e. compiling +// FIXME: The assumes we're using the non-vector ABI, i.e., compiling // for a pre-z13 machine or using -mno-vx. use abi::call::{FnType, ArgType, Reg}; diff --git a/src/librustc_target/abi/call/x86_64.rs b/src/librustc_target/abi/call/x86_64.rs index f091f80924d..0f27300dc3b 100644 --- a/src/librustc_target/abi/call/x86_64.rs +++ b/src/librustc_target/abi/call/x86_64.rs @@ -15,7 +15,7 @@ use abi::call::{ArgType, CastTarget, FnType, Reg, RegKind}; use abi::{self, Abi, HasDataLayout, LayoutOf, Size, TyLayout, TyLayoutMethods}; /// Classification of "eightbyte" components. -// NB: the order of the variants is from general to specific, +// N.B., the order of the variants is from general to specific, // such that `unify(a, b)` is the "smaller" of `a` and `b`. #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] enum Class { diff --git a/src/librustc_target/abi/mod.rs b/src/librustc_target/abi/mod.rs index 50ce0ad6915..5912da9d3aa 100644 --- a/src/librustc_target/abi/mod.rs +++ b/src/librustc_target/abi/mod.rs @@ -409,7 +409,7 @@ impl Align { /// Compute the best alignment possible for the given offset /// (the largest power of two that the offset is a multiple of). /// - /// NB: for an offset of `0`, this happens to return `2^64`. + /// N.B., for an offset of `0`, this happens to return `2^64`. pub fn max_for_offset(offset: Size) -> Align { Align { pow2: offset.bytes().trailing_zeros() as u8, @@ -639,7 +639,7 @@ pub struct Scalar { /// /// This is intended specifically to mirror LLVM’s `!range` metadata, /// semantics. - // FIXME(eddyb) always use the shortest range, e.g. by finding + // FIXME(eddyb) always use the shortest range, e.g., by finding // the largest space between two consecutive valid values and // taking everything else as the (shortest) valid range. pub valid_range: RangeInclusive, @@ -887,12 +887,12 @@ impl LayoutDetails { } /// The details of the layout of a type, alongside the type itself. -/// Provides various type traversal APIs (e.g. recursing into fields). +/// Provides various type traversal APIs (e.g., recursing into fields). /// /// Note that the details are NOT guaranteed to always be identical /// to those obtained from `layout_of(ty)`, as we need to produce /// layouts for which Rust types do not exist, such as enum variants -/// or synthetic fields of enums (i.e. discriminants) and fat pointers. +/// or synthetic fields of enums (i.e., discriminants) and fat pointers. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct TyLayout<'a, Ty> { pub ty: Ty, diff --git a/src/librustc_target/spec/abi.rs b/src/librustc_target/spec/abi.rs index 6d8c8eb19f0..919744fe046 100644 --- a/src/librustc_target/spec/abi.rs +++ b/src/librustc_target/spec/abi.rs @@ -12,7 +12,7 @@ use std::fmt; #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable, Clone, Copy, Debug)] pub enum Abi { - // NB: This ordering MUST match the AbiDatas array below. + // N.B., this ordering MUST match the AbiDatas array below. // (This is ensured by the test indices_are_correct().) // Single platform ABIs diff --git a/src/librustc_target/spec/mod.rs b/src/librustc_target/spec/mod.rs index a9aa721f5c3..d8e8477f3d0 100644 --- a/src/librustc_target/spec/mod.rs +++ b/src/librustc_target/spec/mod.rs @@ -605,7 +605,7 @@ pub struct TargetOptions { /// `eh_unwind_resume` lang item. pub custom_unwind_resume: bool, - /// Flag indicating whether ELF TLS (e.g. #[thread_local]) is available for + /// Flag indicating whether ELF TLS (e.g., #[thread_local]) is available for /// this target. pub has_elf_tls: bool, // This is mainly for easy compatibility with emscripten. diff --git a/src/librustc_target/spec/thumb_base.rs b/src/librustc_target/spec/thumb_base.rs index a5c4b8925e2..d760f5bf1f7 100644 --- a/src/librustc_target/spec/thumb_base.rs +++ b/src/librustc_target/spec/thumb_base.rs @@ -20,7 +20,7 @@ // - Cortex-M23 // - Cortex-M33 // -// We have opted for these instead of one target per processor (e.g. `cortex-m0`, `cortex-m3`, +// We have opted for these instead of one target per processor (e.g., `cortex-m0`, `cortex-m3`, // etc) because the differences between some processors like the cortex-m0 and cortex-m1 are almost // non-existent from the POV of codegen so it doesn't make sense to have separate targets for them. // And if differences exist between two processors under the same target, rustc flags can be used to diff --git a/src/librustc_traits/implied_outlives_bounds.rs b/src/librustc_traits/implied_outlives_bounds.rs index 7514c2c18e7..d46ce8b10b9 100644 --- a/src/librustc_traits/implied_outlives_bounds.rs +++ b/src/librustc_traits/implied_outlives_bounds.rs @@ -77,7 +77,7 @@ fn compute_implied_outlives_bounds<'tcx>( let obligations = wf::obligations(infcx, param_env, DUMMY_NODE_ID, ty, DUMMY_SP).unwrap_or(vec![]); - // NB: All of these predicates *ought* to be easily proven + // N.B., all of these predicates *ought* to be easily proven // true. In fact, their correctness is (mostly) implied by // other parts of the program. However, in #42552, we had // an annoying scenario where: diff --git a/src/librustc_traits/lowering/mod.rs b/src/librustc_traits/lowering/mod.rs index 8024ec96db0..473eebbde78 100644 --- a/src/librustc_traits/lowering/mod.rs +++ b/src/librustc_traits/lowering/mod.rs @@ -43,7 +43,7 @@ crate fn provide(p: &mut Providers) { } crate trait Lower { - /// Lower a rustc construct (e.g. `ty::TraitPredicate`) to a chalk-like type. + /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk-like type. fn lower(&self) -> T; } @@ -90,9 +90,9 @@ where } /// `ty::Binder` is used for wrapping a rustc construction possibly containing generic -/// lifetimes, e.g. `for<'a> T: Fn(&'a i32)`. Instead of representing higher-ranked things -/// in that leaf-form (i.e. `Holds(Implemented(Binder))` in the previous -/// example), we model them with quantified domain goals, e.g. as for the previous example: +/// lifetimes, e.g., `for<'a> T: Fn(&'a i32)`. Instead of representing higher-ranked things +/// in that leaf-form (i.e., `Holds(Implemented(Binder))` in the previous +/// example), we model them with quantified domain goals, e.g., as for the previous example: /// `forall<'a> { T: Fn(&'a i32) }` which corresponds to something like /// `Binder`. impl<'tcx, T> Lower> for ty::Binder @@ -248,7 +248,7 @@ fn program_clauses_for_trait<'a, 'tcx>( // and that named bound regions have a def-id, it is safe // to just inject `hypotheses` (which contains named vars bound at index `0`) // into this binding level. This may change if we ever allow where clauses - // to bind types (e.g. for GATs things), because bound types only use a `BoundVar` + // to bind types (e.g., for GATs things), because bound types only use a `BoundVar` // index (no def-id). hypotheses, @@ -560,7 +560,7 @@ pub fn program_clauses_for_associated_type_value<'a, 'tcx>( // ``` // // FIXME: For the moment, we don't account for where clauses written on the associated - // ty definition (i.e. in the trait def, as in `type AssocType where T: Sized`). + // ty definition (i.e., in the trait def, as in `type AssocType where T: Sized`). // ``` // forall { // forall { diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 752e0a5fac6..fc151d51d37 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -8,38 +8,39 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Conversion from AST representation of types to the `ty.rs` -//! representation. The main routine here is `ast_ty_to_ty()`: each use -//! is parameterized by an instance of `AstConv`. +//! Conversion from AST representation of types to the `ty.rs` representation. +//! The main routine here is `ast_ty_to_ty()`; each use is is parameterized by +//! an instance of `AstConv`. -use smallvec::SmallVec; +use errors::{Applicability, FatalError, DiagnosticId}; use hir::{self, GenericArg, GenericArgs}; use hir::def::Def; use hir::def_id::DefId; use hir::HirVec; +use lint; use middle::resolve_lifetime as rl; use namespace::Namespace; -use rustc::ty::subst::{Kind, Subst, Substs}; -use rustc::traits; +use rustc::traits::{self, TraitRefExpansionInfoDignosticBuilder}; use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable}; use rustc::ty::{GenericParamDef, GenericParamDefKind}; +use rustc::ty::subst::{Kind, Subst, Substs}; use rustc::ty::wf::object_region_bounds; use rustc_data_structures::sync::Lrc; use rustc_target::spec::abi; -use std::collections::BTreeSet; -use std::slice; use require_c_abi_if_variadic; -use util::common::ErrorReported; -use util::nodemap::FxHashMap; -use errors::{Applicability, FatalError, DiagnosticId}; -use lint; - -use std::iter; +use smallvec::SmallVec; use syntax::ast; use syntax::feature_gate::{GateIssue, emit_feature_err}; use syntax::ptr::P; use syntax::util::lev_distance::find_best_match_for_name; use syntax_pos::{DUMMY_SP, Span, MultiSpan}; +use util::common::ErrorReported; +use util::nodemap::FxHashMap; + +use std::collections::BTreeSet; +use std::iter; +use std::ops::Range; +use std::slice; pub trait AstConv<'gcx, 'tcx> { fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>; @@ -80,7 +81,7 @@ pub trait AstConv<'gcx, 'tcx> { fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>; /// Invoked when we encounter an error from some prior pass - /// (e.g. resolve) that is translated into a ty-error. This is + /// (e.g., resolve) that is translated into a ty-error. This is /// used to help suppress derived errors typeck might otherwise /// report. fn set_tainted_by_errors(&self); @@ -97,7 +98,7 @@ struct ConvertedBinding<'tcx> { #[derive(PartialEq)] enum GenericArgPosition { Type, - Value, // e.g. functions + Value, // e.g., functions MethodCall, } @@ -106,7 +107,7 @@ enum GenericArgPosition { /// This type must not appear anywhere in other converted types. const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0)); -impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o { +impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { pub fn ast_region_to_region(&self, lifetime: &hir::Lifetime, def: Option<&ty::GenericParamDef>) @@ -321,8 +322,8 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o { provided, offset| { // We enforce the following: `required` <= `provided` <= `permitted`. - // For kinds without defaults (i.e. lifetimes), `required == permitted`. - // For other kinds (i.e. types), `permitted` may be greater than `required`. + // For kinds without defaults (i.e., lifetimes), `required == permitted`. + // For other kinds (i.e., types), `permitted` may be greater than `required`. if required <= provided && provided <= permitted { return (false, None); } @@ -411,24 +412,24 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o { /// creating the substitutions for, and a partial set of /// substitutions `parent_substs`. In general, the substitutions /// for an item begin with substitutions for all the "parents" of - /// that item -- so e.g. for a method it might include the + /// that item -- e.g., for a method it might include the /// parameters from the impl. /// /// Therefore, the method begins by walking down these parents, /// starting with the outermost parent and proceed inwards until - /// it reaches `def_id`. For each parent P, it will check `parent_substs` + /// it reaches `def_id`. For each parent `P`, it will check `parent_substs` /// first to see if the parent's substitutions are listed in there. If so, /// we can append those and move on. Otherwise, it invokes the /// three callback functions: /// - /// - `args_for_def_id`: given the def-id P, supplies back the + /// - `args_for_def_id`: given the def-id `P`, supplies back the /// generic arguments that were given to that parent from within - /// the path; so e.g. if you have `::Bar`, the def-id + /// the path; so e.g., if you have `::Bar`, the def-id /// might refer to the trait `Foo`, and the arguments might be /// `[T]`. The boolean value indicates whether to infer values /// for arguments whose values were not explicitly provided. /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`, - /// instantiate a `Kind` + /// instantiate a `Kind`. /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then /// creates a suitable inference variable. pub fn create_substs_for_generic_args<'a, 'b>( @@ -441,7 +442,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o { provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>, inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>, ) -> &'tcx Substs<'tcx> { - // Collect the segments of the path: we need to substitute arguments + // Collect the segments of the path; we need to substitute arguments // for parameters throughout the entire path (wherever there are // generic parameters). let mut parent_defs = tcx.generics_of(def_id); @@ -453,8 +454,8 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o { } // We manually build up the substitution, rather than using convenience - // methods in `subst.rs` so that we can iterate over the arguments and - // parameters in lock-step linearly, rather than trying to match each pair. + // methods in `subst.rs`, so that we can iterate over the arguments and + // parameters in lock-step linearly, instead of trying to match each pair. let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count); // Iterate over each segment of the path. @@ -1087,13 +1088,10 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o { } } if !suggestions.is_empty() { - let msg = if suggestions.len() == 1 { - "if you meant to specify the associated type, write" - } else { - "if you meant to specify the associated types, write" - }; + let msg = format!("if you meant to specify the associated {}, write", + if suggestions.len() == 1 { "type" } else { "types" }); err.multipart_suggestion_with_applicability( - msg, + &msg, suggestions, Applicability::MaybeIncorrect, ); @@ -1787,8 +1785,8 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx>+'o { } } -/// Divides a list of general trait bounds into two groups: auto traits (e.g. Sync and Send) and the -/// remaining general trait bounds. +/// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and +/// the remaining general trait bounds. fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>, trait_bounds: &'b [hir::PolyTraitRef]) -> (Vec, Vec<&'b hir::PolyTraitRef>) @@ -1828,7 +1826,7 @@ impl<'a, 'gcx, 'tcx> Bounds<'tcx> { pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>) -> Vec<(ty::Predicate<'tcx>, Span)> { - // If it could be sized, and is, add the sized predicate + // If it could be sized, and is, add the sized predicate. let sized_predicate = self.implicitly_sized.and_then(|span| { tcx.lang_items().sized_trait().map(|sized| { let trait_ref = ty::TraitRef { @@ -1841,8 +1839,8 @@ impl<'a, 'gcx, 'tcx> Bounds<'tcx> { sized_predicate.into_iter().chain( self.region_bounds.iter().map(|&(region_bound, span)| { - // account for the binder being introduced below; no need to shift `param_ty` - // because, at present at least, it can only refer to early-bound regions + // Account for the binder being introduced below; no need to shift `param_ty` + // because, at present at least, it can only refer to early-bound regions. let region_bound = ty::fold::shift_region(tcx, region_bound, 1); let outlives = ty::OutlivesPredicate(param_ty, region_bound); (ty::Binder::dummy(outlives).to_predicate(), span) diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index bc9ba0e0054..87ee903cf43 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use check::{FnCtxt, Expectation, Diverges, Needs}; +use check::coercion::CoerceMany; use rustc::hir::{self, PatKind}; use rustc::hir::def::{Def, CtorKind}; use rustc::hir::pat_util::EnumerateAndAdjustIterator; @@ -15,17 +17,15 @@ use rustc::infer; use rustc::infer::type_variable::TypeVariableOrigin; use rustc::traits::ObligationCauseCode; use rustc::ty::{self, Ty, TypeFoldable}; -use check::{FnCtxt, Expectation, Diverges, Needs}; -use check::coercion::CoerceMany; -use util::nodemap::FxHashMap; - -use std::collections::hash_map::Entry::{Occupied, Vacant}; -use std::cmp; use syntax::ast; use syntax::source_map::Spanned; use syntax::ptr::P; use syntax::util::lev_distance::find_best_match_for_name; use syntax_pos::Span; +use util::nodemap::FxHashMap; + +use std::collections::hash_map::Entry::{Occupied, Vacant}; +use std::cmp; impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// The `is_arg` argument indicates whether this pattern is the @@ -545,7 +545,7 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); // the "discriminant type" (issue #23116). // // arielb1 [writes here in this comment thread][c] that there - // is certainly *some* potential danger, e.g. for an example + // is certainly *some* potential danger, e.g., for an example // like: // // [c]: https://github.com/rust-lang/rust/pull/43399#discussion_r130223956 @@ -729,10 +729,10 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); return self.tcx.types.err; }; - // Type check the path. + // Type-check the path. self.demand_eqtype(pat.span, expected, pat_ty); - // Type check subpatterns. + // Type-check subpatterns. if self.check_struct_pat_fields(pat_ty, pat.id, pat.span, variant, fields, etc, def_bm) { pat_ty } else { @@ -771,7 +771,7 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); _ => bug!("unexpected pattern definition: {:?}", def) } - // Type check the path. + // Type-check the path. let pat_ty = self.instantiate_value_path(segments, opt_ty, def, pat.span, pat.id).0; self.demand_suptype(pat.span, expected, pat_ty); pat_ty @@ -808,7 +808,7 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); return self.tcx.types.err; } - // Type check the path. + // Type-check the path. let (pat_ty, def) = self.instantiate_value_path(segments, opt_ty, def, pat.span, pat.id); if !pat_ty.is_fn() { report_unexpected_def(def); @@ -838,7 +838,7 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); self.demand_eqtype(pat.span, expected, pat_ty); - // Type check subpatterns. + // Type-check subpatterns. if subpats.len() == variant.fields.len() || subpats.len() < variant.fields.len() && ddpos.is_some() { let substs = match pat_ty.sty { diff --git a/src/librustc_typeck/check/autoderef.rs b/src/librustc_typeck/check/autoderef.rs index 2cd2bb50648..1b594342c9a 100644 --- a/src/librustc_typeck/check/autoderef.rs +++ b/src/librustc_typeck/check/autoderef.rs @@ -203,7 +203,7 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> { } /// also dereference through raw pointer types - /// e.g. assuming ptr_to_Foo is the type `*const Foo` + /// e.g., assuming ptr_to_Foo is the type `*const Foo` /// fcx.autoderef(span, ptr_to_Foo) => [*const Foo] /// fcx.autoderef(span, ptr_to_Foo).include_raw_ptrs() => [*const Foo, Foo] pub fn include_raw_pointers(mut self) -> Self { diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index ad4afb0d1a3..e4ce04916ce 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -38,7 +38,7 @@ pub fn check_legal_trait_for_method_call(tcx: TyCtxt, span: Span, trait_id: DefI enum CallStep<'tcx> { Builtin(Ty<'tcx>), DeferredClosure(ty::FnSig<'tcx>), - /// e.g. enum variant constructors + /// e.g., enum variant constructors Overloaded(MethodCallee<'tcx>), } diff --git a/src/librustc_typeck/check/cast.rs b/src/librustc_typeck/check/cast.rs index c35aee7883f..51271f0f351 100644 --- a/src/librustc_typeck/check/cast.rs +++ b/src/librustc_typeck/check/cast.rs @@ -27,7 +27,7 @@ //! //! where `&.T` and `*T` are references of either mutability, //! and where pointer_kind(`T`) is the kind of the unsize info -//! in `T` - the vtable for a trait definition (e.g. `fmt::Display` or +//! in `T` - the vtable for a trait definition (e.g., `fmt::Display` or //! `Iterator`, not `Iterator`) or a length (or `()` if `T: Sized`). //! //! Note that lengths are not adjusted when casting raw slices - diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 629a31a7e1f..be15503e479 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -266,7 +266,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { ty::Predicate::ObjectSafe(..) => None, ty::Predicate::ConstEvaluatable(..) => None, - // NB: This predicate is created by breaking down a + // N.B., this predicate is created by breaking down a // `ClosureType: FnFoo()` predicate, where // `ClosureType` represents some `Closure`. It can't // possibly be referring to the current closure, diff --git a/src/librustc_typeck/check/coercion.rs b/src/librustc_typeck/check/coercion.rs index f7072a6395b..8d844fe3a69 100644 --- a/src/librustc_typeck/check/coercion.rs +++ b/src/librustc_typeck/check/coercion.rs @@ -336,7 +336,7 @@ impl<'f, 'gcx, 'tcx> Coerce<'f, 'gcx, 'tcx> { // the decision to region inference (and regionck, which will add // some more edges to this variable). However, this can wind up // creating a crippling number of variables in some cases -- - // e.g. #32278 -- so we optimize one particular case [3]. + // e.g., #32278 -- so we optimize one particular case [3]. // Let me try to explain with some examples: // - The "running example" above represents the simple case, // where we have one `&` reference at the outer level and @@ -809,7 +809,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Special-case that coercion alone cannot handle: // Two function item types of differing IDs or Substs. if let (&ty::FnDef(..), &ty::FnDef(..)) = (&prev_ty.sty, &new_ty.sty) { - // Don't reify if the function types have a LUB, i.e. they + // Don't reify if the function types have a LUB, i.e., they // are the same function and their parameters have a LUB. let lub_ty = self.commit_if_ok(|_| { self.at(cause, self.param_env) diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index fb83d169d39..f4f6b3d6616 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -91,7 +91,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Checks that the type of `expr` can be coerced to `expected`. // - // NB: This code relies on `self.diverges` to be accurate. In + // N.B., this code relies on `self.diverges` to be accurate. In // particular, assignments to `!` will be permitted if the // diverges flag is currently "always". pub fn demand_coerce_diag(&self, diff --git a/src/librustc_typeck/check/dropck.rs b/src/librustc_typeck/check/dropck.rs index aae99addfcd..f59bc2d0c2d 100644 --- a/src/librustc_typeck/check/dropck.rs +++ b/src/librustc_typeck/check/dropck.rs @@ -32,7 +32,7 @@ use syntax_pos::Span; /// coherence), /// /// 2. The generic region/type parameters of the impl's self-type must -/// all be parameters of the Drop impl itself (i.e. no +/// all be parameters of the Drop impl itself (i.e., no /// specialization like `impl Drop for Foo`), and, /// /// 3. Any bounds on the generic parameters must be reflected in the @@ -180,7 +180,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>( // // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x} // - // Applying this to the predicates (i.e. assumptions) provided by the item + // Applying this to the predicates (i.e., assumptions) provided by the item // definition yields the instantiated assumptions: // // ['y : 'z] diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index b1382057c52..5c0eef5b1f3 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -505,7 +505,7 @@ pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } // walk the expected type and the actual type in lock step, checking they're -// the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with +// the same, in a kinda-structural way, i.e., `Vector`s have to be simd structs with // exactly the right element type fn match_intrinsic_type_to_type<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 5144f3e41d4..11fb3889a74 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -395,7 +395,7 @@ impl<'a, 'gcx, 'tcx> ConfirmContext<'a, 'gcx, 'tcx> { // Instantiate late-bound regions and substitute the trait // parameters into the method type to get the actual method type. // - // NB: Instantiate late-bound regions first so that + // N.B., instantiate late-bound regions first so that // `instantiate_type_scheme` can normalize associated types that // may reference those regions. let method_sig = self.replace_bound_vars_with_fresh_vars(&sig); diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index 209ad45ff34..858d8c742df 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -12,32 +12,29 @@ //! //! [rustc guide]: https://rust-lang.github.io/rustc-guide/method-lookup.html +mod confirm; +pub mod probe; +mod suggest; + +pub use self::MethodError::*; +pub use self::CandidateSource::*; +pub use self::suggest::TraitInfo; + use check::FnCtxt; -use hir::def::Def; -use hir::def_id::DefId; use namespace::Namespace; -use rustc::ty::subst::Substs; +use rustc_data_structures::sync::Lrc; +use rustc::hir; +use rustc::hir::def::Def; +use rustc::hir::def_id::DefId; use rustc::traits; +use rustc::ty::subst::Substs; use rustc::ty::{self, Ty, ToPredicate, ToPolyTraitRef, TraitRef, TypeFoldable}; use rustc::ty::GenericParamDefKind; use rustc::ty::subst::Subst; use rustc::infer::{self, InferOk}; - use syntax::ast; use syntax_pos::Span; -use rustc::hir; - -use rustc_data_structures::sync::Lrc; - -pub use self::MethodError::*; -pub use self::CandidateSource::*; -pub use self::suggest::TraitInfo; - -mod confirm; -pub mod probe; -mod suggest; - use self::probe::{IsSuggestion, ProbeScope}; pub fn provide(providers: &mut ty::query::Providers) { @@ -50,7 +47,7 @@ pub struct MethodCallee<'tcx> { pub def_id: DefId, pub substs: &'tcx Substs<'tcx>, - /// Instantiated method signature, i.e. it has been + /// Instantiated method signature, i.e., it has been /// substituted, normalized, and has had late-bound /// lifetimes replaced with inference variables. pub sig: ty::FnSig<'tcx>, @@ -107,8 +104,7 @@ impl<'tcx> NoMatchData<'tcx> { #[derive(Copy, Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub enum CandidateSource { ImplSource(DefId), - TraitSource(// trait id - DefId), + TraitSource(DefId /* trait id */), } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { @@ -174,7 +170,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let import_def_id = self.tcx.hir().local_def_id(import_id); debug!("used_trait_import: {:?}", import_def_id); Lrc::get_mut(&mut self.tables.borrow_mut().used_trait_imports) - .unwrap().insert(import_def_id); + .unwrap().insert(import_def_id); } self.tcx.check_stability(pick.item.def_id, Some(call_expr.id), span); @@ -239,7 +235,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// an obligation for a particular trait with the given self-type and checks /// whether that trait is implemented. /// - /// FIXME(#18741) -- It seems likely that we can consolidate some of this + /// FIXME(#18741): it seems likely that we can consolidate some of this /// code with the other method-lookup code. In particular, the second half /// of this method is basically the same as confirmation. pub fn lookup_method_in_trait(&self, @@ -307,7 +303,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Instantiate late-bound regions and substitute the trait // parameters into the method type to get the actual method type. // - // NB: Instantiate late-bound regions first so that + // N.B., instantiate late-bound regions first so that // `instantiate_type_scheme` can normalize associated types that // may reference those regions. let fn_sig = tcx.fn_sig(def_id); @@ -324,7 +320,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } }; - // Register obligations for the parameters. This will include the + // Register obligations for the parameters. This will include the // `Self` parameter, which in turn has a bound of the main trait, // so this also effectively registers `obligation` as well. (We // used to register `obligation` explicitly, but that resulted in diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index c794910e6ef..dd3c022d53b 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -41,7 +41,7 @@ use self::CandidateKind::*; pub use self::PickKind::*; /// Boolean flag used to indicate if this search is for a suggestion -/// or not. If true, we can allow ambiguity and so forth. +/// or not. If true, we can allow ambiguity and so forth. #[derive(Clone, Copy)] pub struct IsSuggestion(pub bool); diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index ab7e71a2870..79414cba69b 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -12,29 +12,23 @@ //! found or is otherwise invalid. use check::FnCtxt; -use rustc::hir::map as hir_map; -use hir::Node; -use rustc_data_structures::sync::Lrc; -use rustc::ty::{self, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable}; -use rustc::ty::item_path::with_crate_prefix; -use hir::def::Def; -use hir::def_id::{CRATE_DEF_INDEX, DefId}; +use errors::{Applicability, DiagnosticBuilder}; use middle::lang_items::FnOnceTraitLangItem; use namespace::Namespace; +use rustc_data_structures::sync::Lrc; +use rustc::hir::{self, Node}; +use rustc::hir::def::Def; +use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId}; +use rustc::hir::map as hir_map; +use rustc::hir::print; +use rustc::infer::type_variable::TypeVariableOrigin; use rustc::traits::Obligation; +use rustc::ty::{self, Adt, Ty, TyCtxt, ToPolyTraitRef, ToPredicate, TypeFoldable}; +use rustc::ty::item_path::with_crate_prefix; use util::nodemap::FxHashSet; - +use syntax_pos::{Span, FileName}; use syntax::ast; use syntax::util::lev_distance::find_best_match_for_name; -use errors::{Applicability, DiagnosticBuilder}; -use syntax_pos::{Span, FileName}; - - -use rustc::hir::def_id::LOCAL_CRATE; -use rustc::hir; -use rustc::hir::print; -use rustc::infer::type_variable::TypeVariableOrigin; -use rustc::ty::Adt; use std::cmp::Ordering; @@ -45,12 +39,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { fn is_fn_ty(&self, ty: &Ty<'tcx>, span: Span) -> bool { let tcx = self.tcx; match ty.sty { - // Not all of these (e.g. unsafe fns) implement FnOnce - // so we look for these beforehand + // Not all of these (e.g., unsafe fns) implement `FnOnce`, + // so we look for these beforehand. ty::Closure(..) | ty::FnDef(..) | ty::FnPtr(_) => true, - // If it's not a simple function, look for things which implement FnOnce + // If it's not a simple function, look for things which implement `FnOnce`. _ => { let fn_once = match tcx.lang_items().require(FnOnceTraitLangItem) { Ok(fn_once) => fn_once, @@ -83,7 +77,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { rcvr_expr: Option<&hir::Expr>, error: MethodError<'tcx>, args: Option<&'gcx [hir::Expr]>) { - // avoid suggestions when we don't know what's going on. + // Avoid suggestions when we don't know what's going on. if rcvr_ty.references_error() { return; } @@ -194,7 +188,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let tcx = self.tcx; let actual = self.resolve_type_vars_if_possible(&rcvr_ty); - let ty_string = self.ty_to_string(actual); + let ty_str = self.ty_to_string(actual); let is_method = mode == Mode::MethodCall; let mut suggestion = None; let item_kind = if is_method { @@ -239,7 +233,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { "can't call {} `{}` on ambiguous numeric type `{}`", item_kind, item_name, - ty_string + ty_str ); let concrete_type = if actual.is_integral() { "i32" @@ -247,7 +241,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { "f32" }; match expr.node { - hir::ExprKind::Lit(ref lit) => { // numeric literal + hir::ExprKind::Lit(ref lit) => { + // numeric literal let snippet = tcx.sess.source_map().span_to_snippet(lit.span) .unwrap_or_else(|_| "".to_owned()); @@ -262,7 +257,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { Applicability::MaybeIncorrect, ); } - hir::ExprKind::Path(ref qpath) => { // local binding + hir::ExprKind::Path(ref qpath) => { + // local binding if let &hir::QPath::Resolved(_, ref path) = &qpath { if let hir::def::Def::Local(node_id) = path.def { let span = tcx.hir().span(node_id); @@ -339,7 +335,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } // If the method name is the name of a field with a function or closure type, - // give a helping note that it has to be called as (x.f)(...). + // give a helping note that it has to be called as `(x.f)(...)`. if let Some(expr) = rcvr_expr { for (ty, _) in self.autoderef(span, rcvr_ty) { if let ty::Adt(def, substs) = ty.sty { @@ -351,8 +347,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let expr_string = match snippet { Ok(expr_string) => expr_string, _ => "s".into(), // Default to a generic placeholder for the - // expression when we can't generate a - // string snippet + // expression when we can't generate a + // string snippet. }; let field_ty = field.ty(tcx, substs); @@ -380,7 +376,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } } else { - err.span_label(span, format!("{} not found in `{}`", item_kind, ty_string)); + err.span_label(span, format!("{} not found in `{}`", item_kind, ty_str)); } if self.is_fn_ty(&rcvr_ty, span) { @@ -424,7 +420,6 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { report_candidates(&mut err, static_sources); } else if static_sources.len() > 1 { - report_candidates(&mut err, static_sources); } @@ -509,7 +504,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let (span, found_use) = UsePlacementFinder::check(self.tcx, krate, module_id); if let Some(span) = span { let path_strings = candidates.iter().map(|did| { - // produce an additional newline to separate the new use statement + // Produce an additional newline to separate the new use statement // from the directly following item. let additional_newline = if found_use { "" @@ -597,15 +592,15 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let type_is_local = self.type_derefs_to_local(span, rcvr_ty, rcvr_expr); - // there's no implemented traits, so lets suggest some traits to + // There are no traits implemented, so lets suggest some traits to // implement, by finding ones that have the item name, and are // legal to implement. let mut candidates = all_traits(self.tcx) .into_iter() .filter(|info| { - // we approximate the coherence rules to only suggest + // We approximate the coherence rules to only suggest // traits that are legal to implement by requiring that - // either the type or trait is local. Multidispatch means + // either the type or trait is local. Multi-dispatch means // this isn't perfect (that is, there are cases when // implementing a trait would be legal but is rejected // here). @@ -620,11 +615,11 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { .collect::>(); if !candidates.is_empty() { - // sort from most relevant to least relevant + // Sort from most relevant to least relevant. candidates.sort_by(|a, b| a.cmp(b).reverse()); candidates.dedup(); - // FIXME #21673 this help message could be tuned to the case + // FIXME #21673: this help message could be tuned to the case // of a type parameter: suggest adding a trait bound rather // than implementing. err.help("items from traits can only be used if the trait is implemented and in scope"); @@ -656,8 +651,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { fn type_derefs_to_local(&self, span: Span, rcvr_ty: Ty<'tcx>, - rcvr_expr: Option<&hir::Expr>) - -> bool { + source: SelfSource) -> bool { fn is_local(ty: Ty) -> bool { match ty.sty { ty::Adt(def, _) => def.did.is_local(), @@ -667,8 +661,8 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { ty::Param(_) => true, - // everything else (primitive types etc.) is effectively - // non-local (there are "edge" cases, e.g. (LocalType,), but + // Everything else (primitive types, etc.) is effectively + // non-local (there are "edge" cases, e.g., `(LocalType,)`, but // the noise from these sort of types is usually just really // annoying, rather than any sort of help). _ => false, @@ -703,8 +697,8 @@ impl PartialOrd for TraitInfo { } impl Ord for TraitInfo { fn cmp(&self, other: &TraitInfo) -> Ordering { - // local crates are more important than remote ones (local: - // cnum == 0), and otherwise we throw in the defid for totality + // Local crates are more important than remote ones (local: + // `cnum == 0`), and otherwise we throw in the defid for totality. let lhs = (other.def_id.krate, other.def_id); let rhs = (self.def_id.krate, self.def_id); @@ -719,65 +713,65 @@ pub fn all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec /// Compute all traits in this crate and any dependent crates. fn compute_all_traits<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>) -> Vec { - use rustc::hir::itemlikevisit; + use hir::itemlikevisit; - let mut traits = vec![]; + let mut traits = vec![]; - // Crate-local: - // - // meh. - struct Visitor<'a, 'tcx: 'a> { - map: &'a hir_map::Map<'tcx>, - traits: &'a mut Vec, - } - impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> { - fn visit_item(&mut self, i: &'v hir::Item) { - if let hir::ItemKind::Trait(..) = i.node { - let def_id = self.map.local_def_id(i.id); - self.traits.push(def_id); - } - } + // Crate-local: - fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) { - } + struct Visitor<'a, 'tcx: 'a> { + map: &'a hir_map::Map<'tcx>, + traits: &'a mut Vec, + } - fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) { + impl<'v, 'a, 'tcx> itemlikevisit::ItemLikeVisitor<'v> for Visitor<'a, 'tcx> { + fn visit_item(&mut self, i: &'v hir::Item) { + if let hir::ItemKind::Trait(..) = i.node { + let def_id = self.map.local_def_id(i.id); + self.traits.push(def_id); } } - tcx.hir().krate().visit_all_item_likes(&mut Visitor { - map: &tcx.hir(), - traits: &mut traits, - }); - - // Cross-crate: - let mut external_mods = FxHashSet::default(); - fn handle_external_def(tcx: TyCtxt, - traits: &mut Vec, - external_mods: &mut FxHashSet, - def: Def) { - let def_id = def.def_id(); - match def { - Def::Trait(..) => { - traits.push(def_id); + + fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {} + + fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {} + } + + tcx.hir().krate().visit_all_item_likes(&mut Visitor { + map: &tcx.hir(), + traits: &mut traits, + }); + + // Cross-crate: + + let mut external_mods = FxHashSet::default(); + fn handle_external_def(tcx: TyCtxt, + traits: &mut Vec, + external_mods: &mut FxHashSet, + def: Def) { + let def_id = def.def_id(); + match def { + Def::Trait(..) => { + traits.push(def_id); + } + Def::Mod(..) => { + if !external_mods.insert(def_id) { + return; } - Def::Mod(..) => { - if !external_mods.insert(def_id) { - return; - } - for child in tcx.item_children(def_id).iter() { - handle_external_def(tcx, traits, external_mods, child.def) - } + for child in tcx.item_children(def_id).iter() { + handle_external_def(tcx, traits, external_mods, child.def) } - _ => {} } + _ => {} } - for &cnum in tcx.crates().iter() { - let def_id = DefId { - krate: cnum, - index: CRATE_DEF_INDEX, - }; - handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id)); - } + } + for &cnum in tcx.crates().iter() { + let def_id = DefId { + krate: cnum, + index: CRATE_DEF_INDEX, + }; + handle_external_def(tcx, &mut traits, &mut external_mods, Def::Mod(def_id)); + } traits } @@ -827,29 +821,29 @@ impl<'a, 'tcx, 'gcx> hir::intravisit::Visitor<'tcx> for UsePlacementFinder<'a, ' hir::intravisit::walk_mod(self, module, node_id); return; } - // find a use statement + // Find a `use` statement. for item_id in &module.item_ids { let item = self.tcx.hir().expect_item(item_id.id); match item.node { hir::ItemKind::Use(..) => { - // don't suggest placing a use before the prelude - // import or other generated ones + // Don't suggest placing a `use` before the prelude + // import or other generated ones. if item.span.ctxt().outer().expn_info().is_none() { self.span = Some(item.span.shrink_to_lo()); self.found_use = true; return; } }, - // don't place use before extern crate + // Don't place `use` before `extern crate`... hir::ItemKind::ExternCrate(_) => {} - // but place them before the first other item + // ...but do place them before the first other item. _ => if self.span.map_or(true, |span| item.span < span ) { if item.span.ctxt().outer().expn_info().is_none() { - // don't insert between attributes and an item + // Don't insert between attributes and an item. if item.attrs.is_empty() { self.span = Some(item.span.shrink_to_lo()); } else { - // find the first attribute on the item + // Find the first attribute on the item. for attr in &item.attrs { if self.span.map_or(true, |span| attr.span < span) { self.span = Some(attr.span.shrink_to_lo()); @@ -861,6 +855,7 @@ impl<'a, 'tcx, 'gcx> hir::intravisit::Visitor<'tcx> for UsePlacementFinder<'a, ' } } } + fn nested_visit_map<'this>( &'this mut self ) -> hir::intravisit::NestedVisitorMap<'this, 'tcx> { diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 3116f1aecfe..8901f4b6b29 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -8,14 +8,13 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -/* +/*! # check.rs Within the check phase of type check, we check each item one at a time (bodies of function expressions are checked as part of the containing -function). Inference is used to supply types wherever they are -unknown. +function). Inference is used to supply types wherever they are unknown. By far the most complex case is checking the body of a function. This can be broken down into several distinct phases: @@ -65,7 +64,7 @@ nodes within the function. The types of top-level items, which never contain unbound type variables, are stored directly into the `tcx` tables. -N.B.: A type variable is not the same thing as a type parameter. A +N.B., a type variable is not the same thing as a type parameter. A type variable is rather an "instance" of a type parameter: that is, given a generic function `fn foo(t: T)`: while checking the function `foo`, the type `ty_param(0)` refers to the type `T`, which @@ -76,20 +75,36 @@ type parameter). */ -pub use self::Expectation::*; -use self::autoderef::Autoderef; -use self::callee::DeferredCallResolution; -use self::coercion::{CoerceMany, DynamicCoerceMany}; -pub use self::compare_method::{compare_impl_method, compare_const_impl}; -use self::method::MethodCallee; -use self::TupleArgumentsFlag::*; +mod autoderef; +pub mod dropck; +pub mod _match; +pub mod writeback; +mod regionck; +pub mod coercion; +pub mod demand; +pub mod method; +mod upvar; +mod wfcheck; +mod cast; +mod closure; +mod callee; +mod compare_method; +mod generator_interior; +mod intrinsic; +mod op; use astconv::AstConv; -use hir::GenericArg; -use hir::def::Def; -use hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; -use std::slice; +use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; +use rustc::hir::{self, GenericArg, Node, ItemKind, PatKind}; +use rustc::hir::def::Def; +use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; +use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; +use rustc::hir::itemlikevisit::ItemLikeVisitor; +use middle::lang_items; use namespace::Namespace; +use rustc_data_structures::indexed_vec::Idx; +use rustc_data_structures::sync::Lrc; +use rustc_target::spec::abi::Abi; use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin}; use rustc::infer::opaque_types::OpaqueTypeDecl; use rustc::infer::type_variable::{TypeVariableOrigin}; @@ -104,58 +119,38 @@ use rustc::ty::fold::TypeFoldable; use rustc::ty::query::Providers; use rustc::ty::util::{Representability, IntTypeExt, Discr}; use rustc::ty::layout::VariantIdx; -use rustc_data_structures::indexed_vec::Idx; -use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; - -use require_c_abi_if_variadic; -use session::{CompileIncomplete, config, Session}; -use TypeAndSubsts; -use lint; -use util::common::{ErrorReported, indenter}; -use util::nodemap::{DefIdMap, DefIdSet, FxHashMap, FxHashSet, NodeMap}; +use syntax_pos::{self, BytePos, Span, MultiSpan}; +use syntax::ast; +use syntax::attr; +use syntax::feature_gate::{GateIssue, emit_feature_err}; +use syntax::ptr::P; +use syntax::source_map::{DUMMY_SP, original_sp}; +use syntax::symbol::{Symbol, LocalInternedString, keywords}; +use syntax::util::lev_distance::find_best_match_for_name; use std::cell::{Cell, RefCell, Ref, RefMut}; -use rustc_data_structures::sync::Lrc; use std::collections::hash_map::Entry; use std::cmp; use std::fmt::Display; use std::iter; use std::mem::replace; use std::ops::{self, Deref}; -use rustc_target::spec::abi::Abi; -use syntax::ast; -use syntax::attr; -use syntax::source_map::DUMMY_SP; -use syntax::source_map::original_sp; -use syntax::feature_gate::{GateIssue, emit_feature_err}; -use syntax::ptr::P; -use syntax::symbol::{Symbol, LocalInternedString, keywords}; -use syntax::util::lev_distance::find_best_match_for_name; -use syntax_pos::{self, BytePos, Span, MultiSpan}; +use std::slice; -use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; -use rustc::hir::itemlikevisit::ItemLikeVisitor; -use rustc::hir::Node; -use rustc::hir::{self, PatKind, ItemKind}; -use rustc::middle::lang_items; +use require_c_abi_if_variadic; +use session::{CompileIncomplete, config, Session}; +use TypeAndSubsts; +use lint; +use util::common::{ErrorReported, indenter}; +use util::nodemap::{DefIdMap, DefIdSet, FxHashMap, FxHashSet, NodeMap}; -mod autoderef; -pub mod dropck; -pub mod _match; -pub mod writeback; -mod regionck; -pub mod coercion; -pub mod demand; -pub mod method; -mod upvar; -mod wfcheck; -mod cast; -mod closure; -mod callee; -mod compare_method; -mod generator_interior; -mod intrinsic; -mod op; +pub use self::Expectation::*; +use self::autoderef::Autoderef; +use self::callee::DeferredCallResolution; +use self::coercion::{CoerceMany, DynamicCoerceMany}; +pub use self::compare_method::{compare_impl_method, compare_const_impl}; +use self::method::MethodCallee; +use self::TupleArgumentsFlag::*; /// The type of a local binding, including the revealed type for anon types. #[derive(Copy, Clone)] @@ -2858,10 +2853,10 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::>()); // Check the arguments. - // We do this in a pretty awful way: first we typecheck any arguments - // that are not closures, then we typecheck the closures. This is so + // We do this in a pretty awful way: first we type-check any arguments + // that are not closures, then we type-check the closures. This is so // that we have more information about the types of arguments when we - // typecheck the functions. This isn't really the right way to do this. + // type-check the functions. This isn't really the right way to do this. for &check_closures in &[false, true] { debug!("check_closures={}", check_closures); @@ -2885,7 +2880,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { for (i, arg) in args.iter().take(t).enumerate() { // Warn only for the first loop (the "no closures" one). // Closure arguments themselves can't be diverging, but - // a previous argument can, e.g. `foo(panic!(), || {})`. + // a previous argument can, e.g., `foo(panic!(), || {})`. if !check_closures { self.warn_if_unreachable(arg.id, arg.span, "expression"); } @@ -3092,9 +3087,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs) } - // determine the `self` type, using fresh variables for all variables + // Determine the `Self` type, using fresh variables for all variables // declared on the impl declaration e.g., `impl for Vec<(A,B)>` - // would return ($0, $1) where $0 and $1 are freshly instantiated type + // would return `($0, $1)` where `$0` and `$1` are freshly instantiated type // variables. pub fn impl_self_ty(&self, span: Span, // (potential) receiver for this impl @@ -3539,16 +3534,16 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let mut error_happened = false; - // Typecheck each field. + // Type-check each field. for field in ast_fields { let ident = tcx.adjust_ident(field.ident, variant.did, self.body_id).0; let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { seen_fields.insert(ident, field.span); self.write_field_index(field.id, i); - // we don't look at stability attributes on + // We don't look at stability attributes on // struct-like enums (yet...), but it's definitely not - // a bug to have construct one. + // a bug to have constructed one. if adt_kind != ty::AdtKind::Enum { tcx.check_stability(v_field.did, Some(expr_id), field.span); } @@ -3575,7 +3570,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { }; // Make sure to give a type to the field even if there's - // an error, so we can continue typechecking + // an error, so we can continue type-checking. self.check_expr_coercable_to_type(&field.expr, field_type); } @@ -3707,7 +3702,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { hir::QPath::TypeRelative(ref qself, _) => qself.span }; - // Prohibit struct expressions when non exhaustive flag is set. + // Prohibit struct expressions when non-exhaustive flag is set. let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type"); if !adt.did.is_local() && variant.is_field_list_non_exhaustive() { span_err!(self.tcx.sess, expr.span, E0639, @@ -3760,7 +3755,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { expr: &'gcx hir::Expr, expected: Expectation<'tcx>, needs: Needs) -> Ty<'tcx> { - debug!(">> typechecking: expr={:?} expected={:?}", + debug!(">> type-checking: expr={:?} expected={:?}", expr, expected); // Warn for expressions after diverging siblings. @@ -3962,7 +3957,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { if !tcx.features().unsized_locals { // We want to remove some Sized bounds from std functions, // but don't want to expose the removal to stable Rust. - // i.e. we don't want to allow + // i.e., we don't want to allow // // ```rust // drop as fn(str); @@ -4086,7 +4081,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } } - // There was an error, make typecheck fail + // There was an error; make type-check fail. tcx.types.err } @@ -4095,7 +4090,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { if destination.target_id.is_ok() { tcx.types.never } else { - // There was an error, make typecheck fail + // There was an error; make type-check fail. tcx.types.err } } @@ -4413,7 +4408,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } if needs_note { err.help("to access tuple elements, use tuple indexing \ - syntax (e.g. `tuple.0`)"); + syntax (e.g., `tuple.0`)"); } } err.emit(); @@ -5249,7 +5244,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { assert!(!substs.has_escaping_bound_vars()); assert!(!ty.has_escaping_bound_vars()); - // Write the "user substs" down first thing for later. + // First, store the "user substs" for later. let hir_id = self.tcx.hir().node_to_hir_id(node_id); self.write_user_substs_from_substs(hir_id, substs, user_self_ty); diff --git a/src/librustc_typeck/check/op.rs b/src/librustc_typeck/check/op.rs index 54f4406b4af..c40789ce8ba 100644 --- a/src/librustc_typeck/check/op.rs +++ b/src/librustc_typeck/check/op.rs @@ -170,7 +170,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // Find a suitable supertype of the LHS expression's type, by coercing to // a type variable, to pass as the `Self` to the trait, avoiding invariant // trait matching creating lifetime constraints that are too strict. - // E.g. adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result + // e.g., adding `&'a T` and `&'b T`, given `&'x T: Add<&'x T>`, will result // in `&'a T <: &'x T` and `&'b T <: &'x T`, instead of `'a = 'b = 'x`. let lhs_ty = self.check_expr_with_needs(lhs_expr, Needs::None); let fresh_var = self.next_ty_var(TypeVariableOrigin::MiscVariable(lhs_expr.span)); @@ -186,7 +186,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { }; let lhs_ty = self.resolve_type_vars_with_obligations(lhs_ty); - // NB: As we have not yet type-checked the RHS, we don't have the + // N.B., as we have not yet type-checked the RHS, we don't have the // type at hand. Make a variable to represent it. The whole reason // for this indirection is so that, below, we can check the expr // using this variable as the expected type, which sometimes lets @@ -318,7 +318,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, true) { // This has nothing here because it means we did string - // concatenation (e.g. "Hello " += "World!"). This means + // concatenation (e.g., "Hello " += "World!"). This means // we don't want the note in the else clause to be emitted } else if let ty::Param(_) = lhs_ty.sty { // FIXME: point to span of param @@ -392,7 +392,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { self.check_str_addition(expr, lhs_expr, rhs_expr, lhs_ty, rhs_ty, &mut err, false) { // This has nothing here because it means we did string - // concatenation (e.g. "Hello " + "World!"). This means + // concatenation (e.g., "Hello " + "World!"). This means // we don't want the note in the else clause to be emitted } else if let ty::Param(_) = lhs_ty.sty { // FIXME: point to span of param @@ -682,7 +682,7 @@ enum Op { Unary(hir::UnOp, Span), } -/// Returns true if this is a built-in arithmetic operation (e.g. u32 +/// Returns true if this is a built-in arithmetic operation (e.g., u32 /// + u32, i16x4 == i16x4) and false if these types would have to be /// overloaded to be legal. There are two reasons that we distinguish /// builtin operations from overloaded ones (vs trying to drive diff --git a/src/librustc_typeck/coherence/builtin.rs b/src/librustc_typeck/coherence/builtin.rs index bdb2a9a8af1..2d5dcf0ec1b 100644 --- a/src/librustc_typeck/coherence/builtin.rs +++ b/src/librustc_typeck/coherence/builtin.rs @@ -469,7 +469,7 @@ pub fn coerce_unsized_info<'a, 'gcx>(gcx: TyCtxt<'a, 'gcx, 'gcx>, // variance where possible. (This is because // we may have to evaluate constraint // expressions in the course of execution.) - // See e.g. #41936. + // See e.g., #41936. if let Ok(ok) = infcx.at(&cause, param_env).eq(a, b) { if ok.obligations.is_empty() { return None; @@ -477,7 +477,7 @@ pub fn coerce_unsized_info<'a, 'gcx>(gcx: TyCtxt<'a, 'gcx, 'gcx>, } // Collect up all fields that were significantly changed - // i.e. those that contain T in coerce_unsized T -> U + // i.e., those that contain T in coerce_unsized T -> U Some((i, a, b)) }) .collect::>(); diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index b92916d9c81..0360617be3c 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -40,7 +40,7 @@ fn check_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, node_id: ast::NodeId) { tcx.item_path_str(impl_def_id)); // Skip impls where one of the self type is an error type. - // This occurs with e.g. resolve failures (#30589). + // This occurs with e.g., resolve failures (#30589). if trait_ref.references_error() { return; } diff --git a/src/librustc_typeck/coherence/orphan.rs b/src/librustc_typeck/coherence/orphan.rs index 47edf59f0ad..131413eb402 100644 --- a/src/librustc_typeck/coherence/orphan.rs +++ b/src/librustc_typeck/coherence/orphan.rs @@ -60,7 +60,7 @@ impl<'cx, 'tcx, 'v> ItemLikeVisitor<'v> for OrphanChecker<'cx, 'tcx> { sp, E0210, "type parameter `{}` must be used as the type parameter \ - for some local type (e.g. `MyStruct<{}>`)", + for some local type (e.g., `MyStruct<{}>`)", param_ty, param_ty) .span_label(sp, diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 9104c15bdd5..3b8b6d47d91 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -97,7 +97,7 @@ pub fn provide(providers: &mut Providers) { /// AstConv. It has information about the predicates that are defined /// on the trait. Unfortunately, this predicate information is /// available in various different forms at various points in the -/// process. So we can't just store a pointer to e.g. the AST or the +/// process. So we can't just store a pointer to e.g., the AST or the /// parsed ty form, we have to be more flexible. To this end, the /// `ItemCtxt` is parameterized by a `DefId` that it uses to satisfy /// `get_type_parameter_bounds` requests, drawing the information from @@ -704,16 +704,16 @@ fn super_predicates_of<'a, 'tcx>( let icx = ItemCtxt::new(tcx, trait_def_id); - // Convert the bounds that follow the colon, e.g. `Bar + Zed` in `trait Foo : Bar + Zed`. + // Convert the bounds that follow the colon, e.g., `Bar + Zed` in `trait Foo : Bar + Zed`. let self_param_ty = tcx.mk_self_type(); let superbounds1 = compute_bounds(&icx, self_param_ty, bounds, SizedByDefault::No, item.span); let superbounds1 = superbounds1.predicates(tcx, self_param_ty); // Convert any explicit superbounds in the where clause, - // e.g. `trait Foo where Self : Bar`. + // e.g., `trait Foo where Self : Bar`. // In the case of trait aliases, however, we include all bounds in the where clause, - // so e.g. `trait Foo = where u32: PartialEq` would include `u32: PartialEq` + // so e.g., `trait Foo = where u32: PartialEq` would include `u32: PartialEq` // as one of its "superpredicates". let is_trait_alias = ty::is_trait_alias(tcx, trait_def_id); let superbounds2 = icx.type_parameter_bounds_in_generics( @@ -1715,7 +1715,7 @@ fn explicit_predicates_of<'a, 'tcx>( let substs = Substs::identity_for_item(tcx, def_id); let opaque_ty = tcx.mk_opaque(def_id, substs); - // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`. + // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`. let bounds = compute_bounds( &icx, opaque_ty, @@ -1760,7 +1760,7 @@ fn explicit_predicates_of<'a, 'tcx>( let substs = Substs::identity_for_item(tcx, def_id); let opaque_ty = tcx.mk_opaque(def_id, substs); - // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`. + // Collect the bounds, i.e., the `A+B+'c` in `impl A+B+'c`. let bounds = compute_bounds( &icx, opaque_ty, diff --git a/src/librustc_typeck/constrained_type_params.rs b/src/librustc_typeck/constrained_type_params.rs index 9299e9b7b8f..25fa33ef9fa 100644 --- a/src/librustc_typeck/constrained_type_params.rs +++ b/src/librustc_typeck/constrained_type_params.rs @@ -37,7 +37,7 @@ pub fn parameters_for_impl<'tcx>(impl_self_ty: Ty<'tcx>, } /// If `include_projections` is false, returns the list of parameters that are -/// constrained by `t` - i.e. the value of each parameter in the list is +/// constrained by `t` - i.e., the value of each parameter in the list is /// uniquely determined by `t` (see RFC 447). If it is true, return the list /// of parameters whose values are needed in order to constrain `ty` - these /// differ, with the latter being a superset, in the presence of projections. diff --git a/src/librustc_typeck/diagnostics.rs b/src/librustc_typeck/diagnostics.rs index 084951f4a2c..a0dbaf5ad50 100644 --- a/src/librustc_typeck/diagnostics.rs +++ b/src/librustc_typeck/diagnostics.rs @@ -655,7 +655,7 @@ For example, a function like: fn f(a: u16, b: &str) {} ``` -Must always be called with exactly two arguments, e.g. `f(2, "test")`. +Must always be called with exactly two arguments, e.g., `f(2, "test")`. Note that Rust does not have a notion of optional function arguments or variadic functions (except for its C-FFI). @@ -1610,7 +1610,7 @@ it has been disabled for now. E0185: r##" An associated function for a trait was defined to be static, but an -implementation of the trait declared the same function to be a method (i.e. to +implementation of the trait declared the same function to be a method (i.e., to take a `self` parameter). Here's an example of this error: @@ -1631,7 +1631,7 @@ impl Foo for Bar { "##, E0186: r##" -An associated function for a trait was defined to be a method (i.e. to take a +An associated function for a trait was defined to be a method (i.e., to take a `self` parameter), but an implementation of the trait declared the same function to be static. diff --git a/src/librustc_typeck/lib.rs b/src/librustc_typeck/lib.rs index ae3cfbb9b37..8d6fb8b7f39 100644 --- a/src/librustc_typeck/lib.rs +++ b/src/librustc_typeck/lib.rs @@ -10,24 +10,24 @@ /*! -typeck.rs, an introduction +# typeck.rs The type checker is responsible for: -1. Determining the type of each expression -2. Resolving methods and traits -3. Guaranteeing that most type rules are met ("most?", you say, "why most?" +1. Determining the type of each expression. +2. Resolving methods and traits. +3. Guaranteeing that most type rules are met. ("Most?", you say, "why most?" Well, dear reader, read on) -The main entry point is `check_crate()`. Type checking operates in +The main entry point is `check_crate()`. Type checking operates in several major phases: 1. The collect phase first passes over all items and determines their type, without examining their "innards". -2. Variance inference then runs to compute the variance of each parameter +2. Variance inference then runs to compute the variance of each parameter. -3. Coherence checks for overlapping or orphaned impls +3. Coherence checks for overlapping or orphaned impls. 4. Finally, the check phase then checks function bodies and so forth. Within the check phase, we check each function body one at a time @@ -41,12 +41,12 @@ The type checker is defined into various submodules which are documented independently: - astconv: converts the AST representation of types - into the `ty` representation + into the `ty` representation. - collect: computes the types of each top-level item and enters them into - the `tcx.types` table for later use + the `tcx.types` table for later use. -- coherence: enforces coherence rules, builds some tables +- coherence: enforces coherence rules, builds some tables. - variance: variance inference @@ -59,7 +59,7 @@ independently: all subtyping and assignment constraints are met. In essence, the check module specifies the constraints, and the infer module solves them. -# Note +## Note This API is completely unstable and subject to change. @@ -97,29 +97,7 @@ extern crate rustc_errors as errors; extern crate rustc_target; extern crate smallvec; -use rustc::hir; -use rustc::lint; -use rustc::middle; -use rustc::session; -use rustc::util; - -use hir::Node; -use rustc::infer::InferOk; -use rustc::ty::subst::Substs; -use rustc::ty::{self, Ty, TyCtxt}; -use rustc::ty::query::Providers; -use rustc::traits::{ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt}; -use rustc::util::profiling::ProfileCategory; -use session::{CompileIncomplete, config}; -use util::common::time; - -use syntax::ast; -use rustc_target::spec::abi::Abi; -use syntax_pos::Span; - -use std::iter; - -// NB: This module needs to be declared first so diagnostics are +// N.B., this module needs to be declared first so diagnostics are // registered before they are used. mod diagnostics; @@ -135,6 +113,26 @@ mod namespace; mod outlives; mod variance; +use hir::Node; +use rustc_target::spec::abi::Abi; +use rustc::hir; +use rustc::infer::InferOk; +use rustc::lint; +use rustc::middle; +use rustc::session; +use rustc::traits::{ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt}; +use rustc::ty::subst::Substs; +use rustc::ty::{self, Ty, TyCtxt}; +use rustc::ty::query::Providers; +use rustc::util; +use rustc::util::profiling::ProfileCategory; +use session::{CompileIncomplete, config}; +use syntax_pos::Span; +use syntax::ast; +use util::common::time; + +use std::iter; + pub struct TypeAndSubsts<'tcx> { substs: &'tcx Substs<'tcx>, ty: Ty<'tcx>, diff --git a/src/librustc_typeck/outlives/implicit_infer.rs b/src/librustc_typeck/outlives/implicit_infer.rs index 5f010875842..315e5feea3f 100644 --- a/src/librustc_typeck/outlives/implicit_infer.rs +++ b/src/librustc_typeck/outlives/implicit_infer.rs @@ -314,7 +314,7 @@ pub fn check_explicit_predicates<'tcx>( // case that `substs` come from a `dyn Trait` type, our caller will have // included `Self = usize` as the value for `Self`. If we were // to apply the substs, and not filter this predicate, we might then falsely - // conclude that e.g. `X: 'x` was a reasonable inferred requirement. + // conclude that e.g., `X: 'x` was a reasonable inferred requirement. // // Another similar case is where we have a inferred // requirement like `::Foo: 'b`. We presently diff --git a/src/librustc_typeck/variance/constraints.rs b/src/librustc_typeck/variance/constraints.rs index ee554ee684d..6ea919469e0 100644 --- a/src/librustc_typeck/variance/constraints.rs +++ b/src/librustc_typeck/variance/constraints.rs @@ -44,7 +44,7 @@ pub struct Constraint<'a> { } /// To build constraints, we visit one item (type, trait) at a time -/// and look at its contents. So e.g. if we have +/// and look at its contents. So e.g., if we have /// /// struct Foo { /// b: Bar diff --git a/src/librustc_typeck/variance/terms.rs b/src/librustc_typeck/variance/terms.rs index 6d45b187624..75ff5bb0c54 100644 --- a/src/librustc_typeck/variance/terms.rs +++ b/src/librustc_typeck/variance/terms.rs @@ -125,7 +125,7 @@ impl<'a, 'tcx> TermsContext<'a, 'tcx> { let newly_added = self.inferred_starts.insert(id, InferredIndex(start)).is_none(); assert!(newly_added); - // NB: In the code below for writing the results back into the + // N.B., in the code below for writing the results back into the // `CrateVariancesMap`, we rely on the fact that all inferreds // for a particular item are assigned continuous indices. diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 543df844cb8..ac9680b4570 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -255,7 +255,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> { // handle_lifetimes determines what *needs be* true in order for an impl to hold. // lexical_region_resolve, along with much of the rest of the compiler, is concerned // with determining if a given set up constraints/predicates *are* met, given some - // starting conditions (e.g. user-provided code). For this reason, it's easier + // starting conditions (e.g., user-provided code). For this reason, it's easier // to perform the calculations we need on our own, rather than trying to make // existing inference/solver code do what we want. fn handle_lifetimes<'cx>( @@ -274,7 +274,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> { // Flattening is done in two parts. First, we insert all of the constraints // into a map. Each RegionTarget (either a RegionVid or a Region) maps // to its smaller and larger regions. Note that 'larger' regions correspond - // to sub-regions in Rust code (e.g. in 'a: 'b, 'a is the larger region). + // to sub-regions in Rust code (e.g., in 'a: 'b, 'a is the larger region). for constraint in regions.constraints.keys() { match constraint { &Constraint::VarSubVar(r1, r2) => { @@ -524,7 +524,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> { // display on the docs page. Cleaning the Predicates produces sub-optimal WherePredicate's, // so we fix them up: // - // * Multiple bounds for the same type are coalesced into one: e.g. 'T: Copy', 'T: Debug' + // * Multiple bounds for the same type are coalesced into one: e.g., 'T: Copy', 'T: Debug' // becomes 'T: Copy + Debug' // * Fn bounds are handled specially - instead of leaving it as 'T: Fn(), = // K', we use the dedicated syntax 'T: Fn() -> K' @@ -545,7 +545,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> { ); // The `Sized` trait must be handled specially, since we only only display it when - // it is *not* required (i.e. '?Sized') + // it is *not* required (i.e., '?Sized') let sized_trait = self.cx .tcx .require_lang_item(lang_items::SizedTraitLangItem); @@ -629,7 +629,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> { let is_fn = match &mut b { &mut GenericBound::TraitBound(ref mut p, _) => { // Insert regions into the for_generics hash map first, to ensure - // that we don't end up with duplicate bounds (e.g. for<'b, 'b>) + // that we don't end up with duplicate bounds (e.g., for<'b, 'b>) for_generics.extend(p.generic_params.clone()); p.generic_params = for_generics.into_iter().collect(); self.is_fn_ty(&tcx, &p.trait_) @@ -737,7 +737,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> { hir::TraitBoundModifier::None, )); - // Remove any existing 'plain' bound (e.g. 'T: Iterator`) so + // Remove any existing 'plain' bound (e.g., 'T: Iterator`) so // that we don't see a // duplicate bound like `T: Iterator + Iterator` // on the docs page. @@ -837,7 +837,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> AutoTraitFinder<'a, 'tcx, 'rcx, 'cstore> { // auto-trait impls always render in exactly the same way. // // Using the Debug implementation for sorting prevents us from needing to - // write quite a bit of almost entirely useless code (e.g. how should two + // write quite a bit of almost entirely useless code (e.g., how should two // Types be sorted relative to each other). It also allows us to solve the // problem for both WherePredicates and GenericBounds at the same time. This // approach is probably somewhat slower, but the small number of items diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index f90f1e54da2..847786d123e 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -31,13 +31,13 @@ pub enum Cfg { True, /// Denies all configurations. False, - /// A generic configuration option, e.g. `test` or `target_os = "linux"`. + /// A generic configuration option, e.g., `test` or `target_os = "linux"`. Cfg(Symbol, Option), - /// Negate a configuration requirement, i.e. `not(x)`. + /// Negate a configuration requirement, i.e., `not(x)`. Not(Box), - /// Union of a list of configuration requirements, i.e. `any(...)`. + /// Union of a list of configuration requirements, i.e., `any(...)`. Any(Vec), - /// Intersection of a list of configuration requirements, i.e. `all(...)`. + /// Intersection of a list of configuration requirements, i.e., `all(...)`. All(Vec), } @@ -61,7 +61,7 @@ impl Cfg { /// Parses a `MetaItem` into a `Cfg`. /// - /// The `MetaItem` should be the content of the `#[cfg(...)]`, e.g. `unix` or + /// The `MetaItem` should be the content of the `#[cfg(...)]`, e.g., `unix` or /// `target_os = "redox"`. /// /// If the content is not properly formatted, it will return an error indicating what and where diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index ce7de0e3128..64f66d55fc6 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -11,39 +11,39 @@ //! This module contains the "cleaned" pieces of the AST, and the functions //! that clean them. -pub use self::Type::*; -pub use self::Mutability::*; -pub use self::ItemEnum::*; -pub use self::SelfTy::*; -pub use self::FunctionRetTy::*; -pub use self::Visibility::{Public, Inherited}; +pub mod inline; +pub mod cfg; +mod simplify; +mod auto_trait; +mod blanket_impl; +pub mod def_ctor; +use rustc_data_structures::indexed_vec::{IndexVec, Idx}; +use rustc_data_structures::sync::Lrc; use rustc_target::spec::abi::Abi; -use syntax::ast::{self, AttrStyle, Ident}; -use syntax::attr; -use syntax::ext::base::MacroKind; -use syntax::source_map::{dummy_spanned, Spanned}; -use syntax::ptr::P; -use syntax::symbol::keywords::{self, Keyword}; -use syntax::symbol::InternedString; -use syntax_pos::{self, DUMMY_SP, Pos, FileName}; - +use rustc_typeck::hir_ty_to_ty; +use rustc::infer::region_constraints::{RegionConstraintData, Constraint}; use rustc::mir::interpret::ConstValue; use rustc::middle::resolve_lifetime as rl; -use rustc::ty::fold::TypeFolder; use rustc::middle::lang_items; +use rustc::middle::stability; use rustc::mir::interpret::GlobalId; use rustc::hir::{self, GenericArg, HirVec}; use rustc::hir::def::{self, Def, CtorKind}; use rustc::hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE}; use rustc::ty::subst::Substs; use rustc::ty::{self, TyCtxt, Region, RegionVid, Ty, AdtKind}; +use rustc::ty::fold::TypeFolder; use rustc::ty::layout::VariantIdx; -use rustc::middle::stability; use rustc::util::nodemap::{FxHashMap, FxHashSet}; -use rustc_typeck::hir_ty_to_ty; -use rustc::infer::region_constraints::{RegionConstraintData, Constraint}; -use rustc_data_structures::indexed_vec::{IndexVec, Idx}; +use syntax::ast::{self, AttrStyle, Ident}; +use syntax::attr; +use syntax::ext::base::MacroKind; +use syntax::source_map::{dummy_spanned, Spanned}; +use syntax::ptr::P; +use syntax::symbol::keywords::{self, Keyword}; +use syntax::symbol::InternedString; +use syntax_pos::{self, DUMMY_SP, Pos, FileName}; use std::collections::hash_map::Entry; use std::fmt; @@ -51,7 +51,6 @@ use std::hash::{Hash, Hasher}; use std::default::Default; use std::{mem, slice, vec}; use std::iter::{FromIterator, once}; -use rustc_data_structures::sync::Lrc; use std::rc::Rc; use std::str::FromStr; use std::cell::RefCell; @@ -66,17 +65,17 @@ use visit_ast; use html::render::{cache, ExternalLocation}; use html::item_type::ItemType; -pub mod inline; -pub mod cfg; -mod simplify; -mod auto_trait; -mod blanket_impl; -pub mod def_ctor; - use self::cfg::Cfg; use self::auto_trait::AutoTraitFinder; use self::blanket_impl::BlanketImplFinder; +pub use self::Type::*; +pub use self::Mutability::*; +pub use self::ItemEnum::*; +pub use self::SelfTy::*; +pub use self::FunctionRetTy::*; +pub use self::Visibility::{Public, Inherited}; + thread_local!(pub static MAX_DEF_ID: RefCell> = Default::default()); const FN_OUTPUT_NAME: &'static str = "Output"; @@ -1621,7 +1620,7 @@ impl<'a, 'tcx> Clean for (&'a ty::Generics, } // It would be nice to collect all of the bounds on a type and recombine - // them if possible, to avoid e.g. `where T: Foo, T: Bar, T: Sized, T: 'a` + // them if possible, to avoid e.g., `where T: Foo, T: Bar, T: Sized, T: 'a` // and instead see `where T: Foo + Bar + Sized + 'a` Generics { @@ -3899,7 +3898,7 @@ impl Clean for attr::Deprecation { } } -/// An equality constraint on an associated type, e.g. `A=Bar` in `Foo` +/// An equality constraint on an associated type, e.g., `A=Bar` in `Foo` #[derive(Clone, PartialEq, Eq, RustcDecodable, RustcEncodable, Debug, Hash)] pub struct TypeBinding { pub name: String, diff --git a/src/librustdoc/clean/simplify.rs b/src/librustdoc/clean/simplify.rs index 635608d140d..81608b380d0 100644 --- a/src/librustdoc/clean/simplify.rs +++ b/src/librustdoc/clean/simplify.rs @@ -12,7 +12,7 @@ //! more canonical form. //! //! Currently all cross-crate-inlined function use `rustc::ty` to reconstruct -//! the AST (e.g. see all of `clean::inline`), but this is not always a +//! the AST (e.g., see all of `clean::inline`), but this is not always a //! non-lossy transformation. The current format of storage for where clauses //! for functions and such is simply a list of predicates. One example of this //! is that the AST predicate of: `where T: Trait` is encoded as: diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index fa5d015e5b7..6ce02c313ee 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -130,7 +130,7 @@ pub fn render(
\

Search Tricks

\

\ - Prefix searches with a type followed by a colon (e.g. \ + Prefix searches with a type followed by a colon (e.g., \ fn:) to restrict the search to a given type.\

\

\ @@ -140,11 +140,11 @@ pub fn render( and const.\

\

\ - Search functions by type signature (e.g. \ + Search functions by type signature (e.g., \ vec -> usize or * -> vec)\

\

\ - Search multiple things at once by splitting your query with comma (e.g. \ + Search multiple things at once by splitting your query with comma (e.g., \ str,u8 or String,struct:Vec,test)\

\
\ diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 30054f66e2f..79a2f46a74f 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -2077,7 +2077,7 @@ impl Context { fn item(&mut self, item: clean::Item, all: &mut AllTypes, mut f: F) -> Result<(), Error> where F: FnMut(&mut Context, clean::Item), { - // Stripped modules survive the rustdoc passes (i.e. `strip-private`) + // Stripped modules survive the rustdoc passes (i.e., `strip-private`) // if they contain impls for public types. These modules can also // contain items such as publicly re-exported structures. // diff --git a/src/librustdoc/html/toc.rs b/src/librustdoc/html/toc.rs index 88ada5c7f7f..45bd6990fab 100644 --- a/src/librustdoc/html/toc.rs +++ b/src/librustdoc/html/toc.rs @@ -52,7 +52,7 @@ pub struct TocEntry { pub struct TocBuilder { top_level: Toc, /// The current hierarchy of parent headings, the levels are - /// strictly increasing (i.e. chain[0].level < chain[1].level < + /// strictly increasing (i.e., chain[0].level < chain[1].level < /// ...) with each entry being the most recent occurrence of a /// heading with that level (it doesn't include the most recent /// occurrences of every level, just, if it *is* in `chain` then @@ -76,7 +76,7 @@ impl TocBuilder { } /// Collapse the chain until the first heading more important than - /// `level` (i.e. lower level) + /// `level` (i.e., lower level) /// /// Example: /// @@ -91,7 +91,7 @@ impl TocBuilder { /// ### H /// ``` /// - /// If we are considering H (i.e. level 3), then A and B are in + /// If we are considering H (i.e., level 3), then A and B are in /// self.top_level, D is in C.children, and C, E, F, G are in /// self.chain. /// @@ -102,7 +102,7 @@ impl TocBuilder { /// /// This leaves us looking at E, which does have a smaller level, /// and, by construction, it's the most recent thing with smaller - /// level, i.e. it's the immediate parent of H. + /// level, i.e., it's the immediate parent of H. fn fold_until(&mut self, level: u32) { let mut this = None; loop { @@ -133,7 +133,7 @@ impl TocBuilder { assert!(level >= 1); // collapse all previous sections into their parents until we - // get to relevant heading (i.e. the first one with a smaller + // get to relevant heading (i.e., the first one with a smaller // level than us) self.fold_until(level); @@ -150,7 +150,7 @@ impl TocBuilder { (entry.level, &entry.children) } }; - // fill in any missing zeros, e.g. for + // fill in any missing zeros, e.g., for // # Foo (1) // ### Bar (1.0.1) for _ in toc_level..level - 1 { diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index b21f005c06b..b0045e41f50 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -276,7 +276,7 @@ fn opts() -> Vec { unstable("resource-suffix", |o| { o.optopt("", "resource-suffix", - "suffix to add to CSS and JavaScript files, e.g. \"light.css\" will become \ + "suffix to add to CSS and JavaScript files, e.g., \"light.css\" will become \ \"light-suffix.css\"", "PATH") }), diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index 8008f8848d4..e0e0be717b2 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -46,8 +46,8 @@ fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { (metadata, "") } -/// Render `input` (e.g. "foo.md") into an HTML file in `output` -/// (e.g. output = "bar" => "bar/foo.html"). +/// Render `input` (e.g., "foo.md") into an HTML file in `output` +/// (e.g., output = "bar" => "bar/foo.html"). pub fn render(input: PathBuf, options: RenderOptions, diag: &errors::Handler) -> isize { let mut output = options.output; output.push(input.file_stem().unwrap()); diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index cbbcf92c6aa..426d3f3eeea 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use clean::*; - use rustc::lint as lint; use rustc::hir; use rustc::hir::def::Def; @@ -26,6 +24,7 @@ use core::DocContext; use fold::DocFolder; use html::markdown::markdown_links; +use clean::*; use passes::{look_for_tests, Pass}; pub const COLLECT_INTRA_DOC_LINKS: Pass = @@ -44,13 +43,13 @@ pub fn collect_intra_doc_links(krate: Crate, cx: &DocContext) -> Crate { #[derive(Debug)] enum PathKind { - /// can be either value or type, not a macro + /// Either a value or type, but not a macro Unknown, - /// macro + /// Macro Macro, - /// values, functions, consts, statics, everything in the value namespace + /// Values, functions, consts, statics (everything in the value namespace) Value, - /// types, traits, everything in the type namespace + /// Types, traits (everything in the type namespace) Type, } @@ -71,7 +70,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> LinkCollector<'a, 'tcx, 'rcx, 'cstore> { /// Resolve a given string as a path, along with whether or not it is /// in the value namespace. Also returns an optional URL fragment in the case - /// of variants and methods + /// of variants and methods. fn resolve(&self, path_str: &str, is_val: bool, @@ -82,9 +81,9 @@ impl<'a, 'tcx, 'rcx, 'cstore> LinkCollector<'a, 'tcx, 'rcx, 'cstore> { let cx = self.cx; // In case we're in a module, try to resolve the relative - // path + // path. if let Some(id) = parent_id.or(self.mod_ids.last().cloned()) { - // FIXME: `with_scope` requires the NodeId of a module + // FIXME: `with_scope` requires the `NodeId` of a module. let result = cx.resolver.borrow_mut() .with_scope(id, |resolver| { @@ -94,12 +93,12 @@ impl<'a, 'tcx, 'rcx, 'cstore> LinkCollector<'a, 'tcx, 'rcx, 'cstore> { if let Ok(result) = result { // In case this is a trait item, skip the - // early return and try looking for the trait + // early return and try looking for the trait. let value = match result.def { Def::Method(_) | Def::AssociatedConst(_) => true, Def::AssociatedTy(_) => false, Def::Variant(_) => return handle_variant(cx, result.def), - // not a trait item, just return what we found + // Not a trait item; just return what we found. _ => return Ok((result.def, None)) }; @@ -111,13 +110,13 @@ impl<'a, 'tcx, 'rcx, 'cstore> LinkCollector<'a, 'tcx, 'rcx, 'cstore> { } else { // If resolution failed, it may still be a method // because methods are not handled by the resolver - // If so, bail when we're not looking for a value + // If so, bail when we're not looking for a value. if !is_val { return Err(()) } } - // Try looking for methods and associated items + // Try looking for methods and associated items. let mut split = path_str.rsplitn(2, "::"); let item_name = if let Some(first) = split.next() { first @@ -137,7 +136,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> LinkCollector<'a, 'tcx, 'rcx, 'cstore> { } } - // FIXME: `with_scope` requires the NodeId of a module + // FIXME: `with_scope` requires the `NodeId` of a module. let ty = cx.resolver.borrow_mut() .with_scope(id, |resolver| { @@ -227,10 +226,10 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor None }; - // FIXME: get the resolver to work with non-local resolve scopes + // FIXME: get the resolver to work with non-local resolve scopes. let parent_node = self.cx.as_local_node_id(item.def_id).and_then(|node_id| { // FIXME: this fails hard for impls in non-module scope, but is necessary for the - // current resolve() implementation + // current `resolve()` implementation. match self.cx.tcx.hir().get_module_parent_node(node_id) { id if id != node_id => Some(id), _ => None, @@ -252,7 +251,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor } else { match parent_node.or(self.mod_ids.last().cloned()) { Some(parent) if parent != NodeId::from_u32(0) => { - //FIXME: can we pull the parent module's name from elsewhere? + // FIXME: can we pull the parent module's name from elsewhere? Some(self.cx.tcx.hir().name(parent).to_string()) } _ => None, @@ -262,7 +261,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor ImplItem(Impl { ref for_, .. }) => { for_.def_id().map(|did| self.cx.tcx.item_name(did).to_string()) } - // we don't display docs on `extern crate` items anyway, so don't process them + // we don't display docs on `extern crate` items anyway, so don't process them. ExternCrateItem(..) => return self.fold_item_recur(item), ImportItem(Import::Simple(ref name, ..)) => Some(name.clone()), MacroItem(..) => None, @@ -283,7 +282,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor } for (ori_link, link_range) in markdown_links(&dox) { - // bail early for real links + // Bail early for real links. if ori_link.contains('/') { continue; } @@ -327,9 +326,9 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor def } else { resolution_failure(cx, &item.attrs, path_str, &dox, link_range); - // this could just be a normal link or a broken link + // This could just be a normal link or a broken link // we could potentially check if something is - // "intra-doc-link-like" and warn in that case + // "intra-doc-link-like" and warn in that case. continue; } } @@ -338,12 +337,12 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor def } else { resolution_failure(cx, &item.attrs, path_str, &dox, link_range); - // this could just be a normal link + // This could just be a normal link. continue; } } PathKind::Unknown => { - // try everything! + // Try everything! if let Some(macro_def) = macro_resolve(cx, path_str) { if let Ok(type_def) = self.resolve(path_str, false, ¤t_item, parent_node) @@ -371,8 +370,8 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor { // It is imperative we search for not-a-value first // Otherwise we will find struct ctors for when we are looking - // for structs, and the link won't work. - // if there is something in both namespaces + // for structs, and the link won't work if there is something in + // both namespaces. if let Ok(value_def) = self.resolve(path_str, true, ¤t_item, parent_node) { @@ -432,7 +431,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor } } -/// Resolve a string as a macro +/// Resolve a string as a macro. fn macro_resolve(cx: &DocContext, path_str: &str) -> Option { use syntax::ext::base::{MacroKind, SyntaxExtension}; let segment = ast::PathSegment::from_ident(Ident::from_str(path_str)); @@ -482,19 +481,19 @@ fn resolution_failure( let mut diag; if dox.lines().count() == code_dox.lines().count() { let line_offset = dox[..link_range.start].lines().count(); - // The span starts in the `///`, so we don't have to account for the leading whitespace + // The span starts in the `///`, so we don't have to account for the leading whitespace. let code_dox_len = if line_offset <= 1 { doc_comment_padding } else { - // The first `///` + // The first `///`. doc_comment_padding + - // Each subsequent leading whitespace and `///` + // Each subsequent leading whitespace and `///`. code_dox.lines().skip(1).take(line_offset - 1).fold(0, |sum, line| { sum + doc_comment_padding + line.len() - line.trim_start().len() }) }; - // Extract the specific span + // Extract the specific span. let sp = sp.from_inner_byte_pos( link_range.start + code_dox_len, link_range.end + code_dox_len, @@ -514,7 +513,7 @@ fn resolution_failure( let last_new_line_offset = dox[..link_range.start].rfind('\n').map_or(0, |n| n + 1); let line = dox[last_new_line_offset..].lines().next().unwrap_or(""); - // Print the line containing the `link_range` and manually mark it with '^'s + // Print the line containing the `link_range` and manually mark it with '^'s. diag.note(&format!( "the link appears in this line:\n\n{line}\n\ {indicator: Option<(&'static str, String)> { match def { - // structs, variants, and mods exist in both namespaces. skip them + // Structs, variants, and mods exist in both namespaces; skip them. Def::StructCtor(..) | Def::Mod(..) | Def::Variant(..) | Def::VariantCtor(..) | Def::SelfCtor(..) => None, @@ -578,10 +577,10 @@ fn value_ns_kind(def: Def, path_str: &str) -> Option<(&'static str, String)> { } /// Given a def, returns its name, the article to be used, and a disambiguator -/// for the type namespace +/// for the type namespace. fn type_ns_kind(def: Def, path_str: &str) -> (&'static str, &'static str, String) { let (kind, article) = match def { - // we can still have non-tuple structs + // We can still have non-tuple structs. Def::Struct(..) => ("struct", "a"), Def::Enum(..) => ("enum", "an"), Def::Trait(..) => ("trait", "a"), @@ -591,7 +590,7 @@ fn type_ns_kind(def: Def, path_str: &str) -> (&'static str, &'static str, String (kind, article, format!("{}@{}", kind, path_str)) } -/// Given an enum variant's def, return the def of its enum and the associated fragment +/// Given an enum variant's def, return the def of its enum and the associated fragment. fn handle_variant(cx: &DocContext, def: Def) -> Result<(Def, Option), ()> { use rustc::ty::DefIdTree; diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index 74583196818..be9327ced26 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -8,38 +8,38 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::env; -use std::ffi::OsString; -use std::io::prelude::*; -use std::io; -use std::path::PathBuf; -use std::panic::{self, AssertUnwindSafe}; -use std::process::Command; -use std::str; +use errors; +use errors::emitter::ColorConfig; use rustc_data_structures::sync::Lrc; -use std::sync::{Arc, Mutex}; - -use testing; use rustc_lint; +use rustc_driver::{self, driver, target_features, Compilation}; +use rustc_driver::driver::phase_2_configure_and_expand; +use rustc_metadata::cstore::CStore; +use rustc_metadata::dynamic_lib::DynamicLibrary; +use rustc_resolve::MakeGlobMap; use rustc::hir; use rustc::hir::intravisit; use rustc::session::{self, CompileIncomplete, config}; use rustc::session::config::{OutputType, OutputTypes, Externs, CodegenOptions}; use rustc::session::search_paths::{SearchPaths, PathKind}; -use rustc_metadata::dynamic_lib::DynamicLibrary; -use tempfile::Builder as TempFileBuilder; -use rustc_driver::{self, driver, target_features, Compilation}; -use rustc_driver::driver::phase_2_configure_and_expand; -use rustc_metadata::cstore::CStore; -use rustc_resolve::MakeGlobMap; use syntax::ast; use syntax::source_map::SourceMap; use syntax::edition::Edition; use syntax::feature_gate::UnstableFeatures; use syntax::with_globals; use syntax_pos::{BytePos, DUMMY_SP, Pos, Span, FileName}; -use errors; -use errors::emitter::ColorConfig; +use tempfile::Builder as TempFileBuilder; +use testing; + +use std::env; +use std::ffi::OsString; +use std::io::prelude::*; +use std::io; +use std::path::PathBuf; +use std::panic::{self, AssertUnwindSafe}; +use std::process::Command; +use std::str; +use std::sync::{Arc, Mutex}; use clean::Attributes; use config::Options; @@ -153,7 +153,7 @@ pub fn run(mut options: Options) -> isize { }) } -// Look for #![doc(test(no_crate_inject))], used by crates in the std facade +// Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade. fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions { use syntax::print::pprust; @@ -192,12 +192,11 @@ fn run_test(test: &str, cratename: &str, filename: &FileName, line: usize, should_panic: bool, no_run: bool, as_test_harness: bool, compile_fail: bool, mut error_codes: Vec, opts: &TestOptions, maybe_sysroot: Option, linker: Option, edition: Edition) { - // the test harness wants its own `main` & top level functions, so - // never wrap the test in `fn main() { ... }` + // The test harness wants its own `main` and top-level functions, so + // never wrap the test in `fn main() { ... }`. let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts); // FIXME(#44940): if doctests ever support path remapping, then this filename - // needs to be the result of SourceMap::span_to_unmapped_path - + // needs to be the result of `SourceMap::span_to_unmapped_path`. let path = match filename { FileName::Real(path) => path.clone(), _ => PathBuf::from(r"doctest.rs"), @@ -408,8 +407,8 @@ pub fn make_test(s: &str, let filename = FileName::anon_source_code(s); let source = crates + &everything_else; - // any errors in parsing should also appear when the doctest is compiled for real, so just - // send all the errors that libsyntax emits directly into a Sink instead of stderr + // Any errors in parsing should also appear when the doctest is compiled for real, so just + // send all the errors that libsyntax emits directly into a `Sink` instead of stderr. let cm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let emitter = EmitterWriter::new(box io::sink(), None, false, false); let handler = Handler::with_emitter(false, false, box emitter); @@ -537,10 +536,10 @@ pub struct Collector { // The name of the test displayed to the user, separated by `::`. // // In tests from Rust source, this is the path to the item - // e.g. `["std", "vec", "Vec", "push"]`. + // e.g., `["std", "vec", "Vec", "push"]`. // // In tests from a markdown file, this is the titles of all headers (h1~h6) - // of the sections that contain the code block, e.g. if the markdown file is + // of the sections that contain the code block, e.g., if the markdown file is // written as: // // ``````markdown @@ -689,7 +688,7 @@ impl Tester for Collector { fn register_header(&mut self, name: &str, level: u32) { if self.use_headers { - // we use these headings as test names, so it's good if + // We use these headings as test names, so it's good if // they're valid identifiers. let name = name.chars().enumerate().map(|(i, c)| { if (i == 0 && c.is_xid_start()) || @@ -703,7 +702,7 @@ impl Tester for Collector { // Here we try to efficiently assemble the header titles into the // test name in the form of `h1::h2::h3::h4::h5::h6`. // - // Suppose originally `self.names` contains `[h1, h2, h3]`... + // Suppose that originally `self.names` contains `[h1, h2, h3]`... let level = level as usize; if level <= self.names.len() { // ... Consider `level == 2`. All headers in the lower levels @@ -752,8 +751,8 @@ impl<'a, 'hir> HirCollector<'a, 'hir> { attrs.collapse_doc_comments(); attrs.unindent_doc_comments(); - // the collapse-docs pass won't combine sugared/raw doc attributes, or included files with - // anything else, this will combine them for us + // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with + // anything else, this will combine them for us. if let Some(doc) = attrs.collapsed_doc_value() { self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP)); let res = markdown::find_testable_code(&doc, self.collector, self.codes); @@ -847,8 +846,8 @@ assert_eq!(2+2, 4); #[test] fn make_test_crate_name_no_use() { - //if you give a crate name but *don't* use it within the test, it won't bother inserting - //the `extern crate` statement + // If you give a crate name but *don't* use it within the test, it won't bother inserting + // the `extern crate` statement. let opts = TestOptions::default(); let input = "assert_eq!(2+2, 4);"; @@ -863,8 +862,8 @@ assert_eq!(2+2, 4); #[test] fn make_test_crate_name() { - //if you give a crate name and use it within the test, it will insert an `extern crate` - //statement before `fn main` + // If you give a crate name and use it within the test, it will insert an `extern crate` + // statement before `fn main`. let opts = TestOptions::default(); let input = "use asdf::qwop; @@ -882,8 +881,8 @@ assert_eq!(2+2, 4); #[test] fn make_test_no_crate_inject() { - //even if you do use the crate within the test, setting `opts.no_crate_inject` will skip - //adding it anyway + // Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip + // adding it anyway. let opts = TestOptions { no_crate_inject: true, display_warnings: false, @@ -904,8 +903,9 @@ assert_eq!(2+2, 4); #[test] fn make_test_ignore_std() { - //even if you include a crate name, and use it in the doctest, we still won't include an - //`extern crate` statement if the crate is "std" - that's included already by the compiler! + // Even if you include a crate name, and use it in the doctest, we still won't include an + // `extern crate` statement if the crate is "std" -- that's included already by the + // compiler! let opts = TestOptions::default(); let input = "use std::*; @@ -922,8 +922,8 @@ assert_eq!(2+2, 4); #[test] fn make_test_manual_extern_crate() { - //when you manually include an `extern crate` statement in your doctest, make_test assumes - //you've included one for your own crate too + // When you manually include an `extern crate` statement in your doctest, `make_test` + // assumes you've included one for your own crate too. let opts = TestOptions::default(); let input = "extern crate asdf; @@ -960,8 +960,8 @@ assert_eq!(2+2, 4); #[test] fn make_test_opts_attrs() { - //if you supplied some doctest attributes with #![doc(test(attr(...)))], it will use those - //instead of the stock #![allow(unused)] + // If you supplied some doctest attributes with `#![doc(test(attr(...)))]`, it will use + // those instead of the stock `#![allow(unused)]`. let mut opts = TestOptions::default(); opts.attrs.push("feature(sick_rad)".to_string()); let input = @@ -977,7 +977,7 @@ assert_eq!(2+2, 4); let output = make_test(input, Some("asdf"), false, &opts); assert_eq!(output, (expected, 3)); - //adding more will also bump the returned line offset + // Adding more will also bump the returned line offset. opts.attrs.push("feature(hella_dope)".to_string()); let expected = "#![feature(sick_rad)] @@ -993,8 +993,8 @@ assert_eq!(2+2, 4); #[test] fn make_test_crate_attrs() { - //including inner attributes in your doctest will apply them to the whole "crate", pasting - //them outside the generated main function + // Including inner attributes in your doctest will apply them to the whole "crate", pasting + // them outside the generated main function. let opts = TestOptions::default(); let input = "#![feature(sick_rad)] @@ -1011,7 +1011,7 @@ assert_eq!(2+2, 4); #[test] fn make_test_with_main() { - //including your own `fn main` wrapper lets the test use it verbatim + // Including your own `fn main` wrapper lets the test use it verbatim. let opts = TestOptions::default(); let input = "fn main() { @@ -1028,7 +1028,7 @@ fn main() { #[test] fn make_test_fake_main() { - //...but putting it in a comment will still provide a wrapper + // ... but putting it in a comment will still provide a wrapper. let opts = TestOptions::default(); let input = "//Ceci n'est pas une `fn main` @@ -1045,7 +1045,7 @@ assert_eq!(2+2, 4); #[test] fn make_test_dont_insert_main() { - //even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper + // Even with that, if you set `dont_insert_main`, it won't create the `fn main` wrapper. let opts = TestOptions::default(); let input = "//Ceci n'est pas une `fn main` @@ -1060,7 +1060,7 @@ assert_eq!(2+2, 4);".to_string(); #[test] fn make_test_display_warnings() { - //if the user is asking to display doctest warnings, suppress the default allow(unused) + // If the user is asking to display doctest warnings, suppress the default `allow(unused)`. let mut opts = TestOptions::default(); opts.display_warnings = true; let input = diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index fc7e8d72d69..004be1cfe39 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -8,36 +8,33 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Rust AST Visitor. Extracts useful information and massages it into a form -//! usable for clean - -use std::mem; +//! The Rust AST Visitor. Extracts useful information and massages it into a form +//! usable for `clean`. +use rustc::hir::{self, Node}; +use rustc::hir::def::Def; +use rustc::hir::def_id::{DefId, LOCAL_CRATE}; +use rustc::middle::privacy::AccessLevel; +use rustc::util::nodemap::{FxHashSet, FxHashMap}; use syntax::ast; use syntax::attr; use syntax::ext::base::MacroKind; use syntax::source_map::Spanned; use syntax_pos::{self, Span}; -use rustc::hir::Node; -use rustc::hir::def::Def; -use rustc::hir::def_id::{DefId, LOCAL_CRATE}; -use rustc::middle::privacy::AccessLevel; -use rustc::util::nodemap::{FxHashSet, FxHashMap}; - -use rustc::hir; +use std::mem; use core; use clean::{self, AttributesExt, NestedAttributesExt, def_id_to_path}; use doctree::*; -// looks to me like the first two of these are actually +// Looks to me like the first two of these are actually // output parameters, maybe only mutated once; perhaps // better simply to have the visit method return a tuple // containing them? -// also, is there some reason that this doesn't use the 'visit' -// framework from syntax? +// Also, is there some reason that this doesn't use the 'visit' +// framework from syntax?. pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> { pub module: Module, @@ -45,7 +42,7 @@ pub struct RustdocVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> { pub cx: &'a core::DocContext<'a, 'tcx, 'rcx, 'cstore>, view_item_stack: FxHashSet, inlining: bool, - /// Is the current module and all of its parents public? + /// Are the current module and all of its parents public? inside_public_path: bool, exact_paths: Option>>, } @@ -69,8 +66,8 @@ impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> { } fn store_path(&mut self, did: DefId) { - // We can't use the entry api, as that keeps the mutable borrow of self active - // when we try to use cx + // We can't use the entry API, as that keeps the mutable borrow of `self` active + // when we try to use `cx`. let exact_paths = self.exact_paths.as_mut().unwrap(); if exact_paths.get(&did).is_none() { let path = def_id_to_path(self.cx, did, self.cx.crate_name.clone()); @@ -98,7 +95,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> { ast::CRATE_NODE_ID, &krate.module, None); - // attach the crate's exported macros to the top-level module: + // Attach the crate's exported macros to the top-level module: let macro_exports: Vec<_> = krate.exported_macros.iter().map(|def| self.visit_local_macro(def, None)).collect(); self.module.macros.extend(macro_exports); @@ -303,14 +300,14 @@ impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> { let def_did = def.def_id(); let use_attrs = tcx.hir().attrs(id); - // Don't inline doc(hidden) imports so they can be stripped at a later stage. + // Don't inline `doc(hidden)` imports so they can be stripped at a later stage. let is_no_inline = use_attrs.lists("doc").has_word("no_inline") || use_attrs.lists("doc").has_word("hidden"); // For cross-crate impl inlining we need to know whether items are - // reachable in documentation - a previously nonreachable item can be + // reachable in documentation -- a previously nonreachable item can be // made reachable by cross-crate inlining which we're checking here. - // (this is done here because we need to know this upfront) + // (this is done here because we need to know this upfront). if !def_did.is_local() && !is_no_inline { let attrs = clean::inline::load_attrs(self.cx, def_did); let self_is_hidden = attrs.lists("doc").has_word("hidden"); @@ -342,7 +339,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> { let is_private = !self.cx.renderinfo.borrow().access_levels.is_public(def_did); let is_hidden = inherits_doc_hidden(self.cx, def_node_id); - // Only inline if requested or if the item would otherwise be stripped + // Only inline if requested or if the item would otherwise be stripped. if (!please_inline && !is_private && !is_hidden) || is_no_inline { return false } @@ -366,7 +363,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> { true } Node::ForeignItem(it) if !glob => { - // generate a fresh `extern {}` block if we want to inline a foreign item. + // Generate a fresh `extern {}` block if we want to inline a foreign item. om.foreigns.push(hir::ForeignMod { abi: tcx.hir().get_foreign_abi(it.id), items: vec![hir::ForeignItem { @@ -427,7 +424,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> { hir::ItemKind::Use(ref path, kind) => { let is_glob = kind == hir::UseKind::Glob; - // struct and variant constructors always show up alongside their definitions, we've + // Struct and variant constructors always show up alongside their definitions, we've // already processed them so just discard these. match path.def { Def::StructCtor(..) | Def::VariantCtor(..) | Def::SelfCtor(..) => return, @@ -596,7 +593,7 @@ impl<'a, 'tcx, 'rcx, 'cstore> RustdocVisitor<'a, 'tcx, 'rcx, 'cstore> { } } - // convert each exported_macro into a doc item + // Convert each `exported_macro` into a doc item. fn visit_local_macro( &self, def: &hir::MacroDef, diff --git a/src/librustdoc/visit_lib.rs b/src/librustdoc/visit_lib.rs index 5d1f42c83f4..f64334a8219 100644 --- a/src/librustdoc/visit_lib.rs +++ b/src/librustdoc/visit_lib.rs @@ -21,7 +21,7 @@ use clean::{AttributesExt, NestedAttributesExt}; // FIXME: this may not be exhaustive, but is sufficient for rustdocs current uses /// Similar to `librustc_privacy::EmbargoVisitor`, but also takes -/// specific rustdoc annotations into account (i.e. `doc(hidden)`) +/// specific rustdoc annotations into account (i.e., `doc(hidden)`) pub struct LibEmbargoVisitor<'a, 'tcx: 'a, 'rcx: 'a, 'cstore: 'rcx> { cx: &'a ::core::DocContext<'a, 'tcx, 'rcx, 'cstore>, // Accessibility levels for reachable nodes diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index 4bb3ce0cf44..d3267e4e801 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -342,7 +342,7 @@ impl HashSet } /// Visits the values representing the difference, - /// i.e. the values that are in `self` but not in `other`. + /// i.e., the values that are in `self` but not in `other`. /// /// # Examples /// @@ -373,7 +373,7 @@ impl HashSet } /// Visits the values representing the symmetric difference, - /// i.e. the values that are in `self` or in `other` but not in both. + /// i.e., the values that are in `self` or in `other` but not in both. /// /// # Examples /// @@ -401,7 +401,7 @@ impl HashSet } /// Visits the values representing the intersection, - /// i.e. the values that are both in `self` and `other`. + /// i.e., the values that are both in `self` and `other`. /// /// # Examples /// @@ -427,7 +427,7 @@ impl HashSet } /// Visits the values representing the union, - /// i.e. all the values in `self` or `other`, without duplicates. + /// i.e., all the values in `self` or `other`, without duplicates. /// /// # Examples /// @@ -598,7 +598,7 @@ impl HashSet } /// Returns `true` if the set is a subset of another, - /// i.e. `other` contains at least all the values in `self`. + /// i.e., `other` contains at least all the values in `self`. /// /// # Examples /// @@ -620,7 +620,7 @@ impl HashSet } /// Returns `true` if the set is a superset of another, - /// i.e. `self` contains at least all the values in `other`. + /// i.e., `self` contains at least all the values in `other`. /// /// # Examples /// diff --git a/src/libstd/error.rs b/src/libstd/error.rs index 7a5353bb60f..a9b27115261 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -36,12 +36,12 @@ use str; use string; /// `Error` is a trait representing the basic expectations for error values, -/// i.e. values of type `E` in [`Result`]. Errors must describe +/// i.e., values of type `E` in [`Result`]. Errors must describe /// themselves through the [`Display`] and [`Debug`] traits, and may provide /// cause chain information: /// /// The [`cause`] method is generally used when errors cross "abstraction -/// boundaries", i.e. when a one module must report an error that is "caused" +/// boundaries", i.e., when a one module must report an error that is "caused" /// by an error from a lower-level module. This setup makes it possible for the /// high-level module to provide its own errors that do not commit to any /// particular implementation, but also reveal some of its implementation for diff --git a/src/libstd/f64.rs b/src/libstd/f64.rs index ecaaf8323ab..c800763167f 100644 --- a/src/libstd/f64.rs +++ b/src/libstd/f64.rs @@ -888,7 +888,7 @@ impl f64 { } // Solaris/Illumos requires a wrapper around log, log2, and log10 functions - // because of their non-standard behavior (e.g. log(-n) returns -Inf instead + // because of their non-standard behavior (e.g., log(-n) returns -Inf instead // of expected NaN). fn log_wrapper f64>(self, log_fn: F) -> f64 { if !cfg!(target_os = "solaris") { diff --git a/src/libstd/ffi/c_str.rs b/src/libstd/ffi/c_str.rs index 7c7f83967e0..768998b235e 100644 --- a/src/libstd/ffi/c_str.rs +++ b/src/libstd/ffi/c_str.rs @@ -372,7 +372,7 @@ impl CString { /// # Safety /// /// This should only ever be called with a pointer that was earlier - /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g. trying to take + /// obtained by calling [`into_raw`] on a `CString`. Other usage (e.g., trying to take /// ownership of a string that was allocated by foreign code) is likely to lead /// to undefined behavior or allocator corruption. /// @@ -1167,8 +1167,8 @@ impl CStr { /// ``` #[stable(feature = "cstr_to_str", since = "1.4.0")] pub fn to_str(&self) -> Result<&str, str::Utf8Error> { - // NB: When CStr is changed to perform the length check in .to_bytes() - // instead of in from_ptr(), it may be worth considering if this should + // N.B., when `CStr` is changed to perform the length check in `.to_bytes()` + // instead of in `from_ptr()`, it may be worth considering if this should // be rewritten to do the UTF-8 check inline with the length calculation // instead of doing it afterwards. str::from_utf8(self.to_bytes()) diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs index bd5fc3fa24a..99da73adc63 100644 --- a/src/libstd/ffi/mod.rs +++ b/src/libstd/ffi/mod.rs @@ -21,7 +21,7 @@ //! Rust represents owned strings with the [`String`] type, and //! borrowed slices of strings with the [`str`] primitive. Both are //! always in UTF-8 encoding, and may contain nul bytes in the middle, -//! i.e. if you look at the bytes that make up the string, there may +//! i.e., if you look at the bytes that make up the string, there may //! be a `\0` among them. Both `String` and `str` store their length //! explicitly; there are no nul terminators at the end of strings //! like in C. @@ -44,7 +44,7 @@ //! code point]'. //! //! * **Nul terminators and implicit string lengths** - Often, C -//! strings are nul-terminated, i.e. they have a `\0` character at the +//! strings are nul-terminated, i.e., they have a `\0` character at the //! end. The length of a string buffer is not stored, but has to be //! calculated; to compute the length of a string, C code must //! manually call a function like `strlen()` for `char`-based strings, diff --git a/src/libstd/ffi/os_str.rs b/src/libstd/ffi/os_str.rs index 9c40a31986c..828972187ee 100644 --- a/src/libstd/ffi/os_str.rs +++ b/src/libstd/ffi/os_str.rs @@ -36,7 +36,7 @@ use sys_common::{AsInner, IntoInner, FromInner}; /// and platform-native string values, and in particular allowing a Rust string /// to be converted into an "OS" string with no cost if possible. A consequence /// of this is that `OsString` instances are *not* `NUL` terminated; in order -/// to pass to e.g. Unix system call, you should create a [`CStr`]. +/// to pass to e.g., Unix system call, you should create a [`CStr`]. /// /// `OsString` is to [`&OsStr`] as [`String`] is to [`&str`]: the former /// in each pair are owned strings; the latter are borrowed diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs index 7d054a347f4..b6a0ce63720 100644 --- a/src/libstd/fs.rs +++ b/src/libstd/fs.rs @@ -1406,7 +1406,7 @@ impl AsInner for DirEntry { /// Removes a file from the filesystem. /// /// Note that there is no -/// guarantee that the file is immediately deleted (e.g. depending on +/// guarantee that the file is immediately deleted (e.g., depending on /// platform, other open file descriptors may prevent immediate removal). /// /// # Platform-specific behavior diff --git a/src/libstd/io/cursor.rs b/src/libstd/io/cursor.rs index 14f20151dca..f7a90333ef2 100644 --- a/src/libstd/io/cursor.rs +++ b/src/libstd/io/cursor.rs @@ -90,7 +90,7 @@ pub struct Cursor { impl Cursor { /// Creates a new cursor wrapping the provided underlying in-memory buffer. /// - /// Cursor initial position is `0` even if underlying buffer (e.g. `Vec`) + /// Cursor initial position is `0` even if underlying buffer (e.g., `Vec`) /// is not empty. So writing to cursor starts with overwriting `Vec` /// content, not with appending to it. /// diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index a413432cdaa..8c03f355848 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -131,7 +131,7 @@ fn handle_ebadf(r: io::Result, default: T) -> io::Result { /// /// Each handle is a shared reference to a global buffer of input data to this /// process. A handle can be `lock`'d to gain full access to [`BufRead`] methods -/// (e.g. `.lines()`). Reads to this handle are otherwise locked with respect +/// (e.g., `.lines()`). Reads to this handle are otherwise locked with respect /// to other reads. /// /// This handle implements the `Read` trait, but beware that concurrent reads @@ -269,7 +269,7 @@ impl Stdin { /// /// You can run the example one of two ways: /// - /// - Pipe some text to it, e.g. `printf foo | path/to/executable` + /// - Pipe some text to it, e.g., `printf foo | path/to/executable` /// - Give it text interactively by running the executable directly, /// in which case it will wait for the Enter key to be pressed before /// continuing diff --git a/src/libstd/keyword_docs.rs b/src/libstd/keyword_docs.rs index c1eaf29bb44..12b60313725 100644 --- a/src/libstd/keyword_docs.rs +++ b/src/libstd/keyword_docs.rs @@ -188,7 +188,7 @@ mod enum_keyword { } /// For external connections in Rust code. /// /// The `extern` keyword is used in two places in Rust. One is in conjunction with the [`crate`] -/// keyword to make your Rust code aware of other Rust crates in your project, i.e. `extern crate +/// keyword to make your Rust code aware of other Rust crates in your project, i.e., `extern crate /// lazy_static;`. The other use is in foreign function interfaces (FFI). /// /// `extern` is used in two different contexts within FFI. The first is in the form of external diff --git a/src/libstd/net/addr.rs b/src/libstd/net/addr.rs index 1ac0bdf922f..21def5d93b7 100644 --- a/src/libstd/net/addr.rs +++ b/src/libstd/net/addr.rs @@ -703,7 +703,7 @@ impl hash::Hash for SocketAddrV6 { /// the other: for simple uses a string like `"localhost:12345"` is much nicer /// than manual construction of the corresponding [`SocketAddr`], but sometimes /// [`SocketAddr`] value is *the* main source of the address, and converting it to -/// some other type (e.g. a string) just for it to be converted back to +/// some other type (e.g., a string) just for it to be converted back to /// [`SocketAddr`] in constructor methods is pointless. /// /// Addresses returned by the operating system that are not IP addresses are diff --git a/src/libstd/net/tcp.rs b/src/libstd/net/tcp.rs index be797803233..5aa043b0fcb 100644 --- a/src/libstd/net/tcp.rs +++ b/src/libstd/net/tcp.rs @@ -530,7 +530,7 @@ impl TcpStream { /// Moves this TCP stream into or out of nonblocking mode. /// /// This will result in `read`, `write`, `recv` and `send` operations - /// becoming nonblocking, i.e. immediately returning from their calls. + /// becoming nonblocking, i.e., immediately returning from their calls. /// If the IO operation is successful, `Ok` is returned and no further /// action is required. If the IO operation could not be completed and needs /// to be retried, an error with kind [`io::ErrorKind::WouldBlock`] is @@ -840,7 +840,7 @@ impl TcpListener { /// Moves this TCP stream into or out of nonblocking mode. /// /// This will result in the `accept` operation becoming nonblocking, - /// i.e. immediately returning from their calls. If the IO operation is + /// i.e., immediately returning from their calls. If the IO operation is /// successful, `Ok` is returned and no further action is required. If the /// IO operation could not be completed and needs to be retried, an error /// with kind [`io::ErrorKind::WouldBlock`] is returned. diff --git a/src/libstd/net/udp.rs b/src/libstd/net/udp.rs index fc68abae05a..6c0c636d30c 100644 --- a/src/libstd/net/udp.rs +++ b/src/libstd/net/udp.rs @@ -752,7 +752,7 @@ impl UdpSocket { /// Moves this UDP socket into or out of nonblocking mode. /// /// This will result in `recv`, `recv_from`, `send`, and `send_to` - /// operations becoming nonblocking, i.e. immediately returning from their + /// operations becoming nonblocking, i.e., immediately returning from their /// calls. If the IO operation is successful, `Ok` is returned and no /// further action is required. If the IO operation could not be completed /// and needs to be retried, an error with kind diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index 4bc18a57e92..099b4d6f577 100644 --- a/src/libstd/panic.rs +++ b/src/libstd/panic.rs @@ -80,7 +80,7 @@ pub use core::panic::{PanicInfo, Location}; /// Simply put, a type `T` implements `UnwindSafe` if it cannot easily allow /// witnessing a broken invariant through the use of `catch_unwind` (catching a /// panic). This trait is an auto trait, so it is automatically implemented for -/// many types, and it is also structurally composed (e.g. a struct is unwind +/// many types, and it is also structurally composed (e.g., a struct is unwind /// safe if all of its components are unwind safe). /// /// Note, however, that this is not an unsafe trait, so there is not a succinct diff --git a/src/libstd/panicking.rs b/src/libstd/panicking.rs index b70d56f9e59..6b47ba6d1cb 100644 --- a/src/libstd/panicking.rs +++ b/src/libstd/panicking.rs @@ -460,7 +460,7 @@ fn rust_panic_with_hook(payload: &mut dyn BoxMeUp, let panics = update_panic_count(1); - // If this is the third nested call (e.g. panics == 2, this is 0-indexed), + // If this is the third nested call (e.g., panics == 2, this is 0-indexed), // the panic hook probably triggered the last panic, otherwise the // double-panic check would have aborted the process. In this case abort the // process real quickly as we don't want to try calling it again as it'll diff --git a/src/libstd/path.rs b/src/libstd/path.rs index 9fad40c5649..b882442dd2f 100644 --- a/src/libstd/path.rs +++ b/src/libstd/path.rs @@ -109,11 +109,11 @@ use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix}; // Windows Prefixes //////////////////////////////////////////////////////////////////////////////// -/// Windows path prefixes, e.g. `C:` or `\\server\share`. +/// Windows path prefixes, e.g., `C:` or `\\server\share`. /// /// Windows uses a variety of path prefix styles, including references to drive /// volumes (like `C:`), network shared folders (like `\\server\share`), and -/// others. In addition, some path prefixes are "verbatim" (i.e. prefixed with +/// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with /// `\\?\`), in which case `/` is *not* treated as a separator and essentially /// no normalization is performed. /// @@ -148,7 +148,7 @@ use sys::path::{is_sep_byte, is_verbatim_sep, MAIN_SEP_STR, parse_prefix}; #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] #[stable(feature = "rust1", since = "1.0.0")] pub enum Prefix<'a> { - /// Verbatim prefix, e.g. `\\?\cat_pics`. + /// Verbatim prefix, e.g., `\\?\cat_pics`. /// /// Verbatim prefixes consist of `\\?\` immediately followed by the given /// component. @@ -156,7 +156,7 @@ pub enum Prefix<'a> { Verbatim(#[stable(feature = "rust1", since = "1.0.0")] &'a OsStr), /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_, - /// e.g. `\\?\UNC\server\share`. + /// e.g., `\\?\UNC\server\share`. /// /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the /// server's hostname and a share name. @@ -166,14 +166,14 @@ pub enum Prefix<'a> { #[stable(feature = "rust1", since = "1.0.0")] &'a OsStr, ), - /// Verbatim disk prefix, e.g. `\\?\C:\`. + /// Verbatim disk prefix, e.g., `\\?\C:\`. /// /// Verbatim disk prefixes consist of `\\?\` immediately followed by the /// drive letter and `:\`. #[stable(feature = "rust1", since = "1.0.0")] VerbatimDisk(#[stable(feature = "rust1", since = "1.0.0")] u8), - /// Device namespace prefix, e.g. `\\.\COM42`. + /// Device namespace prefix, e.g., `\\.\COM42`. /// /// Device namespace prefixes consist of `\\.\` immediately followed by the /// device name. @@ -227,7 +227,7 @@ impl<'a> Prefix<'a> { } - /// Determines if the prefix is verbatim, i.e. begins with `\\?\`. + /// Determines if the prefix is verbatim, i.e., begins with `\\?\`. /// /// # Examples /// @@ -509,7 +509,7 @@ impl<'a> Hash for PrefixComponent<'a> { #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[stable(feature = "rust1", since = "1.0.0")] pub enum Component<'a> { - /// A Windows path prefix, e.g. `C:` or `\\server\share`. + /// A Windows path prefix, e.g., `C:` or `\\server\share`. /// /// There is a large variety of prefix types, see [`Prefix`]'s documentation /// for more. @@ -528,15 +528,15 @@ pub enum Component<'a> { #[stable(feature = "rust1", since = "1.0.0")] RootDir, - /// A reference to the current directory, i.e. `.`. + /// A reference to the current directory, i.e., `.`. #[stable(feature = "rust1", since = "1.0.0")] CurDir, - /// A reference to the parent directory, i.e. `..`. + /// A reference to the parent directory, i.e., `..`. #[stable(feature = "rust1", since = "1.0.0")] ParentDir, - /// A normal component, e.g. `a` and `b` in `a/b`. + /// A normal component, e.g., `a` and `b` in `a/b`. /// /// This variant is the most common one, it represents references to files /// or directories. @@ -615,7 +615,7 @@ pub struct Components<'a> { // true if path *physically* has a root separator; for most Windows // prefixes, it may have a "logical" rootseparator for the purposes of - // normalization, e.g. \\server\share == \\server\share\. + // normalization, e.g., \\server\share == \\server\share\. has_physical_root: bool, // The iterator is double-ended, and these two states keep track of what has @@ -798,7 +798,7 @@ impl<'a> Components<'a> { (comp.len() + extra, self.parse_single_component(comp)) } - // trim away repeated separators (i.e. empty components) on the left + // trim away repeated separators (i.e., empty components) on the left fn trim_left(&mut self) { while !self.path.is_empty() { let (size, comp) = self.parse_next_component(); @@ -810,7 +810,7 @@ impl<'a> Components<'a> { } } - // trim away repeated separators (i.e. empty components) on the right + // trim away repeated separators (i.e., empty components) on the right fn trim_right(&mut self) { while self.path.len() > self.len_before_body() { let (size, comp) = self.parse_next_component_back(); @@ -1178,7 +1178,7 @@ impl PathBuf { /// /// On Windows: /// - /// * if `path` has a root but no prefix (e.g. `\windows`), it + /// * if `path` has a root but no prefix (e.g., `\windows`), it /// replaces everything except for the prefix (if any) of `self`. /// * if `path` has a prefix but no root, it replaces `self`. /// @@ -1225,7 +1225,7 @@ impl PathBuf { if path.is_absolute() || path.prefix().is_some() { self.as_mut_vec().truncate(0); - // `path` has a root but no prefix, e.g. `\windows` (Windows only) + // `path` has a root but no prefix, e.g., `\windows` (Windows only) } else if path.has_root() { let prefix_len = self.components().prefix_remaining(); self.as_mut_vec().truncate(prefix_len); @@ -1810,7 +1810,7 @@ impl Path { PathBuf::from(self.inner.to_os_string()) } - /// Returns `true` if the `Path` is absolute, i.e. if it is independent of + /// Returns `true` if the `Path` is absolute, i.e., if it is independent of /// the current directory. /// /// * On Unix, a path is absolute if it starts with the root, so @@ -1839,7 +1839,7 @@ impl Path { } } - /// Returns `true` if the `Path` is relative, i.e. not absolute. + /// Returns `true` if the `Path` is relative, i.e., not absolute. /// /// See [`is_absolute`]'s documentation for more details. /// @@ -1866,9 +1866,9 @@ impl Path { /// * On Unix, a path has a root if it begins with `/`. /// /// * On Windows, a path has a root if it: - /// * has no prefix and begins with a separator, e.g. `\windows` - /// * has a prefix followed by a separator, e.g. `c:\windows` but not `c:windows` - /// * has any non-disk prefix, e.g. `\\server\share` + /// * has no prefix and begins with a separator, e.g., `\windows` + /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows` + /// * has any non-disk prefix, e.g., `\\server\share` /// /// # Examples /// @@ -1980,7 +1980,7 @@ impl Path { /// /// # Errors /// - /// If `base` is not a prefix of `self` (i.e. [`starts_with`] + /// If `base` is not a prefix of `self` (i.e., [`starts_with`] /// returns `false`), returns [`Err`]. /// /// [`starts_with`]: #method.starts_with @@ -2406,7 +2406,7 @@ impl Path { /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// - /// If you cannot access the directory containing the file, e.g. because of a + /// If you cannot access the directory containing the file, e.g., because of a /// permission error, this will return `false`. /// /// # Examples @@ -2432,7 +2432,7 @@ impl Path { /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// - /// If you cannot access the directory containing the file, e.g. because of a + /// If you cannot access the directory containing the file, e.g., because of a /// permission error, this will return `false`. /// /// # Examples @@ -2461,7 +2461,7 @@ impl Path { /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// - /// If you cannot access the directory containing the file, e.g. because of a + /// If you cannot access the directory containing the file, e.g., because of a /// permission error, this will return `false`. /// /// # Examples diff --git a/src/libstd/primitive_docs.rs b/src/libstd/primitive_docs.rs index 48acc1096a6..3b2366a9eca 100644 --- a/src/libstd/primitive_docs.rs +++ b/src/libstd/primitive_docs.rs @@ -462,7 +462,7 @@ mod prim_pointer { } /// /// There are two syntactic forms for creating an array: /// -/// * A list with each element, i.e. `[x, y, z]`. +/// * A list with each element, i.e., `[x, y, z]`. /// * A repeat expression `[x; N]`, which produces an array with `N` copies of `x`. /// The type of `x` must be [`Copy`][copy]. /// diff --git a/src/libstd/process.rs b/src/libstd/process.rs index 2d0848252be..b42ad29034c 100644 --- a/src/libstd/process.rs +++ b/src/libstd/process.rs @@ -628,7 +628,7 @@ impl Command { /// /// # Platform-specific behavior /// - /// If the program path is relative (e.g. `"./script.sh"`), it's ambiguous + /// If the program path is relative (e.g., `"./script.sh"`), it's ambiguous /// whether it should be interpreted relative to the parent's working /// directory or relative to `current_dir`. The behavior in this case is /// platform specific and unstable, and it's recommended to use diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index a7db372a0e2..81356e68bc0 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -89,7 +89,7 @@ //! //! - A **single processor** executing instructions [out-of-order]: //! Modern CPUs are capable of [superscalar] execution, -//! i.e. multiple instructions might be executing at the same time, +//! i.e., multiple instructions might be executing at the same time, //! even though the machine code describes a sequential process. //! //! This kind of reordering is handled transparently by the CPU. diff --git a/src/libstd/sync/mpsc/sync.rs b/src/libstd/sync/mpsc/sync.rs index 90f12c826d6..dc80f561f7a 100644 --- a/src/libstd/sync/mpsc/sync.rs +++ b/src/libstd/sync/mpsc/sync.rs @@ -292,7 +292,7 @@ impl Packet { } } - // NB: Channel could be disconnected while waiting, so the order of + // N.B., channel could be disconnected while waiting, so the order of // these conditionals is important. if guard.disconnected && guard.buf.size() == 0 { return Err(Disconnected); diff --git a/src/libstd/sync/once.rs b/src/libstd/sync/once.rs index cf9698cb2a9..13e0d2edb83 100644 --- a/src/libstd/sync/once.rs +++ b/src/libstd/sync/once.rs @@ -189,7 +189,7 @@ impl Once { /// static INIT: Once = Once::new(); /// /// // Accessing a `static mut` is unsafe much of the time, but if we do so - /// // in a synchronized fashion (e.g. write once or read all) then we're + /// // in a synchronized fashion (e.g., write once or read all) then we're /// // good to go! /// // /// // This function will only call `expensive_computation` once, and will @@ -232,7 +232,7 @@ impl Once { /// Performs the same function as [`call_once`] except ignores poisoning. /// - /// Unlike [`call_once`], if this `Once` has been poisoned (i.e. a previous + /// Unlike [`call_once`], if this `Once` has been poisoned (i.e., a previous /// call to `call_once` or `call_once_force` caused a panic), calling /// `call_once_force` will still invoke the closure `f` and will _not_ /// result in an immediate panic. If `f` panics, the `Once` will remain diff --git a/src/libstd/sys/unix/android.rs b/src/libstd/sys/unix/android.rs index 10436723a81..462eab56664 100644 --- a/src/libstd/sys/unix/android.rs +++ b/src/libstd/sys/unix/android.rs @@ -15,7 +15,7 @@ //! always work with the most recent version of Android, but we also want to //! work with older versions of Android for whenever projects need to. //! -//! Our current minimum supported Android version is `android-9`, e.g. Android +//! Our current minimum supported Android version is `android-9`, e.g., Android //! with API level 9. We then in theory want to work on that and all future //! versions of Android! //! diff --git a/src/libstd/sys/unix/ext/net.rs b/src/libstd/sys/unix/ext/net.rs index 737437c76b7..bcf0d440eba 100644 --- a/src/libstd/sys/unix/ext/net.rs +++ b/src/libstd/sys/unix/ext/net.rs @@ -132,7 +132,7 @@ impl SocketAddr { if len == 0 { // When there is a datagram from unnamed unix socket // linux returns zero bytes of address - len = sun_path_offset() as libc::socklen_t; // i.e. zero-length address + len = sun_path_offset() as libc::socklen_t; // i.e., zero-length address } else if addr.sun_family != libc::AF_UNIX as libc::sa_family_t { return Err(io::Error::new(io::ErrorKind::InvalidInput, "file descriptor did not correspond to a Unix socket")); diff --git a/src/libstd/sys/unix/net.rs b/src/libstd/sys/unix/net.rs index 2d10541752c..d922be520d4 100644 --- a/src/libstd/sys/unix/net.rs +++ b/src/libstd/sys/unix/net.rs @@ -26,7 +26,7 @@ pub extern crate libc as netc; pub type wrlen_t = size_t; // See below for the usage of SOCK_CLOEXEC, but this constant is only defined on -// Linux currently (e.g. support doesn't exist on other platforms). In order to +// Linux currently (e.g., support doesn't exist on other platforms). In order to // get name resolution to work and things to compile we just define a dummy // SOCK_CLOEXEC here for other platforms. Note that the dummy constant isn't // actually ever used (the blocks below are wrapped in `if cfg!` as well. diff --git a/src/libstd/sys/unix/process/zircon.rs b/src/libstd/sys/unix/process/zircon.rs index a06c73ee263..0335c1e914c 100644 --- a/src/libstd/sys/unix/process/zircon.rs +++ b/src/libstd/sys/unix/process/zircon.rs @@ -215,7 +215,7 @@ pub const FDIO_SPAWN_ACTION_TRANSFER_FD: u32 = 0x0002; // and has a closed remote end will return ERR_REMOTE_CLOSED. #[allow(unused)] pub const ERR_SHOULD_WAIT: zx_status_t = -22; -// ERR_CANCELED: The in-progress operation (e.g. a wait) has been +// ERR_CANCELED: The in-progress operation (e.g., a wait) has been // // canceled. #[allow(unused)] pub const ERR_CANCELED: zx_status_t = -23; diff --git a/src/libstd/sys/windows/ext/ffi.rs b/src/libstd/sys/windows/ext/ffi.rs index bae0d02786a..0a13aeabe84 100644 --- a/src/libstd/sys/windows/ext/ffi.rs +++ b/src/libstd/sys/windows/ext/ffi.rs @@ -117,7 +117,7 @@ impl OsStringExt for OsString { /// [`OsStr`]: ../../../../std/ffi/struct.OsStr.html #[stable(feature = "rust1", since = "1.0.0")] pub trait OsStrExt { - /// Re-encodes an `OsStr` as a wide character sequence, i.e. potentially + /// Re-encodes an `OsStr` as a wide character sequence, i.e., potentially /// ill-formed UTF-16. /// /// This is lossless: calling [`OsString::from_wide`] and then diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index 082d4689c7b..949060b34dd 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -443,7 +443,7 @@ impl FromInner for File { impl fmt::Debug for File { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - // FIXME(#24570): add more info here (e.g. mode) + // FIXME(#24570): add more info here (e.g., mode) let mut b = f.debug_struct("File"); b.field("handle", &self.handle.raw()); if let Ok(path) = get_path(&self) { diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index 4d7b7236c59..2be30e68d24 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -67,7 +67,7 @@ pub fn error_string(mut errnum: i32) -> String { buf.len() as c::DWORD, ptr::null()) as usize; if res == 0 { - // Sometimes FormatMessageW can fail e.g. system doesn't like langId, + // Sometimes FormatMessageW can fail e.g., system doesn't like langId, let fm_err = errno(); return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err); diff --git a/src/libstd/sys/windows/pipe.rs b/src/libstd/sys/windows/pipe.rs index 4b19519a57a..f9eed31f0e0 100644 --- a/src/libstd/sys/windows/pipe.rs +++ b/src/libstd/sys/windows/pipe.rs @@ -100,23 +100,23 @@ pub fn anon_pipe(ours_readable: bool) -> io::Result { 0, ptr::null_mut()); - // We pass the FILE_FLAG_FIRST_PIPE_INSTANCE flag above, and we're + // We pass the `FILE_FLAG_FIRST_PIPE_INSTANCE` flag above, and we're // also just doing a best effort at selecting a unique name. If - // ERROR_ACCESS_DENIED is returned then it could mean that we + // `ERROR_ACCESS_DENIED` is returned then it could mean that we // accidentally conflicted with an already existing pipe, so we try // again. // // Don't try again too much though as this could also perhaps be a // legit error. - // If ERROR_INVALID_PARAMETER is returned, this probably means we're - // running on pre-Vista version where PIPE_REJECT_REMOTE_CLIENTS is + // If `ERROR_INVALID_PARAMETER` is returned, this probably means we're + // running on pre-Vista version where `PIPE_REJECT_REMOTE_CLIENTS` is // not supported, so we continue retrying without it. This implies // reduced security on Windows versions older than Vista by allowing // connections to this pipe from remote machines. // Proper fix would increase the number of FFI imports and introduce // significant amount of Windows XP specific code with no clean // testing strategy - // for more info see https://github.com/rust-lang/rust/pull/37677 + // For more info, see https://github.com/rust-lang/rust/pull/37677. if handle == c::INVALID_HANDLE_VALUE { let err = io::Error::last_os_error(); let raw_os_err = err.raw_os_error(); diff --git a/src/libstd/sys_common/gnu/libbacktrace.rs b/src/libstd/sys_common/gnu/libbacktrace.rs index 6ad3af6aee1..c2589d477ee 100644 --- a/src/libstd/sys_common/gnu/libbacktrace.rs +++ b/src/libstd/sys_common/gnu/libbacktrace.rs @@ -23,7 +23,7 @@ pub fn foreach_symbol_fileline(frame: Frame, where F: FnMut(&[u8], u32) -> io::Result<()> { // pcinfo may return an arbitrary number of file:line pairs, - // in the order of stack trace (i.e. inlined calls first). + // in the order of stack trace (i.e., inlined calls first). // in order to avoid allocation, we stack-allocate a fixed size of entries. const FILELINE_SIZE: usize = 32; let mut fileline_buf = [(ptr::null(), !0); FILELINE_SIZE]; diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index 4df47511172..8bb99096061 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -269,7 +269,7 @@ impl LocalKey { // ptr::write(ptr, Some(value)) // // Due to this pattern it's possible for the destructor of the value in - // `ptr` (e.g. if this is being recursively initialized) to re-access + // `ptr` (e.g., if this is being recursively initialized) to re-access // TLS, in which case there will be a `&` and `&mut` pointer to the same // value (an aliasing violation). To avoid setting the "I'm running a // destructor" flag we just use `mem::replace` which should sequence the diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index d15b4902412..194e2881df3 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -93,7 +93,7 @@ //! Threads are represented via the [`Thread`] type, which you can get in one of //! two ways: //! -//! * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`] +//! * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`] //! function, and calling [`thread`][`JoinHandle::thread`] on the [`JoinHandle`]. //! * By requesting the current thread, using the [`thread::current`] function. //! @@ -124,7 +124,7 @@ //! thread, use [`Thread::name`]. A couple examples of where the name of a thread gets used: //! //! * If a panic occurs in a named thread, the thread name will be printed in the panic message. -//! * The thread name is provided to the OS where applicable (e.g. `pthread_setname_np` in +//! * The thread name is provided to the OS where applicable (e.g., `pthread_setname_np` in //! unix-like platforms). //! //! ## Stack size @@ -422,7 +422,7 @@ impl Builder { /// /// - ensure that [`join`][`JoinHandle::join`] is called before any referenced /// data is dropped - /// - use only types with `'static` lifetime bounds, i.e. those with no or only + /// - use only types with `'static` lifetime bounds, i.e., those with no or only /// `'static` references (both [`thread::Builder::spawn`][`Builder::spawn`] /// and [`thread::spawn`][`spawn`] enforce this property statically) /// @@ -692,7 +692,7 @@ pub fn yield_now() { /// already poison themselves when a thread panics while holding the lock. /// /// This can also be used in multithreaded applications, in order to send a -/// message to other threads warning that a thread has panicked (e.g. for +/// message to other threads warning that a thread has panicked (e.g., for /// monitoring purposes). /// /// # Examples @@ -1078,7 +1078,7 @@ struct Inner { /// Threads are represented via the `Thread` type, which you can get in one of /// two ways: /// -/// * By spawning a new thread, e.g. using the [`thread::spawn`][`spawn`] +/// * By spawning a new thread, e.g., using the [`thread::spawn`][`spawn`] /// function, and calling [`thread`][`JoinHandle::thread`] on the /// [`JoinHandle`]. /// * By requesting the current thread, using the [`thread::current`] function. diff --git a/src/libstd/time.rs b/src/libstd/time.rs index 5d0d501615f..667810485ee 100644 --- a/src/libstd/time.rs +++ b/src/libstd/time.rs @@ -330,7 +330,7 @@ impl SystemTime { /// Returns the amount of time elapsed since this system time was created. /// /// This function may fail as the underlying system clock is susceptible to - /// drift and updates (e.g. the system clock could go backwards), so this + /// drift and updates (e.g., the system clock could go backwards), so this /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is /// returned where the duration represents the amount of time elapsed from /// this time measurement to the current time. diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 87225711871..f25f456e3ae 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -68,7 +68,7 @@ impl fmt::Debug for Lifetime { /// It's represented as a sequence of identifiers, /// along with a bunch of supporting information. /// -/// E.g. `std::cmp::PartialEq` +/// E.g., `std::cmp::PartialEq`. #[derive(Clone, RustcEncodable, RustcDecodable)] pub struct Path { pub span: Span, @@ -96,8 +96,8 @@ impl fmt::Display for Path { } impl Path { - // convert a span and an identifier to the corresponding - // 1-segment path + // Convert a span and an identifier to the corresponding + // one-segment path. pub fn from_ident(ident: Ident) -> Path { Path { segments: vec![PathSegment::from_ident(ident)], @@ -112,7 +112,7 @@ impl Path { /// A segment of a path: an identifier, an optional lifetime, and a set of types. /// -/// E.g. `std`, `String` or `Box` +/// E.g., `std`, `String` or `Box`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct PathSegment { /// The identifier portion of this path segment. @@ -140,7 +140,7 @@ impl PathSegment { /// Arguments of a path segment. /// -/// E.g. `` as in `Foo` or `(A, B)` as in `Foo(A, B)` +/// E.g., `` as in `Foo` or `(A, B)` as in `Foo(A, B)`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericArgs { /// The `<'a, A,B,C>` in `foo::bar::baz::<'a, A,B,C>` @@ -282,7 +282,7 @@ pub type GenericBounds = Vec; #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum GenericParamKind { - /// A lifetime definition, e.g. `'a: 'b+'c+'d`. + /// A lifetime definition (e.g., `'a: 'b + 'c + 'd`). Lifetime, Type { default: Option>, @@ -334,11 +334,11 @@ pub struct WhereClause { /// A single predicate in a `where` clause #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum WherePredicate { - /// A type binding, e.g. `for<'c> Foo: Send+Clone+'c` + /// A type binding (e.g., `for<'c> Foo: Send + Clone + 'c`). BoundPredicate(WhereBoundPredicate), - /// A lifetime predicate, e.g. `'a: 'b+'c` + /// A lifetime predicate (e.g., `'a: 'b + 'c`). RegionPredicate(WhereRegionPredicate), - /// An equality predicate (unsupported) + /// An equality predicate (unsupported). EqPredicate(WhereEqPredicate), } @@ -354,7 +354,7 @@ impl WherePredicate { /// A type bound. /// -/// E.g. `for<'c> Foo: Send+Clone+'c` +/// E.g., `for<'c> Foo: Send + Clone + 'c`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereBoundPredicate { pub span: Span, @@ -368,7 +368,7 @@ pub struct WhereBoundPredicate { /// A lifetime predicate. /// -/// E.g. `'a: 'b+'c` +/// E.g., `'a: 'b + 'c`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereRegionPredicate { pub span: Span, @@ -378,7 +378,7 @@ pub struct WhereRegionPredicate { /// An equality predicate (unsupported). /// -/// E.g. `T=int` +/// E.g., `T = int`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct WhereEqPredicate { pub id: NodeId, @@ -387,8 +387,8 @@ pub struct WhereEqPredicate { pub rhs_ty: P, } -/// The set of MetaItems that define the compilation environment of the crate, -/// used to drive conditional compilation +/// The set of `MetaItem`s that define the compilation environment of the crate, +/// used to drive conditional compilation. pub type CrateConfig = FxHashSet<(Name, Option)>; #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] @@ -403,20 +403,20 @@ pub type NestedMetaItem = Spanned; /// Possible values inside of compile-time attribute lists. /// -/// E.g. the '..' in `#[name(..)]`. +/// E.g., the '..' in `#[name(..)]`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum NestedMetaItemKind { /// A full MetaItem, for recursive meta items. MetaItem(MetaItem), /// A literal. /// - /// E.g. "foo", 64, true + /// E.g., `"foo"`, `64`, `true`. Literal(Lit), } /// A spanned compile-time attribute item. /// -/// E.g. `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]` +/// E.g., `#[test]`, `#[derive(..)]`, `#[rustfmt::skip]` or `#[feature = "foo"]`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct MetaItem { pub ident: Path, @@ -426,26 +426,26 @@ pub struct MetaItem { /// A compile-time attribute item. /// -/// E.g. `#[test]`, `#[derive(..)]` or `#[feature = "foo"]` +/// E.g., `#[test]`, `#[derive(..)]` or `#[feature = "foo"]`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum MetaItemKind { /// Word meta item. /// - /// E.g. `test` as in `#[test]` + /// E.g., `test` as in `#[test]`. Word, /// List meta item. /// - /// E.g. `derive(..)` as in `#[derive(..)]` + /// E.g., `derive(..)` as in `#[derive(..)]`. List(Vec), /// Name value meta item. /// - /// E.g. `feature = "foo"` as in `#[feature = "foo"]` + /// E.g., `feature = "foo"` as in `#[feature = "foo"]`. NameValue(Lit), } /// A Block (`{ .. }`). /// -/// E.g. `{ .. }` as in `fn foo() { .. }` +/// E.g., `{ .. }` as in `fn foo() { .. }`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Block { /// Statements in a block @@ -568,7 +568,7 @@ pub enum RangeSyntax { #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum PatKind { - /// Represents a wildcard pattern (`_`) + /// Represents a wildcard pattern (`_`). Wild, /// A `PatKind::Ident` may either be a new bound variable (`ref mut binding @ OPT_SUBPATTERN`), @@ -577,13 +577,13 @@ pub enum PatKind { /// during name resolution. Ident(BindingMode, Ident, Option>), - /// A struct or struct variant pattern, e.g. `Variant {x, y, ..}`. + /// A struct or struct variant pattern (e.g., `Variant {x, y, ..}`). /// The `bool` is `true` in the presence of a `..`. Struct(Path, Vec>, bool), - /// A tuple struct/variant pattern `Variant(x, y, .., z)`. + /// A tuple struct/variant pattern (`Variant(x, y, .., z)`). /// If the `..` pattern fragment is present, then `Option` denotes its position. - /// 0 <= position <= subpats.len() + /// `0 <= position <= subpats.len()`. TupleStruct(Path, Vec>, Option), /// A possibly qualified path pattern. @@ -592,24 +592,24 @@ pub enum PatKind { /// only legally refer to associated constants. Path(Option, Path), - /// A tuple pattern `(a, b)`. + /// A tuple pattern (`(a, b)`). /// If the `..` pattern fragment is present, then `Option` denotes its position. - /// 0 <= position <= subpats.len() + /// `0 <= position <= subpats.len()`. Tuple(Vec>, Option), - /// A `box` pattern + /// A `box` pattern. Box(P), - /// A reference pattern, e.g. `&mut (a, b)` + /// A reference pattern (e.g., `&mut (a, b)`). Ref(P, Mutability), - /// A literal + /// A literal. Lit(P), - /// A range pattern, e.g. `1...2`, `1..=2` or `1..2` + /// A range pattern (e.g., `1...2`, `1..=2` or `1..2`). Range(P, P, Spanned), /// `[a, b, ..i, y, z]` is represented as: /// `PatKind::Slice(box [a, b], Some(i), box [y, z])` Slice(Vec>, Option>, Vec>), - /// Parentheses in patterns used for grouping, i.e. `(PAT)`. + /// Parentheses in patterns used for grouping (i.e., `(PAT)`). Paren(P), - /// A macro pattern; pre-expansion + /// A macro pattern; pre-expansion. Mac(Mac), } @@ -807,23 +807,23 @@ pub enum StmtKind { #[derive(Clone, Copy, PartialEq, RustcEncodable, RustcDecodable, Debug)] pub enum MacStmtStyle { - /// The macro statement had a trailing semicolon, e.g. `foo! { ... };` - /// `foo!(...);`, `foo![...];` + /// The macro statement had a trailing semicolon (e.g., `foo! { ... };` + /// `foo!(...);`, `foo![...];`). Semicolon, - /// The macro statement had braces; e.g. foo! { ... } + /// The macro statement had braces (e.g., `foo! { ... }`). Braces, - /// The macro statement had parentheses or brackets and no semicolon; e.g. - /// `foo!(...)`. All of these will end up being converted into macro + /// The macro statement had parentheses or brackets and no semicolon (e.g., + /// `foo!(...)`). All of these will end up being converted into macro /// expressions. NoBraces, } -/// Local represents a `let` statement, e.g., `let : = ;` +/// Local represents a `let` statement, e.g., `let : = ;`. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct Local { pub pat: P, pub ty: Option>, - /// Initializer expression to set the value, if any + /// Initializer expression to set the value, if any. pub init: Option>, pub id: NodeId, pub span: Span, @@ -832,7 +832,7 @@ 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 { @@ -878,8 +878,8 @@ pub enum UnsafeSource { /// A constant (expression) that's not an item or associated item, /// but needs its own `DefId` for type-checking, const-eval, etc. -/// These are usually found nested inside types (e.g. array lengths) -/// or expressions (e.g. repeat counts), and also used to define +/// These are usually found nested inside types (e.g., array lengths) +/// or expressions (e.g., repeat counts), and also used to define /// explicit discriminant values for enum variants. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub struct AnonConst { @@ -901,7 +901,7 @@ pub struct Expr { static_assert!(MEM_SIZE_OF_EXPR: std::mem::size_of::() == 88); impl Expr { - /// Whether 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 { @@ -1049,24 +1049,24 @@ pub enum ExprKind { /// /// The `PathSegment` represents the method name and its generic arguments /// (within the angle brackets). - /// The first element of the vector of `Expr`s is the expression that evaluates + /// The first element of the vector of an `Expr` is the expression that evaluates /// to the object on which the method is being called on (the receiver), /// and the remaining elements are the rest of the arguments. /// Thus, `x.foo::(a, b, c, d)` is represented as /// `ExprKind::MethodCall(PathSegment { foo, [Bar, Baz] }, [x, a, b, c, d])`. MethodCall(PathSegment, Vec>), - /// A tuple (`(a, b, c ,d)`) + /// A tuple (e.g., `(a, b, c, d)`). Tup(Vec>), - /// A binary operation (For example: `a + b`, `a * b`) + /// A binary operation (e.g., `a + b`, `a * b`). Binary(BinOp, P, P), - /// A unary operation (For example: `!x`, `*x`) + /// A unary operation (e.g., `!x`, `*x`). Unary(UnOp, P), - /// A literal (For example: `1`, `"foo"`) + /// A literal (e.g., `1`, `"foo"`). Lit(Lit), - /// A cast (`foo as f64`) + /// A cast (e.g., `foo as f64`). Cast(P, P), Type(P, P), - /// An `if` block, with an optional else block + /// An `if` block, with an optional `else` block. /// /// `if expr { block } else { expr }` If(P, P, Option>), @@ -1080,31 +1080,31 @@ pub enum ExprKind { /// /// `'label: while expr { block }` While(P, P, Option
, D }` + /// E.g., `enum Foo { C, D }`. Enum(EnumDef, Generics), /// A struct definition (`struct` or `pub struct`). /// - /// E.g. `struct Foo { x: A }` + /// E.g., `struct Foo { x: A }`. Struct(VariantData, Generics), /// A union definition (`union` or `pub union`). /// - /// E.g. `union Foo { x: A, y: B }` + /// E.g., `union Foo { x: A, y: B }`. Union(VariantData, Generics), /// A Trait declaration (`trait` or `pub trait`). /// - /// E.g. `trait Foo { .. }`, `trait Foo { .. }` or `auto trait Foo {}` + /// E.g., `trait Foo { .. }`, `trait Foo { .. }` or `auto trait Foo {}`. Trait(IsAuto, Unsafety, Generics, GenericBounds, Vec), /// Trait alias /// - /// E.g. `trait Foo = Bar + Quux;` + /// E.g., `trait Foo = Bar + Quux;`. TraitAlias(Generics, GenericBounds), /// An implementation. /// - /// E.g. `impl Foo { .. }` or `impl Trait for Foo { .. }` + /// E.g., `impl Foo { .. }` or `impl Trait for Foo { .. }`. Impl( Unsafety, ImplPolarity, @@ -2242,7 +2241,7 @@ pub enum ItemKind { ), /// A macro invocation. /// - /// E.g. `macro_rules! foo { .. }` or `foo!(..)` + /// E.g., `macro_rules! foo { .. }` or `foo!(..)`. Mac(Mac), /// A macro definition. @@ -2282,17 +2281,17 @@ pub struct ForeignItem { pub vis: Visibility, } -/// An item within an `extern` block +/// An item within an `extern` block. #[derive(Clone, RustcEncodable, RustcDecodable, Debug)] pub enum ForeignItemKind { - /// A foreign function + /// A foreign function. Fn(P, Generics), - /// A foreign static item (`static ext: u8`), with optional mutability - /// (the boolean is true when mutable) + /// A foreign static item (`static ext: u8`), with optional mutability. + /// (The boolean is `true` for mutable items). Static(P, bool), - /// A foreign type + /// A foreign type. Ty, - /// A macro invocation + /// A macro invocation. Macro(Mac), } @@ -2312,7 +2311,7 @@ mod tests { use super::*; use serialize; - // are ASTs encodable? + // Are ASTs encodable? #[test] fn check_asts_encodable() { fn assert_encodable() {} diff --git a/src/libsyntax/attr/mod.rs b/src/libsyntax/attr/mod.rs index 518b34eefa8..7e8384bec68 100644 --- a/src/libsyntax/attr/mod.rs +++ b/src/libsyntax/attr/mod.rs @@ -96,7 +96,7 @@ impl NestedMetaItem { self.meta_item().map_or(false, |meta_item| meta_item.check_name(name)) } - /// Returns the name of the meta item, e.g. `foo` in `#[foo]`, + /// Returns the name of the meta item, e.g., `foo` in `#[foo]`, /// `#[foo="bar"]` and `#[foo(bar)]`, if self is a MetaItem pub fn name(&self) -> Option { self.meta_item().and_then(|meta_item| Some(meta_item.name())) @@ -180,7 +180,7 @@ impl Attribute { } /// Returns the **last** segment of the name of this attribute. - /// E.g. `foo` for `#[foo]`, `skip` for `#[rustfmt::skip]`. + /// e.g., `foo` for `#[foo]`, `skip` for `#[rustfmt::skip]`. pub fn name(&self) -> Name { name_from_path(&self.path) } diff --git a/src/libsyntax/config.rs b/src/libsyntax/config.rs index d8fb20d4250..41307175ade 100644 --- a/src/libsyntax/config.rs +++ b/src/libsyntax/config.rs @@ -328,7 +328,7 @@ impl<'a> StripUnconfigured<'a> { // Anything else is always required, and thus has to error out // in case of a cfg attr. // - // NB: This is intentionally not part of the fold_expr() function + // N.B., this is intentionally not part of the fold_expr() function // in order for fold_opt_expr() to be able to avoid this check if let Some(attr) = expr.attrs().iter().find(|a| is_cfg(a)) { let msg = "removing an expression is not supported in this position"; @@ -421,7 +421,7 @@ impl<'a> fold::Folder for StripUnconfigured<'a> { } fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac { - // Don't configure interpolated AST (c.f. #34171). + // Don't configure interpolated AST (cf. issue #34171). // Interpolated AST will get configured once the surrounding tokens are parsed. mac } diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index b898696d349..310cf27689b 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -670,7 +670,7 @@ pub enum SyntaxExtension { /// An attribute-like procedural macro that derives a builtin trait. BuiltinDerive(BuiltinDeriveFn), - /// A declarative macro, e.g. `macro m() {}`. + /// A declarative macro, e.g., `macro m() {}`. DeclMacro { expander: Box, def_info: Option<(ast::NodeId, Span)>, @@ -908,7 +908,7 @@ impl<'a> ExtCtxt<'a> { /// `span_err` should be strongly preferred where-ever possible: /// this should *only* be used when: /// - /// - continuing has a high risk of flow-on errors (e.g. errors in + /// - continuing has a high risk of flow-on errors (e.g., errors in /// declaring a macro would cause all uses of that macro to /// complain about "undefined macro"), or /// - there is literally nothing else that can be done (however, @@ -995,7 +995,7 @@ pub fn expr_to_spanned_string<'a>( expr }); - // we want to be able to handle e.g. `concat!("foo", "bar")` + // we want to be able to handle e.g., `concat!("foo", "bar")` let expr = cx.expander().fold_expr(expr); Err(match expr.node { ast::ExprKind::Lit(ref l) => match l.node { diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 14f19c493b3..0244e1428e4 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -1351,7 +1351,7 @@ impl<'a, 'b> Folder for InvocationCollector<'a, 'b> { module.mod_path.push(item.ident); // Detect if this is an inline module (`mod m { ... }` as opposed to `mod m;`). - // In the non-inline case, `inner` is never the dummy span (c.f. `parse_item_mod`). + // In the non-inline case, `inner` is never the dummy span (cf. `parse_item_mod`). // Thus, if `inner` is the dummy span, we know the module is inline. let inline_module = item.span.contains(inner) || inner.is_dummy(); diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 68d94b43dba..26348d5ec82 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -214,10 +214,10 @@ struct MatcherPos<'root, 'tt: 'root> { up: Option>, /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from - /// a delimited token tree (e.g. something wrapped in `(` `)`) or to get the contents of a doc + /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc /// comment... /// - /// When matching against matchers with nested delimited submatchers (e.g. `pat ( pat ( .. ) + /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. ) /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does /// that where the bottom of the stack is the outermost matcher. /// Also, throughout the comments, this "descent" is often referred to as "unzipping"... @@ -373,7 +373,7 @@ fn nameize>( ms: &[TokenTree], mut res: I, ) -> NamedParseResult { - // Recursively descend into each type of matcher (e.g. sequences, delimited, metavars) and make + // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make // sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one // binding, then there is an error. If it does, then we insert the binding into the // `NamedParseResult`. @@ -895,7 +895,7 @@ fn may_begin_with(name: &str, token: &Token) -> bool { /// /// - `p`: the "black-box" parser to use /// - `sp`: the `Span` we want to parse -/// - `name`: the name of the metavar _matcher_ we want to match (e.g. `tt`, `ident`, `block`, +/// - `name`: the name of the metavar _matcher_ we want to match (e.g., `tt`, `ident`, `block`, /// etc...) /// /// # Returns diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index ff622b0c18f..30322ff523d 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -77,9 +77,9 @@ impl<'a> ParserAnyMacro<'a> { e })); - // We allow semicolons at the end of expressions -- e.g. the semicolon in + // We allow semicolons at the end of expressions -- e.g., the semicolon in // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`, - // but `m!()` is allowed in expression positions (c.f. issue #34706). + // but `m!()` is allowed in expression positions (cf. issue #34706). if kind == AstFragmentKind::Expr && parser.token == token::Semi { parser.bump(); } @@ -482,15 +482,15 @@ fn check_matcher(sess: &ParseSess, err == sess.span_diagnostic.err_count() } -// The FirstSets for a matcher is a mapping from subsequences in the +// `The FirstSets` for a matcher is a mapping from subsequences in the // matcher to the FIRST set for that subsequence. // // This mapping is partially precomputed via a backwards scan over the // token trees of the matcher, which provides a mapping from each -// repetition sequence to its FIRST set. +// repetition sequence to its *first* set. // -// (Hypothetically sequences should be uniquely identifiable via their -// spans, though perhaps that is false e.g. for macro-generated macros +// (Hypothetically, sequences should be uniquely identifiable via their +// spans, though perhaps that is false, e.g., for macro-generated macros // that do not try to inject artificial span information. My plan is // to try to catch such cases ahead of time and not include them in // the precomputed mapping.) diff --git a/src/libsyntax/ext/tt/quoted.rs b/src/libsyntax/ext/tt/quoted.rs index a7415e845ca..1dab0297854 100644 --- a/src/libsyntax/ext/tt/quoted.rs +++ b/src/libsyntax/ext/tt/quoted.rs @@ -93,9 +93,9 @@ pub enum TokenTree { Delimited(DelimSpan, Lrc), /// A kleene-style repetition sequence Sequence(DelimSpan, Lrc), - /// E.g. `$var` + /// e.g., `$var` MetaVar(Span, ast::Ident), - /// E.g. `$var:expr`. This is only used in the left hand side of MBE macros. + /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros. MetaVarDecl( Span, ast::Ident, /* name to bind */ @@ -199,7 +199,7 @@ pub fn parse( let mut trees = input.trees().peekable(); while let Some(tree) = trees.next() { // Given the parsed tree, if there is a metavar and we are expecting matchers, actually - // parse out the matcher (i.e. in `$id:ident` this would parse the `:` and `ident`). + // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`). let tree = parse_tree( tree, &mut trees, @@ -280,7 +280,7 @@ where // `tree` is a `$` token. Look at the next token in `trees` tokenstream::TokenTree::Token(span, token::Dollar) => match trees.next() { // `tree` is followed by a delimited set of token trees. This indicates the beginning - // of a repetition sequence in the macro (e.g. `$(pat)*`). + // of a repetition sequence in the macro (e.g., `$(pat)*`). Some(tokenstream::TokenTree::Delimited(span, delimited)) => { // Must have `(` not `{` or `[` if delimited.delim != token::Paren { @@ -309,7 +309,7 @@ where edition, macro_node_id, ); - // Count the number of captured "names" (i.e. named metavars) + // Count the number of captured "names" (i.e., named metavars) let name_captures = macro_parser::count_names(&sequence); TokenTree::Sequence( span, @@ -352,7 +352,7 @@ where // `tree` is an arbitrary token. Keep it. tokenstream::TokenTree::Token(span, tok) => TokenTree::Token(span, tok), - // `tree` is the beginning of a delimited set of tokens (e.g. `(` or `{`). We need to + // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to // descend into the delimited set and further parse it. tokenstream::TokenTree::Delimited(span, delimited) => TokenTree::Delimited( span, diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 1aea31348a7..e038f4dc677 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Feature gating +//! # Feature gating //! //! This module implements the gating necessary for preventing certain compiler //! features from being used by default. This module will crawl a pre-expanded @@ -105,7 +105,7 @@ macro_rules! declare_features { } } -// If you change this, please modify src/doc/unstable-book as well. +// If you change this, please modify `src/doc/unstable-book` as well. // // Don't ever remove anything from this list; set them to 'Removed'. // @@ -113,7 +113,7 @@ macro_rules! declare_features { // was set. This is most important for knowing when a particular feature became // stable (active). // -// NB: tools/tidy/src/features.rs parses this information directly out of the +// N.B., `tools/tidy/src/features.rs` parses this information directly out of the // source, so take care when modifying it. declare_features! ( @@ -152,62 +152,61 @@ declare_features! ( (active, panic_runtime, "1.10.0", Some(32837), None), (active, needs_panic_runtime, "1.10.0", Some(32837), None), - // OIBIT specific features + // Features specific to OIBIT (auto traits) (active, optin_builtin_traits, "1.0.0", Some(13231), None), - // Allows use of #[staged_api] + // Allows `#[staged_api]`. // // rustc internal (active, staged_api, "1.0.0", None, None), - // Allows using #![no_core] + // Allows `#![no_core]`. (active, no_core, "1.3.0", Some(29639), None), - // Allows using `box` in patterns; RFC 469 + // Allows the use of `box` in patterns (RFC 469). (active, box_patterns, "1.0.0", Some(29641), None), - // Allows using the unsafe_destructor_blind_to_params attribute; - // RFC 1238 + // Allows the use of the `unsafe_destructor_blind_to_params` attribute (RFC 1238). (active, dropck_parametricity, "1.3.0", Some(28498), None), - // Allows using the may_dangle attribute; RFC 1327 + // Allows using the `may_dangle` attribute (RFC 1327). (active, dropck_eyepatch, "1.10.0", Some(34761), None), - // Allows the use of custom attributes; RFC 572 + // Allows the use of custom attributes (RFC 572). (active, custom_attribute, "1.0.0", Some(29642), None), - // Allows the use of rustc_* attributes; RFC 572 + // Allows the use of `rustc_*` attributes (RFC 572). (active, rustc_attrs, "1.0.0", Some(29642), None), - // Allows the use of non lexical lifetimes; RFC 2094 + // Allows the use of non lexical lifetimes (RFC 2094). (active, nll, "1.0.0", Some(43234), None), - // Allows the use of #[allow_internal_unstable]. This is an - // attribute on macro_rules! and can't use the attribute handling + // Allows the use of `#[allow_internal_unstable]`. This is an + // attribute on `macro_rules!` and can't use the attribute handling // below (it has to be checked before expansion possibly makes // macros disappear). // // rustc internal (active, allow_internal_unstable, "1.0.0", None, None), - // Allows the use of #[allow_internal_unsafe]. This is an - // attribute on macro_rules! and can't use the attribute handling + // Allows the use of `#[allow_internal_unsafe]`. This is an + // attribute on `macro_rules!` and can't use the attribute handling // below (it has to be checked before expansion possibly makes // macros disappear). // // rustc internal (active, allow_internal_unsafe, "1.0.0", None, None), - // #23121. Array patterns have some hazards yet. + // Allows the use of slice patterns (RFC 23121). (active, slice_patterns, "1.0.0", Some(23121), None), - // Allows the definition of `const fn` functions with some advanced features. + // Allows the definition of `const` functions with some advanced features. (active, const_fn, "1.2.0", Some(24111), None), - // Allows let bindings and destructuring in `const fn` functions and constants. + // Allows let bindings and destructuring in `const` functions and constants. (active, const_let, "1.22.1", Some(48821), None), - // Allows accessing fields of unions inside const fn. + // Allows accessing fields of unions inside `const` functions. (active, const_fn_union, "1.27.0", Some(51909), None), // Allows casting raw pointers to `usize` during const eval. @@ -222,10 +221,10 @@ declare_features! ( // Allows comparing raw pointers during const eval. (active, const_compare_raw_pointers, "1.27.0", Some(53020), None), - // Allows panicking during const eval (produces compile-time errors) + // Allows panicking during const eval (producing compile-time errors). (active, const_panic, "1.30.0", Some(51999), None), - // Allows using #[prelude_import] on glob `use` items. + // Allows using `#[prelude_import]` on glob `use` items. // // rustc internal (active, prelude_import, "1.2.0", None, None), @@ -233,117 +232,121 @@ declare_features! ( // Allows default type parameters to influence type inference. (active, default_type_parameter_fallback, "1.3.0", Some(27336), None), - // Allows associated type defaults + // Allows associated type defaults. (active, associated_type_defaults, "1.2.0", Some(29661), None), - // Allows `repr(simd)`, and importing the various simd intrinsics + // Allows `repr(simd)` and importing the various simd intrinsics. (active, repr_simd, "1.4.0", Some(27731), None), - // Allows `extern "platform-intrinsic" { ... }` + // Allows `extern "platform-intrinsic" { ... }`. (active, platform_intrinsics, "1.4.0", Some(27731), None), - // Allows `#[unwind(..)]` + // Allows `#[unwind(..)]`. + // // rustc internal for rust runtime (active, unwind_attributes, "1.4.0", None, None), // Allows the use of `#[naked]` on functions. (active, naked_functions, "1.9.0", Some(32408), None), - // Allows `#[no_debug]` + // Allows `#[no_debug]`. (active, no_debug, "1.5.0", Some(29721), None), - // Allows `#[omit_gdb_pretty_printer_section]` + // Allows `#[omit_gdb_pretty_printer_section]`. // // rustc internal (active, omit_gdb_pretty_printer_section, "1.5.0", None, None), - // Allows cfg(target_vendor = "..."). + // Allows `cfg(target_vendor = "...")`. (active, cfg_target_vendor, "1.5.0", Some(29718), None), - // Allow attributes on expressions and non-item statements + // Allows attributes on expressions and non-item statements. (active, stmt_expr_attributes, "1.6.0", Some(15701), None), - // allow using type ascription in expressions + // Allows the use of type ascription in expressions. (active, type_ascription, "1.6.0", Some(23416), None), - // Allows cfg(target_thread_local) + // Allows `cfg(target_thread_local)`. (active, cfg_target_thread_local, "1.7.0", Some(29594), None), // rustc internal (active, abi_vectorcall, "1.7.0", None, None), - // X..Y patterns + // Allows `X..Y` patterns. (active, exclusive_range_pattern, "1.11.0", Some(37854), None), // impl specialization (RFC 1210) (active, specialization, "1.7.0", Some(31844), None), - // Allows cfg(target_has_atomic = "..."). + // Allows `cfg(target_has_atomic = "...")`. (active, cfg_target_has_atomic, "1.9.0", Some(32976), None), - // The `!` type. Does not imply exhaustive_patterns (below) any more. + // The `!` type. Does not imply 'exhaustive_patterns' (below) any more. (active, never_type, "1.13.0", Some(35121), None), - // Allows exhaustive pattern matching on types that contain uninhabited types + // Allows exhaustive pattern matching on types that contain uninhabited types. (active, exhaustive_patterns, "1.13.0", Some(51085), None), - // Allows untagged unions `union U { ... }` + // Allows untagged unions `union U { ... }`. (active, untagged_unions, "1.13.0", Some(32836), None), - // Used to identify the `compiler_builtins` crate - // rustc internal + // Used to identify the `compiler_builtins` crate. + // + // rustc internal. (active, compiler_builtins, "1.13.0", None, None), - // Allows #[link(..., cfg(..))] + // Allows `#[link(..., cfg(..))]`. (active, link_cfg, "1.14.0", Some(37406), None), - // `extern "ptx-*" fn()` + // Allows `extern "ptx-*" fn()`. (active, abi_ptx, "1.15.0", Some(38788), None), - // The `repr(i128)` annotation for enums + // The `repr(i128)` annotation for enums. (active, repr128, "1.16.0", Some(35118), None), - // The `unadjusted` ABI. Perma unstable. + // The `unadjusted` ABI; perma-unstable. + // // rustc internal (active, abi_unadjusted, "1.16.0", None, None), // Declarative macros 2.0 (`macro`). (active, decl_macro, "1.17.0", Some(39412), None), - // Allows #[link(kind="static-nobundle"...)] + // Allows `#[link(kind="static-nobundle"...)]`. (active, static_nobundle, "1.16.0", Some(37403), None), - // `extern "msp430-interrupt" fn()` + // Allows `extern "msp430-interrupt" fn()`. (active, abi_msp430_interrupt, "1.16.0", Some(38487), None), - // Used to identify crates that contain sanitizer runtimes + // Used to identify crates that contain sanitizer runtimes. + // // rustc internal (active, sanitizer_runtime, "1.17.0", None, None), - // Used to identify crates that contain the profiler runtime + // Used to identify crates that contain the profiler runtime. // // rustc internal (active, profiler_runtime, "1.18.0", None, None), - // `extern "x86-interrupt" fn()` + // Allows `extern "x86-interrupt" fn()`. (active, abi_x86_interrupt, "1.17.0", Some(40180), None), - // Allows the `try {...}` expression + // Allows the `try {...}` expression. (active, try_blocks, "1.29.0", Some(31436), None), - // Allows module-level inline assembly by way of global_asm!() + // Allows module-level inline assembly by way of `global_asm!()`. (active, global_asm, "1.18.0", Some(35119), None), - // Allows overlapping impls of marker traits + // Allows overlapping impls of marker traits. (active, overlapping_marker_traits, "1.18.0", Some(29864), None), - // Trait attribute to allow overlapping impls + // Trait attribute to allow overlapping impls. (active, marker_trait_attr, "1.30.0", Some(29864), None), // rustc internal (active, abi_thiscall, "1.19.0", None, None), - // Allows a test to fail without failing the whole suite + // Allows a test to fail without failing the whole suite. (active, allow_fail, "1.19.0", Some(46488), None), // Allows unsized tuple coercion. @@ -358,28 +361,28 @@ declare_features! ( // rustc internal (active, allocator_internals, "1.20.0", None, None), - // #[doc(cfg(...))] + // `#[doc(cfg(...))]` (active, doc_cfg, "1.21.0", Some(43781), None), - // #[doc(masked)] + // `#[doc(masked)]` (active, doc_masked, "1.21.0", Some(44027), None), - // #[doc(spotlight)] + // `#[doc(spotlight)]` (active, doc_spotlight, "1.22.0", Some(45040), None), - // #[doc(include="some-file")] + // `#[doc(include = "some-file")]` (active, external_doc, "1.22.0", Some(44732), None), - // Future-proofing enums/structs with #[non_exhaustive] attribute (RFC 2008) + // Future-proofing enums/structs with `#[non_exhaustive]` attribute (RFC 2008). (active, non_exhaustive, "1.22.0", Some(44109), None), - // `crate` as visibility modifier, synonymous to `pub(crate)` + // Adds `crate` as visibility modifier, synonymous with `pub(crate)`. (active, crate_visibility_modifier, "1.23.0", Some(53120), None), // extern types (active, extern_types, "1.23.0", Some(43467), None), - // Allows trait methods with arbitrary self types + // Allows trait methods with arbitrary self types. (active, arbitrary_self_types, "1.23.0", Some(44874), None), - // In-band lifetime bindings (e.g. `fn foo(x: &'a u8) -> &'a u8`) + // In-band lifetime bindings (e.g., `fn foo(x: &'a u8) -> &'a u8`). (active, in_band_lifetimes, "1.23.0", Some(44524), None), // Generic associated types (RFC 1598) @@ -388,25 +391,25 @@ declare_features! ( // `extern` in paths (active, extern_in_paths, "1.23.0", Some(55600), None), - // Infer static outlives requirements; RFC 2093 + // Infer static outlives requirements (RFC 2093). (active, infer_static_outlives_requirements, "1.26.0", Some(54185), None), - // Multiple patterns with `|` in `if let` and `while let` + // Multiple patterns with `|` in `if let` and `while let`. (active, if_while_or_patterns, "1.26.0", Some(48215), None), - // Allows `#[repr(packed)]` attribute on structs + // Allows `#[repr(packed)]` attribute on structs. (active, repr_packed, "1.26.0", Some(33158), None), - // `use path as _;` and `extern crate c as _;` + // Allows `use path as _;` and `extern crate c as _;`. (active, underscore_imports, "1.26.0", Some(48216), None), - // Allows macro invocations in `extern {}` blocks + // Allows macro invocations in `extern {}` blocks. (active, macros_in_extern, "1.27.0", Some(49476), None), // `existential type` (active, existential_type, "1.28.0", Some(34511), None), - // unstable #[target_feature] directives + // unstable `#[target_feature]` directives (active, arm_target_feature, "1.27.0", Some(44839), None), (active, aarch64_target_feature, "1.27.0", Some(44839), None), (active, hexagon_target_feature, "1.27.0", Some(44839), None), @@ -422,64 +425,64 @@ declare_features! ( // procedural macros to expand to non-items. (active, proc_macro_hygiene, "1.30.0", Some(54727), None), - // #[doc(alias = "...")] + // `#[doc(alias = "...")]` (active, doc_alias, "1.27.0", Some(50146), None), - // Allows irrefutable patterns in if-let and while-let statements (RFC 2086) + // Allows irrefutable patterns in `if let` and `while let` statements (RFC 2086). (active, irrefutable_let_patterns, "1.27.0", Some(44495), None), // inconsistent bounds in where clauses (active, trivial_bounds, "1.28.0", Some(48214), None), - // 'a: { break 'a; } + // `'a: { break 'a; }` (active, label_break_value, "1.28.0", Some(48594), None), // Exhaustive pattern matching on `usize` and `isize`. (active, precise_pointer_size_matching, "1.32.0", Some(56354), None), - // #[doc(keyword = "...")] + // `#[doc(keyword = "...")]` (active, doc_keyword, "1.28.0", Some(51315), None), - // Allows async and await syntax + // Allows async and await syntax. (active, async_await, "1.28.0", Some(50547), None), - // #[alloc_error_handler] + // `#[alloc_error_handler]` (active, alloc_error_handler, "1.29.0", Some(51540), None), (active, abi_amdgpu_kernel, "1.29.0", Some(51575), None), - // Perma-unstable; added for testing E0705 + // Added for testing E0705; perma-unstable. (active, test_2018_feature, "1.31.0", Some(0), Some(Edition::Edition2018)), - // Support for arbitrary delimited token streams in non-macro attributes + // support for arbitrary delimited token streams in non-macro attributes (active, unrestricted_attribute_tokens, "1.30.0", Some(55208), None), - // Allows `use x::y;` to resolve through `self::x`, not just `::x` + // Allows `use x::y;` to resolve through `self::x`, not just `::x`. (active, uniform_paths, "1.30.0", Some(53130), None), - // Allows unsized rvalues at arguments and parameters + // Allows unsized rvalues at arguments and parameters. (active, unsized_locals, "1.30.0", Some(48055), None), - // #![test_runner] - // #[test_case] + // `#![test_runner]` + // `#[test_case]` (active, custom_test_frameworks, "1.30.0", Some(50297), None), - // Non-builtin attributes in inner attribute position + // non-builtin attributes in inner attribute position (active, custom_inner_attributes, "1.30.0", Some(54726), None), - // allow mixing of bind-by-move in patterns and references to + // Allow mixing of bind-by-move in patterns and references to // those identifiers in guards, *if* we are using MIR-borrowck - // (aka NLL). Essentially this means you need to be on - // edition:2018 or later. + // (aka NLL). Essentially this means you need to be using the + // 2018 edition or later. (active, bind_by_move_pattern_guards, "1.30.0", Some(15287), None), - // Allows `impl Trait` in bindings (`let`, `const`, `static`) + // Allows `impl Trait` in bindings (`let`, `const`, `static`). (active, impl_trait_in_bindings, "1.30.0", Some(34511), None), - // #[cfg_attr(predicate, multiple, attributes, here)] + // `#[cfg_attr(predicate, multiple, attributes, here)]` (active, cfg_attr_multi, "1.31.0", Some(54881), None), - // Allows `const _: TYPE = VALUE` + // Allows `const _: TYPE = VALUE`. (active, underscore_const_names, "1.31.0", Some(54912), None), // `reason = ` in lint attributes and `expect` lint attribute @@ -495,7 +498,7 @@ declare_features! ( declare_features! ( (removed, import_shadowing, "1.0.0", None, None, None), (removed, managed_boxes, "1.0.0", None, None, None), - // Allows use of unary negate on unsigned integers, e.g. -e for e: u8 + // Allows use of unary negate on unsigned integers, e.g., -e for e: u8 (removed, negate_unsigned, "1.0.0", Some(29645), None, None), (removed, reflect, "1.0.0", Some(27749), None, None), // A way to temporarily opt out of opt in copy. This will *never* be accepted. @@ -537,9 +540,9 @@ declare_features! ( declare_features! ( (accepted, associated_types, "1.0.0", None, None), - // allow overloading augmented assignment operations like `a += b` + // Allows overloading augmented assignment operations like `a += b`. (accepted, augmented_assignments, "1.8.0", Some(28235), None), - // allow empty structs and enum variants with braces + // Allows empty structs and enum variants with braces. (accepted, braced_empty_structs, "1.8.0", Some(29720), None), // Allows indexing into constant arrays. (accepted, const_indexing, "1.26.0", Some(29947), None), @@ -550,69 +553,68 @@ declare_features! ( // to bootstrap fix for #5723. (accepted, issue_5723_bootstrap, "1.0.0", None, None), (accepted, macro_rules, "1.0.0", None, None), - // Allows using #![no_std] + // Allows using `#![no_std]`. (accepted, no_std, "1.6.0", None, None), (accepted, slicing_syntax, "1.0.0", None, None), (accepted, struct_variant, "1.0.0", None, None), // These are used to test this portion of the compiler, they don't actually - // mean anything + // mean anything. (accepted, test_accepted_feature, "1.0.0", None, None), (accepted, tuple_indexing, "1.0.0", None, None), // Allows macros to appear in the type position. (accepted, type_macros, "1.13.0", Some(27245), None), (accepted, while_let, "1.0.0", None, None), - // Allows `#[deprecated]` attribute + // Allows `#[deprecated]` attribute. (accepted, deprecated, "1.9.0", Some(29935), None), // `expr?` (accepted, question_mark, "1.13.0", Some(31436), None), - // Allows `..` in tuple (struct) patterns + // Allows `..` in tuple (struct) patterns. (accepted, dotdot_in_tuple_patterns, "1.14.0", Some(33627), None), (accepted, item_like_imports, "1.15.0", Some(35120), None), // Allows using `Self` and associated types in struct expressions and patterns. (accepted, more_struct_aliases, "1.16.0", Some(37544), None), - // elide `'static` lifetimes in `static`s and `const`s + // elide `'static` lifetimes in `static`s and `const`s. (accepted, static_in_const, "1.17.0", Some(35897), None), // Allows field shorthands (`x` meaning `x: x`) in struct literal expressions. (accepted, field_init_shorthand, "1.17.0", Some(37340), None), // Allows the definition recursive static items. (accepted, static_recursion, "1.17.0", Some(29719), None), - // pub(restricted) visibilities (RFC 1422) + // `pub(restricted)` visibilities (RFC 1422) (accepted, pub_restricted, "1.18.0", Some(32409), None), - // The #![windows_subsystem] attribute + // `#![windows_subsystem]` (accepted, windows_subsystem, "1.18.0", Some(37499), None), // Allows `break {expr}` with a value inside `loop`s. (accepted, loop_break_value, "1.19.0", Some(37339), None), // Permits numeric fields in struct expressions and patterns. (accepted, relaxed_adts, "1.19.0", Some(35626), None), - // Coerces non capturing closures to function pointers + // Coerces non capturing closures to function pointers. (accepted, closure_to_fn_coercion, "1.19.0", Some(39817), None), // Allows attributes on struct literal fields. (accepted, struct_field_attributes, "1.20.0", Some(38814), None), - // Allows the definition of associated constants in `trait` or `impl` - // blocks. + // Allows the definition of associated constants in `trait` or `impl` blocks. (accepted, associated_consts, "1.20.0", Some(29646), None), - // Usage of the `compile_error!` macro + // Usage of the `compile_error!` macro. (accepted, compile_error, "1.20.0", Some(40872), None), // See rust-lang/rfcs#1414. Allows code like `let x: &'static u32 = &42` to work. (accepted, rvalue_static_promotion, "1.21.0", Some(38865), None), - // Allow Drop types in constants (RFC 1440) + // Allows `Drop` types in constants (RFC 1440). (accepted, drop_types_in_const, "1.22.0", Some(33156), None), // Allows the sysV64 ABI to be specified on all platforms - // instead of just the platforms on which it is the C ABI + // instead of just the platforms on which it is the C ABI. (accepted, abi_sysv64, "1.24.0", Some(36167), None), - // Allows `repr(align(16))` struct attribute (RFC 1358) + // Allows `repr(align(16))` struct attribute (RFC 1358). (accepted, repr_align, "1.25.0", Some(33626), None), - // allow '|' at beginning of match arms (RFC 1925) + // Allows '|' at beginning of match arms (RFC 1925). (accepted, match_beginning_vert, "1.25.0", Some(44101), None), // Nested groups in `use` (RFC 2128) (accepted, use_nested_groups, "1.25.0", Some(44494), None), - // a..=b and ..=b + // `a..=b` and `..=b` (accepted, inclusive_range_syntax, "1.26.0", Some(28237), None), - // allow `..=` in patterns (RFC 1192) + // Allows `..=` in patterns (RFC 1192). (accepted, dotdoteq_in_patterns, "1.26.0", Some(28237), None), // Termination trait in main (RFC 1937) (accepted, termination_trait, "1.26.0", Some(43301), None), - // Copy/Clone closures (RFC 2132) + // `Copy`/`Clone` closures (RFC 2132). (accepted, clone_closures, "1.26.0", Some(44490), None), (accepted, copy_closures, "1.26.0", Some(44490), None), // Allows `impl Trait` in function arguments. @@ -623,70 +625,70 @@ declare_features! ( (accepted, i128_type, "1.26.0", Some(35118), None), // Default match binding modes (RFC 2005) (accepted, match_default_bindings, "1.26.0", Some(42640), None), - // allow `'_` placeholder lifetimes + // Allows `'_` placeholder lifetimes. (accepted, underscore_lifetimes, "1.26.0", Some(44524), None), - // Allows attributes on lifetime/type formal parameters in generics (RFC 1327) + // Allows attributes on lifetime/type formal parameters in generics (RFC 1327). (accepted, generic_param_attrs, "1.27.0", Some(48848), None), - // Allows cfg(target_feature = "..."). + // Allows `cfg(target_feature = "...")`. (accepted, cfg_target_feature, "1.27.0", Some(29717), None), - // Allows #[target_feature(...)] + // Allows `#[target_feature(...)]`. (accepted, target_feature, "1.27.0", None, None), // Trait object syntax with `dyn` prefix (accepted, dyn_trait, "1.27.0", Some(44662), None), - // allow `#[must_use]` on functions; and, must-use operators (RFC 1940) + // Allows `#[must_use]` on functions, and introduces must-use operators (RFC 1940). (accepted, fn_must_use, "1.27.0", Some(43302), None), - // Allows use of the :lifetime macro fragment specifier + // Allows use of the `:lifetime` macro fragment specifier. (accepted, macro_lifetime_matcher, "1.27.0", Some(34303), None), // Termination trait in tests (RFC 1937) (accepted, termination_trait_test, "1.27.0", Some(48854), None), - // The #[global_allocator] attribute + // The `#[global_allocator]` attribute (accepted, global_allocator, "1.28.0", Some(27389), None), - // Allows `#[repr(transparent)]` attribute on newtype structs + // Allows `#[repr(transparent)]` attribute on newtype structs. (accepted, repr_transparent, "1.28.0", Some(43036), None), - // Defining procedural macros in `proc-macro` crates + // Procedural macros in `proc-macro` crates (accepted, proc_macro, "1.29.0", Some(38356), None), // `foo.rs` as an alternative to `foo/mod.rs` (accepted, non_modrs_mods, "1.30.0", Some(44660), None), - // Allows use of the :vis macro fragment specifier + // Allows use of the `:vis` macro fragment specifier (accepted, macro_vis_matcher, "1.30.0", Some(41022), None), // Allows importing and reexporting macros with `use`, // enables macro modularization in general. (accepted, use_extern_macros, "1.30.0", Some(35896), None), - // Allows keywords to be escaped for use as identifiers + // Allows keywords to be escaped for use as identifiers. (accepted, raw_identifiers, "1.30.0", Some(48589), None), - // Attributes scoped to tools + // Attributes scoped to tools. (accepted, tool_attributes, "1.30.0", Some(44690), None), - // Allows multi-segment paths in attributes and derives + // Allows multi-segment paths in attributes and derives. (accepted, proc_macro_path_invoc, "1.30.0", Some(38356), None), // Allows all literals in attribute lists and values of key-value pairs. (accepted, attr_literals, "1.30.0", Some(34981), None), - // Infer outlives requirements; RFC 2093 + // Infer outlives requirements (RFC 2093). (accepted, infer_outlives_requirements, "1.30.0", Some(44493), None), (accepted, panic_handler, "1.30.0", Some(44489), None), - // Used to preserve symbols (see llvm.used) + // Used to preserve symbols (see llvm.used). (accepted, used, "1.30.0", Some(40289), None), // `crate` in paths (accepted, crate_in_paths, "1.30.0", Some(45477), None), - // Resolve absolute paths as paths from other crates + // Resolve absolute paths as paths from other crates. (accepted, extern_absolute_paths, "1.30.0", Some(44660), None), - // Access to crate names passed via `--extern` through prelude + // Access to crate names passed via `--extern` through prelude. (accepted, extern_prelude, "1.30.0", Some(44660), None), // Parentheses in patterns (accepted, pattern_parentheses, "1.31.0", Some(51087), None), - // Allows the definition of `const fn` functions + // Allows the definition of `const fn` functions. (accepted, min_const_fn, "1.31.0", Some(53555), None), // Scoped lints (accepted, tool_lints, "1.31.0", Some(44690), None), - // impl Iterator for &mut Iterator - // impl Debug for Foo<'_> + // `impl Iterator for &mut Iterator` + // `impl Debug for Foo<'_>` (accepted, impl_header_lifetime_elision, "1.31.0", Some(15872), None), - // `extern crate foo as bar;` puts `bar` into extern prelude + // `extern crate foo as bar;` puts `bar` into extern prelude. (accepted, extern_crate_item_prelude, "1.31.0", Some(55599), None), - // Allows use of the :literal macro fragment specifier (RFC 1576) + // Allows use of the `:literal` macro fragment specifier (RFC 1576). (accepted, macro_literal_matcher, "1.31.0", Some(35625), None), // Integer match exhaustiveness checking (RFC 2591) (accepted, exhaustive_integer_patterns, "1.32.0", Some(50907), None), - // Use `?` as the Kleene "at most one" operator + // Use `?` as the Kleene "at most one" operator. (accepted, macro_at_most_once_rep, "1.32.0", Some(48075), None), // `Self` struct constructor (RFC 2302) (accepted, self_struct_ctor, "1.32.0", Some(51994), None), @@ -1276,7 +1278,7 @@ impl<'a> Context<'a> { if attr.path == &**n { // Plugins can't gate attributes, so we don't check for it // unlike the code above; we only use this loop to - // short-circuit to avoid the checks below + // short-circuit to avoid the checks below. debug!("check_attribute: {:?} is registered by a plugin, {:?}", attr.path, ty); return; } @@ -1287,10 +1289,9 @@ impl<'a> Context<'a> { with the prefix `rustc_` \ are reserved for internal compiler diagnostics"); } else if !attr::is_known(attr) { - // Only run the custom attribute lint during regular - // feature gate checking. Macro gating runs - // before the plugin attributes are registered - // so we skip this then + // Only run the custom attribute lint during regular feature gate + // checking. Macro gating runs before the plugin attributes are + // registered, so we skip this in that case. if !is_macro { let msg = format!("The attribute `{}` is currently unknown to the compiler and \ may have meaning added to it in the future", attr.path); @@ -1788,14 +1789,13 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { _node_id: NodeId) { match fn_kind { FnKind::ItemFn(_, header, _, _) => { - // check for const fn and async fn declarations + // Check for const fn and async fn declarations. if header.asyncness.is_async() { gate_feature_post!(&self, async_await, span, "async fn is unstable"); } - // stability of const fn methods are covered in - // visit_trait_item and visit_impl_item below; this is - // because default methods don't pass through this - // point. + // Stability of const fn methods are covered in + // `visit_trait_item` and `visit_impl_item` below; this is + // because default methods don't pass through this point. self.check_abi(header.abi, span); } @@ -1872,7 +1872,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { fn visit_path(&mut self, path: &'a ast::Path, _id: NodeId) { for segment in &path.segments { - // Identifiers we are going to check could come from a legacy macro (e.g. `#[test]`). + // Identifiers we are going to check could come from a legacy macro (e.g., `#[test]`). // For such macros identifiers must have empty context, because this context is // used during name resolution and produced names must be unhygienic for compatibility. // On the other hand, we need the actual non-empty context for feature gate checking @@ -1919,7 +1919,7 @@ pub fn get_features(span_handler: &Handler, krate_attrs: &[ast::Attribute], for &edition in ALL_EDITIONS { if edition <= crate_edition { // The `crate_edition` implies its respective umbrella feature-gate - // (i.e. `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX). + // (i.e., `#![feature(rust_20XX_preview)]` isn't needed on edition 20XX). edition_enabled_features.insert(Symbol::intern(edition.feature_name()), edition); } } @@ -2079,7 +2079,7 @@ pub enum UnstableFeatures { impl UnstableFeatures { pub fn from_environment() -> UnstableFeatures { - // Whether this is a feature-staged build, i.e. on the beta or stable channel + // Whether this is a feature-staged build, i.e., on the beta or stable channel let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some(); // Whether we should enable unstable features for bootstrapping let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok(); diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 0e6e2f90693..82f52931cad 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -229,7 +229,7 @@ pub trait Folder : Sized { fn fold_mac(&mut self, _mac: Mac) -> Mac { panic!("fold_mac disabled by default"); - // NB: see note about macros above. + // N.B., see note about macros above. // if you really want a folder that // works on macros, use this // definition in your trait impl: @@ -637,7 +637,7 @@ pub fn noop_fold_token(t: token::Token, fld: &mut T) -> token::Token /// apply folder to elements of interpolated nodes // -// NB: this can occur only when applying a fold to partially expanded code, where +// N.B., this can occur only when applying a fold to partially expanded code, where // parsed pieces have gotten implanted ito *other* macro invocations. This is relevant // for macro hygiene, but possibly not elsewhere. // diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 3c66db082cc..0c24c20554a 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -134,7 +134,7 @@ pub mod diagnostics { pub mod metadata; } -// NB: This module needs to be declared first so diagnostics are +// N.B., this module needs to be declared first so diagnostics are // registered before they are used. pub mod diagnostic_list; diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 80227fdf82d..4be54e5bacc 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -1127,7 +1127,7 @@ impl<'a> StringReader<'a> { "expected at least one digit in exponent" ); if let Some(ch) = self.ch { - // check for e.g. Unicode minus '−' (Issue #49746) + // check for e.g., Unicode minus '−' (Issue #49746) if unicode_chars::check_for_substitution(self, ch, &mut err) { self.bump(); self.scan_digits(10, 10); diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index c7eaf4d1eee..9a9b615233b 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -92,12 +92,12 @@ pub enum PathStyle { /// `x` - comparisons, `x::` - unambiguously a path. Expr, /// In other contexts, notably in types, no ambiguity exists and paths can be written - /// without the disambiguator, e.g. `x` - unambiguously a path. + /// without the disambiguator, e.g., `x` - unambiguously a path. /// Paths with disambiguators are still accepted, `x::` - unambiguously a path too. Type, - /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports, + /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports, /// visibilities or attributes. - /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead + /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead /// (paths in "mod" contexts have to be checked later for absence of generic arguments /// anyway, due to macros), but it is used to avoid weird suggestions about expected /// tokens when something goes wrong. @@ -1917,7 +1917,7 @@ impl<'a> Parser<'a> { self.parse_arg_general(true) } - /// Parse an argument in a lambda header e.g. |arg, arg| + /// Parse an argument in a lambda header e.g., |arg, arg| fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> { let pat = self.parse_pat(Some("argument name"))?; let t = if self.eat(&token::Colon) { @@ -2334,7 +2334,7 @@ impl<'a> Parser<'a> { /// parse things like parenthesized exprs, /// macros, return, etc. /// - /// NB: This does not parse outer attributes, + /// N.B., this does not parse outer attributes, /// and is private because it only works /// correctly if called from parse_dot_or_call_expr(). fn parse_bottom_expr(&mut self) -> PResult<'a, P> { @@ -3732,7 +3732,7 @@ impl<'a> Parser<'a> { self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs)) } - /// Parse the RHS of a local variable declaration (e.g. '= 14;') + /// Parse the RHS of a local variable declaration (e.g., '= 14;') fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option>> { if self.eat(&token::Eq) { Ok(Some(self.parse_expr()?)) @@ -4114,7 +4114,7 @@ impl<'a> Parser<'a> { self.parse_pat_with_range_pat(true, expected) } - /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are + /// Parse a pattern, with a setting whether modern range patterns e.g., `a..=b`, `a..b` are /// allowed. fn parse_pat_with_range_pat( &mut self, @@ -4456,7 +4456,7 @@ impl<'a> Parser<'a> { } /// Parse a statement. This stops just before trailing semicolons on everything but items. - /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. + /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. pub fn parse_stmt(&mut self) -> PResult<'a, Option> { Ok(self.parse_stmt_(true)) } @@ -5053,9 +5053,9 @@ impl<'a> Parser<'a> { // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. // BOUND = TY_BOUND | LT_BOUND - // LT_BOUND = LIFETIME (e.g. `'a`) + // LT_BOUND = LIFETIME (e.g., `'a`) // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN) - // TY_BOUND_NOPAREN = [?] [for] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`) + // TY_BOUND_NOPAREN = [?] [for] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`) fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> { let mut bounds = Vec::new(); loop { @@ -5110,7 +5110,7 @@ impl<'a> Parser<'a> { } // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`. - // BOUND = LT_BOUND (e.g. `'a`) + // BOUND = LT_BOUND (e.g., `'a`) fn parse_lt_param_bounds(&mut self) -> GenericBounds { let mut lifetimes = Vec::new(); while self.check_lifetime() { @@ -6293,7 +6293,7 @@ impl<'a> Parser<'a> { /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. - /// If the following element can't be a tuple (i.e. it's a function definition, + /// If the following element can't be a tuple (i.e., it's a function definition, /// it's not a tuple struct field) and the contents within the parens /// isn't valid, emit a proper diagnostic. pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> { diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 04a791fbcb9..6b9cc2f9792 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -550,7 +550,7 @@ impl Token { }); // During early phases of the compiler the AST could get modified - // directly (e.g. attributes added or removed) and the internal cache + // directly (e.g., attributes added or removed) and the internal cache // of tokens my not be invalidated or updated. Consequently if the // "lossless" token stream disagrees with our actual stringification // (which has historically been much more battle-tested) then we go diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index aaed56da29d..0890be728f3 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -109,7 +109,7 @@ //! The buffered tokens go through a ring-buffer, 'tokens'. The 'left' and //! 'right' indices denote the active portion of the ring buffer as well as //! describing hypothetical points-in-the-infinite-stream at most 3N tokens -//! apart (i.e. "not wrapped to ring-buffer boundaries"). The paper will switch +//! apart (i.e., "not wrapped to ring-buffer boundaries"). The paper will switch //! between using 'left' and 'right' terms to denote the wrapped-to-ring-buffer //! and point-in-infinite-stream senses freely. //! diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index 9fbc64758da..17e7730120f 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -16,11 +16,11 @@ //! # Motivations and benefits //! //! * **Identity**: sharing AST nodes is problematic for the various analysis -//! passes (e.g. one may be able to bypass the borrow checker with a shared +//! passes (e.g., one may be able to bypass the borrow checker with a shared //! `ExprKind::AddrOf` node taking a mutable borrow). The only reason `@T` in the //! AST hasn't caused issues is because of inefficient folding passes which //! would always deduplicate any such shared nodes. Even if the AST were to -//! switch to an arena, this would still hold, i.e. it couldn't use `&'a T`, +//! switch to an arena, this would still hold, i.e., it couldn't use `&'a T`, //! but rather a wrapper like `P<'a, T>`. //! //! * **Immutability**: `P` disallows mutating its inner `T`, unlike `Box` @@ -34,7 +34,7 @@ //! * **Maintainability**: `P` provides a fixed interface - `Deref`, //! `and_then` and `map` - which can remain fully functional even if the //! implementation changes (using a special thread-local heap, for example). -//! Moreover, a switch to, e.g. `P<'a, T>` would be easy and mostly automated. +//! Moreover, a switch to, e.g., `P<'a, T>` would be easy and mostly automated. use std::fmt::{self, Display, Debug}; use std::iter::FromIterator; diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index 8ff4b0d025c..436a167e6a0 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -281,7 +281,7 @@ fn generate_test_harness(sess: &ParseSess, path: Vec::new(), test_cases: Vec::new(), reexport_test_harness_main, - // NB: doesn't consider the value of `--crate-name` passed on the command line. + // N.B., doesn't consider the value of `--crate-name` passed on the command line. is_libtest: attr::find_crate_name(&krate.attrs).map(|s| s == "test").unwrap_or(false), toplevel_reexport: None, ctxt: SyntaxContext::empty().apply_mark(mark), diff --git a/src/libsyntax/util/parser.rs b/src/libsyntax/util/parser.rs index 6866806cd7c..b7cd2acf8a5 100644 --- a/src/libsyntax/util/parser.rs +++ b/src/libsyntax/util/parser.rs @@ -340,8 +340,8 @@ impl ExprPrecedence { } -/// Expressions that syntactically contain an "exterior" struct literal i.e. not surrounded by any -/// parens or other delimiters, e.g. `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and +/// Expressions that syntactically contain an "exterior" struct literal i.e., not surrounded by any +/// parens or other delimiters, e.g., `X { y: 1 }`, `X { y: 1 }.method()`, `foo == X { y: 1 }` and /// `X { y: 1 } == foo` all do, but `(X { y: 1 }) == foo` does not. pub fn contains_exterior_struct_lit(value: &ast::Expr) -> bool { match value.node { diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 77311bf53fd..4be831a0b3f 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -43,7 +43,7 @@ pub enum FnKind<'a> { /// Each method of the Visitor trait is a hook to be potentially /// overridden. Each method's default implementation recursively visits /// the substructure of the input via the corresponding `walk` method; -/// e.g. the `visit_mod` method by default calls `visit::walk_mod`. +/// e.g., the `visit_mod` method by default calls `visit::walk_mod`. /// /// If you want to ensure that your code handles every variant /// explicitly, you need to override each method. (And you also need @@ -110,7 +110,7 @@ pub trait Visitor<'ast>: Sized { } fn visit_mac(&mut self, _mac: &'ast Mac) { panic!("visit_mac disabled by default"); - // NB: see note about macros above. + // N.B., see note about macros above. // if you really want a visitor that // works on macros, use this // definition in your trait impl: diff --git a/src/libsyntax_ext/deriving/cmp/partial_ord.rs b/src/libsyntax_ext/deriving/cmp/partial_ord.rs index 32a58de3529..196cfa5fe35 100644 --- a/src/libsyntax_ext/deriving/cmp/partial_ord.rs +++ b/src/libsyntax_ext/deriving/cmp/partial_ord.rs @@ -227,7 +227,7 @@ fn cs_op(less: bool, let fold = cs_fold1(false, // need foldr |cx, span, subexpr, self_f, other_fs| { // build up a series of `partial_cmp`s from the inside - // out (hence foldr) to get lexical ordering, i.e. for op == + // out (hence foldr) to get lexical ordering, i.e., for op == // `ast::lt` // // ``` diff --git a/src/libsyntax_ext/deriving/generic/mod.rs b/src/libsyntax_ext/deriving/generic/mod.rs index c0c11f64bc3..443fd48120e 100644 --- a/src/libsyntax_ext/deriving/generic/mod.rs +++ b/src/libsyntax_ext/deriving/generic/mod.rs @@ -18,7 +18,7 @@ //! - Methods taking any number of parameters of any type, and returning //! any type, other than vectors, bottom and closures. //! - Generating `impl`s for types with type parameters and lifetimes -//! (e.g. `Option`), the parameters are automatically given the +//! (e.g., `Option`), the parameters are automatically given the //! current trait as a bound. (This includes separate type parameters //! and lifetimes for methods.) //! - Additional bounds on the type parameters (`TraitDef.additional_bounds`) @@ -30,9 +30,9 @@ //! - `Struct`, when `Self` is a struct (including tuple structs, e.g //! `struct T(i32, char)`). //! - `EnumMatching`, when `Self` is an enum and all the arguments are the -//! same variant of the enum (e.g. `Some(1)`, `Some(3)` and `Some(4)`) +//! same variant of the enum (e.g., `Some(1)`, `Some(3)` and `Some(4)`) //! - `EnumNonMatchingCollapsed` when `Self` is an enum and the arguments -//! are not the same variant (e.g. `None`, `Some(1)` and `None`). +//! are not the same variant (e.g., `None`, `Some(1)` and `None`). //! - `StaticEnum` and `StaticStruct` for static methods, where the type //! being derived upon is either an enum or struct respectively. (Any //! argument with type Self is just grouped among the non-self @@ -224,7 +224,7 @@ pub struct TraitDef<'a> { /// other than the current trait pub additional_bounds: Vec>, - /// Any extra lifetimes and/or bounds, e.g. `D: serialize::Decoder` + /// Any extra lifetimes and/or bounds, e.g., `D: serialize::Decoder` pub generics: LifetimeBounds<'a>, /// Is it an `unsafe` trait? @@ -242,10 +242,10 @@ pub struct TraitDef<'a> { pub struct MethodDef<'a> { /// name of the method pub name: &'a str, - /// List of generics, e.g. `R: rand::Rng` + /// List of generics, e.g., `R: rand::Rng` pub generics: LifetimeBounds<'a>, - /// Whether there is a self argument (outer Option) i.e. whether + /// Whether there is a self argument (outer Option) i.e., whether /// this is a static function, and whether it is a pointer (inner /// Option) pub explicit_self: Option>>, @@ -1371,7 +1371,7 @@ impl<'a> MethodDef<'a> { // that type. Otherwise casts to `i32` (the default repr // type). // - // i.e. for `enum E { A, B(1), C(T, T) }`, and a deriving + // i.e., for `enum E { A, B(1), C(T, T) }`, and a deriving // with three Self args, builds three statements: // // ``` @@ -1489,8 +1489,8 @@ impl<'a> MethodDef<'a> { // // (See also #4499 and #12609; note that some of the // discussions there influence what choice we make here; - // e.g. if we feature-gate `match x { ... }` when x refers - // to an uninhabited type (e.g. a zero-variant enum or a + // e.g., if we feature-gate `match x { ... }` when x refers + // to an uninhabited type (e.g., a zero-variant enum or a // type holding such an enum), but do not feature-gate // zero-variant enums themselves, then attempting to // derive Debug on such a type could here generate code diff --git a/src/libsyntax_ext/deriving/generic/ty.rs b/src/libsyntax_ext/deriving/generic/ty.rs index fa284f4ab0e..11689a98a79 100644 --- a/src/libsyntax_ext/deriving/generic/ty.rs +++ b/src/libsyntax_ext/deriving/generic/ty.rs @@ -32,7 +32,7 @@ pub enum PtrTy<'a> { Raw(ast::Mutability), } -/// A path, e.g. `::std::option::Option::` (global). Has support +/// A path, e.g., `::std::option::Option::` (global). Has support /// for type parameters and a lifetime. #[derive(Clone)] pub struct Path<'a> { diff --git a/src/libsyntax_ext/format.rs b/src/libsyntax_ext/format.rs index 31e608de1f8..24108a30fdc 100644 --- a/src/libsyntax_ext/format.rs +++ b/src/libsyntax_ext/format.rs @@ -209,7 +209,7 @@ fn parse_args(ecx: &mut ExtCtxt, impl<'a, 'b> Context<'a, 'b> { fn resolve_name_inplace(&self, p: &mut parse::Piece) { // NOTE: the `unwrap_or` branch is needed in case of invalid format - // arguments, e.g. `format_args!("{foo}")`. + // arguments, e.g., `format_args!("{foo}")`. let lookup = |s| *self.names.get(s).unwrap_or(&0); match *p { diff --git a/src/libsyntax_ext/test.rs b/src/libsyntax_ext/test.rs index b8a171b52ad..1f2e6fc81c8 100644 --- a/src/libsyntax_ext/test.rs +++ b/src/libsyntax_ext/test.rs @@ -318,7 +318,7 @@ fn has_test_signature(cx: &ExtCtxt, i: &ast::Item) -> bool { fn has_bench_signature(cx: &ExtCtxt, i: &ast::Item) -> bool { let has_sig = if let ast::ItemKind::Fn(ref decl, _, _, _) = i.node { - // NB: inadequate check, but we're running + // N.B., inadequate check, but we're running // well before resolve, can't get too deep. decl.inputs.len() == 1 } else { diff --git a/src/libsyntax_pos/hygiene.rs b/src/libsyntax_pos/hygiene.rs index 074687fc726..74f63b5e2c6 100644 --- a/src/libsyntax_pos/hygiene.rs +++ b/src/libsyntax_pos/hygiene.rs @@ -308,11 +308,11 @@ impl SyntaxContext { } // Otherwise, `mark` is a macros 1.0 definition and the call site is in a - // macros 2.0 expansion, i.e. a macros 1.0 invocation is in a macros 2.0 definition. + // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition. // // In this case, the tokens from the macros 1.0 definition inherit the hygiene // at their invocation. That is, we pretend that the macros 1.0 definition - // was defined at its invocation (i.e. inside the macros 2.0 definition) + // was defined at its invocation (i.e., inside the macros 2.0 definition) // so that the macros 2.0 definition remains hygienic. // // See the example at `test/run-pass/hygiene/legacy_interaction.rs`. @@ -438,7 +438,7 @@ impl SyntaxContext { /// } /// ``` /// This returns the expansion whose definition scope we use to privacy check the resolution, - /// or `None` if we privacy check as usual (i.e. not w.r.t. a macro definition scope). + /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope). pub fn adjust(&mut self, expansion: Mark) -> Option { let mut scope = None; while !expansion.is_descendant_of(self.outer()) { @@ -540,7 +540,7 @@ pub struct ExpnInfo { /// The location of the actual macro invocation or syntax sugar , e.g. /// `let x = foo!();` or `if let Some(y) = x {}` /// - /// This may recursively refer to other macro invocations, e.g. if + /// This may recursively refer to other macro invocations, e.g., if /// `foo!()` invoked `bar!()` internally, and there was an /// expression inside `bar!`; the call_site of the expression in /// the expansion would point to the `bar!` invocation; that @@ -548,7 +548,7 @@ pub struct ExpnInfo { /// pointing to the `foo!` invocation. pub call_site: Span, /// The span of the macro definition itself. The macro may not - /// have a sensible definition span (e.g. something defined + /// have a sensible definition span (e.g., something defined /// completely inside libsyntax) in which case this is None. /// This span serves only informational purpose and is not used for resolution. pub def_site: Option, @@ -571,9 +571,9 @@ pub struct ExpnInfo { /// The source of expansion. #[derive(Clone, Hash, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub enum ExpnFormat { - /// e.g. #[derive(...)] + /// e.g., #[derive(...)] MacroAttribute(Symbol), - /// e.g. `format!()` + /// e.g., `format!()` MacroBang(Symbol), /// Desugaring done by the compiler during HIR lowering. CompilerDesugaring(CompilerDesugaringKind) diff --git a/src/libsyntax_pos/lib.rs b/src/libsyntax_pos/lib.rs index 4e3d1e89a72..8b7ffa499cd 100644 --- a/src/libsyntax_pos/lib.rs +++ b/src/libsyntax_pos/lib.rs @@ -8,9 +8,9 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! The source positions and related helper functions +//! The source positions and related helper functions. //! -//! # Note +//! ## Note //! //! This API is completely unstable and subject to change. @@ -27,17 +27,6 @@ #![feature(specialization)] #![cfg_attr(not(stage0), feature(stdsimd))] -use std::borrow::Cow; -use std::cell::Cell; -use std::cmp::{self, Ordering}; -use std::fmt; -use std::hash::{Hasher, Hash}; -use std::ops::{Add, Sub}; -use std::path::PathBuf; - -use rustc_data_structures::stable_hasher::StableHasher; -use rustc_data_structures::sync::{Lrc, Lock}; - extern crate arena; extern crate rustc_data_structures; @@ -65,6 +54,17 @@ pub mod symbol; mod analyze_source_file; +use rustc_data_structures::stable_hasher::StableHasher; +use rustc_data_structures::sync::{Lrc, Lock}; + +use std::borrow::Cow; +use std::cell::Cell; +use std::cmp::{self, Ordering}; +use std::fmt; +use std::hash::{Hasher, Hash}; +use std::ops::{Add, Sub}; +use std::path::PathBuf; + pub struct Globals { symbol_interner: Lock, span_interner: Lock, @@ -83,25 +83,25 @@ impl Globals { scoped_thread_local!(pub static GLOBALS: Globals); -/// Differentiates between real files and common virtual files +/// Differentiates between real files and common virtual files. #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash, RustcDecodable, RustcEncodable)] pub enum FileName { Real(PathBuf), /// A macro. This includes the full name of the macro, so that there are no clashes. Macros(String), - /// call to `quote!` + /// Call to `quote!`. QuoteExpansion(u64), - /// Command line + /// Command line. Anon(u64), - /// Hack in src/libsyntax/parse.rs - /// FIXME(jseyfried) + /// Hack in `src/libsyntax/parse.rs`. + // FIXME(jseyfried) MacroExpansion(u64), ProcMacroSourceCode(u64), - /// Strings provided as --cfg [cfgspec] stored in a crate_cfg + /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. CfgSpec(u64), - /// Strings provided as crate attributes in the CLI + /// Strings provided as crate attributes in the CLI. CliCrateAttr(u64), - /// Custom sources for explicit parser calls from plugins and drivers + /// Custom sources for explicit parser calls from plugins and drivers. Custom(String), DocTest(PathBuf, isize), } @@ -208,11 +208,11 @@ impl FileName { /// Spans represent a region of code, used for error reporting. Positions in spans /// are *absolute* positions from the beginning of the source_map, not positions -/// relative to SourceFiles. Methods on the SourceMap can be used to relate spans back +/// relative to `SourceFile`s. Methods on the `SourceMap` can be used to relate spans back /// to the original source. /// You must be careful if the span crosses more than one file - you will not be /// able to use many of the functions on spans in source_map and you cannot assume -/// that the length of the span = hi - lo; there may be space in the BytePos +/// that the length of the `span = hi - lo`; there may be space in the `BytePos` /// range between files. /// /// `SpanData` is public because `Span` uses a thread-local interner and can't be @@ -243,7 +243,7 @@ impl SpanData { } // The interner is pointed to by a thread local value which is only set on the main thread -// with parallelization is disabled. So we don't allow Span to transfer between threads +// with parallelization is disabled. So we don't allow `Span` to transfer between threads // to avoid panics and other errors, even though it would be memory safe to do so. #[cfg(not(parallel_queries))] impl !Send for Span {} @@ -263,9 +263,9 @@ impl Ord for Span { /// A collection of spans. Spans have two orthogonal attributes: /// -/// - they can be *primary spans*. In this case they are the locus of +/// - They can be *primary spans*. In this case they are the locus of /// the error, and would be rendered with `^^^`. -/// - they can have a *label*. In this case, the label is written next +/// - They can have a *label*. In this case, the label is written next /// to the mark in the snippet when we render. #[derive(Clone, Debug, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)] pub struct MultiSpan { @@ -312,7 +312,7 @@ impl Span { let span = self.data(); span.with_hi(span.lo) } - /// Returns a new span representing an empty span at the end of this span + /// Returns a new span representing an empty span at the end of this span. #[inline] pub fn shrink_to_hi(self) -> Span { let span = self.data(); @@ -324,7 +324,7 @@ impl Span { if self.is_dummy() { other } else { self } } - /// Return true if `self` fully encloses `other`. + /// Return `true` if `self` fully encloses `other`. pub fn contains(self, other: Span) -> bool { let span = self.data(); let other = other.data(); @@ -341,7 +341,7 @@ impl Span { span.lo == other.lo && span.hi == other.hi } - /// Returns `Some(span)`, where the start is trimmed by the end of `other` + /// Returns `Some(span)`, where the start is trimmed by the end of `other`. pub fn trim_start(self, other: Span) -> Option { let span = self.data(); let other = other.data(); @@ -352,14 +352,14 @@ impl Span { } } - /// Return the source span - this is either the supplied span, or the span for + /// Return the source span -- this is either the supplied span, or the span for /// the macro callsite that expanded to it. pub fn source_callsite(self) -> Span { self.ctxt().outer().expn_info().map(|info| info.call_site.source_callsite()).unwrap_or(self) } /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, - /// if any + /// if any. pub fn parent(self) -> Option { self.ctxt().outer().expn_info().map(|i| i.call_site) } @@ -395,7 +395,7 @@ impl Span { self.ctxt().outer().expn_info().map(source_callee) } - /// Check if a span is "internal" to a macro in which #[unstable] + /// Check if a span is "internal" to a macro in which `#[unstable]` /// items can be used (that is, a macro marked with /// `#[allow_internal_unstable]`). pub fn allows_unstable(&self) -> bool { @@ -416,7 +416,7 @@ impl Span { } } - /// Return the compiler desugaring that created this span, or None + /// Return the compiler desugaring that created this span, or `None` /// if this span is not from a desugaring. pub fn compiler_desugaring_kind(&self) -> Option { match self.ctxt().outer().expn_info() { @@ -442,7 +442,7 @@ impl Span { let mut prev_span = DUMMY_SP; let mut result = vec![]; while let Some(info) = self.ctxt().outer().expn_info() { - // Don't print recursive invocations + // Don't print recursive invocations. if !info.call_site.source_equal(&prev_span) { let (pre, post) = match info.format { ExpnFormat::MacroAttribute(..) => ("#[", "]"), @@ -466,7 +466,7 @@ impl Span { pub fn to(self, end: Span) -> Span { let span_data = self.data(); let end_data = end.data(); - // FIXME(jseyfried): self.ctxt should always equal end.ctxt here (c.f. issue #23480) + // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). // Return the macro span on its own to avoid weird diagnostic output. It is preferable to // have an incomplete span than a completely nonsensical one. if span_data.ctxt != end_data.ctxt { @@ -475,8 +475,8 @@ impl Span { } else if end_data.ctxt == SyntaxContext::empty() { return self; } - // both span fall within a macro - // FIXME(estebank) check if it is the *same* macro + // Both spans fall within a macro. + // FIXME(estebank): check if it is the *same* macro. } Span::new( cmp::min(span_data.lo, end_data.lo), @@ -658,7 +658,7 @@ impl MultiSpan { self.span_labels.push((span, label)); } - /// Selects the first primary span (if any) + /// Selects the first primary span (if any). pub fn primary_span(&self) -> Option { self.primary_spans.first().cloned() } @@ -679,7 +679,7 @@ impl MultiSpan { is_dummy } - /// Replaces all occurrences of one Span with another. Used to move Spans in areas that don't + /// Replaces all occurrences of one Span with another. Used to move `Span`s in areas that don't /// display well (like std macros). Returns true if replacements occurred. pub fn replace(&mut self, before: Span, after: Span) -> bool { let mut replacements_occurred = false; @@ -700,7 +700,7 @@ impl MultiSpan { /// Returns the strings to highlight. We always ensure that there /// is an entry for each of the primary spans -- for each primary - /// span P, if there is at least one label with span P, we return + /// span `P`, if there is at least one label with span `P`, we return /// those labels (marked as primary). But otherwise we return /// `SpanLabel` instances with empty labels. pub fn span_labels(&self) -> Vec { @@ -742,23 +742,23 @@ impl From> for MultiSpan { pub const NO_EXPANSION: SyntaxContext = SyntaxContext::empty(); -/// Identifies an offset of a multi-byte character in a SourceFile +/// Identifies an offset of a multi-byte character in a `SourceFile`. #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)] pub struct MultiByteChar { - /// The absolute offset of the character in the SourceMap + /// The absolute offset of the character in the `SourceMap`. pub pos: BytePos, - /// The number of bytes, >=2 + /// The number of bytes, `>= 2`. pub bytes: u8, } -/// Identifies an offset of a non-narrow character in a SourceFile +/// Identifies an offset of a non-narrow character in a `SourceFile`. #[derive(Copy, Clone, RustcEncodable, RustcDecodable, Eq, PartialEq, Debug)] pub enum NonNarrowChar { - /// Represents a zero-width character + /// Represents a zero-width character. ZeroWidth(BytePos), - /// Represents a wide (fullwidth) character + /// Represents a wide (full-width) character. Wide(BytePos), - /// Represents a tab character, represented visually with a width of 4 characters + /// Represents a tab character, represented visually with a width of 4 characters. Tab(BytePos), } @@ -772,7 +772,7 @@ impl NonNarrowChar { } } - /// Returns the absolute offset of the character in the SourceMap + /// Returns the absolute offset of the character in the `SourceMap`. pub fn pos(&self) -> BytePos { match *self { NonNarrowChar::ZeroWidth(p) | @@ -781,7 +781,7 @@ impl NonNarrowChar { } } - /// Returns the width of the character, 0 (zero-width) or 2 (wide) + /// Returns the width of the character, 0 (zero-width) or 2 (wide). pub fn width(&self) -> usize { match *self { NonNarrowChar::ZeroWidth(_) => 0, @@ -815,7 +815,7 @@ impl Sub for NonNarrowChar { } } -/// The state of the lazy external source loading mechanism of a SourceFile. +/// The state of the lazy external source loading mechanism of a `SourceFile`. #[derive(PartialEq, Eq, Clone)] pub enum ExternalSource { /// The external source has been loaded already. @@ -824,7 +824,7 @@ pub enum ExternalSource { AbsentOk, /// A failed attempt has been made to load the external source. AbsentErr, - /// No external source has to be loaded, since the SourceFile represents a local crate. + /// No external source has to be loaded, since the `SourceFile` represents a local crate. Unneeded, } @@ -844,38 +844,38 @@ impl ExternalSource { } } -/// A single source in the SourceMap. +/// A single source in the `SourceMap`. #[derive(Clone)] pub struct SourceFile { /// The name of the file that the source came from, source that doesn't - /// originate from files has names between angle brackets by convention, - /// e.g. `` + /// originate from files has names between angle brackets by convention + /// (e.g., ``). pub name: FileName, - /// True if the `name` field above has been modified by --remap-path-prefix + /// True if the `name` field above has been modified by `--remap-path-prefix`. pub name_was_remapped: bool, /// The unmapped path of the file that the source came from. - /// Set to `None` if the SourceFile was imported from an external crate. + /// Set to `None` if the `SourceFile` was imported from an external crate. pub unmapped_path: Option, - /// Indicates which crate this SourceFile was imported from. + /// Indicates which crate this `SourceFile` was imported from. pub crate_of_origin: u32, - /// The complete source code + /// The complete source code. pub src: Option>, - /// The source code's hash + /// The source code's hash. pub src_hash: u128, /// The external source code (used for external crates, which will have a `None` /// value as `self.src`. pub external_src: Lock, - /// The start position of this source in the SourceMap + /// The start position of this source in the `SourceMap`. pub start_pos: BytePos, - /// The end position of this source in the SourceMap + /// The end position of this source in the `SourceMap`. pub end_pos: BytePos, - /// Locations of lines beginnings in the source code + /// Locations of lines beginnings in the source code. pub lines: Vec, - /// Locations of multi-byte characters in the source code + /// Locations of multi-byte characters in the source code. pub multibyte_chars: Vec, - /// Width of characters that are not narrow in the source code + /// Width of characters that are not narrow in the source code. pub non_narrow_chars: Vec, - /// A hash of the filename, used for speeding up the incr. comp. hashing. + /// A hash of the filename, used for speeding up hashing in incremental compilation. pub name_hash: u128, } @@ -889,7 +889,7 @@ impl Encodable for SourceFile { s.emit_struct_field("end_pos", 5, |s| self.end_pos.encode(s))?; s.emit_struct_field("lines", 6, |s| { let lines = &self.lines[..]; - // store the length + // Store the length. s.emit_u32(lines.len() as u32)?; if !lines.is_empty() { @@ -1060,7 +1060,7 @@ impl SourceFile { } } - /// Return the BytePos of the beginning of the current line. + /// Return the `BytePos` of the beginning of the current line. pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { let line_index = self.lookup_line(pos).unwrap(); self.lines[line_index] @@ -1148,9 +1148,9 @@ impl SourceFile { } /// Find the line containing the given position. The return value is the - /// index into the `lines` array of this SourceFile, not the 1-based line + /// index into the `lines` array of this `SourceFile`, not the 1-based line /// number. If the source_file is empty or the position is located before the - /// first line, None is returned. + /// first line, `None` is returned. pub fn lookup_line(&self, pos: BytePos) -> Option { if self.lines.len() == 0 { return None; @@ -1207,14 +1207,14 @@ pub trait Pos { #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] pub struct BytePos(pub u32); -/// A character offset. Because of multibyte utf8 characters, a byte offset -/// is not equivalent to a character offset. The SourceMap will convert BytePos -/// values to CharPos values as necessary. +/// A character offset. Because of multibyte UTF-8 characters, a byte offset +/// is not equivalent to a character offset. The `SourceMap` will convert `BytePos` +/// values to `CharPos` values as necessary. #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] pub struct CharPos(pub usize); -// FIXME: Lots of boilerplate in these impls, but so far my attempts to fix -// have been unsuccessful +// FIXME: lots of boilerplate in these impls, but so far my attempts to fix +// have been unsuccessful. impl Pos for BytePos { #[inline(always)] @@ -1296,20 +1296,20 @@ impl Sub for CharPos { // Loc, LocWithOpt, SourceFileAndLine, SourceFileAndBytePos // -/// A source code location used for error reporting +/// A source code location used for error reporting. #[derive(Debug, Clone)] pub struct Loc { - /// Information about the original source + /// Information about the original source. pub file: Lrc, - /// The (1-based) line number + /// The (1-based) line number. pub line: usize, - /// The (0-based) column offset + /// The (0-based) column offset. pub col: CharPos, - /// The (0-based) column offset when displayed + /// The (0-based) column offset when displayed. pub col_display: usize, } -/// A source code location used as the result of lookup_char_pos_adj +/// A source code location used as the result of `lookup_char_pos_adj`. // Actually, *none* of the clients use the filename *or* file field; // perhaps they should just be removed. #[derive(Debug)] @@ -1320,7 +1320,7 @@ pub struct LocWithOpt { pub file: Option>, } -// used to be structural records. Better names, anyone? +// Used to be structural records. #[derive(Debug)] pub struct SourceFileAndLine { pub sf: Lrc, pub line: usize } #[derive(Debug)] diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index 847bf60cefb..05c53878e70 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -9,20 +9,21 @@ // except according to those terms. //! An "interner" is a data structure that associates values with usize tags and -//! allows bidirectional lookup; i.e. given a value, one can easily find the +//! allows bidirectional lookup; i.e., given a value, one can easily find the //! type, and vice versa. -use hygiene::SyntaxContext; -use {Span, DUMMY_SP, GLOBALS}; - -use rustc_data_structures::fx::FxHashMap; use arena::DroplessArena; +use rustc_data_structures::fx::FxHashMap; use serialize::{Decodable, Decoder, Encodable, Encoder}; + use std::fmt; use std::str; use std::cmp::{PartialEq, Ordering, PartialOrd, Ord}; use std::hash::{Hash, Hasher}; +use hygiene::SyntaxContext; +use {Span, DUMMY_SP, GLOBALS}; + #[derive(Copy, Clone, Eq)] pub struct Ident { pub name: Symbol, @@ -34,6 +35,7 @@ impl Ident { pub const fn new(name: Symbol, span: Span) -> Ident { Ident { name, span } } + #[inline] pub const fn with_empty_ctxt(name: Symbol) -> Ident { Ident::new(name, DUMMY_SP) @@ -60,7 +62,7 @@ impl Ident { /// "Normalize" ident for use in comparisons using "item hygiene". /// Identifiers with same string value become same if they came from the same "modern" macro - /// (e.g. `macro` item, but not `macro_rules` item) and stay different if they came from + /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from /// different "modern" macros. /// Technically, this operation strips all non-opaque marks from ident's syntactic context. pub fn modern(self) -> Ident { @@ -69,7 +71,7 @@ impl Ident { /// "Normalize" ident for use in comparisons using "local variable hygiene". /// Identifiers with same string value become same if they came from the same non-transparent - /// macro (e.g. `macro` or `macro_rules!` items) and stay different if they came from different + /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different /// non-transparent macros. /// Technically, this operation strips all transparent marks from ident's syntactic context. pub fn modern_and_legacy(self) -> Ident { @@ -122,7 +124,7 @@ impl Encodable for Ident { fn encode(&self, s: &mut S) -> Result<(), S::Error> { if self.span.ctxt().modern() == SyntaxContext::empty() { s.emit_str(&self.as_str()) - } else { // FIXME(jseyfried) intercrate hygiene + } else { // FIXME(jseyfried): intercrate hygiene let mut string = "#".to_owned(); string.push_str(&self.as_str()); s.emit_str(&string) @@ -135,7 +137,7 @@ impl Decodable for Ident { let string = d.read_str()?; Ok(if !string.starts_with('#') { Ident::from_str(&string) - } else { // FIXME(jseyfried) intercrate hygiene + } else { // FIXME(jseyfried): intercrate hygiene Ident::with_empty_ctxt(Symbol::gensym(&string[1..])) }) } @@ -146,7 +148,7 @@ impl Decodable for Ident { pub struct Symbol(u32); // The interner is pointed to by a thread local value which is only set on the main thread -// with parallelization is disabled. So we don't allow Symbol to transfer between threads +// with parallelization is disabled. So we don't allow `Symbol` to transfer between threads // to avoid panics and other errors, even though it would be memory safe to do so. #[cfg(not(parallel_queries))] impl !Send for Symbol { } @@ -163,7 +165,7 @@ impl Symbol { with_interner(|interner| interner.interned(self)) } - /// gensym's a new usize, using the current interner. + /// Gensyms a new usize, using the current interner. pub fn gensym(string: &str) -> Self { with_interner(|interner| interner.gensym(string)) } @@ -226,7 +228,7 @@ impl> PartialEq for Symbol { } } -// The &'static strs in this type actually point into the arena +// The `&'static str`s in this type actually point into the arena. #[derive(Default)] pub struct Interner { arena: DroplessArena, @@ -240,7 +242,7 @@ impl Interner { let mut this = Interner::default(); for &string in init { if string == "" { - // We can't allocate empty strings in the arena, so handle this here + // We can't allocate empty strings in the arena, so handle this here. let name = Symbol(this.strings.len() as u32); this.names.insert("", name); this.strings.push(""); @@ -258,12 +260,13 @@ impl Interner { let name = Symbol(self.strings.len() as u32); - // from_utf8_unchecked is safe since we just allocated a &str which is known to be utf8 + // `from_utf8_unchecked` is safe since we just allocated a `&str` which is known to be + // UTF-8. let string: &str = unsafe { str::from_utf8_unchecked(self.arena.alloc_slice(string.as_bytes())) }; - // It is safe to extend the arena allocation to 'static because we only access - // these while the arena is still alive + // It is safe to extend the arena allocation to `'static` because we only access + // these while the arena is still alive. let string: &'static str = unsafe { &*(string as *const str) }; @@ -344,7 +347,7 @@ macro_rules! declare_keywords {( } }} -// NB: leaving holes in the ident table is bad! a different ident will get +// N.B., leaving holes in the ident table is bad! a different ident will get // interned with the id from the hole, but it will be between the min and max // of the reserved words, and thus tagged as "reserved". // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`, @@ -438,7 +441,7 @@ impl Symbol { } impl Ident { - // Returns true for reserved identifiers used internally for elided lifetimes, + // Returns `true` for reserved identifiers used internally for elided lifetimes, // unnamed method parameters, crate root module, error recovery etc. pub fn is_special(self) -> bool { self.name <= keywords::Underscore.name() @@ -491,8 +494,8 @@ fn with_interner T>(f: F) -> T { /// Represents a string stored in the interner. Because the interner outlives any thread /// which uses this type, we can safely treat `string` which points to interner data, /// as an immortal string, as long as this type never crosses between threads. -// FIXME: Ensure that the interner outlives any thread which uses LocalInternedString, -// by creating a new thread right after constructing the interner +// FIXME: ensure that the interner outlives any thread which uses `LocalInternedString`, +// by creating a new thread right after constructing the interner. #[derive(Clone, Copy, Hash, PartialOrd, Eq, Ord)] pub struct LocalInternedString { string: &'static str, @@ -581,7 +584,7 @@ impl Encodable for LocalInternedString { } } -/// Represents a string stored in the string interner +/// Represents a string stored in the string interner. #[derive(Clone, Copy, Eq)] pub struct InternedString { symbol: Symbol, diff --git a/src/libterm/lib.rs b/src/libterm/lib.rs index 5ac46c2c5eb..b28e62f16fd 100644 --- a/src/libterm/lib.rs +++ b/src/libterm/lib.rs @@ -198,7 +198,7 @@ pub trait Terminal: Write { /// *Note: This does not flush.* /// /// That means the reset command may get buffered so, if you aren't planning on doing anything - /// else that might flush stdout's buffer (e.g. writing a line of text), you should flush after + /// else that might flush stdout's buffer (e.g., writing a line of text), you should flush after /// calling reset. fn reset(&mut self) -> io::Result; diff --git a/src/libterm/terminfo/searcher.rs b/src/libterm/terminfo/searcher.rs index 492d26e625c..426dc4db87b 100644 --- a/src/libterm/terminfo/searcher.rs +++ b/src/libterm/terminfo/searcher.rs @@ -64,7 +64,7 @@ pub fn get_dbpath_for_term(term: &str) -> Option { p.pop(); // on some installations the dir is named after the hex of the char - // (e.g. macOS) + // (e.g., macOS) p.push(&format!("{:x}", first_char as usize)); p.push(term); if fs::metadata(&p).is_ok() { @@ -79,7 +79,7 @@ pub fn get_dbpath_for_term(term: &str) -> Option { #[ignore(reason = "buildbots don't have ncurses installed and I can't mock everything I need")] fn test_get_dbpath_for_term() { // woefully inadequate test coverage - // note: current tests won't work with non-standard terminfo hierarchies (e.g. macOS's) + // note: current tests won't work with non-standard terminfo hierarchies (e.g., macOS's) use std::env; // FIXME (#9639): This needs to handle non-utf8 paths fn x(t: &str) -> String { diff --git a/src/libtest/formatters/terse.rs b/src/libtest/formatters/terse.rs index 6f7dfee53fa..cf15c89fac2 100644 --- a/src/libtest/formatters/terse.rs +++ b/src/libtest/formatters/terse.rs @@ -66,7 +66,7 @@ impl TerseFormatter { self.write_pretty(result, color)?; if self.test_count % QUIET_MODE_MAX_COLUMN == QUIET_MODE_MAX_COLUMN - 1 { // we insert a new line every 100 dots in order to flush the - // screen when dealing with line-buffered output (e.g. piping to + // screen when dealing with line-buffered output (e.g., piping to // `stamp` in the rust CI). let out = format!(" {}/{}\n", self.test_count+1, self.total_test_count); self.write_plain(&out)?; diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index b8711a69147..bca98881db4 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -23,7 +23,7 @@ // running tests while providing a base that other test frameworks may // build off of. -// NB: this is also specified in this crate's Cargo.toml, but libsyntax contains logic specific to +// N.B., this is also specified in this crate's Cargo.toml, but libsyntax contains logic specific to // this crate, which relies on this attribute (rather than the value of `--crate-name` passed by // cargo) to detect this crate. @@ -100,7 +100,7 @@ mod formatters; use formatters::{JsonFormatter, OutputFormatter, PrettyFormatter, TerseFormatter}; // The name of a test. By convention this follows the rules for rust -// paths; i.e. it should be a series of identifiers separated by double +// paths; i.e., it should be a series of identifiers separated by double // colons. This way if some test runner wants to arrange the tests // hierarchically it may. @@ -515,7 +515,7 @@ Test Attributes: // FIXME: Copied from libsyntax until linkage errors are resolved. Issue #47566 fn is_nightly() -> bool { - // Whether this is a feature-staged build, i.e. on the beta or stable channel + // Whether this is a feature-staged build, i.e., on the beta or stable channel let disable_unstable_features = option_env!("CFG_DISABLE_UNSTABLE_FEATURES").is_some(); // Whether we should enable unstable features for bootstrapping let bootstrap = env::var("RUSTC_BOOTSTRAP").is_ok(); @@ -1614,7 +1614,7 @@ where // be left doing 0 iterations on every loop. The unfortunate // side effect of not being able to do as many runs is // automatically handled by the statistical analysis below - // (i.e. larger error bars). + // (i.e., larger error bars). n = cmp::max(1, n); let mut total_run = Duration::new(0, 0); diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index 9a8749712c3..1fad612b946 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -224,7 +224,7 @@ impl Stats for [f64] { let x = *s - mean; v = v + x * x; } - // NB: this is _supposed to be_ len-1, not len. If you + // N.B., this is _supposed to be_ len-1, not len. If you // change it back to len, you will be calculating a // population variance, not a sample variance. let denom = (self.len() - 1) as f64; diff --git a/src/rtstartup/rsbegin.rs b/src/rtstartup/rsbegin.rs index 8ff401164c1..4ec0857f051 100644 --- a/src/rtstartup/rsbegin.rs +++ b/src/rtstartup/rsbegin.rs @@ -96,7 +96,7 @@ pub mod eh_frames { pub mod ms_init { // .CRT$X?? sections are roughly analogous to ELF's .init_array and .fini_array, // except that they exploit the fact that linker will sort them alphabitically, - // so e.g. sections with names between .CRT$XIA and .CRT$XIZ are guaranteed to be + // so e.g., sections with names between .CRT$XIA and .CRT$XIZ are guaranteed to be // placed between those two, without requiring any ordering of objects on the linker // command line. // Note that ordering of same-named sections from different objects is not guaranteed. diff --git a/src/test/codegen-units/item-collection/unreferenced-inline-function.rs b/src/test/codegen-units/item-collection/unreferenced-inline-function.rs index 829b4fbf3c9..28c1f0a54bf 100644 --- a/src/test/codegen-units/item-collection/unreferenced-inline-function.rs +++ b/src/test/codegen-units/item-collection/unreferenced-inline-function.rs @@ -11,7 +11,7 @@ // ignore-tidy-linelength // compile-flags:-Zprint-mono-items=lazy -// NB: We do not expect *any* monomorphization to be generated here. +// N.B., we do not expect *any* monomorphization to be generated here. #![deny(dead_code)] #![crate_type = "rlib"] diff --git a/src/test/codegen/external-no-mangle-fns.rs b/src/test/codegen/external-no-mangle-fns.rs index 58232852596..e6b952ec9f6 100644 --- a/src/test/codegen/external-no-mangle-fns.rs +++ b/src/test/codegen/external-no-mangle-fns.rs @@ -9,7 +9,7 @@ // except according to those terms. // compile-flags: -C no-prepopulate-passes -// `#[no_mangle]`d functions always have external linkage, i.e. no `internal` in their `define`s +// `#[no_mangle]`d functions always have external linkage, i.e., no `internal` in their `define`s #![crate_type = "lib"] #![no_std] diff --git a/src/test/codegen/external-no-mangle-statics.rs b/src/test/codegen/external-no-mangle-statics.rs index 59d829633e5..b1488e3b8d0 100644 --- a/src/test/codegen/external-no-mangle-statics.rs +++ b/src/test/codegen/external-no-mangle-statics.rs @@ -9,7 +9,7 @@ // except according to those terms. // compile-flags: -O -// `#[no_mangle]`d static variables always have external linkage, i.e. no `internal` in their +// `#[no_mangle]`d static variables always have external linkage, i.e., no `internal` in their // definitions #![crate_type = "lib"] diff --git a/src/test/debuginfo/type-names.rs b/src/test/debuginfo/type-names.rs index 3ec8b048b12..8b4b10ad23c 100644 --- a/src/test/debuginfo/type-names.rs +++ b/src/test/debuginfo/type-names.rs @@ -280,7 +280,7 @@ extern { } // In many of the cases below, the type that is actually under test is wrapped -// in a tuple, e.g. Box, references, raw pointers, fixed-size vectors, ... +// in a tuple, e.g., Box, references, raw pointers, fixed-size vectors, ... // This is because GDB will not print the type name from DWARF debuginfo for // some kinds of types (pointers, arrays, functions, ...) // Since tuples are structs as far as GDB is concerned, their name will be diff --git a/src/test/incremental/hashes/panic_exprs.rs b/src/test/incremental/hashes/panic_exprs.rs index ffb66c29219..f2d610c1ade 100644 --- a/src/test/incremental/hashes/panic_exprs.rs +++ b/src/test/incremental/hashes/panic_exprs.rs @@ -9,7 +9,7 @@ // except according to those terms. // This test case tests the incremental compilation hash (ICH) implementation -// for exprs that can panic at runtime (e.g. because of bounds checking). For +// for exprs that can panic at runtime (e.g., because of bounds checking). For // these expressions an error message containing their source location is // generated, so their hash must always depend on their location in the source // code, not just when debuginfo is enabled. diff --git a/src/test/incremental/hashes/struct_defs.rs b/src/test/incremental/hashes/struct_defs.rs index 10b1beb0413..06842e3c6c4 100644 --- a/src/test/incremental/hashes/struct_defs.rs +++ b/src/test/incremental/hashes/struct_defs.rs @@ -340,7 +340,7 @@ struct AddTypeParameterBoundWhereClause( // Empty struct ---------------------------------------------------------------- // Since we cannot change anything in this case, we just make sure that the -// fingerprint is stable (i.e. that there are no random influences like memory +// fingerprint is stable (i.e., that there are no random influences like memory // addresses taken into account by the hashing algorithm). // Note: there is no #[cfg(...)], so this is ALWAYS compiled #[rustc_clean(label="Hir", cfg="cfail2")] diff --git a/src/test/pretty/block-disambig.rs b/src/test/pretty/block-disambig.rs index c645a66b70e..aed34bf3585 100644 --- a/src/test/pretty/block-disambig.rs +++ b/src/test/pretty/block-disambig.rs @@ -11,7 +11,7 @@ // compile-flags: --crate-type=lib // A bunch of tests for syntactic forms involving blocks that were -// previously ambiguous (e.g. 'if true { } *val;' gets parsed as a +// previously ambiguous (e.g., 'if true { } *val;' gets parsed as a // binop) diff --git a/src/test/run-make-fulldeps/reproducible-build/reproducible-build.rs b/src/test/run-make-fulldeps/reproducible-build/reproducible-build.rs index a040c0f858d..c8c8bb1c850 100644 --- a/src/test/run-make-fulldeps/reproducible-build/reproducible-build.rs +++ b/src/test/run-make-fulldeps/reproducible-build/reproducible-build.rs @@ -9,7 +9,7 @@ // except according to those terms. // This test case makes sure that two identical invocations of the compiler -// (i.e. same code base, same compile-flags, same compiler-versions, etc.) +// (i.e., same code base, same compile-flags, same compiler-versions, etc.) // produce the same output. In the past, symbol names of monomorphized functions // were not deterministic (which we want to avoid). // diff --git a/src/test/run-pass/coerce/coerce-unify.rs b/src/test/run-pass/coerce/coerce-unify.rs index 575d672e092..bfcdf5b143f 100644 --- a/src/test/run-pass/coerce/coerce-unify.rs +++ b/src/test/run-pass/coerce/coerce-unify.rs @@ -47,7 +47,7 @@ macro_rules! check3 { check2!($b, $c); check2!($a, $c); - // Check the remaining cases, i.e. permutations of ($a, $b, $c). + // Check the remaining cases, i.e., permutations of ($a, $b, $c). check!($a, $b, $c); check!($a, $c, $b); check!($b, $a, $c); diff --git a/src/test/run-pass/coerce/coerce-unsize-subtype.rs b/src/test/run-pass/coerce/coerce-unsize-subtype.rs index 068b010da1e..088d10f8d63 100644 --- a/src/test/run-pass/coerce/coerce-unsize-subtype.rs +++ b/src/test/run-pass/coerce/coerce-unsize-subtype.rs @@ -32,7 +32,7 @@ fn long_to_short_rc<'a, T>(xs: Rc<[&'static T; 1]>) -> Rc<[&'a T]> { } // LUB-coercion (if-else/match/array) coerces `xs: &'b [&'static T: N]` -// to a subtype of the LUB of `xs` and `ys` (i.e. `&'b [&'a T]`), +// to a subtype of the LUB of `xs` and `ys` (i.e., `&'b [&'a T]`), // regardless of the order they appear (in if-else/match/array). fn long_and_short_lub1<'a, 'b, T>(xs: &'b [&'static T; 1], ys: &'b [&'a T]) { let _order1 = [xs, ys]; @@ -40,7 +40,7 @@ fn long_and_short_lub1<'a, 'b, T>(xs: &'b [&'static T; 1], ys: &'b [&'a T]) { } // LUB-coercion should also have the exact same effect when `&'b [&'a T; N]` -// needs to be coerced, i.e. the resulting type is not &'b [&'static T], but +// needs to be coerced, i.e., the resulting type is not &'b [&'static T], but // rather the `&'b [&'a T]` LUB. fn long_and_short_lub2<'a, 'b, T>(xs: &'b [&'static T], ys: &'b [&'a T; 1]) { let _order1 = [xs, ys]; diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index aaf017c0ad3..51e26ff68de 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -16,7 +16,7 @@ // ignore-cloudabi no processes // ignore-emscripten no processes -// NB: These tests kill child processes. Valgrind sees these children as leaking +// N.B., these tests kill child processes. Valgrind sees these children as leaking // memory, which makes for some *confusing* logs. That's why these are here // instead of in std. diff --git a/src/test/run-pass/drop/dropck-eyepatch.rs b/src/test/run-pass/drop/dropck-eyepatch.rs index fb9af09a7ce..97820ac7ea8 100644 --- a/src/test/run-pass/drop/dropck-eyepatch.rs +++ b/src/test/run-pass/drop/dropck-eyepatch.rs @@ -32,7 +32,7 @@ // - D means "I implement Drop" // // - P means "I implement Drop but guarantee my (first) parameter is -// pure, i.e. not accessed from the destructor"; no other parameters +// pure, i.e., not accessed from the destructor"; no other parameters // are pure. // // - S means "I do not implement Drop" diff --git a/src/test/run-pass/drop/dropck_legal_cycles.rs b/src/test/run-pass/drop/dropck_legal_cycles.rs index 2c88cfd5c8f..89d70da32cf 100644 --- a/src/test/run-pass/drop/dropck_legal_cycles.rs +++ b/src/test/run-pass/drop/dropck_legal_cycles.rs @@ -108,7 +108,7 @@ // of all-zeroes. // // 6. assert that the context confirms that it actually saw a cycle (since a traversal -// might have terminated, e.g. on a tree structure that contained no cycles). +// might have terminated, e.g., on a tree structure that contained no cycles). use std::cell::{Cell, RefCell}; use std::cmp::Ordering; diff --git a/src/test/run-pass/for-loop-while/loop-no-reinit-needed-post-bot.rs b/src/test/run-pass/for-loop-while/loop-no-reinit-needed-post-bot.rs index 95bb8e8aa64..7bc4dccdcce 100644 --- a/src/test/run-pass/for-loop-while/loop-no-reinit-needed-post-bot.rs +++ b/src/test/run-pass/for-loop-while/loop-no-reinit-needed-post-bot.rs @@ -15,7 +15,7 @@ struct S; // Ensure S is moved, not copied, on assignment. impl Drop for S { fn drop(&mut self) { } } -// user-defined function "returning" bottom (i.e. no return at all). +// user-defined function "returning" bottom (i.e., no return at all). fn my_panic() -> ! { loop {} } pub fn step(f: bool) { diff --git a/src/test/run-pass/impl-trait/example-calendar.rs b/src/test/run-pass/impl-trait/example-calendar.rs index 7373828427e..d622fd6171a 100644 --- a/src/test/run-pass/impl-trait/example-calendar.rs +++ b/src/test/run-pass/impl-trait/example-calendar.rs @@ -86,7 +86,7 @@ impl NaiveDate { let weeks_in_year = self.last_week_number(); // Work out the final result. - // If the week is -1 or >= weeks_in_year, we will need to adjust the year. + // If the week is `-1` or `>= weeks_in_year`, we will need to adjust the year. let year = self.year(); let wd = self.weekday(); @@ -234,7 +234,7 @@ impl Weekday { } } -/// GroupBy implementation. +/// `GroupBy` implementation. struct GroupBy { it: std::iter::Peekable, f: F, @@ -319,7 +319,7 @@ trait IteratorExt: Iterator + Sized { s } - // HACK(eddyb) Only needed because `impl Trait` can't be + // HACK(eddyb): only needed because `impl Trait` can't be // used with trait methods: `.foo()` becomes `.__(foo)`. fn __(self, f: F) -> R where F: FnOnce(Self) -> R { @@ -329,9 +329,7 @@ trait IteratorExt: Iterator + Sized { impl IteratorExt for It where It: Iterator {} -/// -/// Generates an iterator that yields exactly n spaces. -/// +/// Generates an iterator that yields exactly `n` spaces. fn spaces(n: usize) -> std::iter::Take> { std::iter::repeat(' ').take(n) } @@ -341,9 +339,7 @@ fn test_spaces() { assert_eq!(spaces(10).collect::(), " ") } -/// /// Returns an iterator of dates in a given year. -/// fn dates_in_year(year: i32) -> impl Iterator+Clone { InGroup { it: NaiveDate::from_ymd(year, 1, 1).., @@ -357,10 +353,10 @@ fn test_dates_in_year() { let mut dates = dates_in_year(2013); assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 1, 1))); - // Check increment + // Check increment. assert_eq!(dates.next(), Some(NaiveDate::from_ymd(2013, 1, 2))); - // Check monthly rollover + // Check monthly roll-over. for _ in 3..31 { assert!(dates.next() != None); } @@ -370,7 +366,7 @@ fn test_dates_in_year() { } { - // Check length of year + // Check length of year. let mut dates = dates_in_year(2013); for _ in 0..365 { assert!(dates.next() != None); @@ -379,7 +375,7 @@ fn test_dates_in_year() { } { - // Check length of leap year + // Check length of leap year. let mut dates = dates_in_year(1984); for _ in 0..366 { assert!(dates.next() != None); @@ -388,10 +384,8 @@ fn test_dates_in_year() { } } -/// /// Convenience trait for verifying that a given type iterates over /// `NaiveDate`s. -/// trait DateIterator: Iterator + Clone {} impl DateIterator for It where It: Iterator + Clone {} @@ -427,11 +421,9 @@ fn test_group_by() { } } -/// /// Groups an iterator of dates by month. -/// fn by_month(it: impl Iterator + Clone) - -> impl Iterator + Clone)> + Clone + -> impl Iterator + Clone)> + Clone { it.group_by(|d| d.month()) } @@ -444,9 +436,7 @@ fn test_by_month() { assert!(months.next().is_none()); } -/// /// Groups an iterator of dates by week. -/// fn by_week(it: impl DateIterator) -> impl Iterator + Clone { @@ -518,9 +508,7 @@ const COLS_PER_DAY: u32 = 3; /// The number of columns per week in the formatted output. const COLS_PER_WEEK: u32 = 7 * COLS_PER_DAY; -/// /// Formats an iterator of weeks into an iterator of strings. -/// fn format_weeks(it: impl Iterator) -> impl Iterator { it.map(|week| { let mut buf = String::with_capacity((COLS_PER_DAY * COLS_PER_WEEK + 2) as usize); @@ -541,7 +529,7 @@ fn format_weeks(it: impl Iterator) -> impl Iterator String { const MONTH_NAMES: &'static [&'static str] = &[ "January", "February", "March", "April", "May", "June", @@ -584,7 +570,7 @@ fn month_title(month: u32) -> String { let before = (COLS_PER_WEEK as usize - name.len()) / 2; let after = COLS_PER_WEEK as usize - name.len() - before; - // NOTE: Being slightly more verbose to avoid extra allocations. + // Note: being slightly more verbose to avoid extra allocations. let mut result = String::with_capacity(COLS_PER_WEEK as usize); result.extend(spaces(before)); result.push_str(name); @@ -596,9 +582,7 @@ fn test_month_title() { assert_eq!(month_title(1).len(), COLS_PER_WEEK as usize); } -/// /// Formats a month. -/// fn format_month(it: impl DateIterator) -> impl Iterator { let mut month_days = it.peekable(); let title = month_title(month_days.peek().unwrap().month()); @@ -627,22 +611,17 @@ fn test_format_month() { ); } - -/// /// Formats an iterator of months. -/// fn format_months(it: impl Iterator) -> impl Iterator> { it.map(format_month) } -/// /// Takes an iterator of iterators of strings; the sub-iterators are consumed /// in lock-step, with their elements joined together. -/// trait PasteBlocks: Iterator + Sized -where Self::Item: Iterator { +where Self::Item: Iterator { fn paste_blocks(self, sep_width: usize) -> PasteBlocksIter { PasteBlocksIter { iters: self.collect(), @@ -721,9 +700,7 @@ fn test_paste_blocks() { ); } -/// /// Produces an iterator that yields `n` elements at a time. -/// trait Chunks: Iterator + Sized { fn chunks(self, n: usize) -> ChunksIter { assert!(n > 0); @@ -742,7 +719,7 @@ where It: Iterator { n: usize, } -// NOTE: `chunks` in Rust is more-or-less impossible without overhead of some kind. +// Note: `chunks` in Rust is more-or-less impossible without overhead of some kind. // Aliasing rules mean you need to add dynamic borrow checking, and the design of // `Iterator` means that you need to have the iterator's state kept in an allocation // that is jointly owned by the iterator itself and the sub-iterator. @@ -769,9 +746,7 @@ fn test_chunks() { assert_eq!(&*c, &[vec![1, 2, 3], vec![4, 5, 6], vec![7]]); } -/// /// Formats a year. -/// fn format_year(year: i32, months_per_row: usize) -> String { const COL_SPACING: usize = 1; @@ -784,17 +759,17 @@ fn format_year(year: i32, months_per_row: usize) -> String { // Group the months into horizontal rows. .chunks(months_per_row) - // Format each row + // Format each row... .map(|r| r.into_iter() - // By formatting each month + // ... by formatting each month ... .__(format_months) - // Horizontally pasting each respective month's lines together. + // ... and horizontally pasting each respective month's lines together. .paste_blocks(COL_SPACING) .join("\n") ) - // Insert a blank line between each row + // Insert a blank line between each row. .join("\n\n") } diff --git a/src/test/run-pass/issues/issue-23808.rs b/src/test/run-pass/issues/issue-23808.rs index 133da00ffaa..59c3e395cf9 100644 --- a/src/test/run-pass/issues/issue-23808.rs +++ b/src/test/run-pass/issues/issue-23808.rs @@ -9,6 +9,7 @@ // except according to those terms. // run-pass + #![deny(dead_code)] // use different types / traits to test all combinations diff --git a/src/test/run-pass/issues/issue-24805-dropck-itemless.rs b/src/test/run-pass/issues/issue-24805-dropck-itemless.rs index 1d1bd21075b..b9d2523cd79 100644 --- a/src/test/run-pass/issues/issue-24805-dropck-itemless.rs +++ b/src/test/run-pass/issues/issue-24805-dropck-itemless.rs @@ -23,7 +23,7 @@ trait UserDefined { } impl UserDefined for i32 { } impl<'a, T> UserDefined for &'a T { } -// e.g. `impl_drop!(Send, D_Send)` expands to: +// e.g., `impl_drop!(Send, D_Send)` expands to: // ```rust // struct D_Send(T); // impl Drop for D_Send { fn drop(&mut self) { } } diff --git a/src/test/run-pass/issues/issue-26996.rs b/src/test/run-pass/issues/issue-26996.rs index 83445c6657e..61ac665caf6 100644 --- a/src/test/run-pass/issues/issue-26996.rs +++ b/src/test/run-pass/issues/issue-26996.rs @@ -10,7 +10,7 @@ // run-pass -// This test is bogus (i.e. should be compile-fail) during the period +// This test is bogus (i.e., should be compile-fail) during the period // where #54986 is implemented and #54987 is *not* implemented. For // now: just ignore it under nll // diff --git a/src/test/run-pass/issues/issue-27021.rs b/src/test/run-pass/issues/issue-27021.rs index dbad8556aeb..21e4568a520 100644 --- a/src/test/run-pass/issues/issue-27021.rs +++ b/src/test/run-pass/issues/issue-27021.rs @@ -10,7 +10,7 @@ // run-pass -// This test is bogus (i.e. should be compile-fail) during the period +// This test is bogus (i.e., should be compile-fail) during the period // where #54986 is implemented and #54987 is *not* implemented. For // now: just ignore it under nll // diff --git a/src/test/run-pass/issues/issue-3563-3.rs b/src/test/run-pass/issues/issue-3563-3.rs index 13d74be89d8..6ba1a7b8dfa 100644 --- a/src/test/run-pass/issues/issue-3563-3.rs +++ b/src/test/run-pass/issues/issue-3563-3.rs @@ -128,7 +128,7 @@ trait Canvas { } // Here we provide an implementation of the Canvas methods for AsciiArt. -// Other implementations could also be provided (e.g. for PDF or Apple's Quartz) +// Other implementations could also be provided (e.g., for PDF or Apple's Quartz) // and code can use them polymorphically via the Canvas trait. impl Canvas for AsciiArt { fn add_point(&mut self, shape: Point) { diff --git a/src/test/run-pass/issues/issue-49298.rs b/src/test/run-pass/issues/issue-49298.rs index db3c9792f35..42cfb6f6176 100644 --- a/src/test/run-pass/issues/issue-49298.rs +++ b/src/test/run-pass/issues/issue-49298.rs @@ -12,7 +12,7 @@ #![feature(test)] #![allow(unused_mut)] // under NLL we get warning about `x` below: rust-lang/rust#54499 -// This test is bogus (i.e. should be compile-fail) during the period +// This test is bogus (i.e., should be compile-fail) during the period // where #54986 is implemented and #54987 is *not* implemented. For // now: just ignore it under nll // diff --git a/src/test/run-pass/issues/issue-49955-2.rs b/src/test/run-pass/issues/issue-49955-2.rs index 88883821073..94aaa631bc1 100644 --- a/src/test/run-pass/issues/issue-49955-2.rs +++ b/src/test/run-pass/issues/issue-49955-2.rs @@ -18,7 +18,7 @@ const FIVE: Cell = Cell::new(5); #[inline(never)] fn tuple_field() -> &'static u32 { // This test is MIR-borrowck-only because the old borrowck - // doesn't agree that borrows of "frozen" (i.e. without any + // doesn't agree that borrows of "frozen" (i.e., without any // interior mutability) fields of non-frozen temporaries, // should be promoted, while MIR promotion does promote them. &(FIVE, 42).1 diff --git a/src/test/run-pass/lexer-crlf-line-endings-string-literal-doc-comment.rs b/src/test/run-pass/lexer-crlf-line-endings-string-literal-doc-comment.rs index 05f1f1bfea0..77b6ba1e4f8 100644 --- a/src/test/run-pass/lexer-crlf-line-endings-string-literal-doc-comment.rs +++ b/src/test/run-pass/lexer-crlf-line-endings-string-literal-doc-comment.rs @@ -12,7 +12,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// NB: this file needs CRLF line endings. The .gitattributes file in +// N.B., this file needs CRLF line endings. The .gitattributes file in // this directory should enforce it. // ignore-pretty issue #37195 diff --git a/src/test/run-pass/lint-non-camel-case-types-non-uppercase-statics-unicode.rs b/src/test/run-pass/lint-non-camel-case-types-non-uppercase-statics-unicode.rs index 14ef8c1f51f..71f39c12957 100644 --- a/src/test/run-pass/lint-non-camel-case-types-non-uppercase-statics-unicode.rs +++ b/src/test/run-pass/lint-non-camel-case-types-non-uppercase-statics-unicode.rs @@ -15,7 +15,7 @@ #![forbid(non_upper_case_globals)] #![feature(non_ascii_idents)] -// Some scripts (e.g. hiragana) don't have a concept of +// Some scripts (e.g., hiragana) don't have a concept of // upper/lowercase struct ヒ; diff --git a/src/test/run-pass/macros/macro-comma-behavior.rs b/src/test/run-pass/macros/macro-comma-behavior.rs index 95774cad229..b245fe1107b 100644 --- a/src/test/run-pass/macros/macro-comma-behavior.rs +++ b/src/test/run-pass/macros/macro-comma-behavior.rs @@ -15,7 +15,7 @@ // // This checks the behavior of macros with trailing commas in key // places where regressions in behavior seem highly possible (due -// to it being e.g. a place where the addition of an argument +// to it being e.g., a place where the addition of an argument // causes it to go down a code path with subtly different behavior). // // There is a companion test in compile-fail. diff --git a/src/test/run-pass/packed/packed-struct-optimized-enum.rs b/src/test/run-pass/packed/packed-struct-optimized-enum.rs index e22e8c26fe5..98772778010 100644 --- a/src/test/run-pass/packed/packed-struct-optimized-enum.rs +++ b/src/test/run-pass/packed/packed-struct-optimized-enum.rs @@ -34,12 +34,12 @@ fn main() { // In #46769, `Option<(Packed<&()>, bool)>` was found to have // pointer alignment, without actually being aligned in size. - // E.g. on 64-bit platforms, it had alignment `8` but size `9`. + // e.g., on 64-bit platforms, it had alignment `8` but size `9`. type PackedRefAndBool<'a> = (Packed<&'a ()>, bool); sanity_check_size::>(Some((Packed(&()), true))); // Make sure we don't pay for the enum optimization in size, - // e.g. we shouldn't need extra padding after the packed data. + // e.g., we shouldn't need extra padding after the packed data. assert_eq!(std::mem::align_of::>(), 1); assert_eq!(std::mem::size_of::>(), std::mem::size_of::()); diff --git a/src/test/run-pass/regions/regions-early-bound-trait-param.rs b/src/test/run-pass/regions/regions-early-bound-trait-param.rs index 220614c9203..70cb4bcbd6f 100644 --- a/src/test/run-pass/regions/regions-early-bound-trait-param.rs +++ b/src/test/run-pass/regions/regions-early-bound-trait-param.rs @@ -131,7 +131,7 @@ pub fn main() { // for details. assert_eq!(object_invoke2(&*m), 5); - // The RefMakerTrait above is pretty strange (i.e. it is strange + // The RefMakerTrait above is pretty strange (i.e., it is strange // to consume a value of type T and return a &T). Easiest thing // that came to my mind: consume a cell of a linked list and // return a reference to the list it points to. diff --git a/src/test/run-pass/simd/simd-intrinsic-generic-cast.rs b/src/test/run-pass/simd/simd-intrinsic-generic-cast.rs index f0fb24b5832..df5f72e378d 100644 --- a/src/test/run-pass/simd/simd-intrinsic-generic-cast.rs +++ b/src/test/run-pass/simd/simd-intrinsic-generic-cast.rs @@ -94,9 +94,9 @@ fn main() { // there are platform differences for some out of range // casts, so we just normalize such things: it's OK for // "invalid" calculations to result in nonsense answers. - // (E.g. negative float to unsigned integer goes through a + // (e.g., negative float to unsigned integer goes through a // library routine on the default i686 platforms, and the - // implementation of that routine differs on e.g. Linux + // implementation of that routine differs on e.g., Linux // vs. macOS, resulting in different answers.) if $from::is_float() { if !$to::in_range(A) { from.0 = 0 as $to; to.0 = 0 as $to; } diff --git a/src/test/run-pass/try-operator-hygiene.rs b/src/test/run-pass/try-operator-hygiene.rs index 045a8a50320..2771ab4233f 100644 --- a/src/test/run-pass/try-operator-hygiene.rs +++ b/src/test/run-pass/try-operator-hygiene.rs @@ -17,7 +17,7 @@ // Err(err) => return Err(From::from(err)), // } // -// This test verifies that the expansion is hygienic, i.e. it's not affected by other `val` and +// This test verifies that the expansion is hygienic, i.e., it's not affected by other `val` and // `err` bindings that may be in scope. use std::num::ParseIntError; diff --git a/src/test/run-pass/uniform-paths/basic-nested.rs b/src/test/run-pass/uniform-paths/basic-nested.rs index a0256187dbb..c6a95ba4089 100644 --- a/src/test/run-pass/uniform-paths/basic-nested.rs +++ b/src/test/run-pass/uniform-paths/basic-nested.rs @@ -41,7 +41,7 @@ use std::io; mod bar { // Also test the unqualified external crate import in a nested module, // to show that the above import doesn't resolve through a local `std` - // item, e.g. the automatically injected `extern crate std;`, which in + // item, e.g., the automatically injected `extern crate std;`, which in // the Rust 2018 should no longer be visible through `crate::std`. pub use std::io; diff --git a/src/test/run-pass/uniform-paths/macros-nested.rs b/src/test/run-pass/uniform-paths/macros-nested.rs index 373734345fc..f22113df80e 100644 --- a/src/test/run-pass/uniform-paths/macros-nested.rs +++ b/src/test/run-pass/uniform-paths/macros-nested.rs @@ -50,7 +50,7 @@ use std::io; mod bar { // Also test the unqualified external crate import in a nested module, // to show that the above import doesn't resolve through a local `std` - // item, e.g. the automatically injected `extern crate std;`, which in + // item, e.g., the automatically injected `extern crate std;`, which in // the Rust 2018 should no longer be visible through `crate::std`. pub use std::io; } diff --git a/src/test/ui/associated-const/associated-const-no-item.stderr b/src/test/ui/associated-const/associated-const-no-item.stderr index a09c04ea0b2..31f9683ca0f 100644 --- a/src/test/ui/associated-const/associated-const-no-item.stderr +++ b/src/test/ui/associated-const/associated-const-no-item.stderr @@ -1,8 +1,10 @@ error[E0599]: no associated item named `ID` found for type `i32` in the current scope - --> $DIR/associated-const-no-item.rs:16:16 + --> $DIR/associated-const-no-item.rs:16:23 | LL | const X: i32 = ::ID; - | ^^^^^^^^^ associated item not found in `i32` + | -------^^ + | | + | associated item not found in `i32` | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `ID`, perhaps you need to implement it: diff --git a/src/test/ui/bogus-tag.stderr b/src/test/ui/bogus-tag.stderr index f9917b07f07..36ed28c345a 100644 --- a/src/test/ui/bogus-tag.stderr +++ b/src/test/ui/bogus-tag.stderr @@ -1,11 +1,11 @@ error[E0599]: no variant named `hsl` found for type `color` in the current scope - --> $DIR/bogus-tag.rs:18:7 + --> $DIR/bogus-tag.rs:18:14 | LL | enum color { rgb(isize, isize, isize), rgba(isize, isize, isize, isize), } | ---------- variant `hsl` not found here ... LL | color::hsl(h, s, l) => { println!("hsl"); } - | ^^^^^^^^^^^^^^^^^^^ variant not found in `color` + | -------^^^--------- variant not found in `color` error: aborting due to previous error diff --git a/src/test/ui/borrowck/two-phase-nonrecv-autoref.rs b/src/test/ui/borrowck/two-phase-nonrecv-autoref.rs index 30752e8ddb1..fd4c108b594 100644 --- a/src/test/ui/borrowck/two-phase-nonrecv-autoref.rs +++ b/src/test/ui/borrowck/two-phase-nonrecv-autoref.rs @@ -49,7 +49,7 @@ fn deref_coercion(x: &mut u32) { // // - [x] Resolving overloaded_call_traits (call, call_mut, call_once) // - [x] deref_coercion (shown above) -// - [x] coerce_unsized e.g. `&[T; n]`, `&mut [T; n] -> &[T]`, +// - [x] coerce_unsized e.g., `&[T; n]`, `&mut [T; n] -> &[T]`, // `&mut [T; n] -> &mut [T]`, `&Concrete -> &Trait` // - [x] Method Call Receivers (the case we want to support!) // - [x] ExprKind::Index and ExprKind::Unary Deref; only need to handle coerce_index_op diff --git a/src/test/ui/coherence/coherence-all-remote.stderr b/src/test/ui/coherence/coherence-all-remote.stderr index 1f71969989b..718ab3dedc4 100644 --- a/src/test/ui/coherence/coherence-all-remote.stderr +++ b/src/test/ui/coherence/coherence-all-remote.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-all-remote.rs:16:1 | LL | impl Remote1 for isize { } diff --git a/src/test/ui/coherence/coherence-bigint-param.stderr b/src/test/ui/coherence/coherence-bigint-param.stderr index 7d2796ee690..a5d9f5a403f 100644 --- a/src/test/ui/coherence/coherence-bigint-param.stderr +++ b/src/test/ui/coherence/coherence-bigint-param.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-bigint-param.rs:18:1 | LL | impl Remote1 for T { } diff --git a/src/test/ui/coherence/coherence-cow.a.stderr b/src/test/ui/coherence/coherence-cow.a.stderr index f05333348ec..368935f4cfb 100644 --- a/src/test/ui/coherence/coherence-cow.a.stderr +++ b/src/test/ui/coherence/coherence-cow.a.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-cow.rs:26:1 | LL | impl Remote for Pair> { } //[a]~ ERROR E0210 diff --git a/src/test/ui/coherence/coherence-cow.b.stderr b/src/test/ui/coherence/coherence-cow.b.stderr index 269bcd576af..74ad8502add 100644 --- a/src/test/ui/coherence/coherence-cow.b.stderr +++ b/src/test/ui/coherence/coherence-cow.b.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-cow.rs:29:1 | LL | impl Remote for Pair,T> { } //[b]~ ERROR E0210 diff --git a/src/test/ui/coherence/coherence-cow.c.stderr b/src/test/ui/coherence/coherence-cow.c.stderr index e89308db054..2e3a6b54e84 100644 --- a/src/test/ui/coherence/coherence-cow.c.stderr +++ b/src/test/ui/coherence/coherence-cow.c.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-cow.rs:32:1 | LL | impl Remote for Pair,U> { } diff --git a/src/test/ui/coherence/coherence-cross-crate-conflict.stderr b/src/test/ui/coherence/coherence-cross-crate-conflict.stderr index ee11967cc0d..31c41ab7234 100644 --- a/src/test/ui/coherence/coherence-cross-crate-conflict.stderr +++ b/src/test/ui/coherence/coherence-cross-crate-conflict.stderr @@ -7,7 +7,7 @@ LL | impl Foo for A { = note: conflicting implementation in crate `trait_impl_conflict`: - impl trait_impl_conflict::Foo for isize; -error[E0210]: type parameter `A` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `A` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-cross-crate-conflict.rs:18:1 | LL | impl Foo for A { diff --git a/src/test/ui/coherence/coherence-lone-type-parameter.stderr b/src/test/ui/coherence/coherence-lone-type-parameter.stderr index 6389bc0e7ab..e3a77229634 100644 --- a/src/test/ui/coherence/coherence-lone-type-parameter.stderr +++ b/src/test/ui/coherence/coherence-lone-type-parameter.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-lone-type-parameter.rs:16:1 | LL | impl Remote for T { } diff --git a/src/test/ui/coherence/coherence-overlapping-pairs.stderr b/src/test/ui/coherence/coherence-overlapping-pairs.stderr index 41d47888554..286ebefba15 100644 --- a/src/test/ui/coherence/coherence-overlapping-pairs.stderr +++ b/src/test/ui/coherence/coherence-overlapping-pairs.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-overlapping-pairs.rs:18:1 | LL | impl Remote for lib::Pair { } diff --git a/src/test/ui/coherence/coherence-pair-covered-uncovered-1.stderr b/src/test/ui/coherence/coherence-pair-covered-uncovered-1.stderr index 3545593fb6d..80ab0cc09f9 100644 --- a/src/test/ui/coherence/coherence-pair-covered-uncovered-1.stderr +++ b/src/test/ui/coherence/coherence-pair-covered-uncovered-1.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-pair-covered-uncovered-1.rs:21:1 | LL | impl Remote1>> for i32 { } diff --git a/src/test/ui/coherence/coherence-pair-covered-uncovered.stderr b/src/test/ui/coherence/coherence-pair-covered-uncovered.stderr index f58cb4648cb..25b4948e083 100644 --- a/src/test/ui/coherence/coherence-pair-covered-uncovered.stderr +++ b/src/test/ui/coherence/coherence-pair-covered-uncovered.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-pair-covered-uncovered.rs:18:1 | LL | impl Remote for Pair> { } diff --git a/src/test/ui/coherence/coherence-vec-local-2.stderr b/src/test/ui/coherence/coherence-vec-local-2.stderr index 2980d4a3392..0ccd938e900 100644 --- a/src/test/ui/coherence/coherence-vec-local-2.stderr +++ b/src/test/ui/coherence/coherence-vec-local-2.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/coherence-vec-local-2.rs:21:1 | LL | impl Remote for Vec> { } //~ ERROR E0210 diff --git a/src/test/ui/constructor-lifetime-args.rs b/src/test/ui/constructor-lifetime-args.rs index 1fe50cfebba..a03599ada1c 100644 --- a/src/test/ui/constructor-lifetime-args.rs +++ b/src/test/ui/constructor-lifetime-args.rs @@ -9,7 +9,7 @@ // except according to those terms. // All lifetime parameters in struct constructors are currently considered early bound, -// i.e. `S::` is interpreted kinda like an associated item `S::::ctor`. +// i.e., `S::` is interpreted kinda like an associated item `S::::ctor`. // This behavior is a bit weird, because if equivalent constructor were written manually // it would get late bound lifetime parameters. // Variant constructors behave in the same way, lifetime parameters are considered diff --git a/src/test/ui/consts/const-eval/const-eval-overflow2.rs b/src/test/ui/consts/const-eval/const-eval-overflow2.rs index 8e094a7f7dc..7819cafdb0f 100644 --- a/src/test/ui/consts/const-eval/const-eval-overflow2.rs +++ b/src/test/ui/consts/const-eval/const-eval-overflow2.rs @@ -11,7 +11,7 @@ #![allow(unused_imports)] // Note: the relevant lint pass here runs before some of the constant -// evaluation below (e.g. that performed by codegen and llvm), so if you +// evaluation below (e.g., that performed by codegen and llvm), so if you // change this warn to a deny, then the compiler will exit before // those errors are detected. diff --git a/src/test/ui/consts/const-eval/const-eval-overflow2b.rs b/src/test/ui/consts/const-eval/const-eval-overflow2b.rs index c69d03071e7..475a5117685 100644 --- a/src/test/ui/consts/const-eval/const-eval-overflow2b.rs +++ b/src/test/ui/consts/const-eval/const-eval-overflow2b.rs @@ -11,7 +11,7 @@ #![allow(unused_imports)] // Note: the relevant lint pass here runs before some of the constant -// evaluation below (e.g. that performed by codegen and llvm), so if you +// evaluation below (e.g., that performed by codegen and llvm), so if you // change this warn to a deny, then the compiler will exit before // those errors are detected. diff --git a/src/test/ui/consts/const-eval/const-eval-overflow2c.rs b/src/test/ui/consts/const-eval/const-eval-overflow2c.rs index f442661ec63..039e6b251cd 100644 --- a/src/test/ui/consts/const-eval/const-eval-overflow2c.rs +++ b/src/test/ui/consts/const-eval/const-eval-overflow2c.rs @@ -11,7 +11,7 @@ #![allow(unused_imports)] // Note: the relevant lint pass here runs before some of the constant -// evaluation below (e.g. that performed by codegen and llvm), so if you +// evaluation below (e.g., that performed by codegen and llvm), so if you // change this warn to a deny, then the compiler will exit before // those errors are detected. diff --git a/src/test/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr b/src/test/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr index b3d7ba3e5c4..85b63f5c471 100644 --- a/src/test/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr +++ b/src/test/ui/consts/const-eval/dont_promote_unstable_const_fn.stderr @@ -4,7 +4,7 @@ error: `foo` is not yet stable as a const fn LL | const fn bar() -> u32 { foo() } //~ ERROR `foo` is not yet stable as a const fn | ^^^^^ | - = help: in Nightly builds, add `#![feature(foo)]` to the crate attributes to enable + = help: add `#![feature(foo)]` to the crate attributes to enable error[E0597]: borrowed value does not live long enough --> $DIR/dont_promote_unstable_const_fn.rs:28:28 diff --git a/src/test/ui/consts/const-pattern-irrefutable.rs b/src/test/ui/consts/const-pattern-irrefutable.rs index 278864d6de9..2f08d124848 100644 --- a/src/test/ui/consts/const-pattern-irrefutable.rs +++ b/src/test/ui/consts/const-pattern-irrefutable.rs @@ -22,5 +22,5 @@ fn main() { let a = 4; //~ ERROR refutable pattern in local binding: `0u8..=1u8` not covered let c = 4; //~ ERROR refutable pattern in local binding: `0u8..=1u8` not covered let d = 4; //~ ERROR refutable pattern in local binding: `0u8..=1u8` not covered - fn f() {} // Check that the `NOTE`s still work with an item here (c.f. issue #35115). + fn f() {} // Check that the `NOTE`s still work with an item here (cf. issue #35115). } diff --git a/src/test/ui/consts/const-typeid-of.stderr b/src/test/ui/consts/const-typeid-of.stderr index d13ced9a10a..ba5f65988e2 100644 --- a/src/test/ui/consts/const-typeid-of.stderr +++ b/src/test/ui/consts/const-typeid-of.stderr @@ -4,7 +4,7 @@ error: `std::any::TypeId::of` is not yet stable as a const fn LL | const A_ID: TypeId = TypeId::of::(); | ^^^^^^^^^^^^^^^^^ | - = help: in Nightly builds, add `#![feature(const_type_id)]` to the crate attributes to enable + = help: add `#![feature(const_type_id)]` to the crate attributes to enable error: aborting due to previous error diff --git a/src/test/ui/did_you_mean/bad-assoc-pat.stderr b/src/test/ui/did_you_mean/bad-assoc-pat.stderr index 10ee175a97e..a7b3846a8f6 100644 --- a/src/test/ui/did_you_mean/bad-assoc-pat.stderr +++ b/src/test/ui/did_you_mean/bad-assoc-pat.stderr @@ -23,28 +23,36 @@ LL | &(u8,)::AssocItem => {} | ^^^^^^^^^^^^^^^^ help: try: `<(u8,)>::AssocItem` error[E0599]: no associated item named `AssocItem` found for type `[u8]` in the current scope - --> $DIR/bad-assoc-pat.rs:13:9 + --> $DIR/bad-assoc-pat.rs:13:15 | LL | [u8]::AssocItem => {} - | ^^^^^^^^^^^^^^^ associated item not found in `[u8]` + | ------^^^^^^^^^ + | | + | associated item not found in `[u8]` error[E0599]: no associated item named `AssocItem` found for type `(u8, u8)` in the current scope - --> $DIR/bad-assoc-pat.rs:16:9 + --> $DIR/bad-assoc-pat.rs:16:19 | LL | (u8, u8)::AssocItem => {} - | ^^^^^^^^^^^^^^^^^^^ associated item not found in `(u8, u8)` + | ----------^^^^^^^^^ + | | + | associated item not found in `(u8, u8)` error[E0599]: no associated item named `AssocItem` found for type `_` in the current scope - --> $DIR/bad-assoc-pat.rs:19:9 + --> $DIR/bad-assoc-pat.rs:19:12 | LL | _::AssocItem => {} - | ^^^^^^^^^^^^ associated item not found in `_` + | ---^^^^^^^^^ + | | + | associated item not found in `_` error[E0599]: no associated item named `AssocItem` found for type `(u8,)` in the current scope - --> $DIR/bad-assoc-pat.rs:24:10 + --> $DIR/bad-assoc-pat.rs:24:17 | LL | &(u8,)::AssocItem => {} - | ^^^^^^^^^^^^^^^^ associated item not found in `(u8,)` + | -------^^^^^^^^^ + | | + | associated item not found in `(u8,)` error: aborting due to 8 previous errors diff --git a/src/test/ui/dont-suggest-private-trait-method.stderr b/src/test/ui/dont-suggest-private-trait-method.stderr index 81ecc546a6d..c2f21606e21 100644 --- a/src/test/ui/dont-suggest-private-trait-method.stderr +++ b/src/test/ui/dont-suggest-private-trait-method.stderr @@ -1,11 +1,13 @@ error[E0599]: no function or associated item named `new` found for type `T` in the current scope - --> $DIR/dont-suggest-private-trait-method.rs:14:5 + --> $DIR/dont-suggest-private-trait-method.rs:14:8 | LL | struct T; | --------- function or associated item `new` not found for this ... LL | T::new(); - | ^^^^^^ function or associated item not found in `T` + | ---^^^ + | | + | function or associated item not found in `T` error: aborting due to previous error diff --git a/src/test/ui/dropck/dropck-eyepatch.rs b/src/test/ui/dropck/dropck-eyepatch.rs index d7a671fd33c..fb1c03b6786 100644 --- a/src/test/ui/dropck/dropck-eyepatch.rs +++ b/src/test/ui/dropck/dropck-eyepatch.rs @@ -31,7 +31,7 @@ // - D means "I implement Drop" // // - P means "I implement Drop but guarantee my (first) parameter is -// pure, i.e. not accessed from the destructor"; no other parameters +// pure, i.e., not accessed from the destructor"; no other parameters // are pure. // // - S means "I do not implement Drop" diff --git a/src/test/ui/e0119/complex-impl.stderr b/src/test/ui/e0119/complex-impl.stderr index 1fc4c28d67c..d60f9c4e6a8 100644 --- a/src/test/ui/e0119/complex-impl.stderr +++ b/src/test/ui/e0119/complex-impl.stderr @@ -8,7 +8,7 @@ LL | impl External for (Q, R) {} //~ ERROR must be used - impl<'a, 'b, 'c, T, U, V, W> complex_impl_support::External for (T, complex_impl_support::M<'a, 'b, 'c, std::boxed::Box, V, W>) where >::Output == V, ::Item == T, 'b : 'a, T : 'a, U: std::ops::FnOnce<(T,)>, U : 'static, V: std::iter::Iterator, V: std::clone::Clone, W: std::ops::Add, ::Output: std::marker::Copy; -error[E0210]: type parameter `R` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `R` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/complex-impl.rs:19:1 | LL | impl External for (Q, R) {} //~ ERROR must be used diff --git a/src/test/ui/e0119/issue-28981.stderr b/src/test/ui/e0119/issue-28981.stderr index 76ff88d6cc6..b5ec1c8454b 100644 --- a/src/test/ui/e0119/issue-28981.stderr +++ b/src/test/ui/e0119/issue-28981.stderr @@ -8,7 +8,7 @@ LL | impl Deref for Foo { } //~ ERROR must be used - impl std::ops::Deref for &T where T: ?Sized; -error[E0210]: type parameter `Foo` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `Foo` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/issue-28981.rs:15:1 | LL | impl Deref for Foo { } //~ ERROR must be used diff --git a/src/test/ui/empty/empty-struct-braces-expr.stderr b/src/test/ui/empty/empty-struct-braces-expr.stderr index 9b6114875e2..3252d0db4dc 100644 --- a/src/test/ui/empty/empty-struct-braces-expr.stderr +++ b/src/test/ui/empty/empty-struct-braces-expr.stderr @@ -47,20 +47,24 @@ LL | let xe1 = XEmpty1(); //~ ERROR expected function, found struct `XEmpty1 | did you mean `XEmpty1 { /* fields */ }`? error[E0599]: no variant named `Empty3` found for type `empty_struct::XE` in the current scope - --> $DIR/empty-struct-braces-expr.rs:32:15 + --> $DIR/empty-struct-braces-expr.rs:32:19 | LL | let xe3 = XE::Empty3; //~ ERROR no variant named `Empty3` found for type - | ^^^^^^^^^^ variant not found in `empty_struct::XE` + | ----^^^^^^ + | | + | variant not found in `empty_struct::XE` | - = note: did you mean `empty_struct::XE::XEmpty3`? + = help: did you mean `XEmpty3`? error[E0599]: no variant named `Empty3` found for type `empty_struct::XE` in the current scope - --> $DIR/empty-struct-braces-expr.rs:33:15 + --> $DIR/empty-struct-braces-expr.rs:33:19 | LL | let xe3 = XE::Empty3(); //~ ERROR no variant named `Empty3` found for type - | ^^^^^^^^^^ variant not found in `empty_struct::XE` + | ----^^^^^^ + | | + | variant not found in `empty_struct::XE` | - = note: did you mean `empty_struct::XE::XEmpty3`? + = help: did you mean `XEmpty3`? error: aborting due to 8 previous errors diff --git a/src/test/ui/error-codes/E0599.stderr b/src/test/ui/error-codes/E0599.stderr index d118939d17a..f6bdc8b8579 100644 --- a/src/test/ui/error-codes/E0599.stderr +++ b/src/test/ui/error-codes/E0599.stderr @@ -1,11 +1,11 @@ error[E0599]: no associated item named `NotEvenReal` found for type `Foo` in the current scope - --> $DIR/E0599.rs:14:15 + --> $DIR/E0599.rs:14:20 | LL | struct Foo; | ----------- associated item `NotEvenReal` not found for this ... LL | || if let Foo::NotEvenReal() = Foo {}; //~ ERROR E0599 - | ^^^^^^^^^^^^^^^^^^ associated item not found in `Foo` + | -----^^^^^^^^^^^-- associated item not found in `Foo` error: aborting due to previous error diff --git a/src/test/ui/imports/unused.rs b/src/test/ui/imports/unused.rs index 1eb756fe9e4..d241ab62976 100644 --- a/src/test/ui/imports/unused.rs +++ b/src/test/ui/imports/unused.rs @@ -23,7 +23,7 @@ mod foo { } mod m3 { - pub(super) use super::f; // Check that this is counted as used (c.f. #36249). + pub(super) use super::f; // Check that this is counted as used (cf. issue #36249). } pub mod m4 { diff --git a/src/test/ui/invalid/invalid-path-in-const.stderr b/src/test/ui/invalid/invalid-path-in-const.stderr index 9214800b93a..47fb717d0ca 100644 --- a/src/test/ui/invalid/invalid-path-in-const.stderr +++ b/src/test/ui/invalid/invalid-path-in-const.stderr @@ -1,8 +1,10 @@ error[E0599]: no associated item named `DOESNOTEXIST` found for type `u32` in the current scope - --> $DIR/invalid-path-in-const.rs:12:18 + --> $DIR/invalid-path-in-const.rs:12:23 | LL | fn f(a: [u8; u32::DOESNOTEXIST]) {} - | ^^^^^^^^^^^^^^^^^ associated item not found in `u32` + | -----^^^^^^^^^^^^ + | | + | associated item not found in `u32` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-20261.rs b/src/test/ui/issues/issue-20261.rs index bb4dbdcd0cb..0330ac658d8 100644 --- a/src/test/ui/issues/issue-20261.rs +++ b/src/test/ui/issues/issue-20261.rs @@ -9,7 +9,7 @@ // except according to those terms. fn main() { - // NB: this (almost) typechecks when default binding modes are enabled. + // N.B., this (almost) typechecks when default binding modes are enabled. for (ref i,) in [].iter() { i.clone(); //~^ ERROR type annotations needed diff --git a/src/test/ui/issues/issue-22933-2.stderr b/src/test/ui/issues/issue-22933-2.stderr index 435a89b716f..97445b60965 100644 --- a/src/test/ui/issues/issue-22933-2.stderr +++ b/src/test/ui/issues/issue-22933-2.stderr @@ -1,11 +1,13 @@ error[E0599]: no variant named `PIE` found for type `Delicious` in the current scope - --> $DIR/issue-22933-2.rs:14:44 + --> $DIR/issue-22933-2.rs:14:55 | LL | enum Delicious { | -------------- variant `PIE` not found here ... LL | ApplePie = Delicious::Apple as isize | Delicious::PIE as isize, - | ^^^^^^^^^^^^^^ variant not found in `Delicious` + | -----------^^^ + | | + | variant not found in `Delicious` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-22933-3.stderr b/src/test/ui/issues/issue-22933-3.stderr index 3d4d2df4d32..d3ea39b2adb 100644 --- a/src/test/ui/issues/issue-22933-3.stderr +++ b/src/test/ui/issues/issue-22933-3.stderr @@ -1,8 +1,10 @@ error[E0599]: no associated item named `MIN` found for type `u8` in the current scope - --> $DIR/issue-22933-3.rs:11:18 + --> $DIR/issue-22933-3.rs:11:22 | LL | const FOO: [u32; u8::MIN as usize] = []; - | ^^^^^^^ associated item not found in `u8` + | ----^^^ + | | + | associated item not found in `u8` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-23173.stderr b/src/test/ui/issues/issue-23173.stderr index d58a4d2b8f8..14a1188710f 100644 --- a/src/test/ui/issues/issue-23173.stderr +++ b/src/test/ui/issues/issue-23173.stderr @@ -1,38 +1,46 @@ error[E0599]: no variant named `Homura` found for type `Token` in the current scope - --> $DIR/issue-23173.rs:19:16 + --> $DIR/issue-23173.rs:19:23 | LL | enum Token { LeftParen, RightParen, Plus, Minus, /* etc */ } | ---------- variant `Homura` not found here ... LL | use_token(&Token::Homura); - | ^^^^^^^^^^^^^ variant not found in `Token` + | -------^^^^^^ + | | + | variant not found in `Token` error[E0599]: no function or associated item named `method` found for type `Struct` in the current scope - --> $DIR/issue-23173.rs:21:5 + --> $DIR/issue-23173.rs:21:13 | LL | struct Struct { | ------------- function or associated item `method` not found for this ... LL | Struct::method(); - | ^^^^^^^^^^^^^^ function or associated item not found in `Struct` + | --------^^^^^^ + | | + | function or associated item not found in `Struct` error[E0599]: no function or associated item named `method` found for type `Struct` in the current scope - --> $DIR/issue-23173.rs:23:5 + --> $DIR/issue-23173.rs:23:13 | LL | struct Struct { | ------------- function or associated item `method` not found for this ... LL | Struct::method; - | ^^^^^^^^^^^^^^ function or associated item not found in `Struct` + | --------^^^^^^ + | | + | function or associated item not found in `Struct` error[E0599]: no associated item named `Assoc` found for type `Struct` in the current scope - --> $DIR/issue-23173.rs:25:5 + --> $DIR/issue-23173.rs:25:13 | LL | struct Struct { | ------------- associated item `Assoc` not found for this ... LL | Struct::Assoc; - | ^^^^^^^^^^^^^ associated item not found in `Struct` + | --------^^^^^ + | | + | associated item not found in `Struct` error: aborting due to 4 previous errors diff --git a/src/test/ui/issues/issue-23217.stderr b/src/test/ui/issues/issue-23217.stderr index d87f239bca6..1ba8f276cc9 100644 --- a/src/test/ui/issues/issue-23217.stderr +++ b/src/test/ui/issues/issue-23217.stderr @@ -1,12 +1,14 @@ error[E0599]: no variant named `A` found for type `SomeEnum` in the current scope - --> $DIR/issue-23217.rs:12:9 + --> $DIR/issue-23217.rs:12:19 | LL | pub enum SomeEnum { | ----------------- variant `A` not found here LL | B = SomeEnum::A, - | ^^^^^^^^^^^ variant not found in `SomeEnum` + | ----------^ + | | + | variant not found in `SomeEnum` | - = note: did you mean `SomeEnum::B`? + = help: did you mean `B`? error: aborting due to previous error diff --git a/src/test/ui/issues/issue-27842.stderr b/src/test/ui/issues/issue-27842.stderr index 026594811e4..dea7acd9bf8 100644 --- a/src/test/ui/issues/issue-27842.stderr +++ b/src/test/ui/issues/issue-27842.stderr @@ -10,7 +10,7 @@ error[E0608]: cannot index into a value of type `({integer}, {integer}, {integer LL | let _ = tup[i]; | ^^^^^^ | - = help: to access tuple elements, use tuple indexing syntax (e.g. `tuple.0`) + = help: to access tuple elements, use tuple indexing syntax (e.g., `tuple.0`) error: aborting due to 2 previous errors diff --git a/src/test/ui/issues/issue-28344.stderr b/src/test/ui/issues/issue-28344.stderr index 734c761d0b7..bd4f4b88d32 100644 --- a/src/test/ui/issues/issue-28344.stderr +++ b/src/test/ui/issues/issue-28344.stderr @@ -5,10 +5,12 @@ LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8); | ^^^^^^^^^^^^^ associated type `Output` must be specified error[E0599]: no function or associated item named `bitor` found for type `dyn std::ops::BitXor<_>` in the current scope - --> $DIR/issue-28344.rs:14:17 + --> $DIR/issue-28344.rs:14:25 | LL | let x: u8 = BitXor::bitor(0 as u8, 0 as u8); - | ^^^^^^^^^^^^^ function or associated item not found in `dyn std::ops::BitXor<_>` + | --------^^^^^ + | | + | function or associated item not found in `dyn std::ops::BitXor<_>` | = help: did you mean `bitxor`? @@ -19,10 +21,12 @@ LL | let g = BitXor::bitor; | ^^^^^^^^^^^^^ associated type `Output` must be specified error[E0599]: no function or associated item named `bitor` found for type `dyn std::ops::BitXor<_>` in the current scope - --> $DIR/issue-28344.rs:18:13 + --> $DIR/issue-28344.rs:18:21 | LL | let g = BitXor::bitor; - | ^^^^^^^^^^^^^ function or associated item not found in `dyn std::ops::BitXor<_>` + | --------^^^^^ + | | + | function or associated item not found in `dyn std::ops::BitXor<_>` | = help: did you mean `bitxor`? diff --git a/src/test/ui/issues/issue-28586.stderr b/src/test/ui/issues/issue-28586.stderr index 9820d64909e..e48e642301e 100644 --- a/src/test/ui/issues/issue-28586.stderr +++ b/src/test/ui/issues/issue-28586.stderr @@ -1,8 +1,10 @@ error[E0599]: no associated item named `BYTES` found for type `usize` in the current scope - --> $DIR/issue-28586.rs:14:19 + --> $DIR/issue-28586.rs:14:26 | LL | impl Foo for [u8; usize::BYTES] {} - | ^^^^^^^^^^^^ associated item not found in `usize` + | -------^^^^^ + | | + | associated item not found in `usize` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-28971.stderr b/src/test/ui/issues/issue-28971.stderr index c04e21f7c58..77aac975768 100644 --- a/src/test/ui/issues/issue-28971.stderr +++ b/src/test/ui/issues/issue-28971.stderr @@ -1,13 +1,13 @@ error[E0599]: no variant named `Baz` found for type `Foo` in the current scope - --> $DIR/issue-28971.rs:19:13 + --> $DIR/issue-28971.rs:19:18 | LL | enum Foo { | -------- variant `Baz` not found here ... LL | Foo::Baz(..) => (), - | ^^^^^^^^^^^^ variant not found in `Foo` + | -----^^^---- variant not found in `Foo` | - = note: did you mean `Foo::Bar`? + = help: did you mean `Bar`? error: aborting due to previous error diff --git a/src/test/ui/issues/issue-30123.stderr b/src/test/ui/issues/issue-30123.stderr index 094c962de29..a08c1d678d8 100644 --- a/src/test/ui/issues/issue-30123.stderr +++ b/src/test/ui/issues/issue-30123.stderr @@ -1,8 +1,10 @@ error[E0599]: no function or associated item named `new_undirected` found for type `issue_30123_aux::Graph` in the current scope - --> $DIR/issue-30123.rs:17:14 + --> $DIR/issue-30123.rs:17:33 | LL | let ug = Graph::::new_undirected(); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function or associated item not found in `issue_30123_aux::Graph` + | -------------------^^^^^^^^^^^^^^ + | | + | function or associated item not found in `issue_30123_aux::Graph` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-36744-without-calls.rs b/src/test/ui/issues/issue-36744-without-calls.rs index 8a47ebbd0a8..c15840090ea 100644 --- a/src/test/ui/issues/issue-36744-without-calls.rs +++ b/src/test/ui/issues/issue-36744-without-calls.rs @@ -11,7 +11,7 @@ // compile-pass // Tests for an LLVM abort when storing a lifetime-parametric fn into // context that is expecting one that is not lifetime-parametric -// (i.e. has no `for <'_>`). +// (i.e., has no `for <'_>`). pub struct A<'a>(&'a ()); pub struct S(T); diff --git a/src/test/ui/issues/issue-38919.stderr b/src/test/ui/issues/issue-38919.stderr index b80367d7c6c..398a38877d2 100644 --- a/src/test/ui/issues/issue-38919.stderr +++ b/src/test/ui/issues/issue-38919.stderr @@ -1,8 +1,10 @@ error[E0599]: no associated item named `Item` found for type `T` in the current scope - --> $DIR/issue-38919.rs:12:5 + --> $DIR/issue-38919.rs:12:8 | LL | T::Item; //~ ERROR no associated item named `Item` found for type `T` in the current scope - | ^^^^^^^ associated item not found in `T` + | ---^^^^ + | | + | associated item not found in `T` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-39559.stderr b/src/test/ui/issues/issue-39559.stderr index 2ce6dfdbe44..83af9d82e0b 100644 --- a/src/test/ui/issues/issue-39559.stderr +++ b/src/test/ui/issues/issue-39559.stderr @@ -1,8 +1,10 @@ error[E0599]: no function or associated item named `dim` found for type `D` in the current scope - --> $DIR/issue-39559.rs:24:18 + --> $DIR/issue-39559.rs:24:21 | LL | entries: [T; D::dim()], - | ^^^^^^ function or associated item not found in `D` + | ---^^^ + | | + | function or associated item not found in `D` | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `dim`, perhaps you need to implement it: diff --git a/src/test/ui/issues/issue-3973.stderr b/src/test/ui/issues/issue-3973.stderr index 9be07614ec1..1389dcd2a03 100644 --- a/src/test/ui/issues/issue-3973.stderr +++ b/src/test/ui/issues/issue-3973.stderr @@ -8,13 +8,15 @@ LL | | } | |_____^ not a member of trait `ToString_` error[E0599]: no function or associated item named `new` found for type `Point` in the current scope - --> $DIR/issue-3973.rs:32:13 + --> $DIR/issue-3973.rs:32:20 | LL | struct Point { | ------------ function or associated item `new` not found for this ... LL | let p = Point::new(0.0, 0.0); - | ^^^^^^^^^^ function or associated item not found in `Point` + | -------^^^ + | | + | function or associated item not found in `Point` error: aborting due to 2 previous errors diff --git a/src/test/ui/issues/issue-40861.stderr b/src/test/ui/issues/issue-40861.stderr index dbde40fb25e..660f0ff7073 100644 --- a/src/test/ui/issues/issue-40861.stderr +++ b/src/test/ui/issues/issue-40861.stderr @@ -4,7 +4,7 @@ error[E0608]: cannot index into a value of type `()` LL | ()[f(&[1.0])]; | ^^^^^^^^^^^^^ | - = help: to access tuple elements, use tuple indexing syntax (e.g. `tuple.0`) + = help: to access tuple elements, use tuple indexing syntax (e.g., `tuple.0`) error: aborting due to previous error diff --git a/src/test/ui/issues/issue-41974.stderr b/src/test/ui/issues/issue-41974.stderr index eca40ed4355..d6d4f7b5515 100644 --- a/src/test/ui/issues/issue-41974.stderr +++ b/src/test/ui/issues/issue-41974.stderr @@ -15,7 +15,7 @@ error[E0120]: the Drop trait may only be implemented on structures LL | impl Drop for T where T: A { //~ ERROR E0119 | ^ implementing Drop requires a struct -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/issue-41974.rs:17:1 | LL | impl Drop for T where T: A { //~ ERROR E0119 diff --git a/src/test/ui/issues/issue-42880.stderr b/src/test/ui/issues/issue-42880.stderr index cf1c3022a22..1087e5a014e 100644 --- a/src/test/ui/issues/issue-42880.stderr +++ b/src/test/ui/issues/issue-42880.stderr @@ -1,8 +1,8 @@ error[E0599]: no associated item named `String` found for type `std::string::String` in the current scope - --> $DIR/issue-42880.rs:14:15 + --> $DIR/issue-42880.rs:14:22 | LL | let f = |&Value::String(_)| (); //~ ERROR no associated item named - | ^^^^^^^^^^^^^^^^ associated item not found in `std::string::String` + | -------^^^^^^--- associated item not found in `std::string::String` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-52060.stderr b/src/test/ui/issues/issue-52060.stderr index 988bfd480e6..7c3f7695549 100644 --- a/src/test/ui/issues/issue-52060.stderr +++ b/src/test/ui/issues/issue-52060.stderr @@ -10,7 +10,7 @@ error: `core::slice::::len` is not yet stable as a const fn LL | static B: [u32; 1] = [0; A.len()]; | ^^^^^^^ | - = help: in Nightly builds, add `#![feature(const_slice_len)]` to the crate attributes to enable + = help: add `#![feature(const_slice_len)]` to the crate attributes to enable error: aborting due to 2 previous errors diff --git a/src/test/ui/issues/issue-7950.stderr b/src/test/ui/issues/issue-7950.stderr index 750127981b1..bd0b9454c7f 100644 --- a/src/test/ui/issues/issue-7950.stderr +++ b/src/test/ui/issues/issue-7950.stderr @@ -1,11 +1,13 @@ error[E0599]: no function or associated item named `bar` found for type `Foo` in the current scope - --> $DIR/issue-7950.rs:16:5 + --> $DIR/issue-7950.rs:16:10 | LL | struct Foo; | ----------- function or associated item `bar` not found for this ... LL | Foo::bar(); - | ^^^^^^^^ function or associated item not found in `Foo` + | -----^^^ + | | + | function or associated item not found in `Foo` error: aborting due to previous error diff --git a/src/test/ui/lexical-scopes.stderr b/src/test/ui/lexical-scopes.stderr index 3a6ae52c68d..666666c2100 100644 --- a/src/test/ui/lexical-scopes.stderr +++ b/src/test/ui/lexical-scopes.stderr @@ -9,10 +9,12 @@ LL | use T; | error[E0599]: no function or associated item named `f` found for type `Foo` in the current scope - --> $DIR/lexical-scopes.rs:20:5 + --> $DIR/lexical-scopes.rs:20:10 | LL | Foo::f(); //~ ERROR no function or associated item named `f` - | ^^^^^^ function or associated item not found in `Foo` + | -----^ + | | + | function or associated item not found in `Foo` error: aborting due to 2 previous errors diff --git a/src/test/ui/lint/lint-unused-imports.rs b/src/test/ui/lint/lint-unused-imports.rs index 5bb2ab75c53..64a48511bac 100644 --- a/src/test/ui/lint/lint-unused-imports.rs +++ b/src/test/ui/lint/lint-unused-imports.rs @@ -81,7 +81,7 @@ fn g() { } } -// c.f. issue #35135 +// cf. issue #35135. #[allow(unused_variables)] fn h() { use test2::foo; //~ ERROR unused import: `test2::foo` diff --git a/src/test/ui/namespace/namespace-mix.rs b/src/test/ui/namespace/namespace-mix.rs index c1c724fc431..22a9da8d9a6 100644 --- a/src/test/ui/namespace/namespace-mix.rs +++ b/src/test/ui/namespace/namespace-mix.rs @@ -26,7 +26,7 @@ mod c { pub struct Item; } -// Use something emitting the type argument name, e.g. unsatisfied bound. +// Use something emitting the type argument name, e.g., unsatisfied bound. trait Impossible {} fn check(_: T) {} diff --git a/src/test/ui/nll/issue-21232-partial-init-and-use.rs b/src/test/ui/nll/issue-21232-partial-init-and-use.rs index 186ecc54827..633cbdba2d4 100644 --- a/src/test/ui/nll/issue-21232-partial-init-and-use.rs +++ b/src/test/ui/nll/issue-21232-partial-init-and-use.rs @@ -61,7 +61,7 @@ impl R { fn new(f: F) -> Self { R { w: 0, f } } } // As a shorthand for the cases above, adding a numeric summary to // each test's fn name to denote each point on each axis. // -// E.g. 1000 = field fully init struct; 0211 = local void reinit tuple +// e.g., 1000 = field fully init struct; 0211 = local void reinit tuple // It got pretty monotonous writing the same code over and over, and I // feared I would forget details. So I abstracted some desiderata into diff --git a/src/test/ui/no-implicit-prelude-nested.rs b/src/test/ui/no-implicit-prelude-nested.rs index c64839ad0de..0250cf529ee 100644 --- a/src/test/ui/no-implicit-prelude-nested.rs +++ b/src/test/ui/no-implicit-prelude-nested.rs @@ -10,7 +10,7 @@ // Test that things from the prelude aren't in scope. Use many of them // so that renaming some things won't magically make this test fail -// for the wrong reason (e.g. if `Add` changes to `Addition`, and +// for the wrong reason (e.g., if `Add` changes to `Addition`, and // `no_implicit_prelude` stops working, then the `impl Add` will still // fail with the same error message). diff --git a/src/test/ui/no-implicit-prelude.rs b/src/test/ui/no-implicit-prelude.rs index 0e39d9ebdc1..8a4a0aef069 100644 --- a/src/test/ui/no-implicit-prelude.rs +++ b/src/test/ui/no-implicit-prelude.rs @@ -12,7 +12,7 @@ // Test that things from the prelude aren't in scope. Use many of them // so that renaming some things won't magically make this test fail -// for the wrong reason (e.g. if `Add` changes to `Addition`, and +// for the wrong reason (e.g., if `Add` changes to `Addition`, and // `no_implicit_prelude` stops working, then the `impl Add` will still // fail with the same error message). diff --git a/src/test/ui/orphan-check-diagnostics.stderr b/src/test/ui/orphan-check-diagnostics.stderr index dc134dd8d6f..22422f15404 100644 --- a/src/test/ui/orphan-check-diagnostics.stderr +++ b/src/test/ui/orphan-check-diagnostics.stderr @@ -1,4 +1,4 @@ -error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g. `MyStruct`) +error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct`) --> $DIR/orphan-check-diagnostics.rs:20:1 | LL | impl RemoteTrait for T where T: LocalTrait {} diff --git a/src/test/ui/parser/assoc-oddities-1.rs b/src/test/ui/parser/assoc-oddities-1.rs index 63408b76b15..866d7423f14 100644 --- a/src/test/ui/parser/assoc-oddities-1.rs +++ b/src/test/ui/parser/assoc-oddities-1.rs @@ -15,7 +15,7 @@ fn that_odd_parse() { x = if c { a } else { b }(); x = if true { 1 } else { 0 } as *mut _; // however this does not parse and probably should fail to retain compat? - // NB: `..` here is arbitrary, failure happens/should happen ∀ops that aren’t `=` + // N.B., `..` here is arbitrary, failure happens/should happen ∀ops that aren’t `=` // see assoc-oddities-2 and assoc-oddities-3 ..if c { a } else { b }[n]; //~ ERROR expected one of } diff --git a/src/test/ui/print_type_sizes/generics.rs b/src/test/ui/print_type_sizes/generics.rs index fa5921cfb13..5b6918d41b5 100644 --- a/src/test/ui/print_type_sizes/generics.rs +++ b/src/test/ui/print_type_sizes/generics.rs @@ -30,7 +30,7 @@ // Copy. // // (I suspect this reflect some naivety within the rust compiler -// itself; it should be checking for drop glue, i.e. a destructor +// itself; it should be checking for drop glue, i.e., a destructor // somewhere in the monomorphized types. It should not matter whether // the type is Copy.) #[derive(Copy, Clone)] diff --git a/src/test/ui/regions/regions-free-region-ordering-incorrect.rs b/src/test/ui/regions/regions-free-region-ordering-incorrect.rs index 9cb61c24922..250800262db 100644 --- a/src/test/ui/regions/regions-free-region-ordering-incorrect.rs +++ b/src/test/ui/regions/regions-free-region-ordering-incorrect.rs @@ -10,23 +10,23 @@ // Test that free regions ordering only goes one way. That is, // we have `&'a Node<'b, T>`, which implies that `'a <= 'b`, -// but not `'b <= 'a`. Hence returning `&self.val` (which has lifetime +// but not `'b <= 'a`. Hence, returning `&self.val` (which has lifetime // `'a`) where `'b` is expected yields an error. // // This test began its life as a test for issue #4325. -struct Node<'b, T:'b> { - val: T, - next: Option<&'b Node<'b, T>> +struct Node<'b, T: 'b> { + val: T, + next: Option<&'b Node<'b, T>> } impl<'b, T> Node<'b, T> { - fn get<'a>(&'a self) -> &'b T { - match self.next { - Some(ref next) => next.get(), - None => &self.val //~ ERROR cannot infer + fn get<'a>(&'a self) -> &'b T { + match self.next { + Some(ref next) => next.get(), + None => &self.val //~ ERROR cannot infer + } } - } } fn main() {} diff --git a/src/test/ui/regions/regions-free-region-ordering-incorrect.stderr b/src/test/ui/regions/regions-free-region-ordering-incorrect.stderr index 3dce04e2452..6b28ab4004f 100644 --- a/src/test/ui/regions/regions-free-region-ordering-incorrect.stderr +++ b/src/test/ui/regions/regions-free-region-ordering-incorrect.stderr @@ -1,32 +1,32 @@ error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements - --> $DIR/regions-free-region-ordering-incorrect.rs:27:15 + --> $DIR/regions-free-region-ordering-incorrect.rs:27:21 | -LL | None => &self.val //~ ERROR cannot infer - | ^^^^^^^^^ +LL | None => &self.val //~ ERROR cannot infer + | ^^^^^^^^^ | -note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 24:10... - --> $DIR/regions-free-region-ordering-incorrect.rs:24:10 +note: first, the lifetime cannot outlive the lifetime 'a as defined on the method body at 24:12... + --> $DIR/regions-free-region-ordering-incorrect.rs:24:12 | -LL | fn get<'a>(&'a self) -> &'b T { - | ^^ +LL | fn get<'a>(&'a self) -> &'b T { + | ^^ note: ...so that reference does not outlive borrowed content - --> $DIR/regions-free-region-ordering-incorrect.rs:27:15 + --> $DIR/regions-free-region-ordering-incorrect.rs:27:21 | -LL | None => &self.val //~ ERROR cannot infer - | ^^^^^^^^^ +LL | None => &self.val //~ ERROR cannot infer + | ^^^^^^^^^ note: but, the lifetime must be valid for the lifetime 'b as defined on the impl at 23:6... --> $DIR/regions-free-region-ordering-incorrect.rs:23:6 | LL | impl<'b, T> Node<'b, T> { | ^^ note: ...so that reference does not outlive borrowed content - --> $DIR/regions-free-region-ordering-incorrect.rs:25:5 + --> $DIR/regions-free-region-ordering-incorrect.rs:25:9 | -LL | / match self.next { -LL | | Some(ref next) => next.get(), -LL | | None => &self.val //~ ERROR cannot infer -LL | | } - | |_____^ +LL | / match self.next { +LL | | Some(ref next) => next.get(), +LL | | None => &self.val //~ ERROR cannot infer +LL | | } + | |_________^ error: aborting due to previous error diff --git a/src/test/ui/resolve/issue-5035.rs b/src/test/ui/resolve/issue-5035.rs index e9b50dddd30..3ed41c6999f 100644 --- a/src/test/ui/resolve/issue-5035.rs +++ b/src/test/ui/resolve/issue-5035.rs @@ -14,6 +14,6 @@ impl K for isize {} //~ ERROR expected trait, found type alias `K` use ImportError; //~ ERROR unresolved import `ImportError` [E0432] //~^ no `ImportError` in the root -impl ImportError for () {} // check that this is not an additional error (c.f. #35142) +impl ImportError for () {} // check that this is not an additional error (cf. issue #35142) fn main() {} diff --git a/src/test/ui/rfc-2005-default-binding-mode/no-double-error.stderr b/src/test/ui/rfc-2005-default-binding-mode/no-double-error.stderr index e3a613f9261..b5cc7d4aefa 100644 --- a/src/test/ui/rfc-2005-default-binding-mode/no-double-error.stderr +++ b/src/test/ui/rfc-2005-default-binding-mode/no-double-error.stderr @@ -1,8 +1,10 @@ error[E0599]: no associated item named `XXX` found for type `u32` in the current scope - --> $DIR/no-double-error.rs:18:9 + --> $DIR/no-double-error.rs:18:14 | LL | u32::XXX => { } //~ ERROR no associated item named - | ^^^^^^^^ associated item not found in `u32` + | -----^^^ + | | + | associated item not found in `u32` error: aborting due to previous error diff --git a/src/test/ui/rfc-2126-extern-absolute-paths/meta.rs b/src/test/ui/rfc-2126-extern-absolute-paths/meta.rs index 499a322593c..004c4a00231 100644 --- a/src/test/ui/rfc-2126-extern-absolute-paths/meta.rs +++ b/src/test/ui/rfc-2126-extern-absolute-paths/meta.rs @@ -11,7 +11,7 @@ // edition:2018 // Tests that `meta` is whitelisted, even if the crate doesn't exist -// yet (i.e. it causes a different error than `not-whitelisted.rs`). +// yet (i.e., it causes a different error than `not-whitelisted.rs`). use meta; //~ ERROR can't find crate for `meta` fn main() {} diff --git a/src/test/ui/rust-2018/trait-import-suggestions.stderr b/src/test/ui/rust-2018/trait-import-suggestions.stderr index d5d996e27ee..72a0fc694c0 100644 --- a/src/test/ui/rust-2018/trait-import-suggestions.stderr +++ b/src/test/ui/rust-2018/trait-import-suggestions.stderr @@ -27,10 +27,12 @@ LL | x.baz(); //~ ERROR no method named `baz` | ^^^ error[E0599]: no function or associated item named `from_str` found for type `u32` in the current scope - --> $DIR/trait-import-suggestions.rs:40:13 + --> $DIR/trait-import-suggestions.rs:40:18 | LL | let y = u32::from_str("33"); //~ ERROR no function or associated item named `from_str` - | ^^^^^^^^^^^^^ function or associated item not found in `u32` + | -----^^^^^^^^ + | | + | function or associated item not found in `u32` | = help: items from traits can only be used if the trait is in scope help: the following trait is implemented but not in scope, perhaps add a `use` for it: diff --git a/src/test/ui/simd-intrinsic/simd-intrinsic-single-nominal-type.rs b/src/test/ui/simd-intrinsic/simd-intrinsic-single-nominal-type.rs index 0d0bf240f72..5e009ea4431 100644 --- a/src/test/ui/simd-intrinsic/simd-intrinsic-single-nominal-type.rs +++ b/src/test/ui/simd-intrinsic/simd-intrinsic-single-nominal-type.rs @@ -16,7 +16,7 @@ struct A(i16, i16, i16, i16, i16, i16, i16, i16); struct B(i16, i16, i16, i16, i16, i16, i16, i16); // each intrinsic definition has to use the same nominal type for any -// vector structure throughout that declaration (i.e. every instance +// vector structure throughout that declaration (i.e., every instance // of i16x8 in each `fn ...;` needs to be either A or B) extern "platform-intrinsic" { diff --git a/src/test/ui/span/issue-24805-dropck-trait-has-items.rs b/src/test/ui/span/issue-24805-dropck-trait-has-items.rs index 75523386931..b9e4ffa84cd 100644 --- a/src/test/ui/span/issue-24805-dropck-trait-has-items.rs +++ b/src/test/ui/span/issue-24805-dropck-trait-has-items.rs @@ -25,7 +25,7 @@ impl<'a,T> HasSelfMethod for &'a T { } impl<'a,T> HasMethodWithSelfArg for &'a T { } impl<'a,T> HasType for &'a T { type Something = (); } -// e.g. `impl_drop!(Send, D_Send)` expands to: +// e.g., `impl_drop!(Send, D_Send)` expands to: // ```rust // struct D_Send(T); // impl Drop for D_Send { fn drop(&mut self) { } } diff --git a/src/test/ui/traits/trait-item-privacy.stderr b/src/test/ui/traits/trait-item-privacy.stderr index 4ede83d5d73..01719bc4047 100644 --- a/src/test/ui/traits/trait-item-privacy.stderr +++ b/src/test/ui/traits/trait-item-privacy.stderr @@ -33,26 +33,30 @@ LL | c.a(); //~ ERROR method `a` is private | ^ error[E0599]: no function or associated item named `a` found for type `S` in the current scope - --> $DIR/trait-item-privacy.rs:88:5 + --> $DIR/trait-item-privacy.rs:88:8 | LL | struct S; | --------- function or associated item `a` not found for this ... LL | S::a(&S); - | ^^^^ function or associated item not found in `S` + | ---^ + | | + | function or associated item not found in `S` | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `a`, perhaps you need to implement it: candidate #1: `method::A` error[E0599]: no function or associated item named `b` found for type `S` in the current scope - --> $DIR/trait-item-privacy.rs:90:5 + --> $DIR/trait-item-privacy.rs:90:8 | LL | struct S; | --------- function or associated item `b` not found for this ... LL | S::b(&S); - | ^^^^ function or associated item not found in `S` + | ---^ + | | + | function or associated item not found in `S` | = help: items from traits can only be used if the trait is in scope help: the following trait is implemented but not in scope, perhaps add a `use` for it: @@ -67,26 +71,30 @@ LL | C::a(&S); //~ ERROR method `a` is private | ^^^^ error[E0599]: no associated item named `A` found for type `S` in the current scope - --> $DIR/trait-item-privacy.rs:107:5 + --> $DIR/trait-item-privacy.rs:107:8 | LL | struct S; | --------- associated item `A` not found for this ... LL | S::A; //~ ERROR no associated item named `A` found for type `S` in the current scope - | ^^^^ associated item not found in `S` + | ---^ + | | + | associated item not found in `S` | = help: items from traits can only be used if the trait is implemented and in scope = note: the following trait defines an item `A`, perhaps you need to implement it: candidate #1: `assoc_const::A` error[E0599]: no associated item named `B` found for type `S` in the current scope - --> $DIR/trait-item-privacy.rs:108:5 + --> $DIR/trait-item-privacy.rs:108:8 | LL | struct S; | --------- associated item `B` not found for this ... LL | S::B; //~ ERROR no associated item named `B` found for type `S` in the current scope - | ^^^^ associated item not found in `S` + | ---^ + | | + | associated item not found in `S` | = help: items from traits can only be used if the trait is in scope help: the following trait is implemented but not in scope, perhaps add a `use` for it: diff --git a/src/test/ui/type/type-alias-bounds.rs b/src/test/ui/type/type-alias-bounds.rs index a17bb9e952d..41f260aba55 100644 --- a/src/test/ui/type/type-alias-bounds.rs +++ b/src/test/ui/type/type-alias-bounds.rs @@ -48,7 +48,7 @@ fn foo<'a>(y: &'a i32) { x.1.push(y); // &'a i32: 'static does not hold } -// Bounds are not checked either, i.e. the definition is not necessarily well-formed +// Bounds are not checked either, i.e., the definition is not necessarily well-formed struct Sendable(T); type MySendable = Sendable; // no error here! diff --git a/src/test/ui/ufcs/ufcs-partially-resolved.stderr b/src/test/ui/ufcs/ufcs-partially-resolved.stderr index cb571be661d..940e00738d9 100644 --- a/src/test/ui/ufcs/ufcs-partially-resolved.stderr +++ b/src/test/ui/ufcs/ufcs-partially-resolved.stderr @@ -187,16 +187,20 @@ LL | let _: ::Y::NN; //~ ERROR ambiguous associated type | ^^^^^^^^^^^^^^^^^ help: use fully-qualified syntax: `<::Y as Trait>::NN` error[E0599]: no associated item named `NN` found for type `::Y` in the current scope - --> $DIR/ufcs-partially-resolved.rs:48:5 + --> $DIR/ufcs-partially-resolved.rs:48:20 | LL | ::Y::NN; //~ ERROR no associated item named `NN` found for type `::Y` - | ^^^^^^^^^^^^^^^^^ associated item not found in `::Y` + | ---------------^^ + | | + | associated item not found in `::Y` error[E0599]: no associated item named `N` found for type `::X` in the current scope - --> $DIR/ufcs-partially-resolved.rs:65:5 + --> $DIR/ufcs-partially-resolved.rs:65:20 | LL | ::X::N; //~ ERROR no associated item named `N` found for type `::X` - | ^^^^^^^^^^^^^^^^ associated item not found in `::X` + | ---------------^ + | | + | associated item not found in `::X` error: aborting due to 32 previous errors diff --git a/src/test/ui/unspecified-self-in-trait-ref.stderr b/src/test/ui/unspecified-self-in-trait-ref.stderr index c036540068b..005d7bfedd0 100644 --- a/src/test/ui/unspecified-self-in-trait-ref.stderr +++ b/src/test/ui/unspecified-self-in-trait-ref.stderr @@ -1,26 +1,34 @@ error[E0599]: no function or associated item named `lol` found for type `dyn Foo<_>` in the current scope - --> $DIR/unspecified-self-in-trait-ref.rs:20:13 + --> $DIR/unspecified-self-in-trait-ref.rs:20:18 | LL | let a = Foo::lol(); - | ^^^^^^^^ function or associated item not found in `dyn Foo<_>` + | -----^^^ + | | + | function or associated item not found in `dyn Foo<_>` error[E0599]: no function or associated item named `lol` found for type `dyn Foo<_>` in the current scope - --> $DIR/unspecified-self-in-trait-ref.rs:22:13 + --> $DIR/unspecified-self-in-trait-ref.rs:22:23 | LL | let b = Foo::<_>::lol(); - | ^^^^^^^^^^^^^ function or associated item not found in `dyn Foo<_>` + | ----------^^^ + | | + | function or associated item not found in `dyn Foo<_>` error[E0599]: no function or associated item named `lol` found for type `dyn Bar<_, _>` in the current scope - --> $DIR/unspecified-self-in-trait-ref.rs:24:13 + --> $DIR/unspecified-self-in-trait-ref.rs:24:18 | LL | let c = Bar::lol(); - | ^^^^^^^^ function or associated item not found in `dyn Bar<_, _>` + | -----^^^ + | | + | function or associated item not found in `dyn Bar<_, _>` error[E0599]: no function or associated item named `lol` found for type `dyn Bar` in the current scope - --> $DIR/unspecified-self-in-trait-ref.rs:26:13 + --> $DIR/unspecified-self-in-trait-ref.rs:26:30 | LL | let d = Bar::::lol(); - | ^^^^^^^^^^^^^^^^^^^^ function or associated item not found in `dyn Bar` + | -----------------^^^ + | | + | function or associated item not found in `dyn Bar` error[E0393]: the type parameter `A` must be explicitly specified --> $DIR/unspecified-self-in-trait-ref.rs:28:13 diff --git a/src/tools/compiletest/src/errors.rs b/src/tools/compiletest/src/errors.rs index 8d20a9e2717..7b967a10c87 100644 --- a/src/tools/compiletest/src/errors.rs +++ b/src/tools/compiletest/src/errors.rs @@ -56,7 +56,7 @@ impl fmt::Display for ErrorKind { #[derive(Debug)] pub struct Error { pub line_num: usize, - /// What kind of message we expect (e.g. warning, error, suggestion). + /// What kind of message we expect (e.g., warning, error, suggestion). /// `None` if not specified or unknown message kind. pub kind: Option, pub msg: String, diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index f4a82aeb307..00383998242 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -715,7 +715,7 @@ impl Config { } } - /// Parses a name-value directive which contains config-specific information, e.g. `ignore-x86` + /// Parses a name-value directive which contains config-specific information, e.g., `ignore-x86` /// or `normalize-stderr-32bit`. fn parse_cfg_name_directive(&self, line: &str, prefix: &str) -> ParsedNameDirective { if line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-') { -- cgit 1.4.1-3-g733a5 From 81de5d9519270e1c9dc3c1ee97067ac7058edefe Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Thu, 6 Dec 2018 11:26:11 -0700 Subject: Remove dependency on shell32.dll #56510 --- src/libstd/build.rs | 1 - src/libstd/sys/windows/args.rs | 244 ++++++++++++++++++++++++++++++------ src/libstd/sys/windows/c.rs | 3 - src/test/run-make-fulldeps/tools.mk | 2 +- 4 files changed, 207 insertions(+), 43 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/build.rs b/src/libstd/build.rs index 9d6e8c4cafd..8641f28b23f 100644 --- a/src/libstd/build.rs +++ b/src/libstd/build.rs @@ -68,7 +68,6 @@ fn main() { println!("cargo:rustc-link-lib=advapi32"); println!("cargo:rustc-link-lib=ws2_32"); println!("cargo:rustc-link-lib=userenv"); - println!("cargo:rustc-link-lib=shell32"); } else if target.contains("fuchsia") { println!("cargo:rustc-link-lib=zircon"); println!("cargo:rustc-link-lib=fdio"); diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index 4784633edc1..3eea9b19b6f 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -11,12 +11,14 @@ #![allow(dead_code)] // runtime init functions not used during testing use os::windows::prelude::*; +use sys::windows::os::current_exe; use sys::c; -use slice; -use ops::Range; use ffi::OsString; -use libc::{c_int, c_void}; use fmt; +use collections::VecDeque; +use core::iter; +use slice; +use path::PathBuf; pub unsafe fn init(_argc: isize, _argv: *const *const u8) { } @@ -24,20 +26,146 @@ pub unsafe fn cleanup() { } pub fn args() -> Args { unsafe { - let mut nArgs: c_int = 0; - let lpCmdLine = c::GetCommandLineW(); - let szArgList = c::CommandLineToArgvW(lpCmdLine, &mut nArgs); - - // szArcList can be NULL if CommandLinToArgvW failed, - // but in that case nArgs is 0 so we won't actually - // try to read a null pointer - Args { cur: szArgList, range: 0..(nArgs as isize) } + let lp_cmd_line = c::GetCommandLineW(); + let parsed_args_list = parse_lp_cmd_line( + lp_cmd_line as *const u16, + || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())); + + Args { parsed_args_list: parsed_args_list } } } +/// Implements the Windows command-line argument parsing algorithm, described at +/// . +/// +/// Windows includes a function to do this in shell32.dll, +/// but linking with that DLL causes the process to be registered as a GUI application. +/// GUI applications add a bunch of overhead, even if no windows are drawn. See +/// . +unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_name: F) + -> VecDeque { + const BACKSLASH: u16 = '\\' as u16; + const QUOTE: u16 = '"' as u16; + const TAB: u16 = '\t' as u16; + const SPACE: u16 = ' ' as u16; + let mut in_quotes = false; + let mut was_in_quotes = false; + let mut backslash_count: usize = 0; + let mut ret_val = VecDeque::new(); + let mut cur = Vec::new(); + if lp_cmd_line.is_null() || *lp_cmd_line == 0 { + ret_val.push_back(exe_name()); + return ret_val; + } + let mut i = 0; + // The executable name at the beginning is special. + match *lp_cmd_line { + // The executable name ends at the next quote mark, + // no matter what. + QUOTE => { + loop { + i += 1; + if *lp_cmd_line.offset(i) == 0 { + ret_val.push_back(OsString::from_wide( + slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) + )); + return ret_val; + } + if *lp_cmd_line.offset(i) == QUOTE { + break; + } + } + ret_val.push_back(OsString::from_wide( + slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) + )); + i += 1; + } + // Implement quirk: when they say whitespace here, + // they include the entire ASCII control plane: + // "However, if lpCmdLine starts with any amount of whitespace, CommandLineToArgvW + // will consider the first argument to be an empty string. Excess whitespace at the + // end of lpCmdLine is ignored." + 0...SPACE => { + ret_val.push_back(OsString::new()); + i += 1; + }, + // The executable name ends at the next quote mark, + // no matter what. + _ => { + loop { + i += 1; + if *lp_cmd_line.offset(i) == 0 { + ret_val.push_back(OsString::from_wide( + slice::from_raw_parts(lp_cmd_line, i as usize) + )); + return ret_val; + } + if let 0...SPACE = *lp_cmd_line.offset(i) { + break; + } + } + ret_val.push_back(OsString::from_wide( + slice::from_raw_parts(lp_cmd_line, i as usize) + )); + i += 1; + } + } + loop { + let c = *lp_cmd_line.offset(i); + match c { + // backslash + BACKSLASH => { + backslash_count += 1; + was_in_quotes = false; + }, + QUOTE if backslash_count % 2 == 0 => { + cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2)); + backslash_count = 0; + if was_in_quotes { + cur.push('"' as u16); + was_in_quotes = false; + } else { + was_in_quotes = in_quotes; + in_quotes = !in_quotes; + } + } + QUOTE if backslash_count % 2 != 0 => { + cur.extend(iter::repeat(b'\\' as u16).take(backslash_count / 2)); + backslash_count = 0; + was_in_quotes = false; + cur.push(b'"' as u16); + } + SPACE | TAB if !in_quotes => { + cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); + if !cur.is_empty() || was_in_quotes { + ret_val.push_back(OsString::from_wide(&cur[..])); + cur.truncate(0); + } + backslash_count = 0; + was_in_quotes = false; + } + 0x00 => { + cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); + // include empty quoted strings at the end of the arguments list + if !cur.is_empty() || was_in_quotes || in_quotes { + ret_val.push_back(OsString::from_wide(&cur[..])); + } + break; + } + _ => { + cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); + backslash_count = 0; + was_in_quotes = false; + cur.push(c); + } + } + i += 1; + } + ret_val +} + pub struct Args { - range: Range, - cur: *mut *mut u16, + parsed_args_list: VecDeque, } pub struct ArgsInnerDebug<'a> { @@ -48,14 +176,13 @@ impl<'a> fmt::Debug for ArgsInnerDebug<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("[")?; let mut first = true; - for i in self.args.range.clone() { + for i in &self.args.parsed_args_list { if !first { f.write_str(", ")?; } first = false; - // Here we do allocation which could be avoided. - fmt::Debug::fmt(&unsafe { os_string_from_ptr(*self.args.cur.offset(i)) }, f)?; + fmt::Debug::fmt(i, f)?; } f.write_str("]")?; Ok(()) @@ -70,38 +197,79 @@ impl Args { } } -unsafe fn os_string_from_ptr(ptr: *mut u16) -> OsString { - let mut len = 0; - while *ptr.offset(len) != 0 { len += 1; } - - // Push it onto the list. - let ptr = ptr as *const u16; - let buf = slice::from_raw_parts(ptr, len as usize); - OsStringExt::from_wide(buf) -} - impl Iterator for Args { type Item = OsString; - fn next(&mut self) -> Option { - self.range.next().map(|i| unsafe { os_string_from_ptr(*self.cur.offset(i)) } ) + fn next(&mut self) -> Option { self.parsed_args_list.pop_front() } + fn size_hint(&self) -> (usize, Option) { + (self.parsed_args_list.len(), Some(self.parsed_args_list.len())) } - fn size_hint(&self) -> (usize, Option) { self.range.size_hint() } } impl DoubleEndedIterator for Args { - fn next_back(&mut self) -> Option { - self.range.next_back().map(|i| unsafe { os_string_from_ptr(*self.cur.offset(i)) } ) - } + fn next_back(&mut self) -> Option { self.parsed_args_list.pop_back() } } impl ExactSizeIterator for Args { - fn len(&self) -> usize { self.range.len() } + fn len(&self) -> usize { self.parsed_args_list.len() } } -impl Drop for Args { - fn drop(&mut self) { - // self.cur can be null if CommandLineToArgvW previously failed, - // but LocalFree ignores NULL pointers - unsafe { c::LocalFree(self.cur as *mut c_void); } +#[cfg(test)] +mod tests { + use sys::windows::args::*; + use ffi::OsString; + + fn chk(string: &str, parts: &[&str]) { + let mut wide: Vec = OsString::from(string).encode_wide().collect(); + wide.push(0); + let parsed = unsafe { + parse_lp_cmd_line(wide.as_ptr() as *const u16, || OsString::from("TEST.EXE")) + }; + let expected: Vec = parts.iter().map(|k| OsString::from(k)).collect(); + assert_eq!(parsed, expected); + } + + #[test] + fn empty() { + chk("", &["TEST.EXE"]); + chk("\0", &["TEST.EXE"]); + } + + #[test] + fn single_words() { + chk("EXE one_word", &["EXE", "one_word"]); + chk("EXE a", &["EXE", "a"]); + chk("EXE 😅", &["EXE", "😅"]); + chk("EXE 😅🤦", &["EXE", "😅🤦"]); + } + + #[test] + fn official_examples() { + chk(r#"EXE "abc" d e"#, &["EXE", "abc", "d", "e"]); + chk(r#"EXE a\\\b d"e f"g h"#, &["EXE", r#"a\\\b"#, "de fg", "h"]); + chk(r#"EXE a\\\"b c d"#, &["EXE", r#"a\"b"#, "c", "d"]); + chk(r#"EXE a\\\\"b c" d e"#, &["EXE", r#"a\\b c"#, "d", "e"]); + } + + #[test] + fn whitespace_behavior() { + chk(r#" test"#, &["", "test"]); + chk(r#" test"#, &["", "test"]); + chk(r#" test test2"#, &["", "test", "test2"]); + chk(r#" test test2"#, &["", "test", "test2"]); + chk(r#"test test2 "#, &["test", "test2"]); + chk(r#"test test2 "#, &["test", "test2"]); + chk(r#"test "#, &["test"]); + } + + #[test] + fn genius_quotes() { + chk(r#"EXE "" """#, &["EXE", "", ""]); + chk(r#"EXE "" """"#, &["EXE", "", "\""]); + chk( + r#"EXE "this is """all""" in the same argument""#, + &["EXE", "this is \"all\" in the same argument"] + ); + chk(r#"EXE "\u{1}"""#, &["EXE", "\u{1}\""]); + chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]); } } diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index c84874a3e88..fa21f459a8a 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -1035,9 +1035,6 @@ extern "system" { pub fn SetLastError(dwErrCode: DWORD); pub fn GetCommandLineW() -> *mut LPCWSTR; - pub fn LocalFree(ptr: *mut c_void); - pub fn CommandLineToArgvW(lpCmdLine: *mut LPCWSTR, - pNumArgs: *mut c_int) -> *mut *mut u16; pub fn GetTempPathW(nBufferLength: DWORD, lpBuffer: LPCWSTR) -> DWORD; pub fn OpenProcessToken(ProcessHandle: HANDLE, diff --git a/src/test/run-make-fulldeps/tools.mk b/src/test/run-make-fulldeps/tools.mk index 3de358fa500..79399281804 100644 --- a/src/test/run-make-fulldeps/tools.mk +++ b/src/test/run-make-fulldeps/tools.mk @@ -76,7 +76,7 @@ endif # Extra flags needed to compile a working executable with the standard library ifdef IS_WINDOWS ifdef IS_MSVC - EXTRACFLAGS := ws2_32.lib userenv.lib shell32.lib advapi32.lib + EXTRACFLAGS := ws2_32.lib userenv.lib advapi32.lib else EXTRACFLAGS := -lws2_32 -luserenv endif -- cgit 1.4.1-3-g733a5 From 08fbbbd89c2dcdbec353fb0b02ad17015284bd2a Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 10 Dec 2018 13:12:47 -0700 Subject: Fix nitpicks Switch to vec::IntoIter as our backing double-ended iterator. Fix incorrect comment. --- src/libstd/sys/windows/args.rs | 44 ++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 23 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index 3eea9b19b6f..a0369fffa0c 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -15,7 +15,7 @@ use sys::windows::os::current_exe; use sys::c; use ffi::OsString; use fmt; -use collections::VecDeque; +use vec; use core::iter; use slice; use path::PathBuf; @@ -43,7 +43,7 @@ pub fn args() -> Args { /// GUI applications add a bunch of overhead, even if no windows are drawn. See /// . unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_name: F) - -> VecDeque { + -> vec::IntoIter { const BACKSLASH: u16 = '\\' as u16; const QUOTE: u16 = '"' as u16; const TAB: u16 = '\t' as u16; @@ -51,11 +51,11 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na let mut in_quotes = false; let mut was_in_quotes = false; let mut backslash_count: usize = 0; - let mut ret_val = VecDeque::new(); + let mut ret_val = Vec::new(); let mut cur = Vec::new(); if lp_cmd_line.is_null() || *lp_cmd_line == 0 { - ret_val.push_back(exe_name()); - return ret_val; + ret_val.push(exe_name()); + return ret_val.into_iter(); } let mut i = 0; // The executable name at the beginning is special. @@ -66,16 +66,16 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na loop { i += 1; if *lp_cmd_line.offset(i) == 0 { - ret_val.push_back(OsString::from_wide( + ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) )); - return ret_val; + return ret_val.into_iter(); } if *lp_cmd_line.offset(i) == QUOTE { break; } } - ret_val.push_back(OsString::from_wide( + ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) )); i += 1; @@ -86,25 +86,25 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na // will consider the first argument to be an empty string. Excess whitespace at the // end of lpCmdLine is ignored." 0...SPACE => { - ret_val.push_back(OsString::new()); + ret_val.push(OsString::new()); i += 1; }, - // The executable name ends at the next quote mark, + // The executable name ends at the next whitespace, // no matter what. _ => { loop { i += 1; if *lp_cmd_line.offset(i) == 0 { - ret_val.push_back(OsString::from_wide( + ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line, i as usize) )); - return ret_val; + return ret_val.into_iter(); } if let 0...SPACE = *lp_cmd_line.offset(i) { break; } } - ret_val.push_back(OsString::from_wide( + ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line, i as usize) )); i += 1; @@ -138,7 +138,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na SPACE | TAB if !in_quotes => { cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); if !cur.is_empty() || was_in_quotes { - ret_val.push_back(OsString::from_wide(&cur[..])); + ret_val.push(OsString::from_wide(&cur[..])); cur.truncate(0); } backslash_count = 0; @@ -148,7 +148,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); // include empty quoted strings at the end of the arguments list if !cur.is_empty() || was_in_quotes || in_quotes { - ret_val.push_back(OsString::from_wide(&cur[..])); + ret_val.push(OsString::from_wide(&cur[..])); } break; } @@ -161,11 +161,11 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na } i += 1; } - ret_val + ret_val.into_iter() } pub struct Args { - parsed_args_list: VecDeque, + parsed_args_list: vec::IntoIter, } pub struct ArgsInnerDebug<'a> { @@ -176,7 +176,7 @@ impl<'a> fmt::Debug for ArgsInnerDebug<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("[")?; let mut first = true; - for i in &self.args.parsed_args_list { + for i in self.args.parsed_args_list.clone() { if !first { f.write_str(", ")?; } @@ -199,14 +199,12 @@ impl Args { impl Iterator for Args { type Item = OsString; - fn next(&mut self) -> Option { self.parsed_args_list.pop_front() } - fn size_hint(&self) -> (usize, Option) { - (self.parsed_args_list.len(), Some(self.parsed_args_list.len())) - } + fn next(&mut self) -> Option { self.parsed_args_list.next() } + fn size_hint(&self) -> (usize, Option) { self.parsed_args_list.size_hint() } } impl DoubleEndedIterator for Args { - fn next_back(&mut self) -> Option { self.parsed_args_list.pop_back() } + fn next_back(&mut self) -> Option { self.parsed_args_list.next_back() } } impl ExactSizeIterator for Args { -- cgit 1.4.1-3-g733a5 From 5438465b68fd026f68308793c82a69b241788105 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 10 Dec 2018 14:33:03 -0700 Subject: Fix poorly-transcribed test case --- src/libstd/sys/windows/args.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index a0369fffa0c..62ef7a7f0f6 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -182,7 +182,7 @@ impl<'a> fmt::Debug for ArgsInnerDebug<'a> { } first = false; - fmt::Debug::fmt(i, f)?; + fmt::Debug::fmt(&i, f)?; } f.write_str("]")?; Ok(()) @@ -223,7 +223,7 @@ mod tests { parse_lp_cmd_line(wide.as_ptr() as *const u16, || OsString::from("TEST.EXE")) }; let expected: Vec = parts.iter().map(|k| OsString::from(k)).collect(); - assert_eq!(parsed, expected); + assert_eq!(parsed.as_slice(), expected.as_slice()); } #[test] @@ -267,7 +267,7 @@ mod tests { r#"EXE "this is """all""" in the same argument""#, &["EXE", "this is \"all\" in the same argument"] ); - chk(r#"EXE "\u{1}"""#, &["EXE", "\u{1}\""]); + chk(r#"EXE "a"""#, &["EXE", "a\""]); chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]); } } -- cgit 1.4.1-3-g733a5 From 05a22a72e4574b2105c0a190d7a4bd4a84da16ee Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 10 Dec 2018 15:37:50 -0700 Subject: Fix nits Add comments explaining how we test this, and use a slice for debugging instead of a clone of the iterator. --- src/libstd/sys/windows/args.rs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index 62ef7a7f0f6..fd93d389e43 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -35,13 +35,20 @@ pub fn args() -> Args { } } -/// Implements the Windows command-line argument parsing algorithm, described at +/// Implements the Windows command-line argument parsing algorithm. +/// +/// Microsoft's documentation for the Windows CLI argument format can be found at /// . /// /// Windows includes a function to do this in shell32.dll, /// but linking with that DLL causes the process to be registered as a GUI application. /// GUI applications add a bunch of overhead, even if no windows are drawn. See /// . +/// +/// This function was tested for equivalence to the shell32.dll implementation in +/// Windows 10 Pro v1803, using an exhaustive test suite available at +/// or +/// . unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_name: F) -> vec::IntoIter { const BACKSLASH: u16 = '\\' as u16; @@ -176,13 +183,13 @@ impl<'a> fmt::Debug for ArgsInnerDebug<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("[")?; let mut first = true; - for i in self.args.parsed_args_list.clone() { + for i in self.args.parsed_args_list.as_slice() { if !first { f.write_str(", ")?; } first = false; - fmt::Debug::fmt(&i, f)?; + fmt::Debug::fmt(i, f)?; } f.write_str("]")?; Ok(()) -- cgit 1.4.1-3-g733a5 From 083585859b2e499998c5b10ff5241f1f81ce6032 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 10 Dec 2018 15:48:32 -0700 Subject: Fix nit Rewrite it to not use `if let`. --- src/libstd/sys/windows/args.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index fd93d389e43..6dee75214fe 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -72,13 +72,14 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na QUOTE => { loop { i += 1; - if *lp_cmd_line.offset(i) == 0 { + let c = *lp_cmd_line.offset(i); + if c == 0 { ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) )); return ret_val.into_iter(); } - if *lp_cmd_line.offset(i) == QUOTE { + if c == QUOTE { break; } } @@ -101,13 +102,14 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na _ => { loop { i += 1; - if *lp_cmd_line.offset(i) == 0 { + let c = *lp_cmd_line.offset(i); + if c == 0 { ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line, i as usize) )); return ret_val.into_iter(); } - if let 0...SPACE = *lp_cmd_line.offset(i) { + if c > 0 && c <= SPACE { break; } } -- cgit 1.4.1-3-g733a5 From 55420f0f42460e5dc1d724be68496f9ef8557e72 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Mon, 10 Dec 2018 18:31:53 -0700 Subject: Fix iterator nits --- src/libstd/sys/windows/args.rs | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index 6dee75214fe..935466d927c 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -31,7 +31,7 @@ pub fn args() -> Args { lp_cmd_line as *const u16, || current_exe().map(PathBuf::into_os_string).unwrap_or_else(|_| OsString::new())); - Args { parsed_args_list: parsed_args_list } + Args { parsed_args_list: parsed_args_list.into_iter() } } } @@ -50,7 +50,7 @@ pub fn args() -> Args { /// or /// . unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_name: F) - -> vec::IntoIter { + -> Vec { const BACKSLASH: u16 = '\\' as u16; const QUOTE: u16 = '"' as u16; const TAB: u16 = '\t' as u16; @@ -62,7 +62,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na let mut cur = Vec::new(); if lp_cmd_line.is_null() || *lp_cmd_line == 0 { ret_val.push(exe_name()); - return ret_val.into_iter(); + return ret_val; } let mut i = 0; // The executable name at the beginning is special. @@ -77,7 +77,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) )); - return ret_val.into_iter(); + return ret_val; } if c == QUOTE { break; @@ -107,7 +107,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na ret_val.push(OsString::from_wide( slice::from_raw_parts(lp_cmd_line, i as usize) )); - return ret_val.into_iter(); + return ret_val; } if c > 0 && c <= SPACE { break; @@ -170,7 +170,7 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na } i += 1; } - ret_val.into_iter() + ret_val } pub struct Args { @@ -183,18 +183,7 @@ pub struct ArgsInnerDebug<'a> { impl<'a> fmt::Debug for ArgsInnerDebug<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str("[")?; - let mut first = true; - for i in self.args.parsed_args_list.as_slice() { - if !first { - f.write_str(", ")?; - } - first = false; - - fmt::Debug::fmt(i, f)?; - } - f.write_str("]")?; - Ok(()) + self.args.parsed_args_list.as_slice().fmt(f) } } -- cgit 1.4.1-3-g733a5 From 799cadb2bd980d1bcdcc831c2d0e50ec3b27527b Mon Sep 17 00:00:00 2001 From: Oliver Scherer Date: Tue, 11 Dec 2018 10:32:39 +0100 Subject: Remove unnecessary feature gates from const fns --- src/libstd/io/lazy.rs | 1 - src/libstd/lib.rs | 1 + src/libstd/sys/sgx/condvar.rs | 1 - src/libstd/sys/sgx/mutex.rs | 2 -- src/libstd/sys/sgx/rwlock.rs | 1 - src/libstd/sys/sgx/waitqueue.rs | 3 --- src/libstd/sys_common/condvar.rs | 1 - src/libstd/sys_common/mutex.rs | 1 - src/libstd/sys_common/rwlock.rs | 1 - 9 files changed, 1 insertion(+), 11 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/io/lazy.rs b/src/libstd/io/lazy.rs index c2aaeb98907..24965ff6931 100644 --- a/src/libstd/io/lazy.rs +++ b/src/libstd/io/lazy.rs @@ -26,7 +26,6 @@ const fn done() -> *mut Arc { 1_usize as *mut _ } unsafe impl Sync for Lazy {} impl Lazy { - #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Lazy { Lazy { lock: Mutex::new(), diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 90c8eaf0f7c..1feb6f268fa 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -271,6 +271,7 @@ #![feature(libc)] #![feature(link_args)] #![feature(linkage)] +#![feature(min_const_unsafe_fn)] #![feature(needs_panic_runtime)] #![feature(never_type)] #![feature(nll)] diff --git a/src/libstd/sys/sgx/condvar.rs b/src/libstd/sys/sgx/condvar.rs index d3e8165f3df..940f50f25b8 100644 --- a/src/libstd/sys/sgx/condvar.rs +++ b/src/libstd/sys/sgx/condvar.rs @@ -18,7 +18,6 @@ pub struct Condvar { } impl Condvar { - #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Condvar { Condvar { inner: SpinMutex::new(WaitVariable::new(())) } } diff --git a/src/libstd/sys/sgx/mutex.rs b/src/libstd/sys/sgx/mutex.rs index 663361162bc..994cf91eea0 100644 --- a/src/libstd/sys/sgx/mutex.rs +++ b/src/libstd/sys/sgx/mutex.rs @@ -20,7 +20,6 @@ pub struct Mutex { // Implementation according to “Operating Systems: Three Easy Pieces”, chapter 28 impl Mutex { - #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Mutex { Mutex { inner: SpinMutex::new(WaitVariable::new(false)) } } @@ -79,7 +78,6 @@ pub struct ReentrantMutex { } impl ReentrantMutex { - #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn uninitialized() -> ReentrantMutex { ReentrantMutex { inner: SpinMutex::new(WaitVariable::new(ReentrantLock { owner: None, count: 0 })) diff --git a/src/libstd/sys/sgx/rwlock.rs b/src/libstd/sys/sgx/rwlock.rs index 7b6970b825f..a1551dbb53b 100644 --- a/src/libstd/sys/sgx/rwlock.rs +++ b/src/libstd/sys/sgx/rwlock.rs @@ -21,7 +21,6 @@ pub struct RWLock { //unsafe impl Sync for RWLock {} // FIXME impl RWLock { - #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> RWLock { RWLock { readers: SpinMutex::new(WaitVariable::new(None)), diff --git a/src/libstd/sys/sgx/waitqueue.rs b/src/libstd/sys/sgx/waitqueue.rs index ec1135ba30c..ef0def13eee 100644 --- a/src/libstd/sys/sgx/waitqueue.rs +++ b/src/libstd/sys/sgx/waitqueue.rs @@ -50,7 +50,6 @@ pub struct WaitVariable { } impl WaitVariable { - #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new(var: T) -> Self { WaitVariable { queue: WaitQueue::new(), @@ -137,7 +136,6 @@ impl<'a, T> Drop for WaitGuard<'a, T> { } impl WaitQueue { - #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Self { WaitQueue { inner: UnsafeList::new() @@ -255,7 +253,6 @@ mod unsafe_list { } impl UnsafeList { - #[unstable(feature = "sgx_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Self { unsafe { UnsafeList { diff --git a/src/libstd/sys_common/condvar.rs b/src/libstd/sys_common/condvar.rs index 16bf0803a8d..b6f29dd5fc3 100644 --- a/src/libstd/sys_common/condvar.rs +++ b/src/libstd/sys_common/condvar.rs @@ -25,7 +25,6 @@ impl Condvar { /// /// Behavior is undefined if the condition variable is moved after it is /// first used with any of the functions below. - #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Condvar { Condvar(imp::Condvar::new()) } /// Prepares the condition variable for use. diff --git a/src/libstd/sys_common/mutex.rs b/src/libstd/sys_common/mutex.rs index 87684237638..c6d531c7a1a 100644 --- a/src/libstd/sys_common/mutex.rs +++ b/src/libstd/sys_common/mutex.rs @@ -27,7 +27,6 @@ impl Mutex { /// 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. - #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> Mutex { Mutex(imp::Mutex::new()) } /// Prepare the mutex for use. diff --git a/src/libstd/sys_common/rwlock.rs b/src/libstd/sys_common/rwlock.rs index a430c254d3c..71a4f01ec4c 100644 --- a/src/libstd/sys_common/rwlock.rs +++ b/src/libstd/sys_common/rwlock.rs @@ -22,7 +22,6 @@ impl RWLock { /// /// Behavior is undefined if the reader-writer lock is moved after it is /// first used with any of the functions below. - #[unstable(feature = "sys_internals", issue = "0")] // FIXME: min_const_fn pub const fn new() -> RWLock { RWLock(imp::RWLock::new()) } /// Acquires shared access to the underlying lock, blocking the current -- cgit 1.4.1-3-g733a5 From 134661917bf4b086b027a2c58219d50ba57a1453 Mon Sep 17 00:00:00 2001 From: Oliver Scherer Date: Tue, 11 Dec 2018 10:33:17 +0100 Subject: Remove some dead code from `sgx` --- src/libstd/sys/sgx/abi/mem.rs | 7 ------- src/libstd/sys/sgx/abi/usercalls/mod.rs | 8 -------- 2 files changed, 15 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/sgx/abi/mem.rs b/src/libstd/sys/sgx/abi/mem.rs index 508f2ff4d4f..bf32c712216 100644 --- a/src/libstd/sys/sgx/abi/mem.rs +++ b/src/libstd/sys/sgx/abi/mem.rs @@ -34,13 +34,6 @@ fn image_base() -> u64 { base } -pub fn is_enclave_range(p: *const u8, len: usize) -> bool { - let start=p as u64; - let end=start + (len as u64); - start >= image_base() && - end <= image_base() + (unsafe { ENCLAVE_SIZE } as u64) // unsafe ok: link-time constant -} - pub fn is_user_range(p: *const u8, len: usize) -> bool { let start=p as u64; let end=start + (len as u64); diff --git a/src/libstd/sys/sgx/abi/usercalls/mod.rs b/src/libstd/sys/sgx/abi/usercalls/mod.rs index 2bc32c9fefb..d1d180e4825 100644 --- a/src/libstd/sys/sgx/abi/usercalls/mod.rs +++ b/src/libstd/sys/sgx/abi/usercalls/mod.rs @@ -33,14 +33,6 @@ pub fn read(fd: Fd, buf: &mut [u8]) -> IoResult { } } -pub fn read_alloc(fd: Fd) -> IoResult> { - unsafe { - let mut userbuf = alloc::User::::uninitialized(); - raw::read_alloc(fd, userbuf.as_raw_mut_ptr()).from_sgx_result()?; - Ok(copy_user_buffer(&userbuf)) - } -} - pub fn write(fd: Fd, buf: &[u8]) -> IoResult { unsafe { let userbuf = alloc::User::new_from_enclave(buf); -- cgit 1.4.1-3-g733a5 From 83fe6e4392b2b89005f3056cf56a382887c939d5 Mon Sep 17 00:00:00 2001 From: Michael Howell Date: Tue, 11 Dec 2018 11:55:02 -0700 Subject: Use iterators instead of raw offsets in Windows argument parser --- src/libstd/sys/windows/args.rs | 94 ++++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 49 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/windows/args.rs b/src/libstd/sys/windows/args.rs index 935466d927c..9e9198e05ee 100644 --- a/src/libstd/sys/windows/args.rs +++ b/src/libstd/sys/windows/args.rs @@ -55,38 +55,35 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na const QUOTE: u16 = '"' as u16; const TAB: u16 = '\t' as u16; const SPACE: u16 = ' ' as u16; - let mut in_quotes = false; - let mut was_in_quotes = false; - let mut backslash_count: usize = 0; let mut ret_val = Vec::new(); - let mut cur = Vec::new(); if lp_cmd_line.is_null() || *lp_cmd_line == 0 { ret_val.push(exe_name()); return ret_val; } - let mut i = 0; + let mut cmd_line = { + let mut end = 0; + while *lp_cmd_line.offset(end) != 0 { + end += 1; + } + slice::from_raw_parts(lp_cmd_line, end as usize) + }; // The executable name at the beginning is special. - match *lp_cmd_line { + cmd_line = match cmd_line[0] { // The executable name ends at the next quote mark, // no matter what. QUOTE => { - loop { - i += 1; - let c = *lp_cmd_line.offset(i); - if c == 0 { - ret_val.push(OsString::from_wide( - slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) - )); - return ret_val; - } - if c == QUOTE { - break; + let args = { + let mut cut = cmd_line[1..].splitn(2, |&c| c == QUOTE); + if let Some(exe) = cut.next() { + ret_val.push(OsString::from_wide(exe)); } + cut.next() + }; + if let Some(args) = args { + args + } else { + return ret_val; } - ret_val.push(OsString::from_wide( - slice::from_raw_parts(lp_cmd_line.offset(1), i as usize - 1) - )); - i += 1; } // Implement quirk: when they say whitespace here, // they include the entire ASCII control plane: @@ -95,32 +92,30 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na // end of lpCmdLine is ignored." 0...SPACE => { ret_val.push(OsString::new()); - i += 1; + &cmd_line[1..] }, // The executable name ends at the next whitespace, // no matter what. _ => { - loop { - i += 1; - let c = *lp_cmd_line.offset(i); - if c == 0 { - ret_val.push(OsString::from_wide( - slice::from_raw_parts(lp_cmd_line, i as usize) - )); - return ret_val; - } - if c > 0 && c <= SPACE { - break; + let args = { + let mut cut = cmd_line.splitn(2, |&c| c > 0 && c <= SPACE); + if let Some(exe) = cut.next() { + ret_val.push(OsString::from_wide(exe)); } + cut.next() + }; + if let Some(args) = args { + args + } else { + return ret_val; } - ret_val.push(OsString::from_wide( - slice::from_raw_parts(lp_cmd_line, i as usize) - )); - i += 1; } - } - loop { - let c = *lp_cmd_line.offset(i); + }; + let mut cur = Vec::new(); + let mut in_quotes = false; + let mut was_in_quotes = false; + let mut backslash_count: usize = 0; + for &c in cmd_line { match c { // backslash BACKSLASH => { @@ -153,14 +148,6 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na backslash_count = 0; was_in_quotes = false; } - 0x00 => { - cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); - // include empty quoted strings at the end of the arguments list - if !cur.is_empty() || was_in_quotes || in_quotes { - ret_val.push(OsString::from_wide(&cur[..])); - } - break; - } _ => { cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); backslash_count = 0; @@ -168,7 +155,11 @@ unsafe fn parse_lp_cmd_line OsString>(lp_cmd_line: *const u16, exe_na cur.push(c); } } - i += 1; + } + cur.extend(iter::repeat(b'\\' as u16).take(backslash_count)); + // include empty quoted strings at the end of the arguments list + if !cur.is_empty() || was_in_quotes || in_quotes { + ret_val.push(OsString::from_wide(&cur[..])); } ret_val } @@ -267,5 +258,10 @@ mod tests { ); chk(r#"EXE "a"""#, &["EXE", "a\""]); chk(r#"EXE "a"" a"#, &["EXE", "a\"", "a"]); + // quotes cannot be escaped in command names + chk(r#""EXE" check"#, &["EXE", "check"]); + chk(r#""EXE check""#, &["EXE check"]); + chk(r#""EXE """for""" check"#, &["EXE ", r#"for""#, "check"]); + chk(r#""EXE \"for\" check"#, &[r#"EXE \"#, r#"for""#, "check"]); } } -- cgit 1.4.1-3-g733a5 From 4c21a3bc2afc5933f31f1368f6b3406c5f1bdeb3 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Mon, 19 Nov 2018 21:52:50 -0800 Subject: std: Depend directly on crates.io crates Ever since we added a Cargo-based build system for the compiler the standard library has always been a little special, it's never been able to depend on crates.io crates for runtime dependencies. This has been a result of various limitations, namely that Cargo doesn't understand that crates from crates.io depend on libcore, so Cargo tries to build crates before libcore is finished. I had an idea this afternoon, however, which lifts the strategy from #52919 to directly depend on crates.io crates from the standard library. After all is said and done this removes a whopping three submodules that we need to manage! The basic idea here is that for any crate `std` depends on it adds an *optional* dependency on an empty crate on crates.io, in this case named `rustc-std-workspace-core`. This crate is overridden via `[patch]` in this repository to point to a local crate we write, and *that* has a `path` dependency on libcore. Note that all `no_std` crates also depend on `compiler_builtins`, but if we're not using submodules we can publish `compiler_builtins` to crates.io and all crates can depend on it anyway! The basic strategy then looks like: * The standard library (or some transitive dep) decides to depend on a crate `foo`. * The standard library adds ```toml [dependencies] foo = { version = "0.1", features = ['rustc-dep-of-std'] } ``` * The crate `foo` has an optional dependency on `rustc-std-workspace-core` * The crate `foo` has an optional dependency on `compiler_builtins` * The crate `foo` has a feature `rustc-dep-of-std` which activates these crates and any other necessary infrastructure in the crate. A sample commit for `dlmalloc` [turns out to be quite simple][commit]. After that all `no_std` crates should largely build "as is" and still be publishable on crates.io! Notably they should be able to continue to use stable Rust if necessary, since the `rename-dependency` feature of Cargo is soon stabilizing. As a proof of concept, this commit removes the `dlmalloc`, `libcompiler_builtins`, and `libc` submodules from this repository. Long thorns in our side these are now gone for good and we can directly depend on crates.io! It's hoped that in the long term we can bring in other crates as necessary, but for now this is largely intended to simply make it easier to manage these crates and remove submodules. This should be a transparent non-breaking change for all users, but one possible stickler is that this almost for sure breaks out-of-tree `std`-building tools like `xargo` and `cargo-xbuild`. I think it should be relatively easy to get them working, however, as all that's needed is an entry in the `[patch]` section used to build the standard library. Hopefully we can work with these tools to solve this problem! [commit]: https://github.com/alexcrichton/dlmalloc-rs/commit/28ee12db813a3b650a7c25d1c36d2c17dcb88ae3 --- .gitmodules | 12 --- Cargo.lock | 85 ++++++++++++---------- Cargo.toml | 4 + src/bootstrap/compile.rs | 5 +- src/bootstrap/dist.rs | 15 +--- src/bootstrap/lib.rs | 8 +- src/bootstrap/test.rs | 5 +- src/build_helper/lib.rs | 15 ++-- src/dlmalloc | 1 - src/liballoc/Cargo.toml | 4 +- src/liballoc/tests/binary_heap.rs | 4 +- src/liballoc/tests/slice.rs | 4 +- src/libcompiler_builtins | 1 - src/libcore/Cargo.toml | 2 +- src/libcore/tests/num/flt2dec/random.rs | 13 +++- src/libcore/tests/slice.rs | 6 +- src/liblibc | 1 - src/libpanic_abort/Cargo.toml | 4 +- src/libpanic_unwind/Cargo.toml | 4 +- src/libprofiler_builtins/Cargo.toml | 2 +- src/libprofiler_builtins/build.rs | 8 +- src/librustc_asan/Cargo.toml | 2 +- src/librustc_lsan/Cargo.toml | 2 +- src/librustc_msan/Cargo.toml | 2 +- src/librustc_resolve/diagnostics.rs | 6 +- src/librustc_tsan/Cargo.toml | 2 +- src/libstd/Cargo.toml | 10 +-- src/libstd/build.rs | 7 +- src/libstd/fs.rs | 2 +- src/libstd/primitive_docs.rs | 2 +- src/libstd/sys/unix/ext/fs.rs | 2 +- src/libunwind/Cargo.toml | 4 +- src/rust-sgx | 1 - src/rustc/compiler_builtins_shim/Cargo.toml | 40 ---------- src/rustc/compiler_builtins_shim/build.rs | 15 ---- src/rustc/dlmalloc_shim/Cargo.toml | 14 ---- src/rustc/fortanix-sgx-abi_shim/Cargo.toml | 14 ---- src/rustc/libc_shim/Cargo.toml | 40 ---------- src/stage0.txt | 2 +- src/test/incremental/foreign.rs | 2 +- .../c-link-to-rust-va-list-fn/checkrust.rs | 2 +- src/test/run-make-fulldeps/issue-25581/test.rs | 8 +- .../run-make-fulldeps/issue-26006/in/time/lib.rs | 2 +- src/test/run-make-fulldeps/link-path-order/main.rs | 2 +- src/test/run-pass-valgrind/osx-frameworks.rs | 2 +- src/test/run-pass/anon-extern-mod.rs | 2 +- .../run-pass/array-slice-vec/vec-macro-no-std.rs | 2 +- .../auxiliary/anon-extern-mod-cross-crate-1.rs | 2 +- .../check_static_recursion_foreign_helper.rs | 2 +- src/test/run-pass/auxiliary/foreign_lib.rs | 2 +- src/test/run-pass/c-stack-as-value.rs | 2 +- src/test/run-pass/c-stack-returning-int64.rs | 2 +- .../run-pass/check-static-recursion-foreign.rs | 2 +- src/test/run-pass/command-before-exec.rs | 2 +- .../auxiliary/anon-extern-mod-cross-crate-1.rs | 2 +- src/test/run-pass/core-run-destroy.rs | 2 +- .../auxiliary/anon-extern-mod-cross-crate-1.rs | 2 +- src/test/run-pass/env-funky-keys.rs | 2 +- src/test/run-pass/env-null-vars.rs | 2 +- .../extern/auxiliary/extern-crosscrate-source.rs | 2 +- src/test/run-pass/extern/extern-call-deep.rs | 2 +- src/test/run-pass/extern/extern-call-deep2.rs | 2 +- src/test/run-pass/extern/extern-call-indirect.rs | 2 +- src/test/run-pass/extern/extern-call-scrub.rs | 2 +- src/test/run-pass/extern/extern-crosscrate.rs | 2 +- src/test/run-pass/fds-are-cloexec.rs | 2 +- src/test/run-pass/foreign/auxiliary/foreign_lib.rs | 2 +- .../run-pass/foreign/foreign-call-no-runtime.rs | 2 +- src/test/run-pass/foreign/foreign-fn-linkname.rs | 2 +- src/test/run-pass/foreign/foreign-no-abi.rs | 2 +- src/test/run-pass/foreign/foreign2.rs | 2 +- src/test/run-pass/invalid_const_promotion.rs | 2 +- .../issues/issue-13259-windows-tcb-trash.rs | 2 +- src/test/run-pass/issues/issue-2214.rs | 2 +- src/test/run-pass/issues/issue-30490.rs | 2 +- src/test/run-pass/issues/issue-3656.rs | 2 +- src/test/run-pass/no-stdio.rs | 2 +- src/test/run-pass/out-of-stack.rs | 2 +- src/test/run-pass/rfcs/rfc-1014-2.rs | 2 +- src/test/run-pass/rfcs/rfc-1014.rs | 2 +- src/test/run-pass/segfault-no-out-of-stack.rs | 2 +- .../run-pass/signal-alternate-stack-cleanup.rs | 2 +- src/test/run-pass/statics/static-mut-foreign.rs | 2 +- src/test/run-pass/wait-forked-but-failed-child.rs | 2 +- src/test/ui/error-codes/E0259.rs | 2 +- src/test/ui/extern/extern-const.fixed | 2 +- src/test/ui/extern/extern-const.rs | 2 +- src/test/ui/issues/issue-1251.rs | 2 +- src/test/ui/issues/issue-22034.rs | 2 +- src/test/ui/issues/issue-37887.stderr | 4 +- src/test/ui/lint/lint-ctypes.rs | 2 +- src/test/ui/non-copyable-void.rs | 2 +- src/test/ui/unnecessary-extern-crate.rs | 2 +- src/tools/rustc-std-workspace-core/Cargo.toml | 14 ++++ src/tools/rustc-std-workspace-core/README.md | 29 ++++++++ src/tools/rustc-std-workspace-core/lib.rs | 6 ++ src/tools/tidy/src/deps.rs | 1 + src/tools/tidy/src/lib.rs | 6 +- src/tools/tidy/src/pal.rs | 3 - 99 files changed, 231 insertions(+), 314 deletions(-) delete mode 160000 src/dlmalloc delete mode 160000 src/libcompiler_builtins delete mode 160000 src/liblibc delete mode 160000 src/rust-sgx delete mode 100644 src/rustc/compiler_builtins_shim/Cargo.toml delete mode 100644 src/rustc/compiler_builtins_shim/build.rs delete mode 100644 src/rustc/dlmalloc_shim/Cargo.toml delete mode 100644 src/rustc/fortanix-sgx-abi_shim/Cargo.toml delete mode 100644 src/rustc/libc_shim/Cargo.toml create mode 100644 src/tools/rustc-std-workspace-core/Cargo.toml create mode 100644 src/tools/rustc-std-workspace-core/README.md create mode 100644 src/tools/rustc-std-workspace-core/lib.rs (limited to 'src/libstd/sys') diff --git a/.gitmodules b/.gitmodules index 3fc6e45db3e..70164d48a30 100644 --- a/.gitmodules +++ b/.gitmodules @@ -5,9 +5,6 @@ [submodule "src/rust-installer"] path = src/tools/rust-installer url = https://github.com/rust-lang/rust-installer.git -[submodule "src/liblibc"] - path = src/liblibc - url = https://github.com/rust-lang/libc.git [submodule "src/doc/nomicon"] path = src/doc/nomicon url = https://github.com/rust-lang-nursery/nomicon.git @@ -23,9 +20,6 @@ [submodule "src/tools/rls"] path = src/tools/rls url = https://github.com/rust-lang-nursery/rls.git -[submodule "src/libcompiler_builtins"] - path = src/libcompiler_builtins - url = https://github.com/rust-lang-nursery/compiler-builtins.git [submodule "src/tools/clippy"] path = src/tools/clippy url = https://github.com/rust-lang-nursery/rust-clippy.git @@ -35,9 +29,6 @@ [submodule "src/tools/miri"] path = src/tools/miri url = https://github.com/solson/miri.git -[submodule "src/dlmalloc"] - path = src/dlmalloc - url = https://github.com/alexcrichton/dlmalloc-rs.git [submodule "src/doc/rust-by-example"] path = src/doc/rust-by-example url = https://github.com/rust-lang/rust-by-example.git @@ -67,6 +58,3 @@ [submodule "src/doc/edition-guide"] path = src/doc/edition-guide url = https://github.com/rust-lang-nursery/edition-guide -[submodule "src/rust-sgx"] - path = src/rust-sgx - url = https://github.com/fortanix/rust-sgx diff --git a/Cargo.lock b/Cargo.lock index c3c881259db..d22a9107339 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15,9 +15,9 @@ dependencies = [ name = "alloc" version = "0.0.0" dependencies = [ - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", - "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -407,10 +407,11 @@ dependencies = [ [[package]] name = "compiler_builtins" -version = "0.0.0" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)", - "core 0.0.0", + "rustc-std-workspace-core 1.0.0", ] [[package]] @@ -456,7 +457,7 @@ dependencies = [ name = "core" version = "0.0.0" dependencies = [ - "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -658,10 +659,12 @@ dependencies = [ [[package]] name = "dlmalloc" -version = "0.0.0" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "compiler_builtins 0.0.0", - "core 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-std-workspace-core 1.0.0", ] [[package]] @@ -814,10 +817,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "fortanix-sgx-abi" -version = "0.0.0" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "compiler_builtins 0.0.0", - "core 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-std-workspace-core 1.0.0", ] [[package]] @@ -1138,18 +1142,13 @@ name = "lazycell" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "libc" -version = "0.0.0" -dependencies = [ - "compiler_builtins 0.0.0", - "core 0.0.0", -] - [[package]] name = "libc" version = "0.2.45" source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "rustc-std-workspace-core 1.0.0", +] [[package]] name = "libgit2-sys" @@ -1520,9 +1519,9 @@ dependencies = [ name = "panic_abort" version = "0.0.0" dependencies = [ - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", - "libc 0.0.0", + "libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1530,9 +1529,9 @@ name = "panic_unwind" version = "0.0.0" dependencies = [ "alloc 0.0.0", - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", - "libc 0.0.0", + "libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)", "unwind 0.0.0", ] @@ -1683,7 +1682,7 @@ name = "profiler_builtins" version = "0.0.0" dependencies = [ "cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", ] @@ -1814,7 +1813,7 @@ name = "rand_chacha" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1836,7 +1835,7 @@ name = "rand_hc" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1861,7 +1860,7 @@ name = "rand_xorshift" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "rand_core 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand_core 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2242,6 +2241,13 @@ name = "rustc-serialize" version = "0.3.24" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "rustc-std-workspace-core" +version = "1.0.0" +dependencies = [ + "core 0.0.0", +] + [[package]] name = "rustc-workspace-hack" version = "1.0.0" @@ -2284,7 +2290,7 @@ dependencies = [ "alloc 0.0.0", "build_helper 0.1.0", "cmake 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", ] @@ -2479,7 +2485,7 @@ dependencies = [ "alloc 0.0.0", "build_helper 0.1.0", "cmake 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", ] @@ -2531,7 +2537,7 @@ dependencies = [ "alloc 0.0.0", "build_helper 0.1.0", "cmake 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", ] @@ -2644,7 +2650,7 @@ dependencies = [ "alloc 0.0.0", "build_helper 0.1.0", "cmake 0.1.33 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", ] @@ -2877,15 +2883,15 @@ dependencies = [ "alloc 0.0.0", "build_helper 0.1.0", "cc 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)", - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", - "dlmalloc 0.0.0", - "fortanix-sgx-abi 0.0.0", - "libc 0.0.0", + "dlmalloc 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", + "fortanix-sgx-abi 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)", "panic_abort 0.0.0", "panic_unwind 0.0.0", "profiler_builtins 0.0.0", - "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "rustc_asan 0.0.0", "rustc_lsan 0.0.0", "rustc_msan 0.0.0", @@ -3217,9 +3223,9 @@ dependencies = [ name = "unwind" version = "0.0.0" dependencies = [ - "compiler_builtins 0.0.0", + "compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "core 0.0.0", - "libc 0.0.0", + "libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3397,6 +3403,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum colored 1.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b0aa3473e85a3161b59845d6096b289bb577874cafeaf75ea1b1beaa6572c7fc" "checksum commoncrypto 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d056a8586ba25a1e4d61cb090900e495952c7886786fc55f909ab2f819b69007" "checksum commoncrypto-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1fed34f46747aa73dfaa578069fd8279d2818ade2b55f38f22a9401c7f4083e2" +"checksum compiler_builtins 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "8ad611263b9f31bdb66e66227d3b781600fd1e68d5deee29b23f5e2ac9cb4892" "checksum compiletest_rs 0.3.17 (registry+https://github.com/rust-lang/crates.io-index)" = "89747fe073b7838343bd2c2445e7a7c2e0d415598f8925f0fa9205b9cdfc48cb" "checksum core-foundation 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4e2640d6d0bf22e82bed1b73c6aef8d5dd31e5abe6666c57e6d45e2649f4f887" "checksum core-foundation-sys 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" @@ -3418,6 +3425,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum diff 0.1.11 (registry+https://github.com/rust-lang/crates.io-index)" = "3c2b69f912779fbb121ceb775d74d51e915af17aaebc38d28a592843a2dd0a3a" "checksum difference 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "524cbf6897b527295dff137cec09ecf3a05f4fddffd7dfcd1585403449e74198" "checksum directories 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "72d337a64190607d4fcca2cb78982c5dd57f4916e19696b48a575fa746b6cb0f" +"checksum dlmalloc 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4c46c65de42b063004b31c67a98abe071089b289ff0919c660ed7ff4f59317f8" "checksum either 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3be565ca5c557d7f59e7cfcf1844f9e3033650c929c6566f511e8005f205c1d0" "checksum elasticlunr-rs 2.3.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a99a310cd1f9770e7bf8e48810c7bcbb0e078c8fb23a8c7bcf0da4c2bf61a455" "checksum ena 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f56c93cc076508c549d9bb747f79aa9b4eb098be7b8cad8830c3137ef52d1e00" @@ -3434,6 +3442,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" "checksum fnv 1.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2fad85553e09a6f881f739c29f0b00b0f01357c743266d478b68951ce23285f3" "checksum foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" "checksum foreign-types-shared 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" +"checksum fortanix-sgx-abi 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "26105e20b4c3f7a319db1376b54ac9a46e5761e949405553375095d05a0cee4d" "checksum fs2 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" "checksum fs_extra 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5f2a4a2034423744d2cc7ca2068453168dcdb82c438419e639a26bd87839c674" "checksum fst 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d94485a00b1827b861dd9d1a2cc9764f9044d4c535514c0760a5a2012ef3399f" diff --git a/Cargo.toml b/Cargo.toml index b763caa97d7..667c55791bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,6 +65,10 @@ rustfmt-nightly = { path = "src/tools/rustfmt" } # here rustc-workspace-hack = { path = 'src/tools/rustc-workspace-hack' } +# See comments in `tools/rustc-std-workspace-core/README.md` for what's going on +# here +rustc-std-workspace-core = { path = 'src/tools/rustc-std-workspace-core' } + [patch."https://github.com/rust-lang/rust-clippy"] clippy_lints = { path = "src/tools/clippy/clippy_lints" } rustc_tools_util = { path = "src/tools/clippy/rustc_tools_util" } diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index 2e792b6053e..c84abe42a63 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -152,11 +152,10 @@ pub fn std_cargo(builder: &Builder, if builder.no_std(target) == Some(true) { // for no-std targets we only compile a few no_std crates - cargo.arg("--features").arg("c mem") + cargo .args(&["-p", "alloc"]) - .args(&["-p", "compiler_builtins"]) .arg("--manifest-path") - .arg(builder.src.join("src/rustc/compiler_builtins_shim/Cargo.toml")); + .arg(builder.src.join("src/liballoc/Cargo.toml")); } else { let features = builder.std_features(); diff --git a/src/bootstrap/dist.rs b/src/bootstrap/dist.rs index 1ae494bfd44..f03eefb7a12 100644 --- a/src/bootstrap/dist.rs +++ b/src/bootstrap/dist.rs @@ -857,12 +857,9 @@ impl Step for Src { // (essentially libstd and all of its path dependencies) let std_src_dirs = [ "src/build_helper", - "src/dlmalloc", "src/liballoc", "src/libbacktrace", - "src/libcompiler_builtins", "src/libcore", - "src/liblibc", "src/libpanic_abort", "src/libpanic_unwind", "src/librustc_asan", @@ -871,21 +868,15 @@ impl Step for Src { "src/librustc_tsan", "src/libstd", "src/libunwind", - "src/rustc/compiler_builtins_shim", - "src/rustc/libc_shim", - "src/rustc/dlmalloc_shim", - "src/rustc/fortanix-sgx-abi_shim", "src/libtest", "src/libterm", "src/libprofiler_builtins", "src/stdsimd", "src/libproc_macro", - ]; - let std_src_dirs_exclude = [ - "src/libcompiler_builtins/compiler-rt/test", + "src/tools/rustc-std-workspace-core", ]; - copy_src_dirs(builder, &std_src_dirs[..], &std_src_dirs_exclude[..], &dst_src); + copy_src_dirs(builder, &std_src_dirs[..], &[], &dst_src); for file in src_files.iter() { builder.copy(&builder.src.join(file), &dst_src.join(file)); } @@ -909,7 +900,7 @@ impl Step for Src { } } -const CARGO_VENDOR_VERSION: &str = "0.1.19"; +const CARGO_VENDOR_VERSION: &str = "0.1.22"; #[derive(Debug, PartialOrd, Ord, Copy, Clone, Hash, PartialEq, Eq)] pub struct PlainSourceTarball; diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index c31db48dc7e..c8792918db2 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -1134,10 +1134,10 @@ impl Build { let krate = &self.crates[&krate]; if krate.is_local(self) { ret.push(krate); - for dep in &krate.deps { - if visited.insert(dep) && dep != "build_helper" { - list.push(*dep); - } + } + for dep in &krate.deps { + if visited.insert(dep) && dep != "build_helper" { + list.push(*dep); } } } diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index ca9894f8f62..dc061fe5099 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1558,10 +1558,7 @@ impl Step for Crate { let builder = run.builder; run = run.krate("test"); for krate in run.builder.in_tree_crates("std") { - if krate.is_local(&run.builder) - && !(krate.name.starts_with("rustc_") && krate.name.ends_with("san")) - && krate.name != "dlmalloc" - { + if !(krate.name.starts_with("rustc_") && krate.name.ends_with("san")) { run = run.path(krate.local_path(&builder).to_str().unwrap()); } } diff --git a/src/build_helper/lib.rs b/src/build_helper/lib.rs index 0cbb0802361..a580a874b33 100644 --- a/src/build_helper/lib.rs +++ b/src/build_helper/lib.rs @@ -224,14 +224,12 @@ impl Drop for NativeLibBoilerplate { // Timestamps are created automatically when the result of `native_lib_boilerplate` goes out // of scope, so all the build actions should be completed until then. pub fn native_lib_boilerplate( - src_name: &str, + src_dir: &Path, out_name: &str, link_name: &str, search_subdir: &str, ) -> Result { - let current_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); - let src_dir = current_dir.join("..").join(src_name); - rerun_if_changed_anything_in_dir(&src_dir); + rerun_if_changed_anything_in_dir(src_dir); let out_dir = env::var_os("RUSTBUILD_NATIVE_DIR").unwrap_or_else(|| env::var_os("OUT_DIR").unwrap()); @@ -248,9 +246,9 @@ pub fn native_lib_boilerplate( ); let timestamp = out_dir.join("rustbuild.timestamp"); - if !up_to_date(Path::new("build.rs"), ×tamp) || !up_to_date(&src_dir, ×tamp) { + if !up_to_date(Path::new("build.rs"), ×tamp) || !up_to_date(src_dir, ×tamp) { Ok(NativeLibBoilerplate { - src_dir: src_dir, + src_dir: src_dir.to_path_buf(), out_dir: out_dir, }) } else { @@ -279,8 +277,11 @@ pub fn sanitizer_lib_boilerplate(sanitizer_name: &str) } else { format!("static={}", link_name) }; + // The source for `compiler-rt` comes from the `compiler-builtins` crate, so + // load our env var set by cargo to find the source code. + let dir = env::var_os("DEP_COMPILER_RT_COMPILER_RT").unwrap(); let lib = native_lib_boilerplate( - "libcompiler_builtins/compiler-rt", + dir.as_ref(), sanitizer_name, &to_link, search_path, diff --git a/src/dlmalloc b/src/dlmalloc deleted file mode 160000 index de99f4b0c88..00000000000 --- a/src/dlmalloc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit de99f4b0c886f5916cd1a146464276d65bef61b8 diff --git a/src/liballoc/Cargo.toml b/src/liballoc/Cargo.toml index 642a43d4d9c..b7faee1bc7d 100644 --- a/src/liballoc/Cargo.toml +++ b/src/liballoc/Cargo.toml @@ -11,10 +11,10 @@ path = "lib.rs" [dependencies] core = { path = "../libcore" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +compiler_builtins = { version = "0.1.0", features = ['rustc-dep-of-std'] } [dev-dependencies] -rand = "0.5" +rand = "0.6" [[test]] name = "collectionstests" diff --git a/src/liballoc/tests/binary_heap.rs b/src/liballoc/tests/binary_heap.rs index b0d8fa6bd69..536291de8f0 100644 --- a/src/liballoc/tests/binary_heap.rs +++ b/src/liballoc/tests/binary_heap.rs @@ -14,7 +14,7 @@ use std::collections::binary_heap::{Drain, PeekMut}; use std::panic::{self, AssertUnwindSafe}; use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering}; -use rand::{thread_rng, Rng}; +use rand::{thread_rng, seq::SliceRandom}; #[test] fn test_iterator() { @@ -332,7 +332,7 @@ fn panic_safe() { let panic_item = PanicOrd(i, true); // heapify the sane items - rng.shuffle(&mut panic_ords); + panic_ords.shuffle(&mut rng); let mut heap = BinaryHeap::from(panic_ords); let inner_data; diff --git a/src/liballoc/tests/slice.rs b/src/liballoc/tests/slice.rs index 787e4952882..6f31e6ca1a1 100644 --- a/src/liballoc/tests/slice.rs +++ b/src/liballoc/tests/slice.rs @@ -18,7 +18,7 @@ use std::sync::atomic::Ordering::Relaxed; use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize}; use std::thread; -use rand::{Rng, RngCore, thread_rng}; +use rand::{Rng, RngCore, thread_rng, seq::SliceRandom}; use rand::distributions::Standard; fn square(n: usize) -> usize { @@ -459,7 +459,7 @@ fn test_sort() { for i in 0..v.len() { v[i] = i as i32; } - v.sort_by(|_, _| *rng.choose(&[Less, Equal, Greater]).unwrap()); + v.sort_by(|_, _| *[Less, Equal, Greater].choose(&mut rng).unwrap()); v.sort(); for i in 0..v.len() { assert_eq!(v[i], i as i32); diff --git a/src/libcompiler_builtins b/src/libcompiler_builtins deleted file mode 160000 index 10f4f35f967..00000000000 --- a/src/libcompiler_builtins +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 10f4f35f9670bb29715a8c1ec01284852d47ed35 diff --git a/src/libcore/Cargo.toml b/src/libcore/Cargo.toml index 7fd61f07d5e..fa2ab11243b 100644 --- a/src/libcore/Cargo.toml +++ b/src/libcore/Cargo.toml @@ -20,7 +20,7 @@ name = "corebenches" path = "../libcore/benches/lib.rs" [dev-dependencies] -rand = "0.5" +rand = "0.6" [features] # Make panics and failed asserts immediately abort without formatting any message diff --git a/src/libcore/tests/num/flt2dec/random.rs b/src/libcore/tests/num/flt2dec/random.rs index 95dfcb522e0..21a7c9fc6b3 100644 --- a/src/libcore/tests/num/flt2dec/random.rs +++ b/src/libcore/tests/num/flt2dec/random.rs @@ -18,7 +18,8 @@ use core::num::flt2dec::strategy::grisu::format_exact_opt; use core::num::flt2dec::strategy::grisu::format_shortest_opt; use core::num::flt2dec::{decode, DecodableFloat, FullDecoded, Decoded}; -use rand::{FromEntropy, XorShiftRng}; +use rand::FromEntropy; +use rand::rngs::SmallRng; use rand::distributions::{Distribution, Uniform}; pub fn decode_finite(v: T) -> Decoded { @@ -71,7 +72,10 @@ fn iterate(func: &str, k: usize, n: usize, mut f: F, mut g: G, mut v: V pub fn f32_random_equivalence_test(f: F, g: G, k: usize, n: usize) where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { - let mut rng = XorShiftRng::from_entropy(); + if cfg!(target_os = "emscripten") { + return // using rng pulls in i128 support, which doesn't work + } + let mut rng = SmallRng::from_entropy(); let f32_range = Uniform::new(0x0000_0001u32, 0x7f80_0000); iterate("f32_random_equivalence_test", k, n, f, g, |_| { let x = f32::from_bits(f32_range.sample(&mut rng)); @@ -82,7 +86,10 @@ pub fn f32_random_equivalence_test(f: F, g: G, k: usize, n: usize) pub fn f64_random_equivalence_test(f: F, g: G, k: usize, n: usize) where F: FnMut(&Decoded, &mut [u8]) -> Option<(usize, i16)>, G: FnMut(&Decoded, &mut [u8]) -> (usize, i16) { - let mut rng = XorShiftRng::from_entropy(); + if cfg!(target_os = "emscripten") { + return // using rng pulls in i128 support, which doesn't work + } + let mut rng = SmallRng::from_entropy(); let f64_range = Uniform::new(0x0000_0000_0000_0001u64, 0x7ff0_0000_0000_0000); iterate("f64_random_equivalence_test", k, n, f, g, |_| { let x = f64::from_bits(f64_range.sample(&mut rng)); diff --git a/src/libcore/tests/slice.rs b/src/libcore/tests/slice.rs index dba5a43eb21..4f00ebee1d2 100644 --- a/src/libcore/tests/slice.rs +++ b/src/libcore/tests/slice.rs @@ -1024,11 +1024,11 @@ fn test_rotate_right() { fn sort_unstable() { use core::cmp::Ordering::{Equal, Greater, Less}; use core::slice::heapsort; - use rand::{FromEntropy, Rng, XorShiftRng}; + use rand::{FromEntropy, Rng, rngs::SmallRng, seq::SliceRandom}; let mut v = [0; 600]; let mut tmp = [0; 600]; - let mut rng = XorShiftRng::from_entropy(); + let mut rng = SmallRng::from_entropy(); for len in (2..25).chain(500..510) { let v = &mut v[0..len]; @@ -1073,7 +1073,7 @@ fn sort_unstable() { for i in 0..v.len() { v[i] = i as i32; } - v.sort_unstable_by(|_, _| *rng.choose(&[Less, Equal, Greater]).unwrap()); + v.sort_unstable_by(|_, _| *[Less, Equal, Greater].choose(&mut rng).unwrap()); v.sort_unstable(); for i in 0..v.len() { assert_eq!(v[i], i as i32); diff --git a/src/liblibc b/src/liblibc deleted file mode 160000 index 5b403753da9..00000000000 --- a/src/liblibc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 5b403753da9ec8ff501adf34cb6d63b319b4a3ae diff --git a/src/libpanic_abort/Cargo.toml b/src/libpanic_abort/Cargo.toml index 633d273b3b9..e304e61c329 100644 --- a/src/libpanic_abort/Cargo.toml +++ b/src/libpanic_abort/Cargo.toml @@ -11,5 +11,5 @@ doc = false [dependencies] core = { path = "../libcore" } -libc = { path = "../rustc/libc_shim" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +libc = { version = "0.2", default-features = false } +compiler_builtins = "0.1.0" diff --git a/src/libpanic_unwind/Cargo.toml b/src/libpanic_unwind/Cargo.toml index 74aaa4d5ae3..c9fce621608 100644 --- a/src/libpanic_unwind/Cargo.toml +++ b/src/libpanic_unwind/Cargo.toml @@ -12,6 +12,6 @@ doc = false [dependencies] alloc = { path = "../liballoc" } core = { path = "../libcore" } -libc = { path = "../rustc/libc_shim" } +libc = { version = "0.2", default-features = false } unwind = { path = "../libunwind" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +compiler_builtins = "0.1.0" diff --git a/src/libprofiler_builtins/Cargo.toml b/src/libprofiler_builtins/Cargo.toml index 79192fbb681..7c95cf0a054 100644 --- a/src/libprofiler_builtins/Cargo.toml +++ b/src/libprofiler_builtins/Cargo.toml @@ -13,7 +13,7 @@ doc = false [dependencies] core = { path = "../libcore" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +compiler_builtins = { version = "0.1.0", features = ['rustc-dep-of-std'] } [build-dependencies] cc = "1.0.1" diff --git a/src/libprofiler_builtins/build.rs b/src/libprofiler_builtins/build.rs index 8d6c7d68dfe..db72ce77e72 100644 --- a/src/libprofiler_builtins/build.rs +++ b/src/libprofiler_builtins/build.rs @@ -56,9 +56,15 @@ fn main() { cfg.define("COMPILER_RT_HAS_UNAME", Some("1")); } + // The source for `compiler-rt` comes from the `compiler-builtins` crate, so + // load our env var set by cargo to find the source code. + let root = env::var_os("DEP_COMPILER_RT_COMPILER_RT").unwrap(); + let root = Path::new(&root); + for src in profile_sources { - cfg.file(Path::new("../libcompiler_builtins/compiler-rt/lib/profile").join(src)); + cfg.file(root.join("lib").join("profile").join(src)); } + cfg.warnings(false); cfg.compile("profiler-rt"); } diff --git a/src/librustc_asan/Cargo.toml b/src/librustc_asan/Cargo.toml index 734564c2d85..836caf22abf 100644 --- a/src/librustc_asan/Cargo.toml +++ b/src/librustc_asan/Cargo.toml @@ -16,4 +16,4 @@ cmake = "0.1.18" [dependencies] alloc = { path = "../liballoc" } core = { path = "../libcore" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +compiler_builtins = "0.1.0" diff --git a/src/librustc_lsan/Cargo.toml b/src/librustc_lsan/Cargo.toml index 2573825a5ff..a8e11df7670 100644 --- a/src/librustc_lsan/Cargo.toml +++ b/src/librustc_lsan/Cargo.toml @@ -16,4 +16,4 @@ cmake = "0.1.18" [dependencies] alloc = { path = "../liballoc" } core = { path = "../libcore" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +compiler_builtins = "0.1.0" diff --git a/src/librustc_msan/Cargo.toml b/src/librustc_msan/Cargo.toml index 29165675a2a..78c39d03e45 100644 --- a/src/librustc_msan/Cargo.toml +++ b/src/librustc_msan/Cargo.toml @@ -16,4 +16,4 @@ cmake = "0.1.18" [dependencies] alloc = { path = "../liballoc" } core = { path = "../libcore" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +compiler_builtins = "0.1.0" diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 2681295cf9b..77302390714 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -295,9 +295,8 @@ that has been imported into the current module. Erroneous code example: ```compile_fail,E0259 -# #![feature(libc)] extern crate core; -extern crate libc as core; +extern crate std as core; fn main() {} ``` @@ -308,9 +307,8 @@ external crate imported into the current module. Correct example: ``` -# #![feature(libc)] extern crate core; -extern crate libc as other_name; +extern crate std as other_name; fn main() {} ``` diff --git a/src/librustc_tsan/Cargo.toml b/src/librustc_tsan/Cargo.toml index baadb64511a..f0618275f2f 100644 --- a/src/librustc_tsan/Cargo.toml +++ b/src/librustc_tsan/Cargo.toml @@ -16,4 +16,4 @@ cmake = "0.1.18" [dependencies] alloc = { path = "../liballoc" } core = { path = "../libcore" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +compiler_builtins = "0.1.0" diff --git a/src/libstd/Cargo.toml b/src/libstd/Cargo.toml index 274d5bec662..41e778b6a4c 100644 --- a/src/libstd/Cargo.toml +++ b/src/libstd/Cargo.toml @@ -17,13 +17,13 @@ alloc = { path = "../liballoc" } panic_unwind = { path = "../libpanic_unwind", optional = true } panic_abort = { path = "../libpanic_abort" } core = { path = "../libcore" } -libc = { path = "../rustc/libc_shim" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +libc = { version = "0.2.44", default-features = false, features = ['rustc-dep-of-std'] } +compiler_builtins = { version = "0.1.1" } profiler_builtins = { path = "../libprofiler_builtins", optional = true } unwind = { path = "../libunwind" } [dev-dependencies] -rand = "0.5" +rand = "0.6.1" [target.x86_64-apple-darwin.dependencies] rustc_asan = { path = "../librustc_asan" } @@ -36,10 +36,10 @@ rustc_msan = { path = "../librustc_msan" } rustc_tsan = { path = "../librustc_tsan" } [target.'cfg(any(all(target_arch = "wasm32", not(target_os = "emscripten")), target_env = "sgx"))'.dependencies] -dlmalloc = { path = '../rustc/dlmalloc_shim' } +dlmalloc = { version = "0.1", features = ['rustc-dep-of-std'] } [target.x86_64-fortanix-unknown-sgx.dependencies] -fortanix-sgx-abi = { path = "../rustc/fortanix-sgx-abi_shim" } +fortanix-sgx-abi = { version = "0.3.1", features = ['rustc-dep-of-std'] } [build-dependencies] cc = "1.0" diff --git a/src/libstd/build.rs b/src/libstd/build.rs index 9d6e8c4cafd..2386f134b90 100644 --- a/src/libstd/build.rs +++ b/src/libstd/build.rs @@ -82,7 +82,12 @@ fn main() { } fn build_libbacktrace(target: &str) -> Result<(), ()> { - let native = native_lib_boilerplate("libbacktrace", "libbacktrace", "backtrace", "")?; + let native = native_lib_boilerplate( + "../libbacktrace".as_ref(), + "libbacktrace", + "backtrace", + "", + )?; let mut build = cc::Build::new(); build diff --git a/src/libstd/fs.rs b/src/libstd/fs.rs index b6a0ce63720..d581ba1de23 100644 --- a/src/libstd/fs.rs +++ b/src/libstd/fs.rs @@ -2089,7 +2089,7 @@ mod tests { use fs::{self, File, OpenOptions}; use io::{ErrorKind, SeekFrom}; use path::Path; - use rand::{StdRng, FromEntropy, RngCore}; + use rand::{rngs::StdRng, FromEntropy, RngCore}; use str; use sys_common::io::test::{TempDir, tmpdir}; use thread; diff --git a/src/libstd/primitive_docs.rs b/src/libstd/primitive_docs.rs index 3b2366a9eca..7c1654f62fa 100644 --- a/src/libstd/primitive_docs.rs +++ b/src/libstd/primitive_docs.rs @@ -426,7 +426,7 @@ mod prim_unit { } /// ## 3. Get it from C. /// /// ``` -/// # #![feature(libc)] +/// # #![feature(rustc_private)] /// extern crate libc; /// /// use std::mem; diff --git a/src/libstd/sys/unix/ext/fs.rs b/src/libstd/sys/unix/ext/fs.rs index 7e65bbdef2a..af2f1998415 100644 --- a/src/libstd/sys/unix/ext/fs.rs +++ b/src/libstd/sys/unix/ext/fs.rs @@ -348,7 +348,7 @@ pub trait OpenOptionsExt { /// # Examples /// /// ```no_run - /// # #![feature(libc)] + /// # #![feature(rustc_private)] /// extern crate libc; /// use std::fs::OpenOptions; /// use std::os::unix::fs::OpenOptionsExt; diff --git a/src/libunwind/Cargo.toml b/src/libunwind/Cargo.toml index 4760461df64..2577d6dd31d 100644 --- a/src/libunwind/Cargo.toml +++ b/src/libunwind/Cargo.toml @@ -13,5 +13,5 @@ doc = false [dependencies] core = { path = "../libcore" } -libc = { path = "../rustc/libc_shim" } -compiler_builtins = { path = "../rustc/compiler_builtins_shim" } +libc = { version = "0.2.43", features = ['rustc-dep-of-std'], default-features = false } +compiler_builtins = "0.1.0" diff --git a/src/rust-sgx b/src/rust-sgx deleted file mode 160000 index 96562608880..00000000000 --- a/src/rust-sgx +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 9656260888095f44830641ca7bb3da609a793451 diff --git a/src/rustc/compiler_builtins_shim/Cargo.toml b/src/rustc/compiler_builtins_shim/Cargo.toml deleted file mode 100644 index 9804177280f..00000000000 --- a/src/rustc/compiler_builtins_shim/Cargo.toml +++ /dev/null @@ -1,40 +0,0 @@ -[package] -name = "compiler_builtins" -authors = ["The Rust Project Developers"] -version = "0.0.0" -build = "../../libcompiler_builtins/build.rs" - -[lib] -path = "../../libcompiler_builtins/src/lib.rs" -test = false -doctest = false - -[dependencies] -# Specify the path to libcore; at the time of writing, removing this shim in -# favor of using compiler-builtins from git results in a compilation failure: -# -# Building stage0 std artifacts (x86_64-apple-darwin -> x86_64-apple-darwin) -# Compiling compiler_builtins v0.1.0 (https://github.com/rust-lang-nursery/compiler-builtins.git#23f14d3f) -# error[E0463]: can't find crate for `core` -# -# error: aborting due to previous error -# -# error: Could not compile `compiler_builtins`. -# -# Caused by: -# process didn't exit successfully: `/Users/tamird/src/rust/build/bootstrap/debug/rustc --crate-name compiler_builtins /Users/tamird/.cargo/git/checkouts/compiler-builtins-ec094dc45a0179c8/23f14d3/src/lib.rs --error-format json --crate-type lib --emit=dep-info,link -C opt-level=2 --cfg feature="c" --cfg feature="compiler-builtins" --cfg feature="default" --cfg feature="gcc" -C metadata=876d429e8d7eae1f -C extra-filename=-876d429e8d7eae1f --out-dir /Users/tamird/src/rust/build/x86_64-apple-darwin/stage0-std/x86_64-apple-darwin/release/deps --target x86_64-apple-darwin -L dependency=/Users/tamird/src/rust/build/x86_64-apple-darwin/stage0-std/x86_64-apple-darwin/release/deps -L dependency=/Users/tamird/src/rust/build/x86_64-apple-darwin/stage0-std/release/deps --cap-lints allow -L native=/Users/tamird/src/rust/build/x86_64-apple-darwin/stage0-std/x86_64-apple-darwin/release/build/compiler_builtins-f18fab55928102ad/out -l static=compiler-rt` (exit code: 101) -# thread 'main' panicked at 'command did not execute successfully: "/Users/tamird/src/rust/build/x86_64-apple-darwin/stage0/bin/cargo" "build" "-j" "4" "--target" "x86_64-apple-darwin" "--release" "--features" "panic-unwind jemalloc backtrace" "--manifest-path" "/Users/tamird/src/rust/src/libstd/Cargo.toml" "--message-format" "json" -# expected success, got: exit code: 101', src/bootstrap/compile.rs:883:8 -# -# See https://github.com/rust-lang/rfcs/pull/1133. -core = { path = "../../libcore" } - -[build-dependencies] -cc = "1.0.1" - -[features] -c = [] -default = ["rustbuild", "compiler-builtins"] -mem = [] -rustbuild = [] -compiler-builtins = [] diff --git a/src/rustc/compiler_builtins_shim/build.rs b/src/rustc/compiler_builtins_shim/build.rs deleted file mode 100644 index b37543e5f67..00000000000 --- a/src/rustc/compiler_builtins_shim/build.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// This file is left intentionally empty (and not removed) to avoid an issue -// where this crate is always considered dirty due to compiler-builtins' -// `cargo:rerun-if-changed=build.rs` directive; since the path is relative, it -// refers to this file when this shim crate is being built, and the absence of -// this file is considered by cargo to be equivalent to it having changed. diff --git a/src/rustc/dlmalloc_shim/Cargo.toml b/src/rustc/dlmalloc_shim/Cargo.toml deleted file mode 100644 index b6f8550829f..00000000000 --- a/src/rustc/dlmalloc_shim/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "dlmalloc" -version = "0.0.0" -authors = ["The Rust Project Developers"] - -[lib] -path = "../../dlmalloc/src/lib.rs" -test = false -bench = false -doc = false - -[dependencies] -core = { path = "../../libcore" } -compiler_builtins = { path = "../../rustc/compiler_builtins_shim" } diff --git a/src/rustc/fortanix-sgx-abi_shim/Cargo.toml b/src/rustc/fortanix-sgx-abi_shim/Cargo.toml deleted file mode 100644 index fd81d3db3a7..00000000000 --- a/src/rustc/fortanix-sgx-abi_shim/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "fortanix-sgx-abi" -version = "0.0.0" -authors = ["The Rust Project Developers"] - -[lib] -path = "../../rust-sgx/fortanix-sgx-abi/src/lib.rs" -test = false -bench = false -doc = false - -[dependencies] -core = { path = "../../libcore" } -compiler_builtins = { path = "../../rustc/compiler_builtins_shim" } diff --git a/src/rustc/libc_shim/Cargo.toml b/src/rustc/libc_shim/Cargo.toml deleted file mode 100644 index ee037ac68c5..00000000000 --- a/src/rustc/libc_shim/Cargo.toml +++ /dev/null @@ -1,40 +0,0 @@ -[package] -name = "libc" -version = "0.0.0" -authors = ["The Rust Project Developers"] - -[lib] -name = "libc" -path = "../../liblibc/src/lib.rs" -test = false -bench = false -doc = false - -[dependencies] -# Specify the path to libcore; at the time of writing, removing this shim in -# favor of using libc from git results in a compilation failure: -# -# Building stage0 std artifacts (x86_64-apple-darwin -> x86_64-apple-darwin) -# Compiling libc v0.0.0 (file:///Users/tamird/src/rust/src/rustc/libc_shim) -# error[E0463]: can't find crate for `core` -# -# error: aborting due to previous error -# -# error: Could not compile `libc`. -# -# Caused by: -# process didn't exit successfully: `/Users/tamird/src/rust/build/bootstrap/debug/rustc --crate-name libc src/rustc/libc_shim/../../liblibc/src/lib.rs --error-format json --crate-type lib --emit=dep-info,link -C opt-level=2 --cfg feature="default" --cfg feature="no_std" --cfg feature="stdbuild" -C metadata=d758f87058112d7d -C extra-filename=-d758f87058112d7d --out-dir /Users/tamird/src/rust/build/x86_64-apple-darwin/stage0-std/x86_64-apple-darwin/release/deps --target x86_64-apple-darwin -L dependency=/Users/tamird/src/rust/build/x86_64-apple-darwin/stage0-std/x86_64-apple-darwin/release/deps -L dependency=/Users/tamird/src/rust/build/x86_64-apple-darwin/stage0-std/release/deps` (exit code: 101) -# thread 'main' panicked at 'command did not execute successfully: "/Users/tamird/src/rust/build/x86_64-apple-darwin/stage0/bin/cargo" "build" "-j" "4" "--target" "x86_64-apple-darwin" "--release" "--features" "panic-unwind jemalloc backtrace" "--manifest-path" "/Users/tamird/src/rust/src/libstd/Cargo.toml" "--message-format" "json" -# expected success, got: exit code: 101', src/bootstrap/compile.rs:883:8 -# -# See https://github.com/rust-lang/rfcs/pull/1133. -core = { path = "../../libcore" } -compiler_builtins = { path = "../compiler_builtins_shim" } - - -[features] -# Certain parts of libc are conditionally compiled differently than when used -# outside rustc. See https://github.com/rust-lang/libc/search?l=Rust&q=stdbuild&type=&utf8=%E2%9C%93. -stdbuild = [] -default = ["stdbuild", "align"] -align = [] diff --git a/src/stage0.txt b/src/stage0.txt index 9326e22090c..83694137775 100644 --- a/src/stage0.txt +++ b/src/stage0.txt @@ -12,7 +12,7 @@ # source tarball for a stable release you'll likely see `1.x.0` for rustc and # `0.x.0` for Cargo where they were released on `date`. -date: 2018-10-30 +date: 2018-11-21 rustc: beta cargo: beta diff --git a/src/test/incremental/foreign.rs b/src/test/incremental/foreign.rs index dbdebefaf31..648e89be037 100644 --- a/src/test/incremental/foreign.rs +++ b/src/test/incremental/foreign.rs @@ -13,7 +13,7 @@ // revisions: rpass1 -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-make-fulldeps/c-link-to-rust-va-list-fn/checkrust.rs b/src/test/run-make-fulldeps/c-link-to-rust-va-list-fn/checkrust.rs index 90ad6011526..0254c7cf403 100644 --- a/src/test/run-make-fulldeps/c-link-to-rust-va-list-fn/checkrust.rs +++ b/src/test/run-make-fulldeps/c-link-to-rust-va-list-fn/checkrust.rs @@ -10,7 +10,7 @@ #![crate_type = "staticlib"] #![feature(c_variadic)] -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-make-fulldeps/issue-25581/test.rs b/src/test/run-make-fulldeps/issue-25581/test.rs index 6717d16cb7c..b084092d727 100644 --- a/src/test/run-make-fulldeps/issue-25581/test.rs +++ b/src/test/run-make-fulldeps/issue-25581/test.rs @@ -8,14 +8,10 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(libc)] - -extern crate libc; - #[link(name = "test", kind = "static")] extern { - fn slice_len(s: &[u8]) -> libc::size_t; - fn slice_elem(s: &[u8], idx: libc::size_t) -> u8; + fn slice_len(s: &[u8]) -> usize; + fn slice_elem(s: &[u8], idx: usize) -> u8; } fn main() { diff --git a/src/test/run-make-fulldeps/issue-26006/in/time/lib.rs b/src/test/run-make-fulldeps/issue-26006/in/time/lib.rs index b1d07d57337..1427250b9f0 100644 --- a/src/test/run-make-fulldeps/issue-26006/in/time/lib.rs +++ b/src/test/run-make-fulldeps/issue-26006/in/time/lib.rs @@ -7,7 +7,7 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; fn main(){} diff --git a/src/test/run-make-fulldeps/link-path-order/main.rs b/src/test/run-make-fulldeps/link-path-order/main.rs index f3502e8bcd4..4d38dc8fa0f 100644 --- a/src/test/run-make-fulldeps/link-path-order/main.rs +++ b/src/test/run-make-fulldeps/link-path-order/main.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass-valgrind/osx-frameworks.rs b/src/test/run-pass-valgrind/osx-frameworks.rs index 468a20db6f7..afa9374ff67 100644 --- a/src/test/run-pass-valgrind/osx-frameworks.rs +++ b/src/test/run-pass-valgrind/osx-frameworks.rs @@ -11,7 +11,7 @@ // no-prefer-dynamic // pretty-expanded FIXME #23616 -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/anon-extern-mod.rs b/src/test/run-pass/anon-extern-mod.rs index 16ca7bce95b..daa2bd62882 100644 --- a/src/test/run-pass/anon-extern-mod.rs +++ b/src/test/run-pass/anon-extern-mod.rs @@ -11,7 +11,7 @@ // pretty-expanded FIXME #23616 // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/array-slice-vec/vec-macro-no-std.rs b/src/test/run-pass/array-slice-vec/vec-macro-no-std.rs index 509167413b6..7a90a022e0a 100644 --- a/src/test/run-pass/array-slice-vec/vec-macro-no-std.rs +++ b/src/test/run-pass/array-slice-vec/vec-macro-no-std.rs @@ -12,7 +12,7 @@ // ignore-emscripten no no_std executables -#![feature(lang_items, start, libc, alloc)] +#![feature(lang_items, start, rustc_private, alloc)] #![no_std] extern crate std as other; diff --git a/src/test/run-pass/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/run-pass/auxiliary/anon-extern-mod-cross-crate-1.rs index 741ce351da3..6b464c59f2a 100644 --- a/src/test/run-pass/auxiliary/anon-extern-mod-cross-crate-1.rs +++ b/src/test/run-pass/auxiliary/anon-extern-mod-cross-crate-1.rs @@ -9,7 +9,7 @@ // except according to those terms. #![crate_name="anonexternmod"] -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/auxiliary/check_static_recursion_foreign_helper.rs b/src/test/run-pass/auxiliary/check_static_recursion_foreign_helper.rs index cd36a8eedb4..4d1acf31be3 100644 --- a/src/test/run-pass/auxiliary/check_static_recursion_foreign_helper.rs +++ b/src/test/run-pass/auxiliary/check_static_recursion_foreign_helper.rs @@ -10,7 +10,7 @@ // Helper definition for test/run-pass/check-static-recursion-foreign.rs. -#![feature(libc)] +#![feature(rustc_private)] #![crate_name = "check_static_recursion_foreign_helper"] #![crate_type = "lib"] diff --git a/src/test/run-pass/auxiliary/foreign_lib.rs b/src/test/run-pass/auxiliary/foreign_lib.rs index cef36274c62..465feb8eaf7 100644 --- a/src/test/run-pass/auxiliary/foreign_lib.rs +++ b/src/test/run-pass/auxiliary/foreign_lib.rs @@ -10,7 +10,7 @@ #![crate_name="foreign_lib"] -#![feature(libc)] +#![feature(rustc_private)] pub mod rustrt { extern crate libc; diff --git a/src/test/run-pass/c-stack-as-value.rs b/src/test/run-pass/c-stack-as-value.rs index df4989d89ab..1f29a5201bd 100644 --- a/src/test/run-pass/c-stack-as-value.rs +++ b/src/test/run-pass/c-stack-as-value.rs @@ -11,7 +11,7 @@ // pretty-expanded FIXME #23616 // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] mod rustrt { extern crate libc; diff --git a/src/test/run-pass/c-stack-returning-int64.rs b/src/test/run-pass/c-stack-returning-int64.rs index 56a0437146b..7dd3b9a7a5b 100644 --- a/src/test/run-pass/c-stack-returning-int64.rs +++ b/src/test/run-pass/c-stack-returning-int64.rs @@ -10,7 +10,7 @@ // ignore-wasm32-bare no libc to test with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/check-static-recursion-foreign.rs b/src/test/run-pass/check-static-recursion-foreign.rs index a95870c2b27..15f509a1753 100644 --- a/src/test/run-pass/check-static-recursion-foreign.rs +++ b/src/test/run-pass/check-static-recursion-foreign.rs @@ -16,7 +16,7 @@ // pretty-expanded FIXME #23616 -#![feature(custom_attribute, libc)] +#![feature(custom_attribute, rustc_private)] extern crate check_static_recursion_foreign_helper; extern crate libc; diff --git a/src/test/run-pass/command-before-exec.rs b/src/test/run-pass/command-before-exec.rs index 5d8bc31c2a3..b78fa849d0d 100644 --- a/src/test/run-pass/command-before-exec.rs +++ b/src/test/run-pass/command-before-exec.rs @@ -13,7 +13,7 @@ // ignore-cloudabi no processes // ignore-emscripten no processes -#![feature(process_exec, libc)] +#![feature(process_exec, rustc_private)] extern crate libc; diff --git a/src/test/run-pass/consts/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/run-pass/consts/auxiliary/anon-extern-mod-cross-crate-1.rs index 741ce351da3..6b464c59f2a 100644 --- a/src/test/run-pass/consts/auxiliary/anon-extern-mod-cross-crate-1.rs +++ b/src/test/run-pass/consts/auxiliary/anon-extern-mod-cross-crate-1.rs @@ -9,7 +9,7 @@ // except according to those terms. #![crate_name="anonexternmod"] -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/core-run-destroy.rs b/src/test/run-pass/core-run-destroy.rs index 51e26ff68de..902332656a8 100644 --- a/src/test/run-pass/core-run-destroy.rs +++ b/src/test/run-pass/core-run-destroy.rs @@ -20,7 +20,7 @@ // memory, which makes for some *confusing* logs. That's why these are here // instead of in std. -#![feature(libc, duration)] +#![feature(rustc_private, duration)] extern crate libc; diff --git a/src/test/run-pass/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/run-pass/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs index 741ce351da3..6b464c59f2a 100644 --- a/src/test/run-pass/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs +++ b/src/test/run-pass/cross-crate/auxiliary/anon-extern-mod-cross-crate-1.rs @@ -9,7 +9,7 @@ // except according to those terms. #![crate_name="anonexternmod"] -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/env-funky-keys.rs b/src/test/run-pass/env-funky-keys.rs index 12e1cbe97d8..7e7899cf151 100644 --- a/src/test/run-pass/env-funky-keys.rs +++ b/src/test/run-pass/env-funky-keys.rs @@ -16,7 +16,7 @@ // ignore-emscripten no execve // no-prefer-dynamic -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/env-null-vars.rs b/src/test/run-pass/env-null-vars.rs index 9a461991c1e..cdbecf120c3 100644 --- a/src/test/run-pass/env-null-vars.rs +++ b/src/test/run-pass/env-null-vars.rs @@ -15,7 +15,7 @@ // issue-53200 -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; use std::env; diff --git a/src/test/run-pass/extern/auxiliary/extern-crosscrate-source.rs b/src/test/run-pass/extern/auxiliary/extern-crosscrate-source.rs index 150dffeea88..d20d9dbac3d 100644 --- a/src/test/run-pass/extern/auxiliary/extern-crosscrate-source.rs +++ b/src/test/run-pass/extern/auxiliary/extern-crosscrate-source.rs @@ -10,7 +10,7 @@ #![crate_name="externcallback"] #![crate_type = "lib"] -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/extern/extern-call-deep.rs b/src/test/run-pass/extern/extern-call-deep.rs index 6e8d94becbd..f6eff601c4b 100644 --- a/src/test/run-pass/extern/extern-call-deep.rs +++ b/src/test/run-pass/extern/extern-call-deep.rs @@ -11,7 +11,7 @@ // run-pass // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/extern/extern-call-deep2.rs b/src/test/run-pass/extern/extern-call-deep2.rs index 28157c5a8d5..8cb04771cb9 100644 --- a/src/test/run-pass/extern/extern-call-deep2.rs +++ b/src/test/run-pass/extern/extern-call-deep2.rs @@ -12,7 +12,7 @@ #![allow(unused_must_use)] // ignore-emscripten no threads support -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; use std::thread; diff --git a/src/test/run-pass/extern/extern-call-indirect.rs b/src/test/run-pass/extern/extern-call-indirect.rs index 1badb10364e..d20721f2c91 100644 --- a/src/test/run-pass/extern/extern-call-indirect.rs +++ b/src/test/run-pass/extern/extern-call-indirect.rs @@ -11,7 +11,7 @@ // run-pass // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/extern/extern-call-scrub.rs b/src/test/run-pass/extern/extern-call-scrub.rs index ea18069fa32..5e158c2dfc9 100644 --- a/src/test/run-pass/extern/extern-call-scrub.rs +++ b/src/test/run-pass/extern/extern-call-scrub.rs @@ -16,7 +16,7 @@ // ignore-emscripten no threads support -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; use std::thread; diff --git a/src/test/run-pass/extern/extern-crosscrate.rs b/src/test/run-pass/extern/extern-crosscrate.rs index c6fccbe003c..b99e27af920 100644 --- a/src/test/run-pass/extern/extern-crosscrate.rs +++ b/src/test/run-pass/extern/extern-crosscrate.rs @@ -12,7 +12,7 @@ // aux-build:extern-crosscrate-source.rs // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate externcallback; extern crate libc; diff --git a/src/test/run-pass/fds-are-cloexec.rs b/src/test/run-pass/fds-are-cloexec.rs index a5ae0ae9f31..33e64d832fc 100644 --- a/src/test/run-pass/fds-are-cloexec.rs +++ b/src/test/run-pass/fds-are-cloexec.rs @@ -14,7 +14,7 @@ // ignore-emscripten no processes // ignore-haiku -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/foreign/auxiliary/foreign_lib.rs b/src/test/run-pass/foreign/auxiliary/foreign_lib.rs index cef36274c62..465feb8eaf7 100644 --- a/src/test/run-pass/foreign/auxiliary/foreign_lib.rs +++ b/src/test/run-pass/foreign/auxiliary/foreign_lib.rs @@ -10,7 +10,7 @@ #![crate_name="foreign_lib"] -#![feature(libc)] +#![feature(rustc_private)] pub mod rustrt { extern crate libc; diff --git a/src/test/run-pass/foreign/foreign-call-no-runtime.rs b/src/test/run-pass/foreign/foreign-call-no-runtime.rs index 4837f78ce3b..e35ec882132 100644 --- a/src/test/run-pass/foreign/foreign-call-no-runtime.rs +++ b/src/test/run-pass/foreign/foreign-call-no-runtime.rs @@ -11,7 +11,7 @@ // run-pass // ignore-emscripten no threads support -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/foreign/foreign-fn-linkname.rs b/src/test/run-pass/foreign/foreign-fn-linkname.rs index 75876607603..8fe90b7d498 100644 --- a/src/test/run-pass/foreign/foreign-fn-linkname.rs +++ b/src/test/run-pass/foreign/foreign-fn-linkname.rs @@ -11,7 +11,7 @@ // run-pass // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; use std::ffi::CString; diff --git a/src/test/run-pass/foreign/foreign-no-abi.rs b/src/test/run-pass/foreign/foreign-no-abi.rs index 1d35f08a11f..49ddd09beee 100644 --- a/src/test/run-pass/foreign/foreign-no-abi.rs +++ b/src/test/run-pass/foreign/foreign-no-abi.rs @@ -14,7 +14,7 @@ // ignore-wasm32-bare no libc to test ffi with // pretty-expanded FIXME #23616 -#![feature(libc)] +#![feature(rustc_private)] mod rustrt { extern crate libc; diff --git a/src/test/run-pass/foreign/foreign2.rs b/src/test/run-pass/foreign/foreign2.rs index bd6c8e6b53d..f8942bc1712 100644 --- a/src/test/run-pass/foreign/foreign2.rs +++ b/src/test/run-pass/foreign/foreign2.rs @@ -13,7 +13,7 @@ // ignore-wasm32-bare no libc to test ffi with // pretty-expanded FIXME #23616 -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/invalid_const_promotion.rs b/src/test/run-pass/invalid_const_promotion.rs index 0f354e1aad6..3b8a265dd70 100644 --- a/src/test/run-pass/invalid_const_promotion.rs +++ b/src/test/run-pass/invalid_const_promotion.rs @@ -15,7 +15,7 @@ // compile-flags: -C debug_assertions=yes #![stable(feature = "rustc", since = "1.0.0")] -#![feature(const_fn, libc, staged_api, rustc_attrs)] +#![feature(const_fn, rustc_private, staged_api, rustc_attrs)] #![allow(const_err)] extern crate libc; diff --git a/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs b/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs index de18e09532b..9c983eab7d8 100644 --- a/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs +++ b/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs @@ -9,7 +9,7 @@ // except according to those terms. // run-pass -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/issues/issue-2214.rs b/src/test/run-pass/issues/issue-2214.rs index 8329847d3c5..f3795c216c8 100644 --- a/src/test/run-pass/issues/issue-2214.rs +++ b/src/test/run-pass/issues/issue-2214.rs @@ -11,7 +11,7 @@ // run-pass // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/issues/issue-30490.rs b/src/test/run-pass/issues/issue-30490.rs index 500999cc1cf..47f60fb93d7 100644 --- a/src/test/run-pass/issues/issue-30490.rs +++ b/src/test/run-pass/issues/issue-30490.rs @@ -18,7 +18,7 @@ // where the descriptors to inherit were already stdio descriptors. // This test checks to avoid that regression. -#![cfg_attr(unix, feature(libc))] +#![cfg_attr(unix, feature(rustc_private))] #![cfg_attr(windows, allow(unused_imports))] #[cfg(unix)] diff --git a/src/test/run-pass/issues/issue-3656.rs b/src/test/run-pass/issues/issue-3656.rs index 63b27406198..99a72444d73 100644 --- a/src/test/run-pass/issues/issue-3656.rs +++ b/src/test/run-pass/issues/issue-3656.rs @@ -19,7 +19,7 @@ // pretty-expanded FIXME #23616 // ignore-wasm32-bare no libc to test with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; use libc::{c_uint, uint32_t, c_void}; diff --git a/src/test/run-pass/no-stdio.rs b/src/test/run-pass/no-stdio.rs index d3424176960..2f5bfbb501f 100644 --- a/src/test/run-pass/no-stdio.rs +++ b/src/test/run-pass/no-stdio.rs @@ -12,7 +12,7 @@ // ignore-cloudabi no processes // ignore-emscripten no processes -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/out-of-stack.rs b/src/test/run-pass/out-of-stack.rs index cd0f7cdbf6d..1c714e7f7fa 100644 --- a/src/test/run-pass/out-of-stack.rs +++ b/src/test/run-pass/out-of-stack.rs @@ -16,7 +16,7 @@ // ignore-emscripten no processes #![feature(asm)] -#![feature(libc)] +#![feature(rustc_private)] #[cfg(unix)] extern crate libc; diff --git a/src/test/run-pass/rfcs/rfc-1014-2.rs b/src/test/run-pass/rfcs/rfc-1014-2.rs index 7fbc0d1db70..257c7f546b1 100644 --- a/src/test/run-pass/rfcs/rfc-1014-2.rs +++ b/src/test/run-pass/rfcs/rfc-1014-2.rs @@ -11,7 +11,7 @@ // run-pass #![allow(dead_code)] -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/rfcs/rfc-1014.rs b/src/test/run-pass/rfcs/rfc-1014.rs index d101c3c9ab1..578a7f4395c 100644 --- a/src/test/run-pass/rfcs/rfc-1014.rs +++ b/src/test/run-pass/rfcs/rfc-1014.rs @@ -13,7 +13,7 @@ // ignore-cloudabi stdout does not map to file descriptor 1 by default // ignore-wasm32-bare no libc -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/segfault-no-out-of-stack.rs b/src/test/run-pass/segfault-no-out-of-stack.rs index a85fe6733dd..961b8020f3d 100644 --- a/src/test/run-pass/segfault-no-out-of-stack.rs +++ b/src/test/run-pass/segfault-no-out-of-stack.rs @@ -12,7 +12,7 @@ // ignore-cloudabi can't run commands // ignore-emscripten can't run commands -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/signal-alternate-stack-cleanup.rs b/src/test/run-pass/signal-alternate-stack-cleanup.rs index ad099f82d13..a79ab20c160 100644 --- a/src/test/run-pass/signal-alternate-stack-cleanup.rs +++ b/src/test/run-pass/signal-alternate-stack-cleanup.rs @@ -16,7 +16,7 @@ // ignore-wasm32-bare no libc // ignore-windows -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; use libc::*; diff --git a/src/test/run-pass/statics/static-mut-foreign.rs b/src/test/run-pass/statics/static-mut-foreign.rs index d9e43ddea71..460d66a4592 100644 --- a/src/test/run-pass/statics/static-mut-foreign.rs +++ b/src/test/run-pass/statics/static-mut-foreign.rs @@ -15,7 +15,7 @@ // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/run-pass/wait-forked-but-failed-child.rs b/src/test/run-pass/wait-forked-but-failed-child.rs index dc47108e183..d822b67a07c 100644 --- a/src/test/run-pass/wait-forked-but-failed-child.rs +++ b/src/test/run-pass/wait-forked-but-failed-child.rs @@ -11,7 +11,7 @@ // ignore-cloudabi no processes // ignore-emscripten no processes -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/ui/error-codes/E0259.rs b/src/test/ui/error-codes/E0259.rs index 5a47541c708..b3e633a7017 100644 --- a/src/test/ui/error-codes/E0259.rs +++ b/src/test/ui/error-codes/E0259.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(alloc, libc)] +#![feature(alloc, rustc_private)] #![allow(unused_extern_crates)] extern crate alloc; diff --git a/src/test/ui/extern/extern-const.fixed b/src/test/ui/extern/extern-const.fixed index dca5698a70c..fb17934fa9b 100644 --- a/src/test/ui/extern/extern-const.fixed +++ b/src/test/ui/extern/extern-const.fixed @@ -7,7 +7,7 @@ // run-rustfix // ignore-wasm32 no external library to link to. // compile-flags: -g -Z continue-parse-after-error -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] diff --git a/src/test/ui/extern/extern-const.rs b/src/test/ui/extern/extern-const.rs index 07dbe545a85..f2585f5199e 100644 --- a/src/test/ui/extern/extern-const.rs +++ b/src/test/ui/extern/extern-const.rs @@ -7,7 +7,7 @@ // run-rustfix // ignore-wasm32 no external library to link to. // compile-flags: -g -Z continue-parse-after-error -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; #[link(name = "rust_test_helpers", kind = "static")] diff --git a/src/test/ui/issues/issue-1251.rs b/src/test/ui/issues/issue-1251.rs index b42404ce773..125f6e1faa6 100644 --- a/src/test/ui/issues/issue-1251.rs +++ b/src/test/ui/issues/issue-1251.rs @@ -14,7 +14,7 @@ // pretty-expanded FIXME #23616 // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] #![crate_id="rust_get_test_int"] diff --git a/src/test/ui/issues/issue-22034.rs b/src/test/ui/issues/issue-22034.rs index 2708de2c13a..bee324f8746 100644 --- a/src/test/ui/issues/issue-22034.rs +++ b/src/test/ui/issues/issue-22034.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/ui/issues/issue-37887.stderr b/src/test/ui/issues/issue-37887.stderr index 48fb6c2e6fa..7a5a5cde469 100644 --- a/src/test/ui/issues/issue-37887.stderr +++ b/src/test/ui/issues/issue-37887.stderr @@ -4,13 +4,13 @@ error[E0432]: unresolved import `libc` LL | use libc::*; //~ ERROR unresolved import | ^^^^ maybe a missing `extern crate libc;`? -error[E0658]: use of unstable library feature 'libc': use `libc` from crates.io (see issue #27783) +error[E0658]: use of unstable library feature 'rustc_private': this crate is being loaded from the sysroot, an unstable location; did you mean to load this crate from crates.io via `Cargo.toml` instead? (see issue #27812) --> $DIR/issue-37887.rs:12:5 | LL | extern crate libc; //~ ERROR use of unstable | ^^^^^^^^^^^^^^^^^^ | - = help: add #![feature(libc)] to the crate attributes to enable + = help: add #![feature(rustc_private)] to the crate attributes to enable error: aborting due to 2 previous errors diff --git a/src/test/ui/lint/lint-ctypes.rs b/src/test/ui/lint/lint-ctypes.rs index e09aabaf692..4c9f1f980bd 100644 --- a/src/test/ui/lint/lint-ctypes.rs +++ b/src/test/ui/lint/lint-ctypes.rs @@ -9,7 +9,7 @@ // except according to those terms. #![deny(improper_ctypes)] -#![feature(libc)] +#![feature(rustc_private)] #![allow(private_in_public)] diff --git a/src/test/ui/non-copyable-void.rs b/src/test/ui/non-copyable-void.rs index 63e5f963754..35991901e93 100644 --- a/src/test/ui/non-copyable-void.rs +++ b/src/test/ui/non-copyable-void.rs @@ -10,7 +10,7 @@ // ignore-wasm32-bare no libc to test ffi with -#![feature(libc)] +#![feature(rustc_private)] extern crate libc; diff --git a/src/test/ui/unnecessary-extern-crate.rs b/src/test/ui/unnecessary-extern-crate.rs index 110cfefcd92..4eb3c3d6436 100644 --- a/src/test/ui/unnecessary-extern-crate.rs +++ b/src/test/ui/unnecessary-extern-crate.rs @@ -11,7 +11,7 @@ // edition:2018 #![deny(unused_extern_crates)] -#![feature(alloc, test, libc, crate_visibility_modifier)] +#![feature(alloc, test, rustc_private, crate_visibility_modifier)] extern crate libc; //~^ ERROR unused extern crate diff --git a/src/tools/rustc-std-workspace-core/Cargo.toml b/src/tools/rustc-std-workspace-core/Cargo.toml new file mode 100644 index 00000000000..f000d634e19 --- /dev/null +++ b/src/tools/rustc-std-workspace-core/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rustc-std-workspace-core" +version = "1.0.0" +authors = ["Alex Crichton "] +license = 'MIT/Apache-2.0' +description = """ +Hack for the compiler's own build system +""" + +[lib] +path = "lib.rs" + +[dependencies] +core = { path = "../../libcore" } diff --git a/src/tools/rustc-std-workspace-core/README.md b/src/tools/rustc-std-workspace-core/README.md new file mode 100644 index 00000000000..9c2b1fa91d3 --- /dev/null +++ b/src/tools/rustc-std-workspace-core/README.md @@ -0,0 +1,29 @@ +# The `rustc-std-workspace-core` crate + +This crate is a shim and empty crate which simply depends on `libcore` and +reexports all of its contents. The crate is the crux of empowering the standard +library to depend on crates from crates.io + +Crates on crates.io that the standard library depend on the +`rustc-std-workspace-core` crate from crates.io. On crates.io, however, this +crate is empty. We use `[patch]` to override it to this crate in this +repository. As a result, crates on crates.io will draw a dependency edge to +`libcore`, the version defined in this repository. That should draw all the +dependency edges to ensure Cargo builds crates successfully! + +Note that crates on crates.io need to depend on this crate with the name `core` +for everything to work correctly. To do that they can use: + +```toml +core = { version = "1.0.0", optional = true, package = 'rustc-std-workspace-core' } +``` + +Through the use of the `package` key the crate is renamed to `core`, meaning +it'll look like + +``` +--extern core=.../librustc_std_workspace_core-XXXXXXX.rlib +``` + +when Cargo invokes the compiler, satisfying the implicit `extern crate core` +directive injected by the compiler. diff --git a/src/tools/rustc-std-workspace-core/lib.rs b/src/tools/rustc-std-workspace-core/lib.rs new file mode 100644 index 00000000000..e2946fe2a97 --- /dev/null +++ b/src/tools/rustc-std-workspace-core/lib.rs @@ -0,0 +1,6 @@ +#![feature(no_core)] +#![no_core] + +extern crate core; + +pub use core::*; diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index e2758921f19..2b5cff6e07b 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -53,6 +53,7 @@ const EXCEPTIONS: &[&str] = &[ "bytesize", // Apache-2.0, cargo "im-rc", // MPL-2.0+, cargo "adler32", // BSD-3-Clause AND Zlib, cargo dep that isn't used + "fortanix-sgx-abi", // MPL-2.0+, libstd but only for sgx target ]; /// Which crates to check against the whitelist? diff --git a/src/tools/tidy/src/lib.rs b/src/tools/tidy/src/lib.rs index 53db589beaf..614d2053a43 100644 --- a/src/tools/tidy/src/lib.rs +++ b/src/tools/tidy/src/lib.rs @@ -56,15 +56,11 @@ pub mod libcoretest; fn filter_dirs(path: &Path) -> bool { let skip = [ - "src/dlmalloc", "src/llvm", "src/llvm-emscripten", "src/libbacktrace", - "src/libcompiler_builtins", "src/librustc_data_structures/owning_ref", - "src/compiler-rt", - "src/liblibc", - "src/rt/hoedown", + "src/vendor", "src/tools/cargo", "src/tools/clang", "src/tools/rls", diff --git a/src/tools/tidy/src/pal.rs b/src/tools/tidy/src/pal.rs index 822db253191..acf72022c60 100644 --- a/src/tools/tidy/src/pal.rs +++ b/src/tools/tidy/src/pal.rs @@ -26,7 +26,6 @@ //! exceptions: //! //! - core may not have platform-specific code -//! - libcompiler_builtins may have platform-specific code //! - libpanic_abort may have platform-specific code //! - libpanic_unwind may have platform-specific code //! - libunwind may have platform-specific code @@ -50,8 +49,6 @@ use std::iter::Iterator; // Paths that may contain platform-specific code const EXCEPTION_PATHS: &[&str] = &[ // std crates - "src/libcompiler_builtins", - "src/liblibc", "src/libpanic_abort", "src/libpanic_unwind", "src/libunwind", -- cgit 1.4.1-3-g733a5 From cf47a19305d929d1870414dd6911ca3191597668 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 5 Dec 2018 06:42:56 -0800 Subject: Bump to 1.33.0 * Update bootstrap compiler * Update version to 1.33.0 * Remove some `#[cfg(stage0)]` annotations Actually updating the version number is blocked on updating Cargo --- src/bootstrap/channel.rs | 2 +- src/liballoc/tests/str.rs | 8 ++++---- src/libcore/ffi.rs | 4 ---- src/libcore/intrinsics.rs | 3 --- src/libcore/mem.rs | 1 - src/libcore/num/mod.rs | 14 ++------------ src/libcore/ops/unsize.rs | 2 +- src/libcore/sync/atomic.rs | 4 ++-- src/librustc/lint/builtin.rs | 2 +- src/librustc_errors/emitter.rs | 2 +- src/librustc_lint/nonstandard_style.rs | 4 ++-- src/librustc_llvm/build.rs | 4 ++-- src/librustc_mir/borrow_check/move_errors.rs | 4 ++-- src/librustc_mir/interpret/intrinsics.rs | 2 +- src/librustc_typeck/check/demand.rs | 4 ++-- src/librustdoc/markdown.rs | 2 +- src/librustdoc/passes/collect_intra_doc_links.rs | 10 +++++----- src/librustdoc/passes/unindent_comments.rs | 2 +- src/libserialize/json.rs | 2 +- src/libstd/error.rs | 1 + src/libstd/ffi/mod.rs | 1 - src/libstd/io/error.rs | 1 + src/libstd/lib.rs | 4 ---- src/libstd/panic.rs | 4 ++-- src/libstd/sys/windows/os.rs | 2 +- src/libsyntax/diagnostics/plugin.rs | 1 + src/libsyntax/source_map.rs | 8 ++++---- src/libsyntax_pos/symbol.rs | 2 +- src/stage0.txt | 2 +- src/tools/cargo | 2 +- src/tools/compiletest/src/main.rs | 6 +++++- 31 files changed, 47 insertions(+), 63 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/bootstrap/channel.rs b/src/bootstrap/channel.rs index 88b6925b2b1..878b6ed73a3 100644 --- a/src/bootstrap/channel.rs +++ b/src/bootstrap/channel.rs @@ -24,7 +24,7 @@ use Build; use config::Config; // The version number -pub const CFG_RELEASE_NUM: &str = "1.32.0"; +pub const CFG_RELEASE_NUM: &str = "1.33.0"; pub struct GitInfo { inner: Option, diff --git a/src/liballoc/tests/str.rs b/src/liballoc/tests/str.rs index 683ce2bf112..9ad8ad1fc07 100644 --- a/src/liballoc/tests/str.rs +++ b/src/liballoc/tests/str.rs @@ -1514,9 +1514,9 @@ fn contains_weird_cases() { #[test] fn trim_ws() { - assert_eq!(" \t a \t ".trim_left_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t a \t ".trim_start_matches(|c: char| c.is_whitespace()), "a \t "); - assert_eq!(" \t a \t ".trim_right_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t a \t ".trim_end_matches(|c: char| c.is_whitespace()), " \t a"); assert_eq!(" \t a \t ".trim_start_matches(|c: char| c.is_whitespace()), "a \t "); @@ -1524,9 +1524,9 @@ fn trim_ws() { " \t a"); assert_eq!(" \t a \t ".trim_matches(|c: char| c.is_whitespace()), "a"); - assert_eq!(" \t \t ".trim_left_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t \t ".trim_start_matches(|c: char| c.is_whitespace()), ""); - assert_eq!(" \t \t ".trim_right_matches(|c: char| c.is_whitespace()), + assert_eq!(" \t \t ".trim_end_matches(|c: char| c.is_whitespace()), ""); assert_eq!(" \t \t ".trim_start_matches(|c: char| c.is_whitespace()), ""); diff --git a/src/libcore/ffi.rs b/src/libcore/ffi.rs index d7a112eb90d..899fae90946 100644 --- a/src/libcore/ffi.rs +++ b/src/libcore/ffi.rs @@ -1,7 +1,6 @@ #![stable(feature = "", since = "1.30.0")] #![allow(non_camel_case_types)] -#![cfg_attr(stage0, allow(dead_code))] //! Utilities related to FFI bindings. @@ -123,7 +122,6 @@ struct VaListImpl { all supported platforms", issue = "27745")] #[repr(transparent)] -#[cfg(not(stage0))] pub struct VaList<'a>(&'a mut VaListImpl); // The VaArgSafe trait needs to be used in public interfaces, however, the trait @@ -173,7 +171,6 @@ impl sealed_trait::VaArgSafe for *mut T {} issue = "27745")] impl sealed_trait::VaArgSafe for *const T {} -#[cfg(not(stage0))] impl<'a> VaList<'a> { /// Advance to the next arg. #[unstable(feature = "c_variadic", @@ -208,7 +205,6 @@ impl<'a> VaList<'a> { } } -#[cfg(not(stage0))] extern "rust-intrinsic" { /// Destroy the arglist `ap` after initialization with `va_start` or /// `va_copy`. diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index eebb98b5e6d..b94d5b4adcf 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -718,7 +718,6 @@ extern "rust-intrinsic" { pub fn uninit() -> T; /// Moves a value out of scope without running drop glue. - #[cfg(not(stage0))] pub fn forget(_: T); /// Reinterprets the bits of a value of one type as another type. @@ -1476,14 +1475,12 @@ extern "rust-intrinsic" { /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `rotate_left` method. For example, /// [`std::u32::rotate_left`](../../std/primitive.u32.html#method.rotate_left) - #[cfg(not(stage0))] pub fn rotate_left(x: T, y: T) -> T; /// Performs rotate right. /// The stabilized versions of this intrinsic are available on the integer /// primitives via the `rotate_right` method. For example, /// [`std::u32::rotate_right`](../../std/primitive.u32.html#method.rotate_right) - #[cfg(not(stage0))] pub fn rotate_right(x: T, y: T) -> T; /// Returns (a + b) mod 2N, where N is the width of T in bits. diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 06754f17a6f..afd9fcb1fba 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -149,7 +149,6 @@ pub fn forget(t: T) { /// /// [`forget`]: fn.forget.html #[inline] -#[cfg(not(stage0))] #[unstable(feature = "forget_unsized", issue = "0")] pub fn forget_unsized(t: T) { unsafe { intrinsics::forget(t) } diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 13b422162f3..4acf3a15ebf 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -2330,12 +2330,7 @@ assert_eq!(n.rotate_left(", $rot, "), m); #[rustc_const_unstable(feature = "const_int_rotate")] #[inline] pub const fn rotate_left(self, n: u32) -> Self { - #[cfg(not(stage0))] { - unsafe { intrinsics::rotate_left(self, n as $SelfT) } - } - #[cfg(stage0)] { - (self << (n % $BITS)) | (self >> (($BITS - (n % $BITS)) % $BITS)) - } + unsafe { intrinsics::rotate_left(self, n as $SelfT) } } } @@ -2360,12 +2355,7 @@ assert_eq!(n.rotate_right(", $rot, "), m); #[rustc_const_unstable(feature = "const_int_rotate")] #[inline] pub const fn rotate_right(self, n: u32) -> Self { - #[cfg(not(stage0))] { - unsafe { intrinsics::rotate_right(self, n as $SelfT) } - } - #[cfg(stage0)] { - (self >> (n % $BITS)) | (self << (($BITS - (n % $BITS)) % $BITS)) - } + unsafe { intrinsics::rotate_right(self, n as $SelfT) } } } diff --git a/src/libcore/ops/unsize.rs b/src/libcore/ops/unsize.rs index 4d9a40a1b90..e86a392a2c8 100644 --- a/src/libcore/ops/unsize.rs +++ b/src/libcore/ops/unsize.rs @@ -93,7 +93,7 @@ impl, U: ?Sized> CoerceUnsized<*const U> for *const T {} /// {} /// ``` #[unstable(feature = "dispatch_from_dyn", issue = "0")] -#[cfg_attr(not(stage0), lang = "dispatch_from_dyn")] +#[lang = "dispatch_from_dyn"] pub trait DispatchFromDyn { // Empty. } diff --git a/src/libcore/sync/atomic.rs b/src/libcore/sync/atomic.rs index 27eeb045bb1..060983a702f 100644 --- a/src/libcore/sync/atomic.rs +++ b/src/libcore/sync/atomic.rs @@ -1940,7 +1940,7 @@ atomic_int! { 8, u64 AtomicU64 ATOMIC_U64_INIT } -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] atomic_int! { unstable(feature = "integer_atomics", issue = "32976"), unstable(feature = "integer_atomics", issue = "32976"), @@ -1954,7 +1954,7 @@ atomic_int! { 16, i128 AtomicI128 ATOMIC_I128_INIT } -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] atomic_int! { unstable(feature = "integer_atomics", issue = "32976"), unstable(feature = "integer_atomics", issue = "32976"), diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index a09d167f217..b7759a8c92b 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -463,7 +463,7 @@ impl BuiltinLintDiagnostics { Ok(ref s) => { // FIXME(Manishearth) ideally the emitting code // can tell us whether or not this is global - let opt_colon = if s.trim_left().starts_with("::") { + let opt_colon = if s.trim_start().starts_with("::") { "" } else { "::" diff --git a/src/librustc_errors/emitter.rs b/src/librustc_errors/emitter.rs index ae9f6a5e140..7bd0f0f8fc4 100644 --- a/src/librustc_errors/emitter.rs +++ b/src/librustc_errors/emitter.rs @@ -1262,7 +1262,7 @@ impl EmitterWriter { // Do not underline the leading... let start = part.snippet.len() - .saturating_sub(part.snippet.trim_left().len()); + .saturating_sub(part.snippet.trim_start().len()); // ...or trailing spaces. Account for substitutions containing unicode // characters. let sub_len = part.snippet.trim().chars().fold(0, |acc, ch| { diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs index 13be50ef01f..e071c34ff7f 100644 --- a/src/librustc_lint/nonstandard_style.rs +++ b/src/librustc_lint/nonstandard_style.rs @@ -167,7 +167,7 @@ impl NonSnakeCase { fn to_snake_case(mut str: &str) -> String { let mut words = vec![]; // Preserve leading underscores - str = str.trim_left_matches(|c: char| { + str = str.trim_start_matches(|c: char| { if c == '_' { words.push(String::new()); true @@ -199,7 +199,7 @@ impl NonSnakeCase { if ident.is_empty() { return true; } - let ident = ident.trim_left_matches('\''); + let ident = ident.trim_start_matches('\''); let ident = ident.trim_matches('_'); let mut allow_underscore = true; diff --git a/src/librustc_llvm/build.rs b/src/librustc_llvm/build.rs index 7d01ed556c8..ce482087bba 100644 --- a/src/librustc_llvm/build.rs +++ b/src/librustc_llvm/build.rs @@ -192,11 +192,11 @@ fn main() { // On MSVC llvm-config will print the full name to libraries, but // we're only interested in the name part let name = Path::new(lib).file_name().unwrap().to_str().unwrap(); - name.trim_right_matches(".lib") + name.trim_end_matches(".lib") } else if lib.ends_with(".lib") { // Some MSVC libraries just come up with `.lib` tacked on, so chop // that off - lib.trim_right_matches(".lib") + lib.trim_end_matches(".lib") } else { continue; }; diff --git a/src/librustc_mir/borrow_check/move_errors.rs b/src/librustc_mir/borrow_check/move_errors.rs index db60017185a..fb93c41ce4f 100644 --- a/src/librustc_mir/borrow_check/move_errors.rs +++ b/src/librustc_mir/borrow_check/move_errors.rs @@ -426,13 +426,13 @@ impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> { .span_to_snippet(pat_span) .unwrap(); if pat_snippet.starts_with('&') { - let pat_snippet = pat_snippet[1..].trim_left(); + let pat_snippet = pat_snippet[1..].trim_start(); let suggestion; let to_remove; if pat_snippet.starts_with("mut") && pat_snippet["mut".len()..].starts_with(Pattern_White_Space) { - suggestion = pat_snippet["mut".len()..].trim_left(); + suggestion = pat_snippet["mut".len()..].trim_start(); to_remove = "&mut"; } else { suggestion = pat_snippet; diff --git a/src/librustc_mir/interpret/intrinsics.rs b/src/librustc_mir/interpret/intrinsics.rs index bbee6e0b49a..cbe2e25b4fc 100644 --- a/src/librustc_mir/interpret/intrinsics.rs +++ b/src/librustc_mir/interpret/intrinsics.rs @@ -103,7 +103,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> if bits == 0 { return err!(Intrinsic(format!("{} called on 0", intrinsic_name))); } - numeric_intrinsic(intrinsic_name.trim_right_matches("_nonzero"), bits, kind)? + numeric_intrinsic(intrinsic_name.trim_end_matches("_nonzero"), bits, kind)? } else { numeric_intrinsic(intrinsic_name, bits, kind)? }; diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index f4f6b3d6616..db4b68611c5 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -123,7 +123,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let sole_field_ty = sole_field.ty(self.tcx, substs); if self.can_coerce(expr_ty, sole_field_ty) { let variant_path = self.tcx.item_path_str(variant.did); - Some(variant_path.trim_left_matches("std::prelude::v1::").to_string()) + Some(variant_path.trim_start_matches("std::prelude::v1::").to_string()) } else { None } @@ -519,7 +519,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { let suffix_suggestion = format!( "{}{}{}{}", if needs_paren { "(" } else { "" }, - src.trim_right_matches(&checked_ty.to_string()), + src.trim_end_matches(&checked_ty.to_string()), expected_ty, if needs_paren { ")" } else { "" }, ); diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs index e0e0be717b2..504567e96e7 100644 --- a/src/librustdoc/markdown.rs +++ b/src/librustdoc/markdown.rs @@ -35,7 +35,7 @@ fn extract_leading_metadata<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { for line in s.lines() { if line.starts_with("# ") || line.starts_with("%") { // trim the whitespace after the symbol - metadata.push(line[1..].trim_left()); + metadata.push(line[1..].trim_start()); count += line.len() + 1; } else { return (metadata, &s[count..]); diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 29062ba58c2..2e8bfd8f07f 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -294,23 +294,23 @@ impl<'a, 'tcx, 'rcx, 'cstore> DocFolder for LinkCollector<'a, 'tcx, 'rcx, 'cstor "trait@", "union@"].iter() .find(|p| link.starts_with(**p)) { kind = PathKind::Type; - link.trim_left_matches(prefix) + link.trim_start_matches(prefix) } else if let Some(prefix) = ["const@", "static@", "value@", "function@", "mod@", "fn@", "module@", "method@"] .iter().find(|p| link.starts_with(**p)) { kind = PathKind::Value; - link.trim_left_matches(prefix) + link.trim_start_matches(prefix) } else if link.ends_with("()") { kind = PathKind::Value; - link.trim_right_matches("()") + link.trim_end_matches("()") } else if link.starts_with("macro@") { kind = PathKind::Macro; - link.trim_left_matches("macro@") + link.trim_start_matches("macro@") } else if link.ends_with('!') { kind = PathKind::Macro; - link.trim_right_matches('!') + link.trim_end_matches('!') } else { &link[..] }.trim(); diff --git a/src/librustdoc/passes/unindent_comments.rs b/src/librustdoc/passes/unindent_comments.rs index 6d875c107c8..5c565bf8181 100644 --- a/src/librustdoc/passes/unindent_comments.rs +++ b/src/librustdoc/passes/unindent_comments.rs @@ -95,7 +95,7 @@ fn unindent(s: &str) -> String { }); if !lines.is_empty() { - let mut unindented = vec![ lines[0].trim_left().to_string() ]; + let mut unindented = vec![ lines[0].trim_start().to_string() ]; unindented.extend_from_slice(&lines[1..].iter().map(|&line| { if line.chars().all(|c| c.is_whitespace()) { line.to_string() diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 9439dc78d3c..b0884e1fbd1 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -3493,7 +3493,7 @@ mod tests { // Helper function for counting indents fn indents(source: &str) -> usize { - let trimmed = source.trim_left_matches(' '); + let trimmed = source.trim_start_matches(' '); source.len() - trimmed.len() } diff --git a/src/libstd/error.rs b/src/libstd/error.rs index a9b27115261..e5c5ab83cbc 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -533,6 +533,7 @@ impl Error for Box { Error::description(&**self) } + #[allow(deprecated)] fn cause(&self) -> Option<&dyn Error> { Error::cause(&**self) } diff --git a/src/libstd/ffi/mod.rs b/src/libstd/ffi/mod.rs index 99da73adc63..f46c4f2938b 100644 --- a/src/libstd/ffi/mod.rs +++ b/src/libstd/ffi/mod.rs @@ -174,7 +174,6 @@ pub use self::os_str::{OsString, OsStr}; #[stable(feature = "raw_os", since = "1.1.0")] pub use core::ffi::c_void; -#[cfg(not(stage0))] #[unstable(feature = "c_variadic", reason = "the `c_variadic` feature has not been properly tested on \ all supported platforms", diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index 32e29962760..d3844ebe19e 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -555,6 +555,7 @@ impl error::Error for Error { } } + #[allow(deprecated)] fn cause(&self) -> Option<&dyn error::Error> { match self.repr { Repr::Os(..) => None, diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 90c8eaf0f7c..7c43ba5afa7 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -317,10 +317,6 @@ #![default_lib_allocator] -#[cfg(stage0)] -#[global_allocator] -static ALLOC: alloc::System = alloc::System; - // Explicitly import the prelude. The compiler uses this same unstable attribute // to import the prelude implicitly when building crates that depend on std. #[prelude_import] diff --git a/src/libstd/panic.rs b/src/libstd/panic.rs index 099b4d6f577..3eacc7afc41 100644 --- a/src/libstd/panic.rs +++ b/src/libstd/panic.rs @@ -264,7 +264,7 @@ impl RefUnwindSafe for atomic::AtomicI32 {} #[cfg(target_has_atomic = "64")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicI64 {} -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicI128 {} @@ -283,7 +283,7 @@ impl RefUnwindSafe for atomic::AtomicU32 {} #[cfg(target_has_atomic = "64")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicU64 {} -#[cfg(all(not(stage0), target_has_atomic = "128"))] +#[cfg(target_has_atomic = "128")] #[unstable(feature = "integer_atomics", issue = "32976")] impl RefUnwindSafe for atomic::AtomicU128 {} diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index 2be30e68d24..84ef62e5fe9 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -76,7 +76,7 @@ pub fn error_string(mut errnum: i32) -> String { match String::from_utf16(&buf[..res]) { Ok(mut msg) => { // Trim trailing CRLF inserted by FormatMessageW - let len = msg.trim_right().len(); + let len = msg.trim_end().len(); msg.truncate(len); msg }, diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs index 1229db9b0e0..3b88767f0e8 100644 --- a/src/libsyntax/diagnostics/plugin.rs +++ b/src/libsyntax/diagnostics/plugin.rs @@ -141,6 +141,7 @@ pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt, ]) } +#[allow(deprecated)] pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt, span: Span, token_tree: &[TokenTree]) diff --git a/src/libsyntax/source_map.rs b/src/libsyntax/source_map.rs index 45008129e83..9a343123f61 100644 --- a/src/libsyntax/source_map.rs +++ b/src/libsyntax/source_map.rs @@ -579,7 +579,7 @@ impl SourceMap { match self.span_to_prev_source(sp) { Err(_) => None, Ok(source) => source.split('\n').last().map(|last_line| { - last_line.len() - last_line.trim_left().len() + last_line.len() - last_line.trim_start().len() }) } } @@ -593,7 +593,7 @@ impl SourceMap { /// if no character could be found or if an error occurred while retrieving the code snippet. pub fn span_extend_to_prev_char(&self, sp: Span, c: char) -> Span { if let Ok(prev_source) = self.span_to_prev_source(sp) { - let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_left(); + let prev_source = prev_source.rsplit(c).nth(0).unwrap_or("").trim_start(); if !prev_source.is_empty() && !prev_source.contains('\n') { return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32)); } @@ -613,7 +613,7 @@ impl SourceMap { for ws in &[" ", "\t", "\n"] { let pat = pat.to_owned() + ws; if let Ok(prev_source) = self.span_to_prev_source(sp) { - let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_left(); + let prev_source = prev_source.rsplit(&pat).nth(0).unwrap_or("").trim_start(); if !prev_source.is_empty() && (!prev_source.contains('\n') || accept_newlines) { return sp.with_lo(BytePos(sp.lo().0 - prev_source.len() as u32)); } @@ -627,7 +627,7 @@ impl SourceMap { pub fn span_until_char(&self, sp: Span, c: char) -> Span { match self.span_to_snippet(sp) { Ok(snippet) => { - let snippet = snippet.split(c).nth(0).unwrap_or("").trim_right(); + let snippet = snippet.split(c).nth(0).unwrap_or("").trim_end(); if !snippet.is_empty() && !snippet.contains('\n') { sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32)) } else { diff --git a/src/libsyntax_pos/symbol.rs b/src/libsyntax_pos/symbol.rs index 05c53878e70..f1adb9d64da 100644 --- a/src/libsyntax_pos/symbol.rs +++ b/src/libsyntax_pos/symbol.rs @@ -57,7 +57,7 @@ impl Ident { } pub fn without_first_quote(self) -> Ident { - Ident::new(Symbol::intern(self.as_str().trim_left_matches('\'')), self.span) + Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span) } /// "Normalize" ident for use in comparisons using "item hygiene". diff --git a/src/stage0.txt b/src/stage0.txt index 83694137775..843ecae1ce3 100644 --- a/src/stage0.txt +++ b/src/stage0.txt @@ -12,7 +12,7 @@ # source tarball for a stable release you'll likely see `1.x.0` for rustc and # `0.x.0` for Cargo where they were released on `date`. -date: 2018-11-21 +date: 2018-12-09 rustc: beta cargo: beta diff --git a/src/tools/cargo b/src/tools/cargo index 28fb20034a5..2cf1f5dda2f 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 28fb20034a5bb42ea589664de2617dd1840506d3 +Subproject commit 2cf1f5dda2f7ed84e94c4d32f643e0f1f15352f0 diff --git a/src/tools/compiletest/src/main.rs b/src/tools/compiletest/src/main.rs index 65f6bff7eaf..9aefd15765d 100644 --- a/src/tools/compiletest/src/main.rs +++ b/src/tools/compiletest/src/main.rs @@ -511,7 +511,11 @@ pub fn test_opts(config: &Config) -> test::TestOpts { test::TestOpts { filter: config.filter.clone(), filter_exact: config.filter_exact, - run_ignored: config.run_ignored, + run_ignored: if config.run_ignored { + test::RunIgnored::Yes + } else { + test::RunIgnored::No + }, format: if config.quiet { test::OutputFormat::Terse } else { -- cgit 1.4.1-3-g733a5 From 13f0463a195832f10f0f22105ad14e6d6b2eff59 Mon Sep 17 00:00:00 2001 From: Linus Färnstrand Date: Tue, 4 Dec 2018 02:29:57 +0100 Subject: Add checked_add method to Instant time type --- src/libstd/sys/cloudabi/time.rs | 19 ++++++------------- src/libstd/sys/redox/time.rs | 12 ++---------- src/libstd/sys/unix/time.rs | 36 +++++++++++++----------------------- src/libstd/sys/wasm/time.rs | 8 ++------ src/libstd/sys/windows/time.rs | 34 ++++++++++++++-------------------- src/libstd/time.rs | 27 +++++++++++++++++++++++++-- 6 files changed, 62 insertions(+), 74 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/cloudabi/time.rs b/src/libstd/sys/cloudabi/time.rs index a442d1e4ad7..fdd172a896c 100644 --- a/src/libstd/sys/cloudabi/time.rs +++ b/src/libstd/sys/cloudabi/time.rs @@ -21,8 +21,8 @@ pub struct Instant { fn checked_dur2intervals(dur: &Duration) -> Option { dur.as_secs() - .checked_mul(NSEC_PER_SEC) - .and_then(|nanos| nanos.checked_add(dur.subsec_nanos() as abi::timestamp)) + .checked_mul(NSEC_PER_SEC)? + .checked_add(dur.subsec_nanos() as abi::timestamp) } pub fn dur2intervals(dur: &Duration) -> abi::timestamp { @@ -47,12 +47,10 @@ impl Instant { Duration::new(diff / NSEC_PER_SEC, (diff % NSEC_PER_SEC) as u32) } - pub fn add_duration(&self, other: &Duration) -> Instant { - Instant { - t: self.t - .checked_add(dur2intervals(other)) - .expect("overflow when adding duration to instant"), - } + pub fn checked_add_duration(&self, other: &Duration) -> Option { + checked_dur2intervals(other)? + .checked_add(self.t) + .map(|t| Instant {t}) } pub fn sub_duration(&self, other: &Duration) -> Instant { @@ -95,11 +93,6 @@ impl SystemTime { } } - pub fn add_duration(&self, other: &Duration) -> SystemTime { - self.checked_add_duration(other) - .expect("overflow when adding duration to instant") - } - pub fn checked_add_duration(&self, other: &Duration) -> Option { checked_dur2intervals(other) .and_then(|d| self.t.checked_add(d)) diff --git a/src/libstd/sys/redox/time.rs b/src/libstd/sys/redox/time.rs index beff8d287e7..5ba8b780727 100644 --- a/src/libstd/sys/redox/time.rs +++ b/src/libstd/sys/redox/time.rs @@ -41,10 +41,6 @@ impl Timespec { } } - fn add_duration(&self, other: &Duration) -> Timespec { - self.checked_add_duration(other).expect("overflow when adding duration to time") - } - fn checked_add_duration(&self, other: &Duration) -> Option { let mut secs = other .as_secs() @@ -150,8 +146,8 @@ impl Instant { }) } - pub fn add_duration(&self, other: &Duration) -> Instant { - Instant { t: self.t.add_duration(other) } + pub fn checked_add_duration(&self, other: &Duration) -> Option { + self.t.checked_add_duration(other).map(|t| Instant { t }) } pub fn sub_duration(&self, other: &Duration) -> Instant { @@ -178,10 +174,6 @@ impl SystemTime { self.t.sub_timespec(&other.t) } - pub fn add_duration(&self, other: &Duration) -> SystemTime { - SystemTime { t: self.t.add_duration(other) } - } - pub fn checked_add_duration(&self, other: &Duration) -> Option { self.t.checked_add_duration(other).map(|t| SystemTime { t }) } diff --git a/src/libstd/sys/unix/time.rs b/src/libstd/sys/unix/time.rs index 1f9539c36e0..81ef0f48833 100644 --- a/src/libstd/sys/unix/time.rs +++ b/src/libstd/sys/unix/time.rs @@ -42,10 +42,6 @@ impl Timespec { } } - fn add_duration(&self, other: &Duration) -> Timespec { - self.checked_add_duration(other).expect("overflow when adding duration to time") - } - fn checked_add_duration(&self, other: &Duration) -> Option { let mut secs = other .as_secs() @@ -165,11 +161,8 @@ mod inner { Duration::new(nanos / NSEC_PER_SEC, (nanos % NSEC_PER_SEC) as u32) } - pub fn add_duration(&self, other: &Duration) -> Instant { - Instant { - t: self.t.checked_add(dur2intervals(other)) - .expect("overflow when adding duration to instant"), - } + pub fn checked_add_duration(&self, other: &Duration) -> Option { + checked_dur2intervals(other)?.checked_add(self.t).map(|t| Instant {t}) } pub fn sub_duration(&self, other: &Duration) -> Instant { @@ -199,10 +192,6 @@ mod inner { self.t.sub_timespec(&other.t) } - pub fn add_duration(&self, other: &Duration) -> SystemTime { - SystemTime { t: self.t.add_duration(other) } - } - pub fn checked_add_duration(&self, other: &Duration) -> Option { self.t.checked_add_duration(other).map(|t| SystemTime { t }) } @@ -237,11 +226,16 @@ mod inner { } fn dur2intervals(dur: &Duration) -> u64 { + checked_dur2intervals(dur) + .expect("overflow converting duration to nanoseconds") + } + + fn checked_dur2intervals(dur: &Duration) -> Option { + let nanos = dur.as_secs() + .checked_mul(NSEC_PER_SEC)? + .checked_add(dur.subsec_nanos() as u64)?; let info = info(); - let nanos = dur.as_secs().checked_mul(NSEC_PER_SEC).and_then(|nanos| { - nanos.checked_add(dur.subsec_nanos() as u64) - }).expect("overflow converting duration to nanoseconds"); - mul_div_u64(nanos, info.denom as u64, info.numer as u64) + Some(mul_div_u64(nanos, info.denom as u64, info.numer as u64)) } fn info() -> &'static libc::mach_timebase_info { @@ -299,8 +293,8 @@ mod inner { }) } - pub fn add_duration(&self, other: &Duration) -> Instant { - Instant { t: self.t.add_duration(other) } + pub fn checked_add_duration(&self, other: &Duration) -> Option { + self.t.checked_add_duration(other).map(|t| Instant { t }) } pub fn sub_duration(&self, other: &Duration) -> Instant { @@ -327,10 +321,6 @@ mod inner { self.t.sub_timespec(&other.t) } - pub fn add_duration(&self, other: &Duration) -> SystemTime { - SystemTime { t: self.t.add_duration(other) } - } - pub fn checked_add_duration(&self, other: &Duration) -> Option { self.t.checked_add_duration(other).map(|t| SystemTime { t }) } diff --git a/src/libstd/sys/wasm/time.rs b/src/libstd/sys/wasm/time.rs index 991e8176edf..20cd870919c 100644 --- a/src/libstd/sys/wasm/time.rs +++ b/src/libstd/sys/wasm/time.rs @@ -28,8 +28,8 @@ impl Instant { self.0 - other.0 } - pub fn add_duration(&self, other: &Duration) -> Instant { - Instant(self.0 + *other) + pub fn checked_add_duration(&self, other: &Duration) -> Option { + self.0.checked_add(*other).map(|d| Instant(d)) } pub fn sub_duration(&self, other: &Duration) -> Instant { @@ -47,10 +47,6 @@ impl SystemTime { self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) } - pub fn add_duration(&self, other: &Duration) -> SystemTime { - SystemTime(self.0 + *other) - } - pub fn checked_add_duration(&self, other: &Duration) -> Option { self.0.checked_add(*other).map(|d| SystemTime(d)) } diff --git a/src/libstd/sys/windows/time.rs b/src/libstd/sys/windows/time.rs index c809a0b98ac..cad36627bf3 100644 --- a/src/libstd/sys/windows/time.rs +++ b/src/libstd/sys/windows/time.rs @@ -68,17 +68,15 @@ impl Instant { Duration::new(nanos / NANOS_PER_SEC, (nanos % NANOS_PER_SEC) as u32) } - pub fn add_duration(&self, other: &Duration) -> Instant { + pub fn checked_add_duration(&self, other: &Duration) -> Option { let freq = frequency() as u64; - let t = other.as_secs().checked_mul(freq).and_then(|i| { - (self.t as u64).checked_add(i) - }).and_then(|i| { - i.checked_add(mul_div_u64(other.subsec_nanos() as u64, freq, - NANOS_PER_SEC)) - }).expect("overflow when adding duration to time"); - Instant { + let t = other.as_secs() + .checked_mul(freq)? + .checked_add(mul_div_u64(other.subsec_nanos() as u64, freq, NANOS_PER_SEC))? + .checked_add(self.t as u64)?; + Some(Instant { t: t as c::LARGE_INTEGER, - } + }) } pub fn sub_duration(&self, other: &Duration) -> Instant { @@ -86,8 +84,7 @@ impl Instant { let t = other.as_secs().checked_mul(freq).and_then(|i| { (self.t as u64).checked_sub(i) }).and_then(|i| { - i.checked_sub(mul_div_u64(other.subsec_nanos() as u64, freq, - NANOS_PER_SEC)) + i.checked_sub(mul_div_u64(other.subsec_nanos() as u64, freq, NANOS_PER_SEC)) }).expect("overflow when subtracting duration from time"); Instant { t: t as c::LARGE_INTEGER, @@ -127,10 +124,6 @@ impl SystemTime { } } - pub fn add_duration(&self, other: &Duration) -> SystemTime { - self.checked_add_duration(other).expect("overflow when adding duration to time") - } - pub fn checked_add_duration(&self, other: &Duration) -> Option { checked_dur2intervals(other) .and_then(|d| self.intervals().checked_add(d)) @@ -184,11 +177,12 @@ impl Hash for SystemTime { } } -fn checked_dur2intervals(d: &Duration) -> Option { - d.as_secs() - .checked_mul(INTERVALS_PER_SEC) - .and_then(|i| i.checked_add(d.subsec_nanos() as u64 / 100)) - .and_then(|i| i.try_into().ok()) +fn checked_dur2intervals(dur: &Duration) -> Option { + dur.as_secs() + .checked_mul(INTERVALS_PER_SEC)? + .checked_add(dur.subsec_nanos() as u64 / 100)? + .try_into() + .ok() } fn dur2intervals(d: &Duration) -> i64 { diff --git a/src/libstd/time.rs b/src/libstd/time.rs index 667810485ee..a0703fd50d5 100644 --- a/src/libstd/time.rs +++ b/src/libstd/time.rs @@ -208,6 +208,14 @@ impl Instant { pub fn elapsed(&self) -> Duration { Instant::now() - *self } + + /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as + /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` + /// otherwise. + #[unstable(feature = "time_checked_add", issue = "55940")] + pub fn checked_add(&self, duration: Duration) -> Option { + self.0.checked_add_duration(&duration).map(|t| Instant(t)) + } } #[stable(feature = "time2", since = "1.8.0")] @@ -215,7 +223,8 @@ impl Add for Instant { type Output = Instant; fn add(self, other: Duration) -> Instant { - Instant(self.0.add_duration(&other)) + self.checked_add(other) + .expect("overflow when adding duration to instant") } } @@ -372,7 +381,8 @@ impl Add for SystemTime { type Output = SystemTime; fn add(self, dur: Duration) -> SystemTime { - SystemTime(self.0.add_duration(&dur)) + self.checked_add(dur) + .expect("overflow when adding duration to instant") } } @@ -521,6 +531,19 @@ mod tests { let second = Duration::new(1, 0); assert_almost_eq!(a - second + second, a); + + // checked_add_duration will not panic on overflow + let mut maybe_t = Some(Instant::now()); + let max_duration = Duration::from_secs(u64::max_value()); + // in case `Instant` can store `>= now + max_duration`. + for _ in 0..2 { + maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration)); + } + assert_eq!(maybe_t, None); + + // checked_add_duration calculates the right time and will work for another year + let year = Duration::from_secs(60 * 60 * 24 * 365); + assert_eq!(a + year, a.checked_add(year).unwrap()); } #[test] -- cgit 1.4.1-3-g733a5 From f5a99c321b14e69e9d9a6ffaac3a5b7b8906c1f2 Mon Sep 17 00:00:00 2001 From: Linus Färnstrand Date: Mon, 10 Dec 2018 23:55:53 +0100 Subject: Add checked_sub for Instant and SystemTime --- src/libstd/sys/cloudabi/time.rs | 37 ++++++++++++------------------- src/libstd/sys/redox/time.rs | 24 ++++++++++----------- src/libstd/sys/unix/time.rs | 48 ++++++++++++++++++----------------------- src/libstd/sys/wasm/time.rs | 12 +++++------ src/libstd/sys/windows/time.rs | 25 ++++++++------------- src/libstd/time.rs | 24 +++++++++++++++++++-- 6 files changed, 83 insertions(+), 87 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/cloudabi/time.rs b/src/libstd/sys/cloudabi/time.rs index fdd172a896c..6f023230a27 100644 --- a/src/libstd/sys/cloudabi/time.rs +++ b/src/libstd/sys/cloudabi/time.rs @@ -25,11 +25,6 @@ fn checked_dur2intervals(dur: &Duration) -> Option { .checked_add(dur.subsec_nanos() as abi::timestamp) } -pub fn dur2intervals(dur: &Duration) -> abi::timestamp { - checked_dur2intervals(dur) - .expect("overflow converting duration to nanoseconds") -} - impl Instant { pub fn now() -> Instant { unsafe { @@ -48,17 +43,15 @@ impl Instant { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - checked_dur2intervals(other)? - .checked_add(self.t) - .map(|t| Instant {t}) + Some(Instant { + t: self.t.checked_add(checked_dur2intervals(other)?)?, + }) } - pub fn sub_duration(&self, other: &Duration) -> Instant { - Instant { - t: self.t - .checked_sub(dur2intervals(other)) - .expect("overflow when subtracting duration from instant"), - } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(Instant { + t: self.t.checked_sub(checked_dur2intervals(other)?)?, + }) } } @@ -94,17 +87,15 @@ impl SystemTime { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - checked_dur2intervals(other) - .and_then(|d| self.t.checked_add(d)) - .map(|t| SystemTime {t}) + Some(SystemTime { + t: self.t.checked_add(checked_dur2intervals(other)?)?, + }) } - pub fn sub_duration(&self, other: &Duration) -> SystemTime { - SystemTime { - t: self.t - .checked_sub(dur2intervals(other)) - .expect("overflow when subtracting duration from instant"), - } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(SystemTime { + t: self.t.checked_sub(checked_dur2intervals(other)?)?, + }) } } diff --git a/src/libstd/sys/redox/time.rs b/src/libstd/sys/redox/time.rs index 5ba8b780727..cb2eab52211 100644 --- a/src/libstd/sys/redox/time.rs +++ b/src/libstd/sys/redox/time.rs @@ -63,27 +63,25 @@ impl Timespec { }) } - fn sub_duration(&self, other: &Duration) -> Timespec { + fn checked_sub_duration(&self, other: &Duration) -> Option { let mut secs = other .as_secs() .try_into() // <- target type would be `i64` .ok() - .and_then(|secs| self.t.tv_sec.checked_sub(secs)) - .expect("overflow when subtracting duration from time"); + .and_then(|secs| self.t.tv_sec.checked_sub(secs))?; // Similar to above, nanos can't overflow. let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32; if nsec < 0 { nsec += NSEC_PER_SEC as i32; - secs = secs.checked_sub(1).expect("overflow when subtracting \ - duration from time"); + secs = secs.checked_sub(1)?; } - Timespec { + Some(Timespec { t: syscall::TimeSpec { tv_sec: secs, tv_nsec: nsec as i32, }, - } + }) } } @@ -147,11 +145,11 @@ impl Instant { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.t.checked_add_duration(other).map(|t| Instant { t }) + Some(Instant { t: self.t.checked_add_duration(other)? }) } - pub fn sub_duration(&self, other: &Duration) -> Instant { - Instant { t: self.t.sub_duration(other) } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(Instant { t: self.t.checked_sub_duration(other)? }) } } @@ -175,11 +173,11 @@ impl SystemTime { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.t.checked_add_duration(other).map(|t| SystemTime { t }) + Some(SystemTime { t: self.t.checked_add_duration(other)? }) } - pub fn sub_duration(&self, other: &Duration) -> SystemTime { - SystemTime { t: self.t.sub_duration(other) } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(SystemTime { t: self.t.checked_sub_duration(other)? }) } } diff --git a/src/libstd/sys/unix/time.rs b/src/libstd/sys/unix/time.rs index 81ef0f48833..8f8aaa88b22 100644 --- a/src/libstd/sys/unix/time.rs +++ b/src/libstd/sys/unix/time.rs @@ -64,27 +64,25 @@ impl Timespec { }) } - fn sub_duration(&self, other: &Duration) -> Timespec { + fn checked_sub_duration(&self, other: &Duration) -> Option { let mut secs = other .as_secs() .try_into() // <- target type would be `libc::time_t` .ok() - .and_then(|secs| self.t.tv_sec.checked_sub(secs)) - .expect("overflow when subtracting duration from time"); + .and_then(|secs| self.t.tv_sec.checked_sub(secs))?; // Similar to above, nanos can't overflow. let mut nsec = self.t.tv_nsec as i32 - other.subsec_nanos() as i32; if nsec < 0 { nsec += NSEC_PER_SEC as i32; - secs = secs.checked_sub(1).expect("overflow when subtracting \ - duration from time"); + secs = secs.checked_sub(1)?; } - Timespec { + Some(Timespec { t: libc::timespec { tv_sec: secs, tv_nsec: nsec as _, }, - } + }) } } @@ -162,14 +160,15 @@ mod inner { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - checked_dur2intervals(other)?.checked_add(self.t).map(|t| Instant {t}) + Some(Instant { + t: self.t.checked_add(checked_dur2intervals(other)?)?, + }) } - pub fn sub_duration(&self, other: &Duration) -> Instant { - Instant { - t: self.t.checked_sub(dur2intervals(other)) - .expect("overflow when subtracting duration from instant"), - } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(Instant { + t: self.t.checked_sub(checked_dur2intervals(other)?)?, + }) } } @@ -193,11 +192,11 @@ mod inner { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.t.checked_add_duration(other).map(|t| SystemTime { t }) + Some(SystemTime { t: self.t.checked_add_duration(other)? }) } - pub fn sub_duration(&self, other: &Duration) -> SystemTime { - SystemTime { t: self.t.sub_duration(other) } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(SystemTime { t: self.t.checked_sub_duration(other)? }) } } @@ -225,11 +224,6 @@ mod inner { } } - fn dur2intervals(dur: &Duration) -> u64 { - checked_dur2intervals(dur) - .expect("overflow converting duration to nanoseconds") - } - fn checked_dur2intervals(dur: &Duration) -> Option { let nanos = dur.as_secs() .checked_mul(NSEC_PER_SEC)? @@ -294,11 +288,11 @@ mod inner { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.t.checked_add_duration(other).map(|t| Instant { t }) + Some(Instant { t: self.t.checked_add_duration(other)? }) } - pub fn sub_duration(&self, other: &Duration) -> Instant { - Instant { t: self.t.sub_duration(other) } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(Instant { t: self.t.checked_sub_duration(other)? }) } } @@ -322,11 +316,11 @@ mod inner { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.t.checked_add_duration(other).map(|t| SystemTime { t }) + Some(SystemTime { t: self.t.checked_add_duration(other)? }) } - pub fn sub_duration(&self, other: &Duration) -> SystemTime { - SystemTime { t: self.t.sub_duration(other) } + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(SystemTime { t: self.t.checked_sub_duration(other)? }) } } diff --git a/src/libstd/sys/wasm/time.rs b/src/libstd/sys/wasm/time.rs index 20cd870919c..cc56773e0ea 100644 --- a/src/libstd/sys/wasm/time.rs +++ b/src/libstd/sys/wasm/time.rs @@ -29,11 +29,11 @@ impl Instant { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.0.checked_add(*other).map(|d| Instant(d)) + Some(Instant(self.0.checked_add(*other)?)) } - pub fn sub_duration(&self, other: &Duration) -> Instant { - Instant(self.0 - *other) + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(Instant(self.0.checked_sub(*other)?)) } } @@ -48,10 +48,10 @@ impl SystemTime { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.0.checked_add(*other).map(|d| SystemTime(d)) + Some(SystemTime(self.0.checked_add(*other)?)) } - pub fn sub_duration(&self, other: &Duration) -> SystemTime { - SystemTime(self.0 - *other) + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(SystemTime(self.0.checked_sub(*other)?)) } } diff --git a/src/libstd/sys/windows/time.rs b/src/libstd/sys/windows/time.rs index cad36627bf3..bb2c97ea149 100644 --- a/src/libstd/sys/windows/time.rs +++ b/src/libstd/sys/windows/time.rs @@ -79,16 +79,16 @@ impl Instant { }) } - pub fn sub_duration(&self, other: &Duration) -> Instant { + pub fn checked_sub_duration(&self, other: &Duration) -> Option { let freq = frequency() as u64; let t = other.as_secs().checked_mul(freq).and_then(|i| { (self.t as u64).checked_sub(i) }).and_then(|i| { i.checked_sub(mul_div_u64(other.subsec_nanos() as u64, freq, NANOS_PER_SEC)) - }).expect("overflow when subtracting duration from time"); - Instant { + })?; + Some(Instant { t: t as c::LARGE_INTEGER, - } + }) } } @@ -125,15 +125,13 @@ impl SystemTime { } pub fn checked_add_duration(&self, other: &Duration) -> Option { - checked_dur2intervals(other) - .and_then(|d| self.intervals().checked_add(d)) - .map(|i| SystemTime::from_intervals(i)) + let intervals = self.intervals().checked_add(checked_dur2intervals(other)?)?; + Some(SystemTime::from_intervals(intervals)) } - pub fn sub_duration(&self, other: &Duration) -> SystemTime { - let intervals = self.intervals().checked_sub(dur2intervals(other)) - .expect("overflow when subtracting from time"); - SystemTime::from_intervals(intervals) + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + let intervals = self.intervals().checked_sub(checked_dur2intervals(other)?)?; + Some(SystemTime::from_intervals(intervals)) } } @@ -185,11 +183,6 @@ fn checked_dur2intervals(dur: &Duration) -> Option { .ok() } -fn dur2intervals(d: &Duration) -> i64 { - checked_dur2intervals(d) - .expect("overflow when converting duration to intervals") -} - fn intervals2dur(intervals: u64) -> Duration { Duration::new(intervals / INTERVALS_PER_SEC, ((intervals % INTERVALS_PER_SEC) * 100) as u32) diff --git a/src/libstd/time.rs b/src/libstd/time.rs index a0703fd50d5..63cede79e48 100644 --- a/src/libstd/time.rs +++ b/src/libstd/time.rs @@ -216,6 +216,14 @@ impl Instant { pub fn checked_add(&self, duration: Duration) -> Option { self.0.checked_add_duration(&duration).map(|t| Instant(t)) } + + /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as + /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` + /// otherwise. + #[unstable(feature = "time_checked_add", issue = "55940")] + pub fn checked_sub(&self, duration: Duration) -> Option { + self.0.checked_sub_duration(&duration).map(|t| Instant(t)) + } } #[stable(feature = "time2", since = "1.8.0")] @@ -240,7 +248,8 @@ impl Sub for Instant { type Output = Instant; fn sub(self, other: Duration) -> Instant { - Instant(self.0.sub_duration(&other)) + self.checked_sub(other) + .expect("overflow when subtracting duration from instant") } } @@ -374,6 +383,14 @@ impl SystemTime { pub fn checked_add(&self, duration: Duration) -> Option { self.0.checked_add_duration(&duration).map(|t| SystemTime(t)) } + + /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as + /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None` + /// otherwise. + #[unstable(feature = "time_checked_add", issue = "55940")] + pub fn checked_sub(&self, duration: Duration) -> Option { + self.0.checked_sub_duration(&duration).map(|t| SystemTime(t)) + } } #[stable(feature = "time2", since = "1.8.0")] @@ -398,7 +415,8 @@ impl Sub for SystemTime { type Output = SystemTime; fn sub(self, dur: Duration) -> SystemTime { - SystemTime(self.0.sub_duration(&dur)) + self.checked_sub(dur) + .expect("overflow when subtracting duration from instant") } } @@ -531,6 +549,7 @@ mod tests { let second = Duration::new(1, 0); assert_almost_eq!(a - second + second, a); + assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a); // checked_add_duration will not panic on overflow let mut maybe_t = Some(Instant::now()); @@ -580,6 +599,7 @@ mod tests { .duration(), second); assert_almost_eq!(a - second + second, a); + assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a); // A difference of 80 and 800 years cannot fit inside a 32-bit time_t if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) { -- cgit 1.4.1-3-g733a5 From 9511fc7845f108e2af47f9c2b07544a63c2f1ec1 Mon Sep 17 00:00:00 2001 From: Linus Färnstrand Date: Tue, 11 Dec 2018 00:49:32 +0100 Subject: Fix checked_add/sub for sys/sgx/time.rs --- src/libstd/sys/sgx/time.rs | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/sgx/time.rs b/src/libstd/sys/sgx/time.rs index b01c992768e..196e1a97fc4 100644 --- a/src/libstd/sys/sgx/time.rs +++ b/src/libstd/sys/sgx/time.rs @@ -28,12 +28,12 @@ impl Instant { self.0 - other.0 } - pub fn add_duration(&self, other: &Duration) -> Instant { - Instant(self.0 + *other) + pub fn checked_add_duration(&self, other: &Duration) -> Option { + Some(Instant(self.0.checked_add(*other)?)) } - pub fn sub_duration(&self, other: &Duration) -> Instant { - Instant(self.0 - *other) + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(Instant(self.0.checked_sub(*other)?)) } } @@ -47,15 +47,11 @@ impl SystemTime { self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) } - pub fn add_duration(&self, other: &Duration) -> SystemTime { - SystemTime(self.0 + *other) - } - pub fn checked_add_duration(&self, other: &Duration) -> Option { - self.0.checked_add(*other).map(|d| SystemTime(d)) + Some(SystemTime(self.0.checked_add(*other)?)) } - pub fn sub_duration(&self, other: &Duration) -> SystemTime { - SystemTime(self.0 - *other) + pub fn checked_sub_duration(&self, other: &Duration) -> Option { + Some(SystemTime(self.0.checked_sub(*other)?)) } } -- cgit 1.4.1-3-g733a5 From 9e5e89a0d37b06e4f6915809b6a21409727acdc1 Mon Sep 17 00:00:00 2001 From: Linus Färnstrand Date: Thu, 13 Dec 2018 15:24:50 +0100 Subject: Fix dur2intervals import on cloudabi --- src/libstd/sys/cloudabi/condvar.rs | 6 ++++-- src/libstd/sys/cloudabi/thread.rs | 6 ++++-- src/libstd/sys/cloudabi/time.rs | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/cloudabi/condvar.rs b/src/libstd/sys/cloudabi/condvar.rs index ccf848a9be4..3229d98624e 100644 --- a/src/libstd/sys/cloudabi/condvar.rs +++ b/src/libstd/sys/cloudabi/condvar.rs @@ -13,7 +13,7 @@ use mem; use sync::atomic::{AtomicU32, Ordering}; use sys::cloudabi::abi; use sys::mutex::{self, Mutex}; -use sys::time::dur2intervals; +use sys::time::checked_dur2intervals; use time::Duration; extern "C" { @@ -114,6 +114,8 @@ impl Condvar { // Call into the kernel to wait on the condition variable. let condvar = self.condvar.get(); + let timeout = checked_dur2intervals(&dur) + .expect("overflow converting duration to nanoseconds"); let subscriptions = [ abi::subscription { type_: abi::eventtype::CONDVAR, @@ -132,7 +134,7 @@ impl Condvar { union: abi::subscription_union { clock: abi::subscription_clock { clock_id: abi::clockid::MONOTONIC, - timeout: dur2intervals(&dur), + timeout, ..mem::zeroed() }, }, diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs index a76e1fa3345..177321439d8 100644 --- a/src/libstd/sys/cloudabi/thread.rs +++ b/src/libstd/sys/cloudabi/thread.rs @@ -16,7 +16,7 @@ use libc; use mem; use ptr; use sys::cloudabi::abi; -use sys::time::dur2intervals; +use sys::time::checked_dur2intervals; use sys_common::thread::*; use time::Duration; @@ -70,13 +70,15 @@ impl Thread { } pub fn sleep(dur: Duration) { + let timeout = checked_dur2intervals(&dur) + .expect("overflow converting duration to nanoseconds"); unsafe { let subscription = abi::subscription { type_: abi::eventtype::CLOCK, union: abi::subscription_union { clock: abi::subscription_clock { clock_id: abi::clockid::MONOTONIC, - timeout: dur2intervals(&dur), + timeout, ..mem::zeroed() }, }, diff --git a/src/libstd/sys/cloudabi/time.rs b/src/libstd/sys/cloudabi/time.rs index 6f023230a27..c9fea18fda6 100644 --- a/src/libstd/sys/cloudabi/time.rs +++ b/src/libstd/sys/cloudabi/time.rs @@ -19,7 +19,7 @@ pub struct Instant { t: abi::timestamp, } -fn checked_dur2intervals(dur: &Duration) -> Option { +pub fn checked_dur2intervals(dur: &Duration) -> Option { dur.as_secs() .checked_mul(NSEC_PER_SEC)? .checked_add(dur.subsec_nanos() as abi::timestamp) -- cgit 1.4.1-3-g733a5 From 6b96827ae971cec1f1bf83245d8356481e76b644 Mon Sep 17 00:00:00 2001 From: Oliver Scherer Date: Fri, 14 Dec 2018 17:03:45 +0100 Subject: Remove dead code --- src/librustc_driver/lib.rs | 1 - src/libstd/rt.rs | 15 --------------- src/libstd/sys/cloudabi/thread.rs | 1 - src/libstd/sys/redox/thread.rs | 1 - src/libstd/sys/sgx/thread.rs | 1 - src/libstd/sys/unix/thread.rs | 21 --------------------- src/libstd/sys/wasm/thread.rs | 1 - src/libstd/sys/windows/thread.rs | 1 - 8 files changed, 42 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/librustc_driver/lib.rs b/src/librustc_driver/lib.rs index cec0f31819d..013085c156e 100644 --- a/src/librustc_driver/lib.rs +++ b/src/librustc_driver/lib.rs @@ -25,7 +25,6 @@ #![feature(rustc_diagnostic_macros)] #![feature(slice_sort_by_cached_key)] #![feature(set_stdio)] -#![feature(rustc_stack_internals)] #![feature(no_debug)] #![recursion_limit="256"] diff --git a/src/libstd/rt.rs b/src/libstd/rt.rs index 9e957bd87d7..fdaf2a821fa 100644 --- a/src/libstd/rt.rs +++ b/src/libstd/rt.rs @@ -73,18 +73,3 @@ fn lang_start { lang_start_internal(&move || main().report(), argc, argv) } - -/// Function used for reverting changes to the main stack before setrlimit(). -/// This is POSIX (non-Linux) specific and unlikely to be directly stabilized. -#[unstable(feature = "rustc_stack_internals", issue = "0")] -pub unsafe fn deinit_stack_guard() { - ::sys::thread::guard::deinit(); -} - -/// 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 = ::sys::thread::guard::init(); - ::sys_common::thread_info::reset_guard(main_guard); -} diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs index a76e1fa3345..54c79114be4 100644 --- a/src/libstd/sys/cloudabi/thread.rs +++ b/src/libstd/sys/cloudabi/thread.rs @@ -119,7 +119,6 @@ pub mod guard { pub unsafe fn init() -> Option { None } - pub unsafe fn deinit() {} } fn min_stack_size(_: *const libc::pthread_attr_t) -> usize { diff --git a/src/libstd/sys/redox/thread.rs b/src/libstd/sys/redox/thread.rs index ff861805382..ca014fd576b 100644 --- a/src/libstd/sys/redox/thread.rs +++ b/src/libstd/sys/redox/thread.rs @@ -92,5 +92,4 @@ pub mod guard { pub type Guard = !; pub unsafe fn current() -> Option { None } pub unsafe fn init() -> Option { None } - pub unsafe fn deinit() {} } diff --git a/src/libstd/sys/sgx/thread.rs b/src/libstd/sys/sgx/thread.rs index 9de12a5e6f1..9f3c4536cb5 100644 --- a/src/libstd/sys/sgx/thread.rs +++ b/src/libstd/sys/sgx/thread.rs @@ -97,5 +97,4 @@ pub mod guard { pub type Guard = !; pub unsafe fn current() -> Option { None } pub unsafe fn init() -> Option { None } - pub unsafe fn deinit() {} } diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs index 4ff060018ae..e0d2c620498 100644 --- a/src/libstd/sys/unix/thread.rs +++ b/src/libstd/sys/unix/thread.rs @@ -211,7 +211,6 @@ pub mod guard { pub type Guard = Range; pub unsafe fn current() -> Option { None } pub unsafe fn init() -> Option { None } - pub unsafe fn deinit() {} } @@ -355,26 +354,6 @@ pub mod guard { } } - pub unsafe fn deinit() { - if !cfg!(target_os = "linux") { - if let Some(stackaddr) = get_stack_start_aligned() { - // Remove the protection on the guard page. - // FIXME: we cannot unmap the page, because when we mmap() - // above it may be already mapped by the OS, which we can't - // detect from mmap()'s return value. If we unmap this page, - // it will lead to failure growing stack size on platforms like - // macOS. Instead, just restore the page to a writable state. - // This ain't Linux, so we probably don't need to care about - // execstack. - let result = mprotect(stackaddr, PAGE_SIZE, PROT_READ | PROT_WRITE); - - if result != 0 { - panic!("unable to reset the guard page"); - } - } - } - } - #[cfg(any(target_os = "macos", target_os = "bitrig", target_os = "openbsd", diff --git a/src/libstd/sys/wasm/thread.rs b/src/libstd/sys/wasm/thread.rs index 3d74ffdc14a..f9abb0b825a 100644 --- a/src/libstd/sys/wasm/thread.rs +++ b/src/libstd/sys/wasm/thread.rs @@ -68,7 +68,6 @@ pub mod guard { pub type Guard = !; pub unsafe fn current() -> Option { None } pub unsafe fn init() -> Option { None } - pub unsafe fn deinit() {} } cfg_if! { diff --git a/src/libstd/sys/windows/thread.rs b/src/libstd/sys/windows/thread.rs index 1a97dd10ced..621ae2fda58 100644 --- a/src/libstd/sys/windows/thread.rs +++ b/src/libstd/sys/windows/thread.rs @@ -98,5 +98,4 @@ pub mod guard { pub type Guard = !; pub unsafe fn current() -> Option { None } pub unsafe fn init() -> Option { None } - pub unsafe fn deinit() {} } -- cgit 1.4.1-3-g733a5 From 885cf2a2afd6da270287cfc3bfa651ac737d0378 Mon Sep 17 00:00:00 2001 From: Vardhan Thigle Date: Fri, 14 Dec 2018 18:38:15 +0530 Subject: Adding unwinding support for x86_64_fortanix_unknown_sgx target. --- src/libpanic_unwind/lib.rs | 2 +- .../spec/x86_64_fortanix_unknown_sgx.rs | 46 ++++--- src/libstd/sys/sgx/abi/entry.S | 8 ++ src/libstd/sys/sgx/rwlock.rs | 137 ++++++++++++++++++++- src/libunwind/lib.rs | 5 +- 5 files changed, 168 insertions(+), 30 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libpanic_unwind/lib.rs b/src/libpanic_unwind/lib.rs index 49f8a429126..cfe671c626b 100644 --- a/src/libpanic_unwind/lib.rs +++ b/src/libpanic_unwind/lib.rs @@ -62,7 +62,7 @@ cfg_if! { if #[cfg(target_os = "emscripten")] { #[path = "emcc.rs"] mod imp; - } else if #[cfg(any(target_arch = "wasm32", target_env = "sgx"))] { + } else if #[cfg(target_arch = "wasm32")] { #[path = "dummy.rs"] mod imp; } else if #[cfg(all(target_env = "msvc", target_arch = "aarch64"))] { diff --git a/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs b/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs index 5b6d8abc5ef..6a6aab2bea3 100644 --- a/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs +++ b/src/librustc_target/spec/x86_64_fortanix_unknown_sgx.rs @@ -10,28 +10,29 @@ use std::iter; -use super::{LinkerFlavor, Target, TargetOptions, PanicStrategy}; +use super::{LinkerFlavor, PanicStrategy, Target, TargetOptions}; pub fn target() -> Result { const PRE_LINK_ARGS: &[&str] = &[ "-Wl,--as-needed", "-Wl,-z,noexecstack", "-m64", - "-fuse-ld=gold", - "-nostdlib", - "-shared", - "-Wl,-e,sgx_entry", - "-Wl,-Bstatic", - "-Wl,--gc-sections", - "-Wl,-z,text", - "-Wl,-z,norelro", - "-Wl,--rosegment", - "-Wl,--no-undefined", - "-Wl,--error-unresolved-symbols", - "-Wl,--no-undefined-version", - "-Wl,-Bsymbolic", - "-Wl,--export-dynamic", + "-fuse-ld=gold", + "-nostdlib", + "-shared", + "-Wl,-e,sgx_entry", + "-Wl,-Bstatic", + "-Wl,--gc-sections", + "-Wl,-z,text", + "-Wl,-z,norelro", + "-Wl,--rosegment", + "-Wl,--no-undefined", + "-Wl,--error-unresolved-symbols", + "-Wl,--no-undefined-version", + "-Wl,-Bsymbolic", + "-Wl,--export-dynamic", ]; + const EXPORT_SYMBOLS: &[&str] = &[ "sgx_entry", "HEAP_BASE", @@ -41,19 +42,26 @@ pub fn target() -> Result { "ENCLAVE_SIZE", "CFGDATA_BASE", "DEBUG", + "EH_FRM_HDR_BASE", + "EH_FRM_HDR_SIZE", + "TEXT_BASE", + "TEXT_SIZE", ]; let opts = TargetOptions { dynamic_linking: false, executables: true, linker_is_gnu: true, max_atomic_width: Some(64), - panic_strategy: PanicStrategy::Abort, + panic_strategy: PanicStrategy::Unwind, cpu: "x86-64".into(), features: "+rdrnd,+rdseed".into(), position_independent_executables: true, - pre_link_args: iter::once( - (LinkerFlavor::Gcc, PRE_LINK_ARGS.iter().cloned().map(String::from).collect()) - ).collect(), + pre_link_args: iter::once(( + LinkerFlavor::Gcc, + PRE_LINK_ARGS.iter().cloned().map(String::from).collect(), + )) + .collect(), + post_link_objects: vec!["libunwind.a".into()], override_export_symbols: Some(EXPORT_SYMBOLS.iter().cloned().map(String::from).collect()), ..Default::default() }; diff --git a/src/libstd/sys/sgx/abi/entry.S b/src/libstd/sys/sgx/abi/entry.S index 4d5cc02e11e..49ede0674ce 100644 --- a/src/libstd/sys/sgx/abi/entry.S +++ b/src/libstd/sys/sgx/abi/entry.S @@ -56,6 +56,14 @@ IMAGE_BASE: globvar CFGDATA_BASE 8 /* Non-zero if debugging is enabled, zero otherwise */ globvar DEBUG 1 + /* The base address (relative to enclave start) of the enclave text section */ + globvar TEXT_BASE 8 + /* The size in bytes of enclacve text section */ + globvar TEXT_SIZE 8 + /* The base address (relative to enclave start) of the enclave EH_FRM_HDR section */ + globvar EH_FRM_HDR_BASE 8 + /* The size in bytes of enclacve EH_FRM_HDR section */ + globvar EH_FRM_HDR_SIZE 8 .Lreentry_panic_msg: .asciz "Re-entered panicked enclave!" diff --git a/src/libstd/sys/sgx/rwlock.rs b/src/libstd/sys/sgx/rwlock.rs index a1551dbb53b..d1af98bd4f5 100644 --- a/src/libstd/sys/sgx/rwlock.rs +++ b/src/libstd/sys/sgx/rwlock.rs @@ -9,14 +9,25 @@ // except according to those terms. use num::NonZeroUsize; +use slice; +use str; -use super::waitqueue::{WaitVariable, WaitQueue, SpinMutex, NotifiedTcs, try_lock_or_false}; +use super::waitqueue::{ + try_lock_or_false, NotifiedTcs, SpinMutex, SpinMutexGuard, WaitQueue, WaitVariable, +}; +use mem; pub struct RWLock { readers: SpinMutex>>, writer: SpinMutex>, } +// Below is to check at compile time, that RWLock has size of 128 bytes. +#[allow(dead_code)] +unsafe fn rw_lock_size_assert(r: RWLock) { + mem::transmute::(r); +} + //unsafe impl Send for RWLock {} //unsafe impl Sync for RWLock {} // FIXME @@ -24,7 +35,7 @@ impl RWLock { pub const fn new() -> RWLock { RWLock { readers: SpinMutex::new(WaitVariable::new(None)), - writer: SpinMutex::new(WaitVariable::new(false)) + writer: SpinMutex::new(WaitVariable::new(false)), } } @@ -89,9 +100,11 @@ impl RWLock { } #[inline] - pub unsafe fn read_unlock(&self) { - let mut rguard = self.readers.lock(); - let wguard = self.writer.lock(); + unsafe fn __read_unlock( + &self, + mut rguard: SpinMutexGuard>>, + wguard: SpinMutexGuard>, + ) { *rguard.lock_var_mut() = NonZeroUsize::new(rguard.lock_var().unwrap().get() - 1); if rguard.lock_var().is_some() { // There are other active readers @@ -107,9 +120,18 @@ impl RWLock { } #[inline] - pub unsafe fn write_unlock(&self) { + pub unsafe fn read_unlock(&self) { let rguard = self.readers.lock(); let wguard = self.writer.lock(); + self.__read_unlock(rguard, wguard); + } + + #[inline] + unsafe fn __write_unlock( + &self, + rguard: SpinMutexGuard>>, + wguard: SpinMutexGuard>, + ) { if let Err(mut wguard) = WaitQueue::notify_one(wguard) { // No writers waiting, release the write lock *wguard.lock_var_mut() = false; @@ -128,6 +150,109 @@ impl RWLock { } } + #[inline] + pub unsafe fn write_unlock(&self) { + let rguard = self.readers.lock(); + let wguard = self.writer.lock(); + self.__write_unlock(rguard, wguard); + } + + #[inline] + unsafe fn unlock(&self) { + let rguard = self.readers.lock(); + let wguard = self.writer.lock(); + if *wguard.lock_var() == true { + self.__write_unlock(rguard, wguard); + } else { + self.__read_unlock(rguard, wguard); + } + } + #[inline] pub unsafe fn destroy(&self) {} } + +const EINVAL: i32 = 22; + +#[no_mangle] +pub unsafe extern "C" fn __rust_rwlock_rdlock(p: *mut RWLock) -> i32 { + if p.is_null() { + return EINVAL; + } + (*p).read(); + return 0; +} + +#[no_mangle] +pub unsafe extern "C" fn __rust_rwlock_wrlock(p: *mut RWLock) -> i32 { + if p.is_null() { + return EINVAL; + } + (*p).write(); + return 0; +} +#[no_mangle] +pub unsafe extern "C" fn __rust_rwlock_unlock(p: *mut RWLock) -> i32 { + if p.is_null() { + return EINVAL; + } + (*p).unlock(); + return 0; +} + +#[no_mangle] +pub unsafe extern "C" fn __rust_print_err(m: *mut u8, s: i32) { + if s < 0 { + return; + } + let buf = slice::from_raw_parts(m as *const u8, s as _); + if let Ok(s) = str::from_utf8(&buf[..buf.iter().position(|&b| b == 0).unwrap_or(buf.len())]) { + eprint!("{}", s); + } +} + +#[no_mangle] +pub unsafe extern "C" fn __rust_abort() { + ::sys::abort_internal(); +} + +#[cfg(test)] +mod tests { + + use super::*; + use core::array::FixedSizeArray; + use mem::MaybeUninit; + use {mem, ptr}; + + // The below test verifies that the bytes of initialized RWLock are the ones + // we use in libunwind. + // If they change we need to update src/UnwindRustSgx.h in libunwind. + #[test] + fn test_c_rwlock_initializer() { + const RWLOCK_INIT: &[u8] = &[ + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, + ]; + + let mut init = MaybeUninit::::zeroed(); + init.set(RWLock::new()); + assert_eq!( + mem::transmute::<_, [u8; 128]>(init.into_inner()).as_slice(), + RWLOCK_INIT + ); + } +} diff --git a/src/libunwind/lib.rs b/src/libunwind/lib.rs index eb53332ab33..954eb9d6d03 100644 --- a/src/libunwind/lib.rs +++ b/src/libunwind/lib.rs @@ -26,10 +26,7 @@ mod macros; cfg_if! { if #[cfg(target_env = "msvc")] { // no extra unwinder support needed - } else if #[cfg(any( - all(target_arch = "wasm32", not(target_os = "emscripten")), - target_env = "sgx" - ))] { + } else if #[cfg(all(target_arch = "wasm32", not(target_os = "emscripten")))] { // no unwinder on the system! } else { extern crate libc; -- cgit 1.4.1-3-g733a5 From cc53f4e9f48747d44718bb1b51e549437edae916 Mon Sep 17 00:00:00 2001 From: Adrian Budau Date: Wed, 19 Dec 2018 16:13:43 +0200 Subject: Fix pipe2 and accept4 on static linked executables on linux (like musl). --- src/libstd/lib.rs | 1 + src/libstd/sys/unix/net.rs | 25 ++++++++++++---------- src/libstd/sys/unix/pipe.rs | 30 ++++++++++++-------------- src/libstd/sys/unix/weak.rs | 52 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 27 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index ead38f21126..9042cb3c72d 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -250,6 +250,7 @@ #![feature(cfg_target_vendor)] #![feature(char_error_internals)] #![feature(compiler_builtins_lib)] +#![feature(concat_idents)] #![feature(const_int_ops)] #![feature(const_ip)] #![feature(const_raw_ptr_deref)] diff --git a/src/libstd/sys/unix/net.rs b/src/libstd/sys/unix/net.rs index d922be520d4..f30817e69ab 100644 --- a/src/libstd/sys/unix/net.rs +++ b/src/libstd/sys/unix/net.rs @@ -203,18 +203,21 @@ impl Socket { // Linux. This was added in 2.6.28, however, and because we support // 2.6.18 we must detect this support dynamically. if cfg!(target_os = "linux") { - weak! { - fn accept4(c_int, *mut sockaddr, *mut socklen_t, c_int) -> c_int + syscall! { + fn accept4( + fd: c_int, + addr: *mut sockaddr, + addr_len: *mut socklen_t, + flags: c_int + ) -> c_int } - if let Some(accept) = accept4.get() { - let res = cvt_r(|| unsafe { - accept(self.0.raw(), storage, len, SOCK_CLOEXEC) - }); - match res { - Ok(fd) => return Ok(Socket(FileDesc::new(fd))), - Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} - Err(e) => return Err(e), - } + let res = cvt_r(|| unsafe { + accept4(self.0.raw(), storage, len, SOCK_CLOEXEC) + }); + match res { + Ok(fd) => return Ok(Socket(FileDesc::new(fd))), + Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => {} + Err(e) => return Err(e), } } diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs index 0a5dccdddda..24b2959a3fa 100644 --- a/src/libstd/sys/unix/pipe.rs +++ b/src/libstd/sys/unix/pipe.rs @@ -22,7 +22,7 @@ use sys::{cvt, cvt_r}; pub struct AnonPipe(FileDesc); pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { - weak! { fn pipe2(*mut c_int, c_int) -> c_int } + syscall! { fn pipe2(fds: *mut c_int, flags: c_int) -> c_int } static INVALID: AtomicBool = ATOMIC_BOOL_INIT; let mut fds = [0; 2]; @@ -39,22 +39,20 @@ pub fn anon_pipe() -> io::Result<(AnonPipe, AnonPipe)> { !INVALID.load(Ordering::SeqCst) { - if let Some(pipe) = pipe2.get() { - // Note that despite calling a glibc function here we may still - // get ENOSYS. Glibc has `pipe2` since 2.9 and doesn't try to - // emulate on older kernels, so if you happen to be running on - // an older kernel you may see `pipe2` as a symbol but still not - // see the syscall. - match cvt(unsafe { pipe(fds.as_mut_ptr(), libc::O_CLOEXEC) }) { - Ok(_) => { - return Ok((AnonPipe(FileDesc::new(fds[0])), - AnonPipe(FileDesc::new(fds[1])))); - } - Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { - INVALID.store(true, Ordering::SeqCst); - } - Err(e) => return Err(e), + // Note that despite calling a glibc function here we may still + // get ENOSYS. Glibc has `pipe2` since 2.9 and doesn't try to + // emulate on older kernels, so if you happen to be running on + // an older kernel you may see `pipe2` as a symbol but still not + // see the syscall. + match cvt(unsafe { pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }) { + Ok(_) => { + return Ok((AnonPipe(FileDesc::new(fds[0])), + AnonPipe(FileDesc::new(fds[1])))); + } + Err(ref e) if e.raw_os_error() == Some(libc::ENOSYS) => { + INVALID.store(true, Ordering::SeqCst); } + Err(e) => return Err(e), } } cvt(unsafe { libc::pipe(fds.as_mut_ptr()) })?; diff --git a/src/libstd/sys/unix/weak.rs b/src/libstd/sys/unix/weak.rs index 18944be58ee..3b73e3b7c50 100644 --- a/src/libstd/sys/unix/weak.rs +++ b/src/libstd/sys/unix/weak.rs @@ -77,3 +77,55 @@ unsafe fn fetch(name: &str) -> usize { }; libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) as usize } + +#[cfg(not(target_os = "linux"))] +macro_rules! syscall { + (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( + unsafe fn $name($($arg_name: $t),*) -> $ret { + use libc; + + weak! { fn $name($($t),*) -> $ret } + + if let Some(fun) = $name.get() { + fun($($arg_name),*) + } else { + libc::ENOSYS + } + } + ) +} + +#[cfg(target_os = "linux")] +macro_rules! syscall { + (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( + unsafe fn $name($($arg_name:$t),*) -> $ret { + // This like a hack, but concat_idents only accepts idents + // (not paths). + use libc::*; + + syscall( + concat_idents!(SYS_, $name), + $(::sys::weak::SyscallParam::to_param($arg_name)),* + ) as $ret + } + ) +} + +#[cfg(target_os = "linux")] +pub trait SyscallParam { + fn to_param(self) -> libc::c_long; +} + +#[cfg(target_os = "linux")] +impl SyscallParam for libc::c_int { + fn to_param(self) -> libc::c_long { + self as libc::c_long + } +} + +#[cfg(target_os = "linux")] +impl SyscallParam for *mut T { + fn to_param(self) -> libc::c_long { + unsafe { mem::transmute(self) } + } +} -- cgit 1.4.1-3-g733a5 From da47bd3ae01f9a651b652bb141685b128c5058b0 Mon Sep 17 00:00:00 2001 From: Adrian Budau Date: Thu, 20 Dec 2018 13:29:04 +0200 Subject: Fix typo in comment --- src/libstd/sys/unix/weak.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/unix/weak.rs b/src/libstd/sys/unix/weak.rs index 3b73e3b7c50..ab75a39eecc 100644 --- a/src/libstd/sys/unix/weak.rs +++ b/src/libstd/sys/unix/weak.rs @@ -99,7 +99,7 @@ macro_rules! syscall { macro_rules! syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( unsafe fn $name($($arg_name:$t),*) -> $ret { - // This like a hack, but concat_idents only accepts idents + // This looks like a hack, but concat_idents only accepts idents // (not paths). use libc::*; -- cgit 1.4.1-3-g733a5 From bf172c532af44628e3c3323a5f8a8c1726ffbd30 Mon Sep 17 00:00:00 2001 From: Adrian Budau Date: Fri, 21 Dec 2018 15:53:37 +0200 Subject: Properly report ENOSYS by modifying errno --- src/libstd/sys/unix/os.rs | 15 ++++++++++++++- src/libstd/sys/unix/weak.rs | 25 ++++--------------------- 2 files changed, 18 insertions(+), 22 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/unix/os.rs b/src/libstd/sys/unix/os.rs index 03e81a720dc..6e8ee445994 100644 --- a/src/libstd/sys/unix/os.rs +++ b/src/libstd/sys/unix/os.rs @@ -67,7 +67,8 @@ pub fn errno() -> i32 { } /// Sets the platform-specific value of errno -#[cfg(any(target_os = "solaris", target_os = "fuchsia"))] // only needed for readdir so far +#[cfg(all(not(target_os = "linux"), + not(target_os = "dragonfly")))] // needed for readdir and syscall! pub fn set_errno(e: i32) { unsafe { *errno_location() = e as c_int @@ -84,6 +85,18 @@ pub fn errno() -> i32 { unsafe { errno as i32 } } +#[cfg(target_os = "dragonfly")] +pub fn set_errno(e: i32) { + extern { + #[thread_local] + static mut errno: c_int; + } + + unsafe { + errno = e; + } +} + /// Gets a detailed string description for the given error number. pub fn error_string(errno: i32) -> String { extern { diff --git a/src/libstd/sys/unix/weak.rs b/src/libstd/sys/unix/weak.rs index ab75a39eecc..7d293f1c47a 100644 --- a/src/libstd/sys/unix/weak.rs +++ b/src/libstd/sys/unix/weak.rs @@ -83,13 +83,15 @@ macro_rules! syscall { (fn $name:ident($($arg_name:ident: $t:ty),*) -> $ret:ty) => ( unsafe fn $name($($arg_name: $t),*) -> $ret { use libc; + use super::os; weak! { fn $name($($t),*) -> $ret } if let Some(fun) = $name.get() { fun($($arg_name),*) } else { - libc::ENOSYS + os::set_errno(libc::ENOSYS); + -1 } } ) @@ -105,27 +107,8 @@ macro_rules! syscall { syscall( concat_idents!(SYS_, $name), - $(::sys::weak::SyscallParam::to_param($arg_name)),* + $($arg_name as c_long),* ) as $ret } ) } - -#[cfg(target_os = "linux")] -pub trait SyscallParam { - fn to_param(self) -> libc::c_long; -} - -#[cfg(target_os = "linux")] -impl SyscallParam for libc::c_int { - fn to_param(self) -> libc::c_long { - self as libc::c_long - } -} - -#[cfg(target_os = "linux")] -impl SyscallParam for *mut T { - fn to_param(self) -> libc::c_long { - unsafe { mem::transmute(self) } - } -} -- cgit 1.4.1-3-g733a5