From 380dd7d47b574697fe87ef00ad5ffcbb6651c501 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Thu, 15 Nov 2018 16:41:06 +0100 Subject: Add rc::Weak.ptr_eq --- src/liballoc/rc.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) (limited to 'src/liballoc') diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 705345ce963..064b3180d4c 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -1260,6 +1260,52 @@ impl Weak { Some(unsafe { self.ptr.as_ref() }) } } + + /// Returns true if the two `Weak`s point to the same value (not just values + /// that compare as equal). + /// + /// # Notes + /// + /// Since this compares pointers it means that `Weak::new()` will equal each + /// other, even though they don't point to any value. + /// + /// # Examples + /// + /// ``` + /// #![feature(weak_ptr_eq)] + /// use std::rc::{Rc, Weak}; + /// + /// let first_rc = Rc::new(5); + /// let first = Rc::downgrade(&first_rc); + /// let second = Rc::downgrade(&first_rc); + /// + /// assert!(Weak::ptr_eq(&first, &second)); + /// + /// let third_rc = Rc::new(5); + /// let third = Rc::downgrade(&third_rc); + /// + /// assert!(!Weak::ptr_eq(&first, &third)); + /// ``` + /// + /// Comparing `Weak::new`. + /// + /// ``` + /// #![feature(weak_ptr_eq)] + /// use std::rc::{Rc, Weak}; + /// + /// let first = Weak::new(); + /// let second = Weak::new(); + /// assert!(Weak::ptr_eq(&first, &second)); + /// + /// let third_rc = Rc::new(()); + /// let third = Rc::downgrade(&third_rc); + /// assert!(!Weak::ptr_eq(&first, &third)); + /// ``` + #[inline] + #[unstable(feature = "weak_ptr_eq", issue = "55981")] + pub fn ptr_eq(this: &Self, other: &Self) -> bool { + this.ptr.as_ptr() == other.ptr.as_ptr() + } } #[stable(feature = "rc_weak", since = "1.4.0")] -- cgit 1.4.1-3-g733a5 From d4b41fa0313ace66d5f4e5d4a6201cd3aa81b87d Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Thu, 15 Nov 2018 20:24:02 +0100 Subject: Add sync::Weak::ptr_eq --- src/liballoc/sync.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'src/liballoc') diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index 4f4031e3c4e..0a397f79103 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -1130,6 +1130,53 @@ impl Weak { Some(unsafe { self.ptr.as_ref() }) } } + + /// Returns true if the two `Weak`s point to the same value (not just values + /// that compare as equal). + /// + /// # Notes + /// + /// Since this compares pointers it means that `Weak::new()` will equal each + /// other, even though they don't point to any value. + /// + /// + /// # Examples + /// + /// ``` + /// #![feature(weak_ptr_eq)] + /// use std::sync::{Arc, Weak}; + /// + /// let first_rc = Arc::new(5); + /// let first = Arc::downgrade(&first_rc); + /// let second = Arc::downgrade(&first_rc); + /// + /// assert!(Weak::ptr_eq(&first, &second)); + /// + /// let third_rc = Arc::new(5); + /// let third = Arc::downgrade(&third_rc); + /// + /// assert!(!Weak::ptr_eq(&first, &third)); + /// ``` + /// + /// Comparing `Weak::new`. + /// + /// ``` + /// #![feature(weak_ptr_eq)] + /// use std::sync::{Arc, Weak}; + /// + /// let first = Weak::new(); + /// let second = Weak::new(); + /// assert!(Weak::ptr_eq(&first, &second)); + /// + /// let third_rc = Arc::new(()); + /// let third = Arc::downgrade(&third_rc); + /// assert!(!Weak::ptr_eq(&first, &third)); + /// ``` + #[inline] + #[unstable(feature = "weak_ptr_eq", issue = "55981")] + pub fn ptr_eq(this: &Self, other: &Self) -> bool { + this.ptr.as_ptr() == other.ptr.as_ptr() + } } #[stable(feature = "arc_weak", since = "1.4.0")] -- cgit 1.4.1-3-g733a5 From 38e21f92f1c09a597788062045b1e1d8c879e4f2 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Fri, 23 Nov 2018 12:26:13 +0100 Subject: Fix link in Weak::new --- src/liballoc/rc.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/liballoc') diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 064b3180d4c..d81b8a1974d 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -1187,8 +1187,9 @@ impl, U: ?Sized> DispatchFromDyn> for Weak {} impl Weak { /// Constructs a new `Weak`, without allocating any memory. - /// Calling [`upgrade`][Weak::upgrade] on the return value always gives [`None`]. + /// Calling [`upgrade`] on the return value always gives [`None`]. /// + /// [`upgrade`]: #method.upgrade /// [`None`]: ../../std/option/enum.Option.html /// /// # Examples -- cgit 1.4.1-3-g733a5 From ae532730215f1e74b175d1aa214146e9d900e5fd Mon Sep 17 00:00:00 2001 From: ljedrz Date: Mon, 3 Dec 2018 16:22:27 +0100 Subject: slice: tweak concat & join --- src/liballoc/slice.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 22da9dd6e96..e012d56f48b 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -589,7 +589,7 @@ impl> SliceConcatExt for [V] { type Output = Vec; fn concat(&self) -> Vec { - let size = self.iter().fold(0, |acc, v| acc + v.borrow().len()); + let size = self.iter().map(|slice| slice.borrow().len()).sum(); let mut result = Vec::with_capacity(size); for v in self { result.extend_from_slice(v.borrow()) @@ -603,8 +603,8 @@ impl> SliceConcatExt for [V] { Some(first) => first, None => return vec![], }; - let size = self.iter().fold(0, |acc, v| acc + v.borrow().len()); - let mut result = Vec::with_capacity(size + self.len()); + let size = self.iter().map(|slice| slice.borrow().len()).sum::() + self.len() - 1; + let mut result = Vec::with_capacity(size); result.extend_from_slice(first.borrow()); for v in iter { -- cgit 1.4.1-3-g733a5 From d0c64bb29631fc5e5fafbe88374e7e1325b70ba5 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Tue, 4 Dec 2018 12:46:10 +0100 Subject: cleanup: remove static lifetimes from consts --- src/liballoc/string.rs | 2 +- src/libcore/fmt/mod.rs | 2 +- src/libcore/unicode/printable.rs | 12 +++---- src/librustc/dep_graph/dep_node.rs | 2 +- src/librustc/hir/print.rs | 2 +- src/librustc/ich/mod.rs | 16 ++++----- src/librustc/session/config.rs | 43 +++++++++++------------ src/librustc/session/filesearch.rs | 8 ++--- src/librustc/util/common.rs | 2 +- src/librustc_codegen_ssa/back/symbol_export.rs | 2 +- src/librustc_codegen_utils/symbol_names.rs | 2 +- src/librustc_incremental/assert_module_sources.rs | 6 ++-- src/librustc_incremental/persist/file_format.rs | 4 +-- src/librustc_incremental/persist/fs.rs | 8 ++--- src/librustc_metadata/schema.rs | 2 +- src/librustc_mir/dataflow/graphviz.rs | 4 +-- src/librustc_mir/diagnostics.rs | 8 ++--- src/librustc_mir/util/pretty.rs | 2 +- src/librustc_target/spec/mod.rs | 2 +- src/libsyntax/feature_gate.rs | 35 +++++++++--------- src/libsyntax/parse/attr.rs | 4 +-- src/libsyntax/parse/lexer/unicode_chars.rs | 2 +- src/libsyntax_ext/asm.rs | 2 +- src/libsyntax_ext/global_asm.rs | 2 +- src/libsyntax_ext/proc_macro_decls.rs | 3 +- src/libsyntax_pos/edition.rs | 2 +- 26 files changed, 88 insertions(+), 91 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs index 662f8ae614f..acc1f9b306e 100644 --- a/src/liballoc/string.rs +++ b/src/liballoc/string.rs @@ -577,7 +577,7 @@ impl String { return Cow::Borrowed(""); }; - const REPLACEMENT: &'static str = "\u{FFFD}"; + const REPLACEMENT: &str = "\u{FFFD}"; let mut res = String::with_capacity(v.len()); res.push_str(first_valid); diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 75ec0d7d50b..0c5256b981e 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -1381,7 +1381,7 @@ impl<'a> Formatter<'a> { for part in formatted.parts { match *part { flt2dec::Part::Zero(mut nzeroes) => { - const ZEROES: &'static str = // 64 zeroes + const ZEROES: &str = // 64 zeroes "0000000000000000000000000000000000000000000000000000000000000000"; while nzeroes > ZEROES.len() { self.buf.write_str(ZEROES)?; diff --git a/src/libcore/unicode/printable.rs b/src/libcore/unicode/printable.rs index 519dd17bb9b..32e4b6b0fa5 100644 --- a/src/libcore/unicode/printable.rs +++ b/src/libcore/unicode/printable.rs @@ -80,7 +80,7 @@ pub(crate) fn is_printable(x: char) -> bool { } } -const SINGLETONS0U: &'static [(u8, u8)] = &[ +const SINGLETONS0U: &[(u8, u8)] = &[ (0x00, 1), (0x03, 5), (0x05, 6), @@ -122,7 +122,7 @@ const SINGLETONS0U: &'static [(u8, u8)] = &[ (0xfe, 3), (0xff, 9), ]; -const SINGLETONS0L: &'static [u8] = &[ +const SINGLETONS0L: &[u8] = &[ 0xad, 0x78, 0x79, 0x8b, 0x8d, 0xa2, 0x30, 0x57, 0x58, 0x8b, 0x8c, 0x90, 0x1c, 0x1d, 0xdd, 0x0e, 0x0f, 0x4b, 0x4c, 0xfb, 0xfc, 0x2e, 0x2f, 0x3f, @@ -162,7 +162,7 @@ const SINGLETONS0L: &'static [u8] = &[ 0x91, 0xfe, 0xff, 0x53, 0x67, 0x75, 0xc8, 0xc9, 0xd0, 0xd1, 0xd8, 0xd9, 0xe7, 0xfe, 0xff, ]; -const SINGLETONS1U: &'static [(u8, u8)] = &[ +const SINGLETONS1U: &[(u8, u8)] = &[ (0x00, 6), (0x01, 1), (0x03, 1), @@ -197,7 +197,7 @@ const SINGLETONS1U: &'static [(u8, u8)] = &[ (0xf0, 4), (0xf9, 4), ]; -const SINGLETONS1L: &'static [u8] = &[ +const SINGLETONS1L: &[u8] = &[ 0x0c, 0x27, 0x3b, 0x3e, 0x4e, 0x4f, 0x8f, 0x9e, 0x9e, 0x9f, 0x06, 0x07, 0x09, 0x36, 0x3d, 0x3e, 0x56, 0xf3, 0xd0, 0xd1, 0x04, 0x14, 0x18, 0x36, @@ -219,7 +219,7 @@ const SINGLETONS1L: &'static [u8] = &[ 0x78, 0x7d, 0x7f, 0x8a, 0xa4, 0xaa, 0xaf, 0xb0, 0xc0, 0xd0, 0x3f, 0x71, 0x72, 0x7b, ]; -const NORMAL0: &'static [u8] = &[ +const NORMAL0: &[u8] = &[ 0x00, 0x20, 0x5f, 0x22, 0x82, 0xdf, 0x04, @@ -363,7 +363,7 @@ const NORMAL0: &'static [u8] = &[ 0x1b, 0x03, 0x0f, 0x0d, ]; -const NORMAL1: &'static [u8] = &[ +const NORMAL1: &[u8] = &[ 0x5e, 0x22, 0x7b, 0x05, 0x03, 0x04, diff --git a/src/librustc/dep_graph/dep_node.rs b/src/librustc/dep_graph/dep_node.rs index 388bbc52c3b..a20d04972fd 100644 --- a/src/librustc/dep_graph/dep_node.rs +++ b/src/librustc/dep_graph/dep_node.rs @@ -381,7 +381,7 @@ macro_rules! define_dep_nodes { #[allow(dead_code, non_upper_case_globals)] pub mod label_strs { $( - pub const $variant: &'static str = stringify!($variant); + pub const $variant: &str = stringify!($variant); )* } ); diff --git a/src/librustc/hir/print.rs b/src/librustc/hir/print.rs index 9a0ceddcf1b..113a2377ac9 100644 --- a/src/librustc/hir/print.rs +++ b/src/librustc/hir/print.rs @@ -65,7 +65,7 @@ pub trait PpAnn { pub struct NoAnn; impl PpAnn for NoAnn {} -pub const NO_ANN: &'static dyn PpAnn = &NoAnn; +pub const NO_ANN: &dyn PpAnn = &NoAnn; impl PpAnn for hir::Crate { fn try_fetch_item(&self, item: ast::NodeId) -> Option<&hir::Item> { diff --git a/src/librustc/ich/mod.rs b/src/librustc/ich/mod.rs index 9751c560acd..fc2f1ee6ff8 100644 --- a/src/librustc/ich/mod.rs +++ b/src/librustc/ich/mod.rs @@ -24,15 +24,15 @@ mod impls_misc; mod impls_ty; mod impls_syntax; -pub const ATTR_DIRTY: &'static str = "rustc_dirty"; -pub const ATTR_CLEAN: &'static str = "rustc_clean"; -pub const ATTR_IF_THIS_CHANGED: &'static str = "rustc_if_this_changed"; -pub const ATTR_THEN_THIS_WOULD_NEED: &'static str = "rustc_then_this_would_need"; -pub const ATTR_PARTITION_REUSED: &'static str = "rustc_partition_reused"; -pub const ATTR_PARTITION_CODEGENED: &'static str = "rustc_partition_codegened"; -pub const ATTR_EXPECTED_CGU_REUSE: &'static str = "rustc_expected_cgu_reuse"; +pub const ATTR_DIRTY: &str = "rustc_dirty"; +pub const ATTR_CLEAN: &str = "rustc_clean"; +pub const ATTR_IF_THIS_CHANGED: &str = "rustc_if_this_changed"; +pub const ATTR_THEN_THIS_WOULD_NEED: &str = "rustc_then_this_would_need"; +pub const ATTR_PARTITION_REUSED: &str = "rustc_partition_reused"; +pub const ATTR_PARTITION_CODEGENED: &str = "rustc_partition_codegened"; +pub const ATTR_EXPECTED_CGU_REUSE: &str = "rustc_expected_cgu_reuse"; -pub const IGNORED_ATTRIBUTES: &'static [&'static str] = &[ +pub const IGNORED_ATTRIBUTES: &[&str] = &[ "cfg", ATTR_IF_THIS_CHANGED, ATTR_THEN_THIS_WOULD_NEED, diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 480d4a8e48f..e8b280fb3d8 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -780,43 +780,42 @@ macro_rules! options { } pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool; - pub const $stat: &'static [(&'static str, $setter_name, - Option<&'static str>, &'static str)] = + pub const $stat: &[(&str, $setter_name, Option<&str>, &str)] = &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ]; #[allow(non_upper_case_globals, dead_code)] mod $mod_desc { - pub const parse_bool: Option<&'static str> = None; - pub const parse_opt_bool: Option<&'static str> = + pub const parse_bool: Option<&str> = None; + pub const parse_opt_bool: Option<&str> = Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`"); - pub const parse_string: Option<&'static str> = Some("a string"); - pub const parse_string_push: Option<&'static str> = Some("a string"); - pub const parse_pathbuf_push: Option<&'static str> = Some("a path"); - pub const parse_opt_string: Option<&'static str> = Some("a string"); - pub const parse_opt_pathbuf: Option<&'static str> = Some("a path"); - pub const parse_list: Option<&'static str> = Some("a space-separated list of strings"); - pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings"); - pub const parse_uint: Option<&'static str> = Some("a number"); - pub const parse_passes: Option<&'static str> = + pub const parse_string: Option<&str> = Some("a string"); + pub const parse_string_push: Option<&str> = Some("a string"); + pub const parse_pathbuf_push: Option<&str> = Some("a path"); + pub const parse_opt_string: Option<&str> = Some("a string"); + pub const parse_opt_pathbuf: Option<&str> = Some("a path"); + pub const parse_list: Option<&str> = Some("a space-separated list of strings"); + pub const parse_opt_list: Option<&str> = Some("a space-separated list of strings"); + pub const parse_uint: Option<&str> = Some("a number"); + pub const parse_passes: Option<&str> = Some("a space-separated list of passes, or `all`"); - pub const parse_opt_uint: Option<&'static str> = + pub const parse_opt_uint: Option<&str> = Some("a number"); - pub const parse_panic_strategy: Option<&'static str> = + pub const parse_panic_strategy: Option<&str> = Some("either `unwind` or `abort`"); - pub const parse_relro_level: Option<&'static str> = + pub const parse_relro_level: Option<&str> = Some("one of: `full`, `partial`, or `off`"); - pub const parse_sanitizer: Option<&'static str> = + pub const parse_sanitizer: Option<&str> = Some("one of: `address`, `leak`, `memory` or `thread`"); - pub const parse_linker_flavor: Option<&'static str> = + pub const parse_linker_flavor: Option<&str> = Some(::rustc_target::spec::LinkerFlavor::one_of()); - pub const parse_optimization_fuel: Option<&'static str> = + pub const parse_optimization_fuel: Option<&str> = Some("crate=integer"); - pub const parse_unpretty: Option<&'static str> = + pub const parse_unpretty: Option<&str> = Some("`string` or `string=string`"); - pub const parse_lto: Option<&'static str> = + pub const parse_lto: Option<&str> = Some("either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, \ `fat`, or omitted"); - pub const parse_cross_lang_lto: Option<&'static str> = + pub const parse_cross_lang_lto: Option<&str> = Some("either a boolean (`yes`, `no`, `on`, `off`, etc), \ or the path to the linker plugin"); } diff --git a/src/librustc/session/filesearch.rs b/src/librustc/session/filesearch.rs index f410c270bce..e686a1d1275 100644 --- a/src/librustc/session/filesearch.rs +++ b/src/librustc/session/filesearch.rs @@ -179,12 +179,12 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> { // "lib" (i.e. non-default), this value is used (see issue #16552). #[cfg(target_pointer_width = "64")] - const PRIMARY_LIB_DIR: &'static str = "lib64"; + const PRIMARY_LIB_DIR: &str = "lib64"; #[cfg(target_pointer_width = "32")] - const PRIMARY_LIB_DIR: &'static str = "lib32"; + const PRIMARY_LIB_DIR: &str = "lib32"; - const SECONDARY_LIB_DIR: &'static str = "lib"; + const SECONDARY_LIB_DIR: &str = "lib"; match option_env!("CFG_LIBDIR_RELATIVE") { Some(libdir) if libdir != "lib" => libdir.into(), @@ -198,4 +198,4 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> { // The name of rustc's own place to organize libraries. // Used to be "rustc", now the default is "rustlib" -const RUST_LIB_DIR: &'static str = "rustlib"; +const RUST_LIB_DIR: &str = "rustlib"; diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 7a246af82e5..c6ba20de0d3 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -28,7 +28,7 @@ use lazy_static; use session::Session; // The name of the associated type for `Fn` return types -pub const FN_OUTPUT_NAME: &'static str = "Output"; +pub const FN_OUTPUT_NAME: &str = "Output"; // Useful type to use with `Result<>` indicate that an error has already // been reported to the user, so no need to continue checking. diff --git a/src/librustc_codegen_ssa/back/symbol_export.rs b/src/librustc_codegen_ssa/back/symbol_export.rs index 0fb2641a4f8..23b35b2e416 100644 --- a/src/librustc_codegen_ssa/back/symbol_export.rs +++ b/src/librustc_codegen_ssa/back/symbol_export.rs @@ -225,7 +225,7 @@ fn exported_symbols_provider_local<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // These are weak symbols that point to the profile version and the // profile name, which need to be treated as exported so LTO doesn't nix // them. - const PROFILER_WEAK_SYMBOLS: [&'static str; 2] = [ + const PROFILER_WEAK_SYMBOLS: [&str; 2] = [ "__llvm_profile_raw_version", "__llvm_profile_filename", ]; diff --git a/src/librustc_codegen_utils/symbol_names.rs b/src/librustc_codegen_utils/symbol_names.rs index 344a2525784..611d7b137c6 100644 --- a/src/librustc_codegen_utils/symbol_names.rs +++ b/src/librustc_codegen_utils/symbol_names.rs @@ -389,7 +389,7 @@ impl SymbolPathBuffer { impl ItemPathBuffer for SymbolPathBuffer { fn root_mode(&self) -> &RootMode { - const ABSOLUTE: &'static RootMode = &RootMode::Absolute; + const ABSOLUTE: &RootMode = &RootMode::Absolute; ABSOLUTE } diff --git a/src/librustc_incremental/assert_module_sources.rs b/src/librustc_incremental/assert_module_sources.rs index 4ff2529b26d..17ac9a6b539 100644 --- a/src/librustc_incremental/assert_module_sources.rs +++ b/src/librustc_incremental/assert_module_sources.rs @@ -40,9 +40,9 @@ use syntax::ast; use rustc::ich::{ATTR_PARTITION_REUSED, ATTR_PARTITION_CODEGENED, ATTR_EXPECTED_CGU_REUSE}; -const MODULE: &'static str = "module"; -const CFG: &'static str = "cfg"; -const KIND: &'static str = "kind"; +const MODULE: &str = "module"; +const CFG: &str = "cfg"; +const KIND: &str = "kind"; pub fn assert_module_sources<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) { tcx.dep_graph.with_ignore(|| { diff --git a/src/librustc_incremental/persist/file_format.rs b/src/librustc_incremental/persist/file_format.rs index 98f7873fda0..e5faba61782 100644 --- a/src/librustc_incremental/persist/file_format.rs +++ b/src/librustc_incremental/persist/file_format.rs @@ -28,7 +28,7 @@ use rustc::session::config::nightly_options; use rustc_serialize::opaque::Encoder; /// The first few bytes of files generated by incremental compilation -const FILE_MAGIC: &'static [u8] = b"RSIC"; +const FILE_MAGIC: &[u8] = b"RSIC"; /// Change this if the header format changes const HEADER_FORMAT_VERSION: u16 = 0; @@ -36,7 +36,7 @@ const HEADER_FORMAT_VERSION: u16 = 0; /// A version string that hopefully is always different for compiler versions /// with different encodings of incremental compilation artifacts. Contains /// the git commit hash. -const RUSTC_VERSION: Option<&'static str> = option_env!("CFG_VERSION"); +const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION"); pub fn write_file_header(stream: &mut Encoder) { stream.emit_raw_bytes(FILE_MAGIC); diff --git a/src/librustc_incremental/persist/fs.rs b/src/librustc_incremental/persist/fs.rs index 75cdefaf49f..bc98798f772 100644 --- a/src/librustc_incremental/persist/fs.rs +++ b/src/librustc_incremental/persist/fs.rs @@ -128,10 +128,10 @@ use std::time::{UNIX_EPOCH, SystemTime, Duration}; use rand::{RngCore, thread_rng}; -const LOCK_FILE_EXT: &'static str = ".lock"; -const DEP_GRAPH_FILENAME: &'static str = "dep-graph.bin"; -const WORK_PRODUCTS_FILENAME: &'static str = "work-products.bin"; -const QUERY_CACHE_FILENAME: &'static str = "query-cache.bin"; +const LOCK_FILE_EXT: &str = ".lock"; +const DEP_GRAPH_FILENAME: &str = "dep-graph.bin"; +const WORK_PRODUCTS_FILENAME: &str = "work-products.bin"; +const QUERY_CACHE_FILENAME: &str = "query-cache.bin"; // We encode integers using the following base, so they are shorter than decimal // or hexadecimal numbers (we want short file and directory names). Since these diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs index e91d15b78c0..fc3af6cf2e7 100644 --- a/src/librustc_metadata/schema.rs +++ b/src/librustc_metadata/schema.rs @@ -52,7 +52,7 @@ pub const METADATA_VERSION: u8 = 4; /// This header is followed by the position of the `CrateRoot`, /// which is encoded as a 32-bit big-endian unsigned integer, /// and further followed by the rustc version string. -pub const METADATA_HEADER: &'static [u8; 12] = +pub const METADATA_HEADER: &[u8; 12] = &[0, 0, 0, 0, b'r', b'u', b's', b't', 0, 0, 0, METADATA_VERSION]; /// A value of type T referred to by its absolute position diff --git a/src/librustc_mir/dataflow/graphviz.rs b/src/librustc_mir/dataflow/graphviz.rs index 6896c91352f..f6a9d46b5e2 100644 --- a/src/librustc_mir/dataflow/graphviz.rs +++ b/src/librustc_mir/dataflow/graphviz.rs @@ -137,8 +137,8 @@ where MWF: MirWithFlowState<'tcx>, block: BasicBlock, mir: &Mir) -> io::Result<()> { // Header rows - const HDRS: [&'static str; 4] = ["ENTRY", "MIR", "BLOCK GENS", "BLOCK KILLS"]; - const HDR_FMT: &'static str = "bgcolor=\"grey\""; + const HDRS: [&str; 4] = ["ENTRY", "MIR", "BLOCK GENS", "BLOCK KILLS"]; + const HDR_FMT: &str = "bgcolor=\"grey\""; write!(w, "")?; diff --git a/src/librustc_mir/diagnostics.rs b/src/librustc_mir/diagnostics.rs index 56a9daf84f7..ec5617d7052 100644 --- a/src/librustc_mir/diagnostics.rs +++ b/src/librustc_mir/diagnostics.rs @@ -606,7 +606,7 @@ static X: i32 = 1; const C: i32 = 2; // these three are not allowed: -const CR: &'static mut i32 = &mut C; +const CR: &mut i32 = &mut C; static STATIC_REF: &'static mut i32 = &mut X; static CONST_REF: &'static mut i32 = &mut C; ``` @@ -1163,7 +1163,7 @@ You can also have this error while using a cell type: use std::cell::Cell; const A: Cell = Cell::new(1); -const B: &'static Cell = &A; +const B: &Cell = &A; // error: cannot borrow a constant which may contain interior mutability, // create a static instead @@ -1171,10 +1171,10 @@ const B: &'static Cell = &A; struct C { a: Cell } const D: C = C { a: Cell::new(1) }; -const E: &'static Cell = &D.a; // error +const E: &Cell = &D.a; // error // or: -const F: &'static C = &D; // error +const F: &C = &D; // error ``` This is because cell types do operations that are not thread-safe. Due to this, diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index c74492fe649..2d7e7d01274 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -24,7 +24,7 @@ use std::path::{Path, PathBuf}; use super::graphviz::write_mir_fn_graphviz; use transform::MirSource; -const INDENT: &'static str = " "; +const INDENT: &str = " "; /// Alignment for lining up comments following MIR statements pub(crate) const ALIGN: usize = 40; diff --git a/src/librustc_target/spec/mod.rs b/src/librustc_target/spec/mod.rs index 5b8070cbf3d..5830fa00be8 100644 --- a/src/librustc_target/spec/mod.rs +++ b/src/librustc_target/spec/mod.rs @@ -234,7 +234,7 @@ macro_rules! supported_targets { $(mod $module;)* /// List of supported targets - const TARGETS: &'static [&'static str] = &[$($triple),*]; + const TARGETS: &[&str] = &[$($triple),*]; fn load_specific(target: &str) -> TargetResult { match target { diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index fac7ff2bf34..f41de99001a 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -53,8 +53,7 @@ macro_rules! declare_features { /// Represents active features that are currently being implemented or /// currently being considered for addition/removal. const ACTIVE_FEATURES: - &'static [(&'static str, &'static str, Option, - Option, fn(&mut Features, Span))] = + &[(&str, &str, Option, Option, fn(&mut Features, Span))] = &[$((stringify!($feature), $ver, $issue, $edition, set!($feature))),+]; /// A set of features to be used by later passes. @@ -769,7 +768,7 @@ pub fn is_builtin_attr(attr: &ast::Attribute) -> bool { } // Attributes that have a special meaning to rustc or rustdoc -pub const BUILTIN_ATTRIBUTES: &'static [(&'static str, AttributeType, AttributeGate)] = &[ +pub const BUILTIN_ATTRIBUTES: &[(&str, AttributeType, AttributeGate)] = &[ // Normal attributes ("warn", Normal, Ungated), @@ -1383,48 +1382,48 @@ fn leveled_feature_err<'a>(sess: &'a ParseSess, feature: &str, span: Span, issue } -const EXPLAIN_BOX_SYNTAX: &'static str = +const EXPLAIN_BOX_SYNTAX: &str = "box expression syntax is experimental; you can call `Box::new` instead."; -pub const EXPLAIN_STMT_ATTR_SYNTAX: &'static str = +pub const EXPLAIN_STMT_ATTR_SYNTAX: &str = "attributes on expressions are experimental."; -pub const EXPLAIN_ASM: &'static str = +pub const EXPLAIN_ASM: &str = "inline assembly is not stable enough for use and is subject to change"; -pub const EXPLAIN_GLOBAL_ASM: &'static str = +pub const EXPLAIN_GLOBAL_ASM: &str = "`global_asm!` is not stable enough for use and is subject to change"; -pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &'static str = +pub const EXPLAIN_CUSTOM_TEST_FRAMEWORKS: &str = "custom test frameworks are an unstable feature"; -pub const EXPLAIN_LOG_SYNTAX: &'static str = +pub const EXPLAIN_LOG_SYNTAX: &str = "`log_syntax!` is not stable enough for use and is subject to change"; -pub const EXPLAIN_CONCAT_IDENTS: &'static str = +pub const EXPLAIN_CONCAT_IDENTS: &str = "`concat_idents` is not stable enough for use and is subject to change"; -pub const EXPLAIN_FORMAT_ARGS_NL: &'static str = +pub const EXPLAIN_FORMAT_ARGS_NL: &str = "`format_args_nl` is only for internal language use and is subject to change"; -pub const EXPLAIN_TRACE_MACROS: &'static str = +pub const EXPLAIN_TRACE_MACROS: &str = "`trace_macros` is not stable enough for use and is subject to change"; -pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &'static str = +pub const EXPLAIN_ALLOW_INTERNAL_UNSTABLE: &str = "allow_internal_unstable side-steps feature gating and stability checks"; -pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &'static str = +pub const EXPLAIN_ALLOW_INTERNAL_UNSAFE: &str = "allow_internal_unsafe side-steps the unsafe_code lint"; -pub const EXPLAIN_CUSTOM_DERIVE: &'static str = +pub const EXPLAIN_CUSTOM_DERIVE: &str = "`#[derive]` for custom traits is deprecated and will be removed in the future."; -pub const EXPLAIN_DEPR_CUSTOM_DERIVE: &'static str = +pub const EXPLAIN_DEPR_CUSTOM_DERIVE: &str = "`#[derive]` for custom traits is deprecated and will be removed in the future. \ Prefer using procedural macro custom derive."; -pub const EXPLAIN_DERIVE_UNDERSCORE: &'static str = +pub const EXPLAIN_DERIVE_UNDERSCORE: &str = "attributes of the form `#[derive_*]` are reserved for the compiler"; -pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &'static str = +pub const EXPLAIN_UNSIZED_TUPLE_COERCION: &str = "unsized tuple coercion is not stable enough for use and is subject to change"; struct PostExpansionVisitor<'a> { diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index a240604bfe0..4ff6048e821 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -22,8 +22,8 @@ enum InnerAttributeParsePolicy<'a> { NotPermitted { reason: &'a str }, } -const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &'static str = "an inner attribute is not \ - permitted in this context"; +const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \ + permitted in this context"; impl<'a> Parser<'a> { /// Parse attributes that appear before an item diff --git a/src/libsyntax/parse/lexer/unicode_chars.rs b/src/libsyntax/parse/lexer/unicode_chars.rs index 03bf1b5a4e1..8a620c8067d 100644 --- a/src/libsyntax/parse/lexer/unicode_chars.rs +++ b/src/libsyntax/parse/lexer/unicode_chars.rs @@ -306,7 +306,7 @@ const UNICODE_ARRAY: &[(char, &str, char)] = &[ ('>', "Fullwidth Greater-Than Sign", '>'), ]; -const ASCII_ARRAY: &'static [(char, &'static str)] = &[ +const ASCII_ARRAY: &[(char, &str)] = &[ (' ', "Space"), ('_', "Underscore"), ('-', "Minus/Hyphen"), diff --git a/src/libsyntax_ext/asm.rs b/src/libsyntax_ext/asm.rs index 026ddccd7be..2ff9fb487c4 100644 --- a/src/libsyntax_ext/asm.rs +++ b/src/libsyntax_ext/asm.rs @@ -47,7 +47,7 @@ impl State { } } -const OPTIONS: &'static [&'static str] = &["volatile", "alignstack", "intel"]; +const OPTIONS: &[&str] = &["volatile", "alignstack", "intel"]; pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, diff --git a/src/libsyntax_ext/global_asm.rs b/src/libsyntax_ext/global_asm.rs index 1130a50537d..000bede7348 100644 --- a/src/libsyntax_ext/global_asm.rs +++ b/src/libsyntax_ext/global_asm.rs @@ -28,7 +28,7 @@ use syntax::symbol::Symbol; use syntax_pos::Span; use syntax::tokenstream; -pub const MACRO: &'static str = "global_asm"; +pub const MACRO: &str = "global_asm"; pub fn expand_global_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, diff --git a/src/libsyntax_ext/proc_macro_decls.rs b/src/libsyntax_ext/proc_macro_decls.rs index c859275ed02..f4ff0989b5d 100644 --- a/src/libsyntax_ext/proc_macro_decls.rs +++ b/src/libsyntax_ext/proc_macro_decls.rs @@ -30,8 +30,7 @@ use syntax_pos::{Span, DUMMY_SP}; use deriving; -const PROC_MACRO_KINDS: [&'static str; 3] = - ["proc_macro_derive", "proc_macro_attribute", "proc_macro"]; +const PROC_MACRO_KINDS: [&str; 3] = ["proc_macro_derive", "proc_macro_attribute", "proc_macro"]; struct ProcMacroDerive { trait_name: ast::Name, diff --git a/src/libsyntax_pos/edition.rs b/src/libsyntax_pos/edition.rs index 5819cd7f480..54b24054401 100644 --- a/src/libsyntax_pos/edition.rs +++ b/src/libsyntax_pos/edition.rs @@ -33,7 +33,7 @@ pub enum Edition { // must be in order from oldest to newest pub const ALL_EDITIONS: &[Edition] = &[Edition::Edition2015, Edition::Edition2018]; -pub const EDITION_NAME_LIST: &'static str = "2015|2018"; +pub const EDITION_NAME_LIST: &str = "2015|2018"; pub const DEFAULT_EDITION: Edition = Edition::Edition2015; -- cgit 1.4.1-3-g733a5 From c025d6140999e07ddf0294f0676c64ff2322a210 Mon Sep 17 00:00:00 2001 From: Corey Farwell Date: Tue, 4 Dec 2018 11:17:58 -0800 Subject: Replace usages of `..i + 1` ranges with `..=i`. --- src/liballoc/collections/vec_deque.rs | 18 +++++++++--------- src/liballoc/tests/binary_heap.rs | 4 ++-- src/liballoc/tests/btree/map.rs | 4 ++-- src/liballoc/tests/str.rs | 2 +- src/liballoc/tests/vec_deque.rs | 8 ++++---- src/librustc/hir/map/hir_id_validator.rs | 2 +- src/librustc/mir/mod.rs | 2 +- src/librustc_apfloat/ieee.rs | 4 ++-- src/librustc_errors/emitter.rs | 6 +++--- src/librustc_incremental/persist/fs.rs | 2 +- .../borrow_check/nll/region_infer/values.rs | 2 +- src/librustc_mir/build/matches/mod.rs | 2 +- src/librustc_resolve/lib.rs | 2 +- src/librustdoc/html/render.rs | 2 +- src/libstd/collections/hash/map.rs | 4 ++-- src/libstd/io/buffered.rs | 2 +- src/libstd/io/mod.rs | 2 +- src/libstd/sys/windows/process.rs | 2 +- src/libsyntax/util/lev_distance.rs | 2 +- 19 files changed, 36 insertions(+), 36 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs index c8ee40f3d27..c0adeca4eb5 100644 --- a/src/liballoc/collections/vec_deque.rs +++ b/src/liballoc/collections/vec_deque.rs @@ -2795,7 +2795,7 @@ mod tests { // 0, 1, 2, .., len - 1 let expected = (0..).take(len).collect::>(); for tail_pos in 0..cap { - for to_remove in 0..len + 1 { + for to_remove in 0..=len { tester.tail = tail_pos; tester.head = tail_pos; for i in 0..len { @@ -2821,10 +2821,10 @@ mod tests { let mut tester: VecDeque = VecDeque::with_capacity(7); let cap = tester.capacity(); - for len in 0..cap + 1 { - for tail in 0..cap + 1 { - for drain_start in 0..len + 1 { - for drain_end in drain_start..len + 1 { + for len in 0..=cap { + for tail in 0..=cap { + for drain_start in 0..=len { + for drain_end in drain_start..=len { tester.tail = tail; tester.head = tail; for i in 0..len { @@ -2866,10 +2866,10 @@ mod tests { tester.reserve(63); let max_cap = tester.capacity(); - for len in 0..cap + 1 { + for len in 0..=cap { // 0, 1, 2, .., len - 1 let expected = (0..).take(len).collect::>(); - for tail_pos in 0..max_cap + 1 { + for tail_pos in 0..=max_cap { tester.tail = tail_pos; tester.head = tail_pos; tester.reserve(63); @@ -2899,7 +2899,7 @@ mod tests { // len is the length *before* splitting for len in 0..cap { // index to split at - for at in 0..len + 1 { + for at in 0..=len { // 0, 1, 2, .., at - 1 (may be empty) let expected_self = (0..).take(at).collect::>(); // at, at + 1, .., len - 1 (may be empty) @@ -2927,7 +2927,7 @@ mod tests { fn test_from_vec() { use vec::Vec; for cap in 0..35 { - for len in 0..cap + 1 { + for len in 0..=cap { let mut vec = Vec::with_capacity(cap); vec.extend(0..len); diff --git a/src/liballoc/tests/binary_heap.rs b/src/liballoc/tests/binary_heap.rs index 8494463463c..b0d8fa6bd69 100644 --- a/src/liballoc/tests/binary_heap.rs +++ b/src/liballoc/tests/binary_heap.rs @@ -318,11 +318,11 @@ fn panic_safe() { const NTEST: usize = 10; // don't use 0 in the data -- we want to catch the zeroed-out case. - let data = (1..DATASZ + 1).collect::>(); + let data = (1..=DATASZ).collect::>(); // since it's a fuzzy test, run several tries. for _ in 0..NTEST { - for i in 1..DATASZ + 1 { + for i in 1..=DATASZ { DROP_COUNTER.store(0, Ordering::SeqCst); let mut panic_ords: Vec<_> = data.iter() diff --git a/src/liballoc/tests/btree/map.rs b/src/liballoc/tests/btree/map.rs index 6ebdb86cc4a..33ef13ab811 100644 --- a/src/liballoc/tests/btree/map.rs +++ b/src/liballoc/tests/btree/map.rs @@ -302,7 +302,7 @@ fn test_range() { for i in 0..size { for j in i..size { let mut kvs = map.range((Included(&i), Included(&j))).map(|(&k, &v)| (k, v)); - let mut pairs = (i..j + 1).map(|i| (i, i)); + let mut pairs = (i..=j).map(|i| (i, i)); for (kv, pair) in kvs.by_ref().zip(pairs.by_ref()) { assert_eq!(kv, pair); @@ -321,7 +321,7 @@ fn test_range_mut() { for i in 0..size { for j in i..size { let mut kvs = map.range_mut((Included(&i), Included(&j))).map(|(&k, &mut v)| (k, v)); - let mut pairs = (i..j + 1).map(|i| (i, i)); + let mut pairs = (i..=j).map(|i| (i, i)); for (kv, pair) in kvs.by_ref().zip(pairs.by_ref()) { assert_eq!(kv, pair); diff --git a/src/liballoc/tests/str.rs b/src/liballoc/tests/str.rs index a5fa7f0c4d9..494b36f8541 100644 --- a/src/liballoc/tests/str.rs +++ b/src/liballoc/tests/str.rs @@ -1378,7 +1378,7 @@ fn test_bool_from_str() { fn check_contains_all_substrings(s: &str) { assert!(s.contains("")); for i in 0..s.len() { - for j in i+1..s.len() + 1 { + for j in i+1..=s.len() { assert!(s.contains(&s[i..j])); } } diff --git a/src/liballoc/tests/vec_deque.rs b/src/liballoc/tests/vec_deque.rs index 3ea6c87a651..1f2a7211c65 100644 --- a/src/liballoc/tests/vec_deque.rs +++ b/src/liballoc/tests/vec_deque.rs @@ -861,7 +861,7 @@ fn test_as_slices() { ring.push_back(i); let (left, right) = ring.as_slices(); - let expected: Vec<_> = (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 180dcc3118998ebbe390f876df51f85f1b33407a Mon Sep 17 00:00:00 2001 From: Nathan West Date: Wed, 5 Dec 2018 14:37:38 -0800 Subject: Optimized string FromIterator impls --- src/liballoc/string.rs | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs index 662f8ae614f..ef9a34ec611 100644 --- a/src/liballoc/string.rs +++ b/src/liballoc/string.rs @@ -1732,18 +1732,31 @@ impl<'a> FromIterator<&'a str> for String { #[stable(feature = "extend_string", since = "1.4.0")] impl FromIterator for String { fn from_iter>(iter: I) -> String { - let mut buf = String::new(); - buf.extend(iter); - buf + let iterator = iter.into_iter(); + + match iterator.next() { + None => String::new(), + Some(buf) => { + buf.extend(iterator); + buf + } + } } } #[stable(feature = "herd_cows", since = "1.19.0")] impl<'a> FromIterator> for String { fn from_iter>>(iter: I) -> String { - let mut buf = String::new(); - buf.extend(iter); - buf + let iterator = iter.into_iter(); + + match iterator.next() { + None => String::new(), + Some(cow) => { + let buf = cow.into_owned(); + buf.extend(iterator); + buf + } + } } } @@ -1753,9 +1766,7 @@ impl Extend for String { let iterator = iter.into_iter(); let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); - for ch in iterator { - self.push(ch) - } + iterator.for_each(move |c| self.push(c)); } } @@ -1769,27 +1780,21 @@ impl<'a> Extend<&'a char> for String { #[stable(feature = "rust1", since = "1.0.0")] impl<'a> Extend<&'a str> for String { fn extend>(&mut self, iter: I) { - for s in iter { - self.push_str(s) - } + iter.into_iter().for_each(move |s| self.push_str(s)); } } #[stable(feature = "extend_string", since = "1.4.0")] impl Extend for String { fn extend>(&mut self, iter: I) { - for s in iter { - self.push_str(&s) - } + iter.into_iter().for_each(move |s| self.push_str(&s)); } } #[stable(feature = "herd_cows", since = "1.19.0")] impl<'a> Extend> for String { fn extend>>(&mut self, iter: I) { - for s in iter { - self.push_str(&s) - } + iter.into_iter().for_each(move |s| self.push_str(&s)); } } -- cgit 1.4.1-3-g733a5 From 823dd8ca334951962e8b192ca1362c08e33d6bcf Mon Sep 17 00:00:00 2001 From: Nathan West Date: Wed, 5 Dec 2018 15:11:32 -0800 Subject: Fixed mutability --- src/liballoc/string.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs index ef9a34ec611..6962f2ba852 100644 --- a/src/liballoc/string.rs +++ b/src/liballoc/string.rs @@ -1732,11 +1732,11 @@ impl<'a> FromIterator<&'a str> for String { #[stable(feature = "extend_string", since = "1.4.0")] impl FromIterator for String { fn from_iter>(iter: I) -> String { - let iterator = iter.into_iter(); + let mut iterator = iter.into_iter(); match iterator.next() { None => String::new(), - Some(buf) => { + Some(mut buf) => { buf.extend(iterator); buf } @@ -1747,12 +1747,12 @@ impl FromIterator for String { #[stable(feature = "herd_cows", since = "1.19.0")] impl<'a> FromIterator> for String { fn from_iter>>(iter: I) -> String { - let iterator = iter.into_iter(); + let mut iterator = iter.into_iter(); match iterator.next() { None => String::new(), Some(cow) => { - let buf = cow.into_owned(); + let mut buf = cow.into_owned(); buf.extend(iterator); buf } -- cgit 1.4.1-3-g733a5 From 811a2bfe5332081d7145de6c488ea7f6c5cf42a5 Mon Sep 17 00:00:00 2001 From: Nathan West Date: Wed, 5 Dec 2018 17:46:03 -0800 Subject: Added explainatory comments --- src/liballoc/string.rs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/liballoc') diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs index 6962f2ba852..f0a64f4631a 100644 --- a/src/liballoc/string.rs +++ b/src/liballoc/string.rs @@ -1734,6 +1734,9 @@ impl FromIterator for String { fn from_iter>(iter: I) -> String { let mut iterator = iter.into_iter(); + // Because we're iterating over `String`s, we can avoid at least + // one allocation by getting the first string from the iterator + // and appending to it all the subsequent strings. match iterator.next() { None => String::new(), Some(mut buf) => { @@ -1749,6 +1752,9 @@ impl<'a> FromIterator> for String { fn from_iter>>(iter: I) -> String { let mut iterator = iter.into_iter(); + // Because we're iterating over CoWs, we can (potentially) avoid at least + // one allocation by getting the first item and appending to it all the + // subsequent items. match iterator.next() { None => String::new(), Some(cow) => { -- cgit 1.4.1-3-g733a5 From b0c4a35a969aa94f6667cb885eebb184ee318a6d Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 22 Nov 2018 08:57:26 +0100 Subject: VecDeque::drain: make sure the 'drain' raw pointer is actually still usable --- src/liballoc/collections/vec_deque.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs index c8ee40f3d27..60b5d8063bf 100644 --- a/src/liballoc/collections/vec_deque.rs +++ b/src/liballoc/collections/vec_deque.rs @@ -1019,14 +1019,19 @@ impl VecDeque { // the drain is complete and the Drain destructor is run. self.head = drain_tail; + // `deque` and `ring` overlap in what they point to, so we must make sure + // that `ring` is "derived-from" `deque`, or else even just creating ring + // from `self` already invalidates `deque`. + let deque = NonNull::from(&mut *self); + Drain { - deque: NonNull::from(&mut *self), + deque, after_tail: drain_head, after_head: head, iter: Iter { tail: drain_tail, head: drain_head, - ring: unsafe { self.buffer_as_mut_slice() }, + ring: unsafe { (&mut *deque.as_ptr()).buffer_as_mut_slice() }, }, } } -- cgit 1.4.1-3-g733a5 From feb775c834361f635df9e3824f9d2ae9582becbb Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 22 Nov 2018 16:03:24 +0100 Subject: Drain only needs a shared reference --- src/liballoc/collections/vec_deque.rs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs index 60b5d8063bf..4a3604f202f 100644 --- a/src/liballoc/collections/vec_deque.rs +++ b/src/liballoc/collections/vec_deque.rs @@ -1019,19 +1019,17 @@ impl VecDeque { // the drain is complete and the Drain destructor is run. self.head = drain_tail; - // `deque` and `ring` overlap in what they point to, so we must make sure - // that `ring` is "derived-from" `deque`, or else even just creating ring - // from `self` already invalidates `deque`. - let deque = NonNull::from(&mut *self); - Drain { - deque, + deque: NonNull::from(&mut *self), after_tail: drain_head, after_head: head, iter: Iter { tail: drain_tail, head: drain_head, - ring: unsafe { (&mut *deque.as_ptr()).buffer_as_mut_slice() }, + // Crucially, we only create shared references from `self` here and read from + // it. We do not write to `self` nor reborrow to a mutable reference. + // Hence the raw pointer we created above, for `deque`, remains valid. + ring: unsafe { self.buffer_as_slice() }, }, } } -- 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/liballoc') 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 2a916a617f6c6c62536a3b164f4b15ea58eaa148 Mon Sep 17 00:00:00 2001 From: Jo Liss Date: Tue, 27 Jun 2017 17:23:31 +0000 Subject: Short-circuit Rc/Arc equality checking on equal pointers where T: Eq Closes #42655 --- src/liballoc/rc.rs | 25 +++++++++++++++++++++++-- src/liballoc/sync.rs | 26 +++++++++++++++++++++++--- 2 files changed, 46 insertions(+), 5 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 52ad30c411a..85bde5f63ce 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(specialization)] #![allow(deprecated)] //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference @@ -906,6 +907,9 @@ impl PartialEq for Rc { /// /// Two `Rc`s are equal if their inner values are equal. /// + /// If `T` also implements `Eq`, two `Rc`s that point to the same value are + /// always equal. + /// /// # Examples /// /// ``` @@ -916,7 +920,7 @@ impl PartialEq for Rc { /// assert!(five == Rc::new(5)); /// ``` #[inline(always)] - fn eq(&self, other: &Rc) -> bool { + default fn eq(&self, other: &Rc) -> bool { **self == **other } @@ -924,6 +928,9 @@ impl PartialEq for Rc { /// /// Two `Rc`s are unequal if their inner values are unequal. /// + /// If `T` also implements `Eq`, two `Rc`s that point to the same value are + /// never unequal. + /// /// # Examples /// /// ``` @@ -934,11 +941,25 @@ impl PartialEq for Rc { /// assert!(five != Rc::new(6)); /// ``` #[inline(always)] - fn ne(&self, other: &Rc) -> bool { + default fn ne(&self, other: &Rc) -> bool { **self != **other } } +#[doc(hidden)] +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialEq for Rc { + #[inline(always)] + fn eq(&self, other: &Rc) -> bool { + Rc::ptr_eq(self, other) || **self == **other + } + + #[inline(always)] + fn ne(&self, other: &Rc) -> bool { + !Rc::ptr_eq(self, other) && **self != **other + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl Eq for Rc {} diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index 111459d12a4..d6863238cd4 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -8,6 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +#![feature(specialization)] #![stable(feature = "rust1", since = "1.0.0")] //! Thread-safe reference-counting pointers. @@ -1293,6 +1294,9 @@ impl PartialEq for Arc { /// /// Two `Arc`s are equal if their inner values are equal. /// + /// If `T` also implements `Eq`, two `Arc`s that point to the same value are + /// always equal. + /// /// # Examples /// /// ``` @@ -1302,14 +1306,17 @@ impl PartialEq for Arc { /// /// assert!(five == Arc::new(5)); /// ``` - fn eq(&self, other: &Arc) -> bool { - *(*self) == *(*other) + default fn eq(&self, other: &Arc) -> bool { + **self == **other } /// Inequality for two `Arc`s. /// /// Two `Arc`s are unequal if their inner values are unequal. /// + /// If `T` also implements `Eq`, two `Arc`s that point to the same value are + /// never unequal. + /// /// # Examples /// /// ``` @@ -1319,8 +1326,21 @@ impl PartialEq for Arc { /// /// assert!(five != Arc::new(6)); /// ``` + default fn ne(&self, other: &Arc) -> bool { + **self != **other + } +} +#[doc(hidden)] +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialEq for Arc { + #[inline(always)] + fn eq(&self, other: &Arc) -> bool { + Arc::ptr_eq(self, other) || **self == **other + } + + #[inline(always)] fn ne(&self, other: &Arc) -> bool { - *(*self) != *(*other) + !Arc::ptr_eq(self, other) && **self != **other } } #[stable(feature = "rust1", since = "1.0.0")] -- cgit 1.4.1-3-g733a5 From 40d60a4608c76e8a74ab643f4629dbaf129e07a4 Mon Sep 17 00:00:00 2001 From: Thomas Heck Date: Wed, 5 Dec 2018 21:43:44 +0100 Subject: Use private trait for Rc/Arc Eq specialization --- src/liballoc/rc.rs | 57 ++++++++++++++++++++++++++++++++++------------------ src/liballoc/sync.rs | 54 +++++++++++++++++++++++++++++++++---------------- 2 files changed, 74 insertions(+), 37 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 85bde5f63ce..6769a70ddbe 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(specialization)] #![allow(deprecated)] //! Single-threaded reference-counting pointers. 'Rc' stands for 'Reference @@ -901,6 +900,38 @@ impl Default for Rc { } } +#[stable(feature = "rust1", since = "1.0.0")] +trait RcEqIdent { + fn eq(&self, other: &Rc) -> bool; + fn ne(&self, other: &Rc) -> bool; +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl RcEqIdent for Rc { + #[inline] + default fn eq(&self, other: &Rc) -> bool { + **self == **other + } + + #[inline] + default fn ne(&self, other: &Rc) -> bool { + **self != **other + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl RcEqIdent for Rc { + #[inline] + fn eq(&self, other: &Rc) -> bool { + Rc::ptr_eq(self, other) || **self == **other + } + + #[inline] + fn ne(&self, other: &Rc) -> bool { + !Rc::ptr_eq(self, other) && **self != **other + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for Rc { /// Equality for two `Rc`s. @@ -919,9 +950,9 @@ impl PartialEq for Rc { /// /// assert!(five == Rc::new(5)); /// ``` - #[inline(always)] - default fn eq(&self, other: &Rc) -> bool { - **self == **other + #[inline] + fn eq(&self, other: &Rc) -> bool { + RcEqIdent::eq(self, other) } /// Inequality for two `Rc`s. @@ -940,23 +971,9 @@ impl PartialEq for Rc { /// /// assert!(five != Rc::new(6)); /// ``` - #[inline(always)] - default fn ne(&self, other: &Rc) -> bool { - **self != **other - } -} - -#[doc(hidden)] -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for Rc { - #[inline(always)] - fn eq(&self, other: &Rc) -> bool { - Rc::ptr_eq(self, other) || **self == **other - } - - #[inline(always)] + #[inline] fn ne(&self, other: &Rc) -> bool { - !Rc::ptr_eq(self, other) && **self != **other + RcEqIdent::ne(self, other) } } diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index d6863238cd4..e596694fb9d 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(specialization)] #![stable(feature = "rust1", since = "1.0.0")] //! Thread-safe reference-counting pointers. @@ -1288,6 +1287,37 @@ impl Drop for Weak { } } +#[stable(feature = "rust1", since = "1.0.0")] +trait ArcEqIdent { + fn eq(&self, other: &Arc) -> bool; + fn ne(&self, other: &Arc) -> bool; +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + default fn eq(&self, other: &Arc) -> bool { + **self == **other + } + #[inline] + default fn ne(&self, other: &Arc) -> bool { + **self != **other + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + fn eq(&self, other: &Arc) -> bool { + Arc::ptr_eq(self, other) || **self == **other + } + + #[inline] + fn ne(&self, other: &Arc) -> bool { + !Arc::ptr_eq(self, other) && **self != **other + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl PartialEq for Arc { /// Equality for two `Arc`s. @@ -1306,8 +1336,9 @@ impl PartialEq for Arc { /// /// assert!(five == Arc::new(5)); /// ``` - default fn eq(&self, other: &Arc) -> bool { - **self == **other + #[inline] + fn eq(&self, other: &Arc) -> bool { + ArcEqIdent::eq(self, other) } /// Inequality for two `Arc`s. @@ -1326,23 +1357,12 @@ impl PartialEq for Arc { /// /// assert!(five != Arc::new(6)); /// ``` - default fn ne(&self, other: &Arc) -> bool { - **self != **other - } -} -#[doc(hidden)] -#[stable(feature = "rust1", since = "1.0.0")] -impl PartialEq for Arc { - #[inline(always)] - fn eq(&self, other: &Arc) -> bool { - Arc::ptr_eq(self, other) || **self == **other - } - - #[inline(always)] + #[inline] fn ne(&self, other: &Arc) -> bool { - !Arc::ptr_eq(self, other) && **self != **other + ArcEqIdent::ne(self, other) } } + #[stable(feature = "rust1", since = "1.0.0")] impl PartialOrd for Arc { /// Partial comparison for two `Arc`s. -- cgit 1.4.1-3-g733a5 From d828c22bd6ff6059c75dfa63e024997619eb6e7c Mon Sep 17 00:00:00 2001 From: Thomas Heck Date: Sat, 8 Dec 2018 09:35:23 +0100 Subject: Add Arc/Rc Eq tests --- src/liballoc/tests/arc.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ src/liballoc/tests/rc.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) (limited to 'src/liballoc') diff --git a/src/liballoc/tests/arc.rs b/src/liballoc/tests/arc.rs index d90c22a3b18..ec589710216 100644 --- a/src/liballoc/tests/arc.rs +++ b/src/liballoc/tests/arc.rs @@ -10,6 +10,8 @@ use std::any::Any; use std::sync::{Arc, Weak}; +use std::cell::RefCell; +use std::cmp::PartialEq; #[test] fn uninhabited() { @@ -53,3 +55,43 @@ fn trait_object() { b = b.clone(); assert!(b.upgrade().is_none()); } + +#[test] +fn float_nan_ne() { + let x = Arc::new(std::f32::NAN); + assert!(x != x); + assert!(!(x == x)); +} + +#[test] +fn partial_eq() { + struct TestPEq (RefCell); + impl PartialEq for TestPEq { + fn eq(&self, other: &TestPEq) -> bool { + *self.0.borrow_mut() += 1; + *other.0.borrow_mut() += 1; + true + } + } + let x = Arc::new(TestPEq(RefCell::new(0))); + assert!(x == x); + assert!(!(x != x)); + assert_eq!(*x.0.borrow(), 4); +} + +#[test] +fn eq() { + #[derive(Eq)] + struct TestEq (RefCell); + impl PartialEq for TestEq { + fn eq(&self, other: &TestEq) -> bool { + *self.0.borrow_mut() += 1; + *other.0.borrow_mut() += 1; + true + } + } + let x = Arc::new(TestEq(RefCell::new(0))); + assert!(x == x); + assert!(!(x != x)); + assert_eq!(*x.0.borrow(), 0); +} diff --git a/src/liballoc/tests/rc.rs b/src/liballoc/tests/rc.rs index 9ec7c831444..02e1dfe13bb 100644 --- a/src/liballoc/tests/rc.rs +++ b/src/liballoc/tests/rc.rs @@ -10,6 +10,8 @@ use std::any::Any; use std::rc::{Rc, Weak}; +use std::cell::RefCell; +use std::cmp::PartialEq; #[test] fn uninhabited() { @@ -53,3 +55,43 @@ fn trait_object() { b = b.clone(); assert!(b.upgrade().is_none()); } + +#[test] +fn float_nan_ne() { + let x = Rc::new(std::f32::NAN); + assert!(x != x); + assert!(!(x == x)); +} + +#[test] +fn partial_eq() { + struct TestPEq (RefCell); + impl PartialEq for TestPEq { + fn eq(&self, other: &TestPEq) -> bool { + *self.0.borrow_mut() += 1; + *other.0.borrow_mut() += 1; + true + } + } + let x = Rc::new(TestPEq(RefCell::new(0))); + assert!(x == x); + assert!(!(x != x)); + assert_eq!(*x.0.borrow(), 4); +} + +#[test] +fn eq() { + #[derive(Eq)] + struct TestEq (RefCell); + impl PartialEq for TestEq { + fn eq(&self, other: &TestEq) -> bool { + *self.0.borrow_mut() += 1; + *other.0.borrow_mut() += 1; + true + } + } + let x = Rc::new(TestEq(RefCell::new(0))); + assert!(x == x); + assert!(!(x != x)); + assert_eq!(*x.0.borrow(), 0); +} -- cgit 1.4.1-3-g733a5 From 0e70c269feece979427bcc8795afc43efc1e47c1 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Fri, 7 Dec 2018 16:52:10 +0100 Subject: fix BTree creating shared references that are not entirely in-bounds --- src/liballoc/collections/btree/node.rs | 115 ++++++++++++++++++++++++--------- 1 file changed, 86 insertions(+), 29 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/btree/node.rs b/src/liballoc/collections/btree/node.rs index 215689dfc48..13cbcee2f8e 100644 --- a/src/liballoc/collections/btree/node.rs +++ b/src/liballoc/collections/btree/node.rs @@ -58,9 +58,34 @@ pub const CAPACITY: usize = 2 * B - 1; /// these should always be put behind pointers, and specifically behind `BoxedNode` in the owned /// case. /// -/// We put the metadata first so that its position is the same for every `K` and `V`, in order -/// to statically allocate a single dummy node to avoid allocations. This struct is `repr(C)` to -/// prevent them from being reordered. +/// We have a separate type for the header and rely on it matching the prefix of `LeafNode`, in +/// order to statically allocate a single dummy node to avoid allocations. This struct is +/// `repr(C)` to prevent them from being reordered. `LeafNode` does not just contain a +/// `NodeHeader` because we do not want unnecessary padding between `len` and the keys. +/// Crucially, `NodeHeader` can be safely transmuted to different K and V. (This is exploited +/// by `as_header`.) +/// See `into_key_slice` for an explanation of K2. K2 cannot be safely transmuted around +/// because the size of `NodeHeader` depends on its alignment! +#[repr(C)] +struct NodeHeader { + /// We use `*const` as opposed to `*mut` so as to be covariant in `K` and `V`. + /// This either points to an actual node or is null. + parent: *const InternalNode, + + /// This node's index into the parent node's `edges` array. + /// `*node.parent.edges[node.parent_idx]` should be the same thing as `node`. + /// This is only guaranteed to be initialized when `parent` is non-null. + parent_idx: MaybeUninit, + + /// The number of keys and values this node stores. + /// + /// This next to `parent_idx` to encourage the compiler to join `len` and + /// `parent_idx` into the same 32-bit word, reducing space overhead. + len: u16, + + /// See `into_key_slice`. + keys_start: [K2; 0], +} #[repr(C)] struct LeafNode { /// We use `*const` as opposed to `*mut` so as to be covariant in `K` and `V`. @@ -98,24 +123,25 @@ impl LeafNode { len: 0 } } +} +impl NodeHeader { fn is_shared_root(&self) -> bool { ptr::eq(self, &EMPTY_ROOT_NODE as *const _ as *const _) } } // We need to implement Sync here in order to make a static instance. -unsafe impl Sync for LeafNode<(), ()> {} +unsafe impl Sync for NodeHeader<(), ()> {} // An empty node used as a placeholder for the root node, to avoid allocations. -// We use () in order to save space, since no operation on an empty tree will +// We use just a header in order to save space, since no operation on an empty tree will // ever take a pointer past the first key. -static EMPTY_ROOT_NODE: LeafNode<(), ()> = LeafNode { +static EMPTY_ROOT_NODE: NodeHeader<(), ()> = NodeHeader { parent: ptr::null(), parent_idx: MaybeUninit::uninitialized(), len: 0, - keys: MaybeUninit::uninitialized(), - vals: MaybeUninit::uninitialized(), + keys_start: [], }; /// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden @@ -306,6 +332,11 @@ impl Root { /// `Leaf`, the `NodeRef` points to a leaf node, when this is `Internal` the /// `NodeRef` points to an internal node, and when this is `LeafOrInternal` the /// `NodeRef` could be pointing to either type of node. +/// Note that in case of a leaf node, this might still be the shared root! Only turn +/// this into a `LeafNode` reference if you know it is not a root! Shared references +/// must be dereferencable *for the entire size of their pointee*, so `&InternalNode` +/// pointing to the shared root is UB. +/// Turning this into a `NodeHeader` is always safe. pub struct NodeRef { height: usize, node: NonNull>, @@ -352,7 +383,7 @@ impl NodeRef { /// Finds the length of the node. This is the number of keys or values. In an /// internal node, the number of edges is `len() + 1`. pub fn len(&self) -> usize { - self.as_leaf().len as usize + self.as_header().len as usize } /// Returns the height of this node in the whole tree. Zero height denotes the @@ -382,14 +413,19 @@ impl NodeRef { } } - fn as_leaf(&self) -> &LeafNode { + /// Assert that this is indeed a proper leaf node, and not the shared root. + unsafe fn as_leaf(&self) -> &LeafNode { + self.node.as_ref() + } + + fn as_header(&self) -> &NodeHeader { unsafe { - self.node.as_ref() + &*(self.node.as_ptr() as *const NodeHeader) } } pub fn is_shared_root(&self) -> bool { - self.as_leaf().is_shared_root() + self.as_header().is_shared_root() } pub fn keys(&self) -> &[K] { @@ -418,7 +454,7 @@ impl NodeRef { >, Self > { - let parent_as_leaf = self.as_leaf().parent as *const LeafNode; + let parent_as_leaf = self.as_header().parent as *const LeafNode; if let Some(non_zero) = NonNull::new(parent_as_leaf as *mut _) { Ok(Handle { node: NodeRef { @@ -427,7 +463,7 @@ impl NodeRef { root: self.root, _marker: PhantomData }, - idx: unsafe { usize::from(*self.as_leaf().parent_idx.get_ref()) }, + idx: unsafe { usize::from(*self.as_header().parent_idx.get_ref()) }, _marker: PhantomData }) } else { @@ -535,9 +571,8 @@ impl<'a, K, V, Type> NodeRef, K, V, Type> { } fn as_leaf_mut(&mut self) -> &mut LeafNode { - unsafe { - self.node.as_mut() - } + // We are mutable, so we cannot be the root, so this is okay. + unsafe { self.node.as_mut() } } fn keys_mut(&mut self) -> &mut [K] { @@ -551,28 +586,50 @@ impl<'a, K, V, Type> NodeRef, K, V, Type> { impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { fn into_key_slice(self) -> &'a [K] { - // When taking a pointer to the keys, if our key has a stricter - // alignment requirement than the shared root does, then the pointer - // would be out of bounds, which LLVM assumes will not happen. If the - // alignment is more strict, we need to make an empty slice that doesn't - // use an out of bounds pointer. + // We have to be careful here because we might be pointing to the shared root. + // In that case, we must not create an `&LeafNode`. We could just return + // an empty slice whenever the lenght is 0 (this includes the shared root), + // but we want to avoid that run-time check. + // Instead, we create a slice pointing into the node whenever possible. + // We can sometimes do this even for the shared root, as the slice will be + // empty. We cannot *always* do this because if the type is too highly + // aligned, the offset of `keys` in a "full node" might be outside the bounds + // of the header! So we do an alignment check first, that will be + // evaluated at compile-time, and only do any run-time check in the rare case + // that the alignment is very big. if mem::align_of::() > mem::align_of::>() && self.is_shared_root() { &[] } else { - // Here either it's not the root, or the alignment is less strict, - // in which case the keys pointer will point "one-past-the-end" of - // the node, which is allowed by LLVM. + // Thanks to the alignment check above, we know that `keys` will be + // in-bounds of some allocation even if this is the shared root! + // (We might be one-past-the-end, but that is allowed by LLVM.) + // Getting the pointer is tricky though. `NodeHeader` does not have a `keys` + // field because we want its size to not depend on the alignment of `K` + // (needed becuase `as_header` should be safe). We cannot call `as_leaf` + // because we might be the shared root. + // For this reason, `NodeHeader` has this `K2` parameter (that's usually `()` + // and hence just adds a size-0-align-1 field, not affecting layout). + // We know that we can transmute `NodeHeader` to `NodeHeader` + // because we did the alignment check above, and hence `NodeHeader` + // is not bigger than `NodeHeader`! Then we can use `NodeHeader` + // to compute the pointer where the keys start. + // This entire hack will become unnecessary once + // lands, then we can just take a raw + // pointer to the `keys` field of `*const InternalNode`. + + // This is a non-debug-assert because it can be completely compile-time evaluated. + assert!(mem::size_of::>() == mem::size_of::>()); + let header = self.as_header() as *const _ as *const NodeHeader; + let keys = unsafe { &(*header).keys_start as *const _ as *const K }; unsafe { - slice::from_raw_parts( - self.as_leaf().keys.as_ptr() as *const K, - self.len() - ) + slice::from_raw_parts(keys, self.len()) } } } fn into_val_slice(self) -> &'a [V] { debug_assert!(!self.is_shared_root()); + // We cannot be the root, so `as_leaf` is okay unsafe { slice::from_raw_parts( self.as_leaf().vals.as_ptr() as *const V, -- cgit 1.4.1-3-g733a5 From 4558340ecc64c2702ad89b8175e07ac1c71e273b Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 8 Dec 2018 23:38:12 +0100 Subject: avoid as_leaf_mut asserting exclusive access --- src/liballoc/collections/btree/node.rs | 63 ++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 30 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/btree/node.rs b/src/liballoc/collections/btree/node.rs index 13cbcee2f8e..a9f6cdbb51f 100644 --- a/src/liballoc/collections/btree/node.rs +++ b/src/liballoc/collections/btree/node.rs @@ -307,7 +307,7 @@ impl Root { .node) }; self.height -= 1; - self.as_mut().as_leaf_mut().parent = ptr::null(); + unsafe { (*self.as_mut().as_leaf_mut()).parent = ptr::null(); } unsafe { Global.dealloc(NonNull::from(top).cast(), Layout::new::>()); @@ -570,9 +570,10 @@ impl<'a, K, V, Type> NodeRef, K, V, Type> { } } - fn as_leaf_mut(&mut self) -> &mut LeafNode { - // We are mutable, so we cannot be the root, so this is okay. - unsafe { self.node.as_mut() } + /// Returns a raw ptr to avoid asserting exclusive access to the entire node. + fn as_leaf_mut(&mut self) -> *mut LeafNode { + // We are mutable, so we cannot be the root, so accessing this as a leaf is okay. + self.node.as_ptr() } fn keys_mut(&mut self) -> &mut [K] { @@ -659,7 +660,7 @@ impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { } else { unsafe { slice::from_raw_parts_mut( - self.as_leaf_mut().keys.as_mut_ptr() as *mut K, + (*self.as_leaf_mut()).keys.as_mut_ptr() as *mut K, self.len() ) } @@ -670,7 +671,7 @@ impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { debug_assert!(!self.is_shared_root()); unsafe { slice::from_raw_parts_mut( - self.as_leaf_mut().vals.as_mut_ptr() as *mut V, + (*self.as_leaf_mut()).vals.as_mut_ptr() as *mut V, self.len() ) } @@ -694,9 +695,9 @@ impl<'a, K, V> NodeRef, K, V, marker::Leaf> { unsafe { ptr::write(self.keys_mut().get_unchecked_mut(idx), key); ptr::write(self.vals_mut().get_unchecked_mut(idx), val); - } - self.as_leaf_mut().len += 1; + (*self.as_leaf_mut()).len += 1; + } } /// Adds a key/value pair to the beginning of the node. @@ -708,9 +709,9 @@ impl<'a, K, V> NodeRef, K, V, marker::Leaf> { unsafe { slice_insert(self.keys_mut(), 0, key); slice_insert(self.vals_mut(), 0, val); - } - self.as_leaf_mut().len += 1; + (*self.as_leaf_mut()).len += 1; + } } } @@ -729,7 +730,7 @@ impl<'a, K, V> NodeRef, K, V, marker::Internal> { ptr::write(self.vals_mut().get_unchecked_mut(idx), val); ptr::write(self.as_internal_mut().edges.get_unchecked_mut(idx + 1), edge.node); - self.as_leaf_mut().len += 1; + (*self.as_leaf_mut()).len += 1; Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); } @@ -765,7 +766,7 @@ impl<'a, K, V> NodeRef, K, V, marker::Internal> { edge.node ); - self.as_leaf_mut().len += 1; + (*self.as_leaf_mut()).len += 1; self.correct_all_childrens_parent_links(); } @@ -789,12 +790,12 @@ impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { ForceResult::Internal(internal) => { let edge = ptr::read(internal.as_internal().edges.get_unchecked(idx + 1)); let mut new_root = Root { node: edge, height: internal.height - 1 }; - new_root.as_mut().as_leaf_mut().parent = ptr::null(); + (*new_root.as_mut().as_leaf_mut()).parent = ptr::null(); Some(new_root) } }; - self.as_leaf_mut().len -= 1; + (*self.as_leaf_mut()).len -= 1; (key, val, edge) } } @@ -822,7 +823,7 @@ impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { ); let mut new_root = Root { node: edge, height: internal.height - 1 }; - new_root.as_mut().as_leaf_mut().parent = ptr::null(); + (*new_root.as_mut().as_leaf_mut()).parent = ptr::null(); for i in 0..old_len { Handle::new_edge(internal.reborrow_mut(), i).correct_parent_link(); @@ -832,7 +833,7 @@ impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { } }; - self.as_leaf_mut().len -= 1; + (*self.as_leaf_mut()).len -= 1; (key, val, edge) } @@ -1023,7 +1024,7 @@ impl<'a, K, V> Handle, K, V, marker::Leaf>, marker::Edge slice_insert(self.node.keys_mut(), self.idx, key); slice_insert(self.node.vals_mut(), self.idx, val); - self.node.as_leaf_mut().len += 1; + (*self.node.as_leaf_mut()).len += 1; self.node.vals_mut().get_unchecked_mut(self.idx) } @@ -1066,8 +1067,10 @@ impl<'a, K, V> Handle, K, V, marker::Internal>, marker:: let idx = self.idx as u16; let ptr = self.node.as_internal_mut() as *mut _; let mut child = self.descend(); - child.as_leaf_mut().parent = ptr; - child.as_leaf_mut().parent_idx.set(idx); + unsafe { + (*child.as_leaf_mut()).parent = ptr; + (*child.as_leaf_mut()).parent_idx.set(idx); + } } /// Unsafely asserts to the compiler some static information about whether the underlying @@ -1215,7 +1218,7 @@ impl<'a, K, V> Handle, K, V, marker::Leaf>, marker::KV> new_len ); - self.node.as_leaf_mut().len = self.idx as u16; + (*self.node.as_leaf_mut()).len = self.idx as u16; new_node.len = new_len as u16; ( @@ -1237,7 +1240,7 @@ impl<'a, K, V> Handle, K, V, marker::Leaf>, marker::KV> unsafe { let k = slice_remove(self.node.keys_mut(), self.idx); let v = slice_remove(self.node.vals_mut(), self.idx); - self.node.as_leaf_mut().len -= 1; + (*self.node.as_leaf_mut()).len -= 1; (self.left_edge(), k, v) } } @@ -1278,7 +1281,7 @@ impl<'a, K, V> Handle, K, V, marker::Internal>, marker:: new_len + 1 ); - self.node.as_leaf_mut().len = self.idx as u16; + (*self.node.as_leaf_mut()).len = self.idx as u16; new_node.data.len = new_len as u16; let mut new_root = Root { @@ -1352,9 +1355,9 @@ impl<'a, K, V> Handle, K, V, marker::Internal>, marker:: for i in self.idx+1..self.node.len() { Handle::new_edge(self.node.reborrow_mut(), i).correct_parent_link(); } - self.node.as_leaf_mut().len -= 1; + (*self.node.as_leaf_mut()).len -= 1; - left_node.as_leaf_mut().len += right_len as u16 + 1; + (*left_node.as_leaf_mut()).len += right_len as u16 + 1; if self.node.height > 1 { ptr::copy_nonoverlapping( @@ -1464,8 +1467,8 @@ impl<'a, K, V> Handle, K, V, marker::Internal>, marker:: move_kv(left_kv, new_left_len, parent_kv, 0, 1); } - left_node.reborrow_mut().as_leaf_mut().len -= count as u16; - right_node.reborrow_mut().as_leaf_mut().len += count as u16; + (*left_node.reborrow_mut().as_leaf_mut()).len -= count as u16; + (*right_node.reborrow_mut().as_leaf_mut()).len += count as u16; match (left_node.force(), right_node.force()) { (ForceResult::Internal(left), ForceResult::Internal(mut right)) => { @@ -1525,8 +1528,8 @@ impl<'a, K, V> Handle, K, V, marker::Internal>, marker:: new_right_len); } - left_node.reborrow_mut().as_leaf_mut().len += count as u16; - right_node.reborrow_mut().as_leaf_mut().len -= count as u16; + (*left_node.reborrow_mut().as_leaf_mut()).len += count as u16; + (*right_node.reborrow_mut().as_leaf_mut()).len -= count as u16; match (left_node.force(), right_node.force()) { (ForceResult::Internal(left), ForceResult::Internal(mut right)) => { @@ -1617,8 +1620,8 @@ impl<'a, K, V> Handle, K, V, marker::LeafOrInternal>, ma move_kv(left_kv, left_new_len, right_kv, 0, right_new_len); - left_node.reborrow_mut().as_leaf_mut().len = left_new_len as u16; - right_node.reborrow_mut().as_leaf_mut().len = right_new_len as u16; + (*left_node.reborrow_mut().as_leaf_mut()).len = left_new_len as u16; + (*right_node.reborrow_mut().as_leaf_mut()).len = right_new_len as u16; match (left_node.force(), right_node.force()) { (ForceResult::Internal(left), ForceResult::Internal(right)) => { -- cgit 1.4.1-3-g733a5 From 6f288ea33712b34c8eabcd57bb10607ab01f0cdb Mon Sep 17 00:00:00 2001 From: BeatButton Date: Sun, 9 Dec 2018 14:10:20 -0700 Subject: Fix typo --- src/liballoc/string.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/liballoc') diff --git a/src/liballoc/string.rs b/src/liballoc/string.rs index 006c602649b..4652c0e7efa 100644 --- a/src/liballoc/string.rs +++ b/src/liballoc/string.rs @@ -2169,7 +2169,7 @@ impl ToString for T { use core::fmt::Write; let mut buf = String::new(); buf.write_fmt(format_args!("{}", self)) - .expect("a Display implementation return an error unexpectedly"); + .expect("a Display implementation returned an error unexpectedly"); buf.shrink_to_fit(); buf } -- cgit 1.4.1-3-g733a5 From 562f33b1a57acb4ccbc741fb32687aedfc4a8398 Mon Sep 17 00:00:00 2001 From: Chris Couzens Date: Mon, 10 Dec 2018 12:43:15 +0000 Subject: Document time of back operations of a Linked List Popping and pushing from the end of a linked list is constant time. This documentation is already there for popping and pushing from the front. @bors: r+ 38fe8d2 rollup --- src/liballoc/collections/linked_list.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/linked_list.rs b/src/liballoc/collections/linked_list.rs index 2ef84dbade0..ba46fafaf16 100644 --- a/src/liballoc/collections/linked_list.rs +++ b/src/liballoc/collections/linked_list.rs @@ -627,7 +627,9 @@ impl LinkedList { self.pop_front_node().map(Node::into_element) } - /// Appends an element to the back of a list + /// Appends an element to the back of a list. + /// + /// This operation should compute in O(1) time. /// /// # Examples /// @@ -647,6 +649,8 @@ impl LinkedList { /// Removes the last element from a list and returns it, or `None` if /// it is empty. /// + /// This operation should compute in O(1) time. + /// /// # Examples /// /// ``` -- cgit 1.4.1-3-g733a5 From d9c64e50a07dec062c273f4ec4c8f5985af13273 Mon Sep 17 00:00:00 2001 From: Alexis Beingessner Date: Tue, 11 Dec 2018 08:55:15 +0100 Subject: Typo Co-Authored-By: RalfJung --- src/liballoc/collections/btree/node.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/btree/node.rs b/src/liballoc/collections/btree/node.rs index a9f6cdbb51f..a2d2d3c74be 100644 --- a/src/liballoc/collections/btree/node.rs +++ b/src/liballoc/collections/btree/node.rs @@ -589,7 +589,7 @@ impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { fn into_key_slice(self) -> &'a [K] { // We have to be careful here because we might be pointing to the shared root. // In that case, we must not create an `&LeafNode`. We could just return - // an empty slice whenever the lenght is 0 (this includes the shared root), + // an empty slice whenever the length is 0 (this includes the shared root), // but we want to avoid that run-time check. // Instead, we create a slice pointing into the node whenever possible. // We can sometimes do this even for the shared root, as the slice will be -- cgit 1.4.1-3-g733a5 From 1006425769ada70d0f394ccdab3caecaf6fa3e77 Mon Sep 17 00:00:00 2001 From: Konrad Borowski Date: Tue, 11 Dec 2018 15:07:07 +0100 Subject: Test capacity of ZST vector Initially, #50233 accidentally changed the capacity of empty ZST. This was pointed out during code review. This commit adds a test to prevent capacity of ZST vectors from accidentally changing to prevent that from happening again. --- src/liballoc/tests/vec.rs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/liballoc') diff --git a/src/liballoc/tests/vec.rs b/src/liballoc/tests/vec.rs index e329b45a617..509195cd047 100644 --- a/src/liballoc/tests/vec.rs +++ b/src/liballoc/tests/vec.rs @@ -79,6 +79,11 @@ fn test_reserve() { assert!(v.capacity() >= 33) } +#[test] +fn test_zst_capacity() { + assert_eq!(Vec::<()>::new().capacity(), usize::max_value()); +} + #[test] fn test_extend() { let mut v = Vec::new(); -- 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/liballoc') 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/liballoc') 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 c811915eafb349759d2bba9d7a39a53aef02bb3d Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Fri, 14 Dec 2018 09:05:31 -0800 Subject: std: Activate compiler_builtins `mem` feature for no_std targets This was an accidental regression from #56092, but for `no_std` targets being built and distributed we want to be sure to activate the compiler-builtins `mem` feature which demangles important memory-related intrinsics. --- src/bootstrap/compile.rs | 4 +++- src/liballoc/Cargo.toml | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'src/liballoc') diff --git a/src/bootstrap/compile.rs b/src/bootstrap/compile.rs index c84abe42a63..689d0530f8b 100644 --- a/src/bootstrap/compile.rs +++ b/src/bootstrap/compile.rs @@ -155,7 +155,9 @@ pub fn std_cargo(builder: &Builder, cargo .args(&["-p", "alloc"]) .arg("--manifest-path") - .arg(builder.src.join("src/liballoc/Cargo.toml")); + .arg(builder.src.join("src/liballoc/Cargo.toml")) + .arg("--features") + .arg("compiler-builtins-mem"); } else { let features = builder.std_features(); diff --git a/src/liballoc/Cargo.toml b/src/liballoc/Cargo.toml index b7faee1bc7d..b2eb3566c04 100644 --- a/src/liballoc/Cargo.toml +++ b/src/liballoc/Cargo.toml @@ -28,3 +28,6 @@ path = "../liballoc/benches/lib.rs" name = "vec_deque_append_bench" path = "../liballoc/benches/vec_deque_append.rs" harness = false + +[features] +compiler-builtins-mem = ['compiler_builtins/mem'] -- cgit 1.4.1-3-g733a5 From 7f9883d79e517741dd3531688d026b1fa4a2a0ad Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sat, 15 Dec 2018 02:34:10 -0800 Subject: Add unstable VecDeque::rotate_{left|right} --- src/liballoc/collections/vec_deque.rs | 102 ++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs index 0c5926fbaf1..954a1c8becf 100644 --- a/src/liballoc/collections/vec_deque.rs +++ b/src/liballoc/collections/vec_deque.rs @@ -1927,6 +1927,108 @@ impl VecDeque { self.truncate(new_len); } } + + /// Rotates the double-ended queue `mid` places to the left. + /// + /// Equivalently, + /// - Rotates item `mid` into the first position. + /// - Pops the first `mid` items and pushes them to the end. + /// - Rotates `len() - mid` places to the right. + /// + /// # Panics + /// + /// If `mid` is greater than `len()`. Note that `mid == len()` + /// does _not_ panic and is a no-op rotation. + /// + /// # Complexity + /// + /// Takes `O(min(mid, len() - mid))` time and no extra space. + /// + /// # Examples + /// + /// ``` + /// #![feature(vecdeque_rotate)] + /// + /// use std::collections::VecDeque; + /// + /// let mut buf: VecDeque<_> = (0..10).collect(); + /// + /// buf.rotate_left(3); + /// assert_eq!(buf, [3, 4, 5, 6, 7, 8, 9, 0, 1, 2]); + /// + /// for i in 1..10 { + /// assert_eq!(i * 3 % 10, buf[0]); + /// buf.rotate_left(3); + /// } + /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + /// ``` + #[unstable(feature = "vecdeque_rotate", issue = "56686")] + pub fn rotate_left(&mut self, mid: usize) { + assert!(mid <= self.len()); + let k = self.len() - mid; + if mid <= k { + unsafe { self.rotate_left_inner(mid) } + } else { + unsafe { self.rotate_right_inner(k) } + } + } + + /// Rotates the double-ended queue `k` places to the right. + /// + /// Equivalently, + /// - Rotates the first item into position `k`. + /// - Pops the last `k` items and pushes them to the front. + /// - Rotates `len() - k` places to the left. + /// + /// # Panics + /// + /// If `k` is greater than `len()`. Note that `k == len()` + /// does _not_ panic and is a no-op rotation. + /// + /// # Complexity + /// + /// Takes `O(min(k, len() - k))` time and no extra space. + /// + /// # Examples + /// + /// ``` + /// #![feature(vecdeque_rotate)] + /// + /// use std::collections::VecDeque; + /// + /// let mut buf: VecDeque<_> = (0..10).collect(); + /// + /// buf.rotate_right(3); + /// assert_eq!(buf, [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]); + /// + /// for i in 1..10 { + /// assert_eq!(0, buf[i * 3 % 10]); + /// buf.rotate_right(3); + /// } + /// assert_eq!(buf, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + /// ``` + #[unstable(feature = "vecdeque_rotate", issue = "56686")] + pub fn rotate_right(&mut self, k: usize) { + assert!(k <= self.len()); + let mid = self.len() - k; + if k <= mid { + unsafe { self.rotate_right_inner(k) } + } else { + unsafe { self.rotate_left_inner(mid) } + } + } + + unsafe fn rotate_left_inner(&mut self, mid: usize) { + self.wrap_copy(self.head, self.tail, mid); + self.head = self.wrap_add(self.head, mid); + self.tail = self.wrap_add(self.tail, mid); + } + + unsafe fn rotate_right_inner(&mut self, k: usize) { + self.head = self.wrap_sub(self.head, k); + self.tail = self.wrap_sub(self.tail, k); + self.wrap_copy(self.tail, self.head, k); + } } impl VecDeque { -- cgit 1.4.1-3-g733a5 From 08155314889e9c9b4cb0e35c117cc4ba93c29388 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Sat, 15 Dec 2018 16:33:23 -0800 Subject: Add a note about why the unsafe is sound --- src/liballoc/collections/vec_deque.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs index 954a1c8becf..5171ca254e4 100644 --- a/src/liballoc/collections/vec_deque.rs +++ b/src/liballoc/collections/vec_deque.rs @@ -2018,13 +2018,23 @@ impl VecDeque { } } + // Safety: the following two methods require that the rotation amount + // be less than half the length of the deque. + // + // `wrap_copy` requres that `min(x, cap() - x) + copy_len <= cap()`, + // but than `min` is never more than half the capacity, regardless of x, + // so it's sound to call here because we're calling with something + // less than half the length, which is never above half the capacity. + unsafe fn rotate_left_inner(&mut self, mid: usize) { + debug_assert!(mid * 2 <= self.len()); self.wrap_copy(self.head, self.tail, mid); self.head = self.wrap_add(self.head, mid); self.tail = self.wrap_add(self.tail, mid); } unsafe fn rotate_right_inner(&mut self, k: usize) { + debug_assert!(k * 2 <= self.len()); self.head = self.wrap_sub(self.head, k); self.tail = self.wrap_sub(self.tail, k); self.wrap_copy(self.tail, self.head, k); -- cgit 1.4.1-3-g733a5 From 82e55c1bdcf0a20a2652152447160414a9cd57d7 Mon Sep 17 00:00:00 2001 From: Andy Russell Date: Mon, 17 Dec 2018 21:10:24 -0500 Subject: deny intra-doc link resolution failures in libstd --- src/liballoc/lib.rs | 2 ++ src/liballoc/rc.rs | 5 ++++- src/liballoc/sync.rs | 5 ++++- src/libcore/lib.rs | 1 + src/libcore/mem.rs | 3 +++ src/libcore/slice/mod.rs | 2 ++ src/libstd/io/buffered.rs | 5 ++++- src/libstd/io/error.rs | 3 +++ src/libstd/lib.rs | 1 + 9 files changed, 24 insertions(+), 3 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index abacc62c856..31a4aeeab4b 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -72,6 +72,8 @@ test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))] #![no_std] #![needs_allocator] + +#![deny(intra_doc_link_resolution_failure)] #![deny(missing_debug_implementations)] #![cfg_attr(not(test), feature(fn_traits))] diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 52ad30c411a..37204bc20c2 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -840,6 +840,8 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { /// drop(foo); // Doesn't print anything /// drop(foo2); // Prints "dropped!" /// ``` + /// + /// [`Weak`]: ../../std/rc/struct.Weak.html fn drop(&mut self) { unsafe { self.dec_strong(); @@ -1381,9 +1383,10 @@ impl fmt::Debug for Weak { #[stable(feature = "downgraded_weak", since = "1.10.0")] impl Default for Weak { /// Constructs a new `Weak`, allocating memory for `T` without initializing - /// it. Calling [`upgrade`][Weak::upgrade] on the return value always gives [`None`]. + /// it. Calling [`upgrade`] on the return value always gives [`None`]. /// /// [`None`]: ../../std/option/enum.Option.html + /// [`upgrade`]: ../../std/rc/struct.Weak.html#method.upgrade /// /// # Examples /// diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index 111459d12a4..5f72b232c64 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -952,6 +952,8 @@ unsafe impl<#[may_dangle] T: ?Sized> Drop for Arc { /// drop(foo); // Doesn't print anything /// drop(foo2); // Prints "dropped!" /// ``` + /// + /// [`Weak`]: ../../std/sync/struct.Weak.html #[inline] fn drop(&mut self) { // Because `fetch_sub` is already atomic, we do not need to synchronize @@ -1219,10 +1221,11 @@ impl Clone for Weak { #[stable(feature = "downgraded_weak", since = "1.10.0")] impl Default for Weak { /// Constructs a new `Weak`, without allocating memory. - /// Calling [`upgrade`][Weak::upgrade] on the return value always + /// Calling [`upgrade`] on the return value always /// gives [`None`]. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None + /// [`upgrade`]: ../../std/sync/struct.Weak.html#method.upgrade /// /// # Examples /// diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index a51674fbfc7..258f499d444 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -71,6 +71,7 @@ #![no_core] #![deny(missing_docs)] +#![deny(intra_doc_link_resolution_failure)] #![deny(missing_debug_implementations)] #![feature(allow_internal_unstable)] diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index afd9fcb1fba..0cde23cde40 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -984,6 +984,9 @@ impl ManuallyDrop { /// /// This function semantically moves out the contained value without preventing further usage. /// It is up to the user of this method to ensure that this container is not used again. + /// + /// [`ManuallyDrop::drop`]: #method.drop + /// [`ManuallyDrop::into_inner`]: #method.into_inner #[must_use = "if you don't need the value, you can use `ManuallyDrop::drop` instead"] #[unstable(feature = "manually_drop_take", issue = "55422")] #[inline] diff --git a/src/libcore/slice/mod.rs b/src/libcore/slice/mod.rs index 59c11b27329..193061457b5 100644 --- a/src/libcore/slice/mod.rs +++ b/src/libcore/slice/mod.rs @@ -877,6 +877,7 @@ impl [T] { /// assert_eq!(iter.remainder(), &['l']); /// ``` /// + /// [`chunks`]: #method.chunks /// [`rchunks`]: #method.rchunks /// [`chunks_exact`]: #method.chunks_exact #[stable(feature = "rchunks", since = "1.31.0")] @@ -921,6 +922,7 @@ impl [T] { /// assert_eq!(v, &[0, 2, 2, 1, 1]); /// ``` /// + /// [`chunks_mut`]: #method.chunks_mut /// [`rchunks_mut`]: #method.rchunks_mut /// [`chunks_exact_mut`]: #method.chunks_exact_mut #[stable(feature = "rchunks", since = "1.31.0")] diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 7ede050da6c..7aaf89cd0ff 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -294,7 +294,7 @@ impl Seek for BufReader { /// `.into_inner()` immediately after a seek yields the underlying reader /// at the same position. /// - /// To seek without discarding the internal buffer, use [`Seek::seek_relative`]. + /// To seek without discarding the internal buffer, use [`BufReader::seek_relative`]. /// /// See [`std::io::Seek`] for more details. /// @@ -303,6 +303,9 @@ impl Seek for BufReader { /// seeks will be performed instead of one. If the second seek returns /// `Err`, the underlying reader will be left at the same position it would /// have if you called `seek` with `SeekFrom::Current(0)`. + /// + /// [`BufReader::seek_relative`]: struct.BufReader.html#method.seek_relative + /// [`std::io::Seek`]: trait.Seek.html fn seek(&mut self, pos: SeekFrom) -> io::Result { let result: u64; if let SeekFrom::Current(n) = pos { diff --git a/src/libstd/io/error.rs b/src/libstd/io/error.rs index d3844ebe19e..324852355b0 100644 --- a/src/libstd/io/error.rs +++ b/src/libstd/io/error.rs @@ -225,6 +225,9 @@ impl From for Error { /// let error = Error::from(not_found); /// assert_eq!("entity not found", format!("{}", error)); /// ``` + /// + /// [`ErrorKind`]: ../../std/io/enum.ErrorKind.html + /// [`Error`]: ../../std/io/struct.Error.html #[inline] fn from(kind: ErrorKind) -> Error { Error { diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index ead38f21126..13de55a6a54 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -222,6 +222,7 @@ #![no_std] #![deny(missing_docs)] +#![deny(intra_doc_link_resolution_failure)] #![deny(missing_debug_implementations)] // Tell the compiler to link to either panic_abort or panic_unwind -- cgit 1.4.1-3-g733a5 From cbe9abb78cd6c1b8c74b78110b8c92c1f0984ba0 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Wed, 19 Dec 2018 00:38:15 -0800 Subject: Add more VecDeque::rotate_{left|right} tests --- src/liballoc/tests/lib.rs | 3 +- src/liballoc/tests/vec_deque.rs | 134 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 136 insertions(+), 1 deletion(-) (limited to 'src/liballoc') diff --git a/src/liballoc/tests/lib.rs b/src/liballoc/tests/lib.rs index e514a8a69c0..146abd1b750 100644 --- a/src/liballoc/tests/lib.rs +++ b/src/liballoc/tests/lib.rs @@ -13,11 +13,12 @@ #![feature(drain_filter)] #![feature(exact_size_is_empty)] #![feature(pattern)] +#![feature(repeat_generic_slice)] #![feature(slice_sort_by_cached_key)] #![feature(str_escape)] #![feature(try_reserve)] #![feature(unboxed_closures)] -#![feature(repeat_generic_slice)] +#![feature(vecdeque_rotate)] extern crate core; extern crate rand; diff --git a/src/liballoc/tests/vec_deque.rs b/src/liballoc/tests/vec_deque.rs index 1f2a7211c65..c8a6d86413a 100644 --- a/src/liballoc/tests/vec_deque.rs +++ b/src/liballoc/tests/vec_deque.rs @@ -1309,3 +1309,137 @@ fn test_try_reserve_exact() { } } + +#[test] +fn test_rotate_nop() { + let mut v: VecDeque<_> = (0..10).collect(); + assert_unchanged(&v); + + v.rotate_left(0); + assert_unchanged(&v); + + v.rotate_left(10); + assert_unchanged(&v); + + v.rotate_right(0); + assert_unchanged(&v); + + v.rotate_right(10); + assert_unchanged(&v); + + v.rotate_left(3); + v.rotate_right(3); + assert_unchanged(&v); + + v.rotate_right(3); + v.rotate_left(3); + assert_unchanged(&v); + + v.rotate_left(6); + v.rotate_right(6); + assert_unchanged(&v); + + v.rotate_right(6); + v.rotate_left(6); + assert_unchanged(&v); + + v.rotate_left(3); + v.rotate_left(7); + assert_unchanged(&v); + + v.rotate_right(4); + v.rotate_right(6); + assert_unchanged(&v); + + v.rotate_left(1); + v.rotate_left(2); + v.rotate_left(3); + v.rotate_left(4); + assert_unchanged(&v); + + v.rotate_right(1); + v.rotate_right(2); + v.rotate_right(3); + v.rotate_right(4); + assert_unchanged(&v); + + fn assert_unchanged(v: &VecDeque) { + assert_eq!(v, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + } +} + +#[test] +fn test_rotate_left_parts() { + let mut v: VecDeque<_> = (1..=7).collect(); + v.rotate_left(2); + assert_eq!(v.as_slices(), (&[3, 4, 5, 6, 7, 1][..], &[2][..])); + v.rotate_left(2); + assert_eq!(v.as_slices(), (&[5, 6, 7, 1][..], &[2, 3, 4][..])); + v.rotate_left(2); + assert_eq!(v.as_slices(), (&[7, 1][..], &[2, 3, 4, 5, 6][..])); + v.rotate_left(2); + assert_eq!(v.as_slices(), (&[2, 3, 4, 5, 6, 7, 1][..], &[][..])); + v.rotate_left(2); + assert_eq!(v.as_slices(), (&[4, 5, 6, 7, 1, 2][..], &[3][..])); + v.rotate_left(2); + assert_eq!(v.as_slices(), (&[6, 7, 1, 2][..], &[3, 4, 5][..])); + v.rotate_left(2); + assert_eq!(v.as_slices(), (&[1, 2][..], &[3, 4, 5, 6, 7][..])); +} + +#[test] +fn test_rotate_right_parts() { + let mut v: VecDeque<_> = (1..=7).collect(); + v.rotate_right(2); + assert_eq!(v.as_slices(), (&[6, 7][..], &[1, 2, 3, 4, 5][..])); + v.rotate_right(2); + assert_eq!(v.as_slices(), (&[4, 5, 6, 7][..], &[1, 2, 3][..])); + v.rotate_right(2); + assert_eq!(v.as_slices(), (&[2, 3, 4, 5, 6, 7][..], &[1][..])); + v.rotate_right(2); + assert_eq!(v.as_slices(), (&[7, 1, 2, 3, 4, 5, 6][..], &[][..])); + v.rotate_right(2); + assert_eq!(v.as_slices(), (&[5, 6][..], &[7, 1, 2, 3, 4][..])); + v.rotate_right(2); + assert_eq!(v.as_slices(), (&[3, 4, 5, 6][..], &[7, 1, 2][..])); + v.rotate_right(2); + assert_eq!(v.as_slices(), (&[1, 2, 3, 4, 5, 6][..], &[7][..])); +} + +#[test] +fn test_rotate_left_random() { + let shifts = [ + 6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, + 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, + 9, 4, 12, 3, 12, 9, 11, 1, 7, 9, 7, 2, + ]; + let n = 12; + let mut v: VecDeque<_> = (0..n).collect(); + let mut total_shift = 0; + for shift in shifts.iter().cloned() { + v.rotate_left(shift); + total_shift += shift; + for i in 0..n { + assert_eq!(v[i], (i + total_shift) % n); + } + } +} + +#[test] +fn test_rotate_right_random() { + let shifts = [ + 6, 1, 0, 11, 12, 1, 11, 7, 9, 3, 6, 1, + 4, 0, 5, 1, 3, 1, 12, 8, 3, 1, 11, 11, + 9, 4, 12, 3, 12, 9, 11, 1, 7, 9, 7, 2, + ]; + let n = 12; + let mut v: VecDeque<_> = (0..n).collect(); + let mut total_shift = 0; + for shift in shifts.iter().cloned() { + v.rotate_right(shift); + total_shift += shift; + for i in 0..n { + assert_eq!(v[(i + total_shift) % n], i); + } + } +} -- cgit 1.4.1-3-g733a5 From 7b6cf6e87b5d0d54687dd56a803d3a86f1994182 Mon Sep 17 00:00:00 2001 From: Scott McMurray Date: Wed, 19 Dec 2018 22:00:25 -0800 Subject: Stabilize Vec(Deque)::resize_with Closes #41758 --- src/liballoc/collections/vec_deque.rs | 4 +--- src/liballoc/vec.rs | 4 +--- src/librustc_data_structures/lib.rs | 1 - 3 files changed, 2 insertions(+), 7 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/collections/vec_deque.rs b/src/liballoc/collections/vec_deque.rs index 0c5926fbaf1..99b1ad8d6e2 100644 --- a/src/liballoc/collections/vec_deque.rs +++ b/src/liballoc/collections/vec_deque.rs @@ -1897,8 +1897,6 @@ impl VecDeque { /// # Examples /// /// ``` - /// #![feature(vec_resize_with)] - /// /// use std::collections::VecDeque; /// /// let mut buf = VecDeque::new(); @@ -1917,7 +1915,7 @@ impl VecDeque { /// buf.resize_with(5, || { state += 1; state }); /// assert_eq!(buf, [5, 10, 101, 102, 103]); /// ``` - #[unstable(feature = "vec_resize_with", issue = "41758")] + #[stable(feature = "vec_resize_with", since = "1.33.0")] pub fn resize_with(&mut self, new_len: usize, generator: impl FnMut()->T) { let len = self.len(); diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs index 63af69dda1d..b78e71331a9 100644 --- a/src/liballoc/vec.rs +++ b/src/liballoc/vec.rs @@ -1241,8 +1241,6 @@ impl Vec { /// # Examples /// /// ``` - /// #![feature(vec_resize_with)] - /// /// let mut vec = vec![1, 2, 3]; /// vec.resize_with(5, Default::default); /// assert_eq!(vec, [1, 2, 3, 0, 0]); @@ -1255,7 +1253,7 @@ impl Vec { /// /// [`resize`]: #method.resize /// [`Clone`]: ../../std/clone/trait.Clone.html - #[unstable(feature = "vec_resize_with", issue = "41758")] + #[stable(feature = "vec_resize_with", since = "1.33.0")] pub fn resize_with(&mut self, new_len: usize, f: F) where F: FnMut() -> T { diff --git a/src/librustc_data_structures/lib.rs b/src/librustc_data_structures/lib.rs index bc2b8f1d652..9e29b2798d8 100644 --- a/src/librustc_data_structures/lib.rs +++ b/src/librustc_data_structures/lib.rs @@ -28,7 +28,6 @@ #![feature(optin_builtin_traits)] #![feature(nll)] #![feature(allow_internal_unstable)] -#![feature(vec_resize_with)] #![feature(hash_raw_entry)] #![feature(stmt_expr_attributes)] #![feature(core_intrinsics)] -- cgit 1.4.1-3-g733a5 From 153f5a7892274764256862692fa7e2c51474e5d0 Mon Sep 17 00:00:00 2001 From: Michael Hewson Date: Tue, 20 Nov 2018 11:50:50 -0500 Subject: Stabilize `Rc`, `Arc` and `Pin` as method receivers This lets you write methods using `self: Rc`, `self: Arc`, `self: Pin<&mut Self>`, `self: Pin`, and other combinations involving `Pin` and another stdlib receiver type, without needing the `arbitrary_self_types`. Other user-created receiver types can be used, but they still require the feature flag to use. This is implemented by introducing a new trait, `Receiver`, which the method receiver's type must implement if the `arbitrary_self_types` feature is not enabled. To keep composed receiver types such as `&Arc` unstable, the receiver type is also required to implement `Deref` when the feature flag is not enabled. This lets you use `self: Rc` and `self: Arc` in stable Rust, which was not allowed previously. It was agreed that they would be stabilized in #55786. `self: Pin<&Self>` and other pinned receiver types do not require the `arbitrary_self_types` feature, but they cannot be used on stable because `Pin` still requires the `pin` feature. --- src/liballoc/boxed.rs | 7 +- src/liballoc/lib.rs | 1 + src/liballoc/rc.rs | 5 +- src/liballoc/sync.rs | 5 +- src/libcore/ops/deref.rs | 16 ++ src/libcore/ops/mod.rs | 3 + src/libcore/pin.rs | 5 +- src/librustc/middle/lang_items.rs | 1 + src/librustc_typeck/check/wfcheck.rs | 185 +++++++++++++++------ .../arbitrary_self_types_stdlib_pointers.rs | 9 +- .../feature-gate-arbitrary-self-types.rs | 20 ++- .../feature-gate-arbitrary-self-types.stderr | 24 +-- ...eature-gate-arbitrary_self_types-raw-pointer.rs | 6 +- ...re-gate-arbitrary_self_types-raw-pointer.stderr | 6 +- src/test/ui/privacy/privacy1.rs | 14 ++ src/test/ui/privacy/privacy1.stderr | 34 ++-- 16 files changed, 250 insertions(+), 91 deletions(-) (limited to 'src/liballoc') diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 83adcce5c74..f1581310b48 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -77,7 +77,9 @@ use core::iter::{Iterator, FromIterator, FusedIterator}; use core::marker::{Unpin, Unsize}; use core::mem; use core::pin::Pin; -use core::ops::{CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Generator, GeneratorState}; +use core::ops::{ + CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState +}; use core::ptr::{self, NonNull, Unique}; use core::task::{LocalWaker, Poll}; @@ -583,6 +585,9 @@ impl DerefMut for Box { } } +#[unstable(feature = "receiver_trait", issue = "0")] +impl Receiver for Box {} + #[stable(feature = "rust1", since = "1.0.0")] impl Iterator for Box { type Item = I::Item; diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index abacc62c856..e00e430fab6 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -104,6 +104,7 @@ #![feature(ptr_internals)] #![feature(ptr_offset_from)] #![feature(rustc_attrs)] +#![feature(receiver_trait)] #![feature(specialization)] #![feature(split_ascii_whitespace)] #![feature(staged_api)] diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 6769a70ddbe..3fc70f4ac37 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -253,7 +253,7 @@ use core::intrinsics::abort; use core::marker; use core::marker::{Unpin, Unsize, PhantomData}; use core::mem::{self, align_of_val, forget, size_of_val}; -use core::ops::Deref; +use core::ops::{Deref, Receiver}; use core::ops::{CoerceUnsized, DispatchFromDyn}; use core::pin::Pin; use core::ptr::{self, NonNull}; @@ -813,6 +813,9 @@ impl Deref for Rc { } } +#[unstable(feature = "receiver_trait", issue = "0")] +impl Receiver for Rc {} + #[stable(feature = "rust1", since = "1.0.0")] unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { /// Drops the `Rc`. diff --git a/src/liballoc/sync.rs b/src/liballoc/sync.rs index e596694fb9d..55737016608 100644 --- a/src/liballoc/sync.rs +++ b/src/liballoc/sync.rs @@ -24,7 +24,7 @@ use core::fmt; use core::cmp::Ordering; use core::intrinsics::abort; use core::mem::{self, align_of_val, size_of_val}; -use core::ops::Deref; +use core::ops::{Deref, Receiver}; use core::ops::{CoerceUnsized, DispatchFromDyn}; use core::pin::Pin; use core::ptr::{self, NonNull}; @@ -767,6 +767,9 @@ impl Deref for Arc { } } +#[unstable(feature = "receiver_trait", issue = "0")] +impl Receiver for Arc {} + impl Arc { /// Makes a mutable reference into the given `Arc`. /// diff --git a/src/libcore/ops/deref.rs b/src/libcore/ops/deref.rs index 91a3d77e8b2..ff836f4aa69 100644 --- a/src/libcore/ops/deref.rs +++ b/src/libcore/ops/deref.rs @@ -177,3 +177,19 @@ pub trait DerefMut: Deref { impl DerefMut for &mut T { fn deref_mut(&mut self) -> &mut T { *self } } + +/// Indicates that a struct can be used as a method receiver, without the +/// `arbitrary_self_types` feature. This is implemented by stdlib pointer types like `Box`, +/// `Rc`, `&T`, and `Pin

`. +#[cfg_attr(not(stage0), lang = "receiver")] +#[unstable(feature = "receiver_trait", issue = "0")] +#[doc(hidden)] +pub trait Receiver { + // Empty. +} + +#[unstable(feature = "receiver_trait", issue = "0")] +impl Receiver for &T {} + +#[unstable(feature = "receiver_trait", issue = "0")] +impl Receiver for &mut T {} diff --git a/src/libcore/ops/mod.rs b/src/libcore/ops/mod.rs index 785f0733df2..06740d2e4cd 100644 --- a/src/libcore/ops/mod.rs +++ b/src/libcore/ops/mod.rs @@ -178,6 +178,9 @@ pub use self::bit::{BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssig #[stable(feature = "rust1", since = "1.0.0")] pub use self::deref::{Deref, DerefMut}; +#[unstable(feature = "receiver_trait", issue = "0")] +pub use self::deref::Receiver; + #[stable(feature = "rust1", since = "1.0.0")] pub use self::drop::Drop; diff --git a/src/libcore/pin.rs b/src/libcore/pin.rs index 0ad6e8c7c1c..521ce9b5f6b 100644 --- a/src/libcore/pin.rs +++ b/src/libcore/pin.rs @@ -101,7 +101,7 @@ use fmt; use marker::Sized; -use ops::{Deref, DerefMut, CoerceUnsized, DispatchFromDyn}; +use ops::{Deref, DerefMut, Receiver, CoerceUnsized, DispatchFromDyn}; #[doc(inline)] pub use marker::Unpin; @@ -302,6 +302,9 @@ where } } +#[unstable(feature = "receiver_trait", issue = "0")] +impl Receiver for Pin

{} + #[unstable(feature = "pin", issue = "49150")] impl fmt::Debug for Pin

{ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 23ec24d71d2..cfcc7c83719 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -301,6 +301,7 @@ language_item_table! { DerefTraitLangItem, "deref", deref_trait, Target::Trait; DerefMutTraitLangItem, "deref_mut", deref_mut_trait, Target::Trait; + ReceiverTraitLangItem, "receiver", receiver_trait, Target::Trait; FnTraitLangItem, "fn", fn_trait, Target::Trait; FnMutTraitLangItem, "fn_mut", fn_mut_trait, Target::Trait; diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index e24548cfb23..be8e36afdd6 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -13,9 +13,8 @@ use constrained_type_params::{identify_constrained_type_params, Parameter}; use hir::def_id::DefId; use rustc::traits::{self, ObligationCauseCode}; -use rustc::ty::{self, Lift, Ty, TyCtxt, TyKind, GenericParamDefKind, TypeFoldable}; +use rustc::ty::{self, Lift, Ty, TyCtxt, TyKind, GenericParamDefKind, TypeFoldable, ToPredicate}; use rustc::ty::subst::{Subst, Substs}; -use rustc::ty::util::ExplicitSelf; use rustc::util::nodemap::{FxHashSet, FxHashMap}; use rustc::middle::lang_items; use rustc::infer::opaque_types::may_define_existential_type; @@ -749,72 +748,164 @@ fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>, &ty::Binder::bind(self_ty) ); - let self_arg_ty = sig.inputs()[0]; + let receiver_ty = sig.inputs()[0]; - let cause = fcx.cause(span, ObligationCauseCode::MethodReceiver); - let self_arg_ty = fcx.normalize_associated_types_in(span, &self_arg_ty); - let self_arg_ty = fcx.tcx.liberate_late_bound_regions( + let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty); + let receiver_ty = fcx.tcx.liberate_late_bound_regions( method.def_id, - &ty::Binder::bind(self_arg_ty) + &ty::Binder::bind(receiver_ty) ); - let mut autoderef = fcx.autoderef(span, self_arg_ty).include_raw_pointers(); - - loop { - if let Some((potential_self_ty, _)) = autoderef.next() { - debug!("check_method_receiver: potential self type `{:?}` to match `{:?}`", - potential_self_ty, self_ty); - - if fcx.infcx.can_eq(fcx.param_env, self_ty, potential_self_ty).is_ok() { - autoderef.finalize(fcx); - if let Some(mut err) = fcx.demand_eqtype_with_origin( - &cause, self_ty, potential_self_ty) { - err.emit(); - } - break - } - } else { + if fcx.tcx.features().arbitrary_self_types { + if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) { + // report error, arbitrary_self_types was enabled fcx.tcx.sess.diagnostic().mut_span_err( - span, &format!("invalid `self` type: {:?}", self_arg_ty)) - .note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty)) + span, &format!("invalid `self` type: {:?}", receiver_ty) + ).note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty)) .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box`") .code(DiagnosticId::Error("E0307".into())) .emit(); - return } - } - - let is_self_ty = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok(); - let self_kind = ExplicitSelf::determine(self_arg_ty, is_self_ty); - - if !fcx.tcx.features().arbitrary_self_types { - match self_kind { - ExplicitSelf::ByValue | - ExplicitSelf::ByReference(_, _) | - ExplicitSelf::ByBox => (), - - ExplicitSelf::ByRawPointer(_) => { + } else { + if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) { + if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) { + // report error, would have worked with arbitrary_self_types feature_gate::feature_err( &fcx.tcx.sess.parse_sess, "arbitrary_self_types", span, GateIssue::Language, - "raw pointer `self` is unstable") + &format!( + "`{}` cannot be used as the type of `self` without \ + the `arbitrary_self_types` feature", + receiver_ty, + ), + ).help("consider changing to `self`, `&self`, `&mut self`, or `self: Box`") + .emit(); + } else { + // report error, would not have worked with arbitrary_self_types + fcx.tcx.sess.diagnostic().mut_span_err( + span, &format!("invalid `self` type: {:?}", receiver_ty) + ).note(&format!("type must be `{:?}` or a type that dereferences to it", self_ty)) .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box`") + .code(DiagnosticId::Error("E0307".into())) .emit(); } + } + } +} - ExplicitSelf::Other => { - feature_gate::feature_err( - &fcx.tcx.sess.parse_sess, - "arbitrary_self_types", - span, - GateIssue::Language,"arbitrary `self` types are unstable") - .help("consider changing to `self`, `&self`, `&mut self`, or `self: Box`") - .emit(); +fn receiver_is_valid<'fcx, 'tcx, 'gcx>( + fcx: &FnCtxt<'fcx, 'gcx, 'tcx>, + span: Span, + receiver_ty: Ty<'tcx>, + self_ty: Ty<'tcx>, + arbitrary_self_types_enabled: bool, +) -> bool { + let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver); + + let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok(); + + if can_eq_self(receiver_ty) { + if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) { + err.emit(); + } + return true + } + + let mut autoderef = fcx.autoderef(span, receiver_ty); + + if arbitrary_self_types_enabled { + autoderef = autoderef.include_raw_pointers(); + } + + // skip the first type, we know its not equal to `self_ty` + autoderef.next(); + + let potential_self_ty = loop { + if let Some((potential_self_ty, _)) = autoderef.next() { + debug!("receiver_is_valid: potential self type `{:?}` to match `{:?}`", + potential_self_ty, self_ty); + + if can_eq_self(potential_self_ty) { + break potential_self_ty + } + } else { + debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", + receiver_ty, self_ty); + return false + } + }; + + if !arbitrary_self_types_enabled { + // check that receiver_ty: Receiver + + let receiver_trait_def_id = match fcx.tcx.lang_items().receiver_trait() { + Some(did) => did, + None => { + debug!("receiver_is_valid: missing Receiver trait"); + return false } + }; + + let receiver_trait_ref = ty::TraitRef{ + def_id: receiver_trait_def_id, + substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]), + }; + + let receiver_obligation = traits::Obligation::new( + cause.clone(), + fcx.param_env, + receiver_trait_ref.to_predicate() + ); + + if !fcx.predicate_must_hold(&receiver_obligation) { + debug!("receiver_is_valid: type `{:?}` does not implement `Receiver` trait", + receiver_ty); + return false + } + + let deref_trait_def_id = match fcx.tcx.lang_items().deref_trait() { + Some(did) => did, + None => { + debug!("receiver_is_valid: missing Deref trait"); + return false + } + }; + + let deref_trait_ref = ty::TraitRef { + def_id: deref_trait_def_id, + substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]), + }; + + let projection_ty = ty::ProjectionTy::from_ref_and_name( + fcx.tcx, deref_trait_ref, ast::Ident::from_str("Target") + ); + + let projection_predicate = ty::Binder::dummy(ty::ProjectionPredicate { + projection_ty, ty: self_ty + }).to_predicate(); + + let deref_obligation = traits::Obligation::new( + cause.clone(), + fcx.param_env, + projection_predicate, + ); + + if !fcx.predicate_must_hold(&deref_obligation) { + debug!("receiver_is_valid: type `{:?}` does not directly deref to `{:?}`", + receiver_ty, self_ty); + return false } } + + if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty) { + err.emit(); + } + + autoderef.finalize(fcx); + + true } fn check_variances_for_type_defn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, diff --git a/src/test/run-pass/arbitrary_self_types_stdlib_pointers.rs b/src/test/run-pass/arbitrary_self_types_stdlib_pointers.rs index 80a7ce96911..6ec70bb8c09 100644 --- a/src/test/run-pass/arbitrary_self_types_stdlib_pointers.rs +++ b/src/test/run-pass/arbitrary_self_types_stdlib_pointers.rs @@ -8,7 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![feature(arbitrary_self_types)] #![feature(pin)] #![feature(rustc_attrs)] @@ -23,6 +22,7 @@ trait Trait { fn by_arc(self: Arc) -> i64; fn by_pin_mut(self: Pin<&mut Self>) -> i64; fn by_pin_box(self: Pin>) -> i64; + fn by_pin_pin_pin_ref(self: Pin>>) -> i64; } impl Trait for i64 { @@ -38,6 +38,9 @@ impl Trait for i64 { fn by_pin_box(self: Pin>) -> i64 { *self } + fn by_pin_pin_pin_ref(self: Pin>>) -> i64 { + *self + } } fn main() { @@ -53,4 +56,8 @@ fn main() { let pin_box = Into::>>::into(Box::new(4i64)) as Pin>; assert_eq!(4, pin_box.by_pin_box()); + + let value = 5i64; + let pin_pin_pin_ref = Pin::new(Pin::new(Pin::new(&value))) as Pin>>; + assert_eq!(5, pin_pin_pin_ref.by_pin_pin_pin_ref()); } diff --git a/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.rs b/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.rs index ff0306f1993..84cd5c2bffa 100644 --- a/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.rs +++ b/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.rs @@ -8,20 +8,32 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::rc::Rc; +use std::{ + ops::Deref, +}; + +struct Ptr(Box); + +impl Deref for Ptr { + type Target = T; + + fn deref(&self) -> &T { + &*self.0 + } +} trait Foo { - fn foo(self: Rc>); //~ ERROR arbitrary `self` types are unstable + fn foo(self: Ptr); //~ ERROR `Ptr` cannot be used as the type of `self` without } struct Bar; impl Foo for Bar { - fn foo(self: Rc>) {} //~ ERROR arbitrary `self` types are unstable + fn foo(self: Ptr) {} //~ ERROR `Ptr` cannot be used as the type of `self` without } impl Bar { - fn bar(self: Box>) {} //~ ERROR arbitrary `self` types are unstable + fn bar(self: Box>) {} //~ ERROR `std::boxed::Box>` cannot be used as the } fn main() {} diff --git a/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.stderr b/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.stderr index ea259aa22ad..c70774b3710 100644 --- a/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.stderr +++ b/src/test/ui/feature-gates/feature-gate-arbitrary-self-types.stderr @@ -1,26 +1,26 @@ -error[E0658]: arbitrary `self` types are unstable (see issue #44874) - --> $DIR/feature-gate-arbitrary-self-types.rs:14:18 +error[E0658]: `Ptr` cannot be used as the type of `self` without the `arbitrary_self_types` feature (see issue #44874) + --> $DIR/feature-gate-arbitrary-self-types.rs:26:18 | -LL | fn foo(self: Rc>); //~ ERROR arbitrary `self` types are unstable - | ^^^^^^^^^^^^^ +LL | fn foo(self: Ptr); //~ ERROR `Ptr` cannot be used as the type of `self` without + | ^^^^^^^^^ | = help: add #![feature(arbitrary_self_types)] to the crate attributes to enable = help: consider changing to `self`, `&self`, `&mut self`, or `self: Box` -error[E0658]: arbitrary `self` types are unstable (see issue #44874) - --> $DIR/feature-gate-arbitrary-self-types.rs:20:18 +error[E0658]: `Ptr` cannot be used as the type of `self` without the `arbitrary_self_types` feature (see issue #44874) + --> $DIR/feature-gate-arbitrary-self-types.rs:32:18 | -LL | fn foo(self: Rc>) {} //~ ERROR arbitrary `self` types are unstable - | ^^^^^^^^^^^^^ +LL | fn foo(self: Ptr) {} //~ ERROR `Ptr` cannot be used as the type of `self` without + | ^^^^^^^^^ | = help: add #![feature(arbitrary_self_types)] to the crate attributes to enable = help: consider changing to `self`, `&self`, `&mut self`, or `self: Box` -error[E0658]: arbitrary `self` types are unstable (see issue #44874) - --> $DIR/feature-gate-arbitrary-self-types.rs:24:18 +error[E0658]: `std::boxed::Box>` cannot be used as the type of `self` without the `arbitrary_self_types` feature (see issue #44874) + --> $DIR/feature-gate-arbitrary-self-types.rs:36:18 | -LL | fn bar(self: Box>) {} //~ ERROR arbitrary `self` types are unstable - | ^^^^^^^^^^^^^ +LL | fn bar(self: Box>) {} //~ ERROR `std::boxed::Box>` cannot be used as the + | ^^^^^^^^^^^^^^ | = help: add #![feature(arbitrary_self_types)] to the crate attributes to enable = help: consider changing to `self`, `&self`, `&mut self`, or `self: Box` diff --git a/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.rs b/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.rs index 29e51727edc..6d42460ba56 100644 --- a/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.rs +++ b/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.rs @@ -12,17 +12,17 @@ struct Foo; impl Foo { fn foo(self: *const Self) {} - //~^ ERROR raw pointer `self` is unstable + //~^ ERROR `*const Foo` cannot be used as the type of `self` without } trait Bar { fn bar(self: *const Self); - //~^ ERROR raw pointer `self` is unstable + //~^ ERROR `*const Self` cannot be used as the type of `self` without } impl Bar for () { fn bar(self: *const Self) {} - //~^ ERROR raw pointer `self` is unstable + //~^ ERROR `*const ()` cannot be used as the type of `self` without } fn main() {} diff --git a/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.stderr b/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.stderr index 5ed9a0f4ed0..b8cc7dee986 100644 --- a/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.stderr +++ b/src/test/ui/feature-gates/feature-gate-arbitrary_self_types-raw-pointer.stderr @@ -1,4 +1,4 @@ -error[E0658]: raw pointer `self` is unstable (see issue #44874) +error[E0658]: `*const Self` cannot be used as the type of `self` without the `arbitrary_self_types` feature (see issue #44874) --> $DIR/feature-gate-arbitrary_self_types-raw-pointer.rs:19:18 | LL | fn bar(self: *const Self); @@ -7,7 +7,7 @@ LL | fn bar(self: *const Self); = help: add #![feature(arbitrary_self_types)] to the crate attributes to enable = help: consider changing to `self`, `&self`, `&mut self`, or `self: Box` -error[E0658]: raw pointer `self` is unstable (see issue #44874) +error[E0658]: `*const Foo` cannot be used as the type of `self` without the `arbitrary_self_types` feature (see issue #44874) --> $DIR/feature-gate-arbitrary_self_types-raw-pointer.rs:14:18 | LL | fn foo(self: *const Self) {} @@ -16,7 +16,7 @@ LL | fn foo(self: *const Self) {} = help: add #![feature(arbitrary_self_types)] to the crate attributes to enable = help: consider changing to `self`, `&self`, `&mut self`, or `self: Box` -error[E0658]: raw pointer `self` is unstable (see issue #44874) +error[E0658]: `*const ()` cannot be used as the type of `self` without the `arbitrary_self_types` feature (see issue #44874) --> $DIR/feature-gate-arbitrary_self_types-raw-pointer.rs:24:18 | LL | fn bar(self: *const Self) {} diff --git a/src/test/ui/privacy/privacy1.rs b/src/test/ui/privacy/privacy1.rs index 9aff4bbc41c..c336cc6299e 100644 --- a/src/test/ui/privacy/privacy1.rs +++ b/src/test/ui/privacy/privacy1.rs @@ -17,6 +17,20 @@ pub trait Sized {} #[lang="copy"] pub trait Copy {} +#[lang="deref"] +pub trait Deref { + type Target; +} + +#[lang="receiver"] +pub trait Receiver: Deref {} + +impl<'a, T> Deref for &'a T { + type Target = T; +} + +impl<'a, T> Receiver for &'a T {} + mod bar { // shouldn't bring in too much pub use self::glob::*; diff --git a/src/test/ui/privacy/privacy1.stderr b/src/test/ui/privacy/privacy1.stderr index d6197575447..54e01cca6c4 100644 --- a/src/test/ui/privacy/privacy1.stderr +++ b/src/test/ui/privacy/privacy1.stderr @@ -1,101 +1,101 @@ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:128:18 + --> $DIR/privacy1.rs:142:18 | LL | use bar::baz::{foo, bar}; | ^^^ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:136:18 + --> $DIR/privacy1.rs:150:18 | LL | use bar::baz; | ^^^ error[E0603]: module `i` is private - --> $DIR/privacy1.rs:160:20 + --> $DIR/privacy1.rs:174:20 | LL | use self::foo::i::A; //~ ERROR: module `i` is private | ^ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:100:16 + --> $DIR/privacy1.rs:114:16 | LL | ::bar::baz::A::foo(); //~ ERROR: module `baz` is private | ^^^ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:101:16 + --> $DIR/privacy1.rs:115:16 | LL | ::bar::baz::A::bar(); //~ ERROR: module `baz` is private | ^^^ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:103:16 + --> $DIR/privacy1.rs:117:16 | LL | ::bar::baz::A.foo2(); //~ ERROR: module `baz` is private | ^^^ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:104:16 + --> $DIR/privacy1.rs:118:16 | LL | ::bar::baz::A.bar2(); //~ ERROR: module `baz` is private | ^^^ error[E0603]: trait `B` is private - --> $DIR/privacy1.rs:108:16 + --> $DIR/privacy1.rs:122:16 | LL | ::bar::B::foo(); //~ ERROR: trait `B` is private | ^ error[E0603]: function `epriv` is private - --> $DIR/privacy1.rs:114:20 + --> $DIR/privacy1.rs:128:20 | LL | ::bar::epriv(); //~ ERROR: function `epriv` is private | ^^^^^ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:123:16 + --> $DIR/privacy1.rs:137:16 | LL | ::bar::baz::foo(); //~ ERROR: module `baz` is private | ^^^ error[E0603]: module `baz` is private - --> $DIR/privacy1.rs:124:16 + --> $DIR/privacy1.rs:138:16 | LL | ::bar::baz::bar(); //~ ERROR: module `baz` is private | ^^^ error[E0603]: trait `B` is private - --> $DIR/privacy1.rs:152:17 + --> $DIR/privacy1.rs:166:17 | LL | impl ::bar::B for f32 { fn foo() -> f32 { 1.0 } } | ^ error[E0624]: method `bar` is private - --> $DIR/privacy1.rs:73:9 + --> $DIR/privacy1.rs:87:9 | LL | self::baz::A::bar(); //~ ERROR: method `bar` is private | ^^^^^^^^^^^^^^^^^ error[E0624]: method `bar` is private - --> $DIR/privacy1.rs:91:5 + --> $DIR/privacy1.rs:105:5 | LL | bar::A::bar(); //~ ERROR: method `bar` is private | ^^^^^^^^^^^ error[E0624]: method `bar` is private - --> $DIR/privacy1.rs:98:9 + --> $DIR/privacy1.rs:112:9 | LL | ::bar::A::bar(); //~ ERROR: method `bar` is private | ^^^^^^^^^^^^^ error[E0624]: method `bar` is private - --> $DIR/privacy1.rs:101:9 + --> $DIR/privacy1.rs:115:9 | LL | ::bar::baz::A::bar(); //~ ERROR: module `baz` is private | ^^^^^^^^^^^^^^^^^^ error[E0624]: method `bar2` is private - --> $DIR/privacy1.rs:104:23 + --> $DIR/privacy1.rs:118:23 | LL | ::bar::baz::A.bar2(); //~ ERROR: module `baz` is private | ^^^^ -- cgit 1.4.1-3-g733a5

", HDRS.len())?; write!(w, "{:?}", block.index())?; write!(w, "