From 3f14f4b3cec811017079564e16a92a1dc9870f41 Mon Sep 17 00:00:00 2001
From: Jacob Pratt <jacob@jhpratt.dev>
Date: Thu, 24 Jun 2021 04:16:11 -0400
Subject: [PATCH] Use `#[non_exhaustive]` where appropriate

Due to the std/alloc split, it is not possible to make
`alloc::collections::TryReserveError::AllocError` non-exhaustive without
having an unstable, doc-hidden method to construct (which negates the
benefits from `#[non_exhaustive]`.
---
 compiler/rustc_metadata/src/dynamic_lib.rs |  7 +++----
 library/core/src/alloc/layout.rs           | 19 +++++++++----------
 library/core/src/cell.rs                   |  7 ++-----
 library/core/src/str/error.rs              |  5 ++---
 library/core/src/str/traits.rs             |  2 +-
 library/proc_macro/src/lib.rs              |  7 +++----
 library/std/src/io/util.rs                 | 14 ++++++--------
 library/std/src/thread/local.rs            |  7 +++----
 8 files changed, 29 insertions(+), 39 deletions(-)

diff --git a/compiler/rustc_metadata/src/dynamic_lib.rs b/compiler/rustc_metadata/src/dynamic_lib.rs
index 1a900ccbf65fa..e8929cd5c0237 100644
--- a/compiler/rustc_metadata/src/dynamic_lib.rs
+++ b/compiler/rustc_metadata/src/dynamic_lib.rs
@@ -70,13 +70,12 @@ mod dl {
         use std::sync::{Mutex, MutexGuard};
 
         pub fn lock() -> MutexGuard<'static, Guard> {
-            static LOCK: SyncLazy<Mutex<Guard>> = SyncLazy::new(|| Mutex::new(Guard { _priv: () }));
+            static LOCK: SyncLazy<Mutex<Guard>> = SyncLazy::new(|| Mutex::new(Guard));
             LOCK.lock().unwrap()
         }
 
-        pub struct Guard {
-            _priv: (),
-        }
+        #[non_exhaustive]
+        pub struct Guard;
 
         impl Guard {
             pub fn get(&mut self) -> Result<(), String> {
diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs
index 0e7667dd89e64..ccf6e420de7a9 100644
--- a/library/core/src/alloc/layout.rs
+++ b/library/core/src/alloc/layout.rs
@@ -60,7 +60,7 @@ impl Layout {
     #[inline]
     pub const fn from_size_align(size: usize, align: usize) -> Result<Self, LayoutError> {
         if !align.is_power_of_two() {
-            return Err(LayoutError { private: () });
+            return Err(LayoutError);
         }
 
         // (power-of-two implies align != 0.)
@@ -78,7 +78,7 @@ impl Layout {
         // Above implies that checking for summation overflow is both
         // necessary and sufficient.
         if size > usize::MAX - (align - 1) {
-            return Err(LayoutError { private: () });
+            return Err(LayoutError);
         }
 
         // SAFETY: the conditions for `from_size_align_unchecked` have been
@@ -288,7 +288,7 @@ impl Layout {
         // > must not overflow (i.e., the rounded value must be less than
         // > `usize::MAX`)
         let padded_size = self.size() + self.padding_needed_for(self.align());
-        let alloc_size = padded_size.checked_mul(n).ok_or(LayoutError { private: () })?;
+        let alloc_size = padded_size.checked_mul(n).ok_or(LayoutError)?;
 
         // SAFETY: self.align is already known to be valid and alloc_size has been
         // padded already.
@@ -346,8 +346,8 @@ impl Layout {
         let new_align = cmp::max(self.align(), next.align());
         let pad = self.padding_needed_for(next.align());
 
-        let offset = self.size().checked_add(pad).ok_or(LayoutError { private: () })?;
-        let new_size = offset.checked_add(next.size()).ok_or(LayoutError { private: () })?;
+        let offset = self.size().checked_add(pad).ok_or(LayoutError)?;
+        let new_size = offset.checked_add(next.size()).ok_or(LayoutError)?;
 
         let layout = Layout::from_size_align(new_size, new_align)?;
         Ok((layout, offset))
@@ -368,7 +368,7 @@ impl Layout {
     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
     #[inline]
     pub fn repeat_packed(&self, n: usize) -> Result<Self, LayoutError> {
-        let size = self.size().checked_mul(n).ok_or(LayoutError { private: () })?;
+        let size = self.size().checked_mul(n).ok_or(LayoutError)?;
         Layout::from_size_align(size, self.align())
     }
 
@@ -381,7 +381,7 @@ impl Layout {
     #[unstable(feature = "alloc_layout_extra", issue = "55724")]
     #[inline]
     pub fn extend_packed(&self, next: Self) -> Result<Self, LayoutError> {
-        let new_size = self.size().checked_add(next.size()).ok_or(LayoutError { private: () })?;
+        let new_size = self.size().checked_add(next.size()).ok_or(LayoutError)?;
         Layout::from_size_align(new_size, self.align())
     }
 
@@ -409,10 +409,9 @@ pub type LayoutErr = LayoutError;
 /// or some other `Layout` constructor
 /// do not satisfy its documented constraints.
 #[stable(feature = "alloc_layout_error", since = "1.50.0")]
+#[non_exhaustive]
 #[derive(Clone, PartialEq, Eq, Debug)]
-pub struct LayoutError {
-    private: (),
-}
+pub struct LayoutError;
 
 // (we need this for downstream impl of trait Error)
 #[stable(feature = "alloc_layout", since = "1.28.0")]
diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs
index 6af010e796d67..24b0797f93a50 100644
--- a/library/core/src/cell.rs
+++ b/library/core/src/cell.rs
@@ -593,8 +593,8 @@ pub struct RefCell<T: ?Sized> {
 
 /// An error returned by [`RefCell::try_borrow`].
 #[stable(feature = "try_borrow", since = "1.13.0")]
+#[non_exhaustive]
 pub struct BorrowError {
-    _private: (),
     #[cfg(feature = "debug_refcell")]
     location: &'static crate::panic::Location<'static>,
 }
@@ -620,8 +620,8 @@ impl Display for BorrowError {
 
 /// An error returned by [`RefCell::try_borrow_mut`].
 #[stable(feature = "try_borrow", since = "1.13.0")]
+#[non_exhaustive]
 pub struct BorrowMutError {
-    _private: (),
     #[cfg(feature = "debug_refcell")]
     location: &'static crate::panic::Location<'static>,
 }
@@ -872,7 +872,6 @@ impl<T: ?Sized> RefCell<T> {
                 Ok(Ref { value: unsafe { &*self.value.get() }, borrow: b })
             }
             None => Err(BorrowError {
-                _private: (),
                 // If a borrow occured, then we must already have an outstanding borrow,
                 // so `borrowed_at` will be `Some`
                 #[cfg(feature = "debug_refcell")]
@@ -958,7 +957,6 @@ impl<T: ?Sized> RefCell<T> {
                 Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b })
             }
             None => Err(BorrowMutError {
-                _private: (),
                 // If a borrow occured, then we must already have an outstanding borrow,
                 // so `borrowed_at` will be `Some`
                 #[cfg(feature = "debug_refcell")]
@@ -1080,7 +1078,6 @@ impl<T: ?Sized> RefCell<T> {
             Ok(unsafe { &*self.value.get() })
         } else {
             Err(BorrowError {
-                _private: (),
                 // If a borrow occured, then we must already have an outstanding borrow,
                 // so `borrowed_at` will be `Some`
                 #[cfg(feature = "debug_refcell")]
diff --git a/library/core/src/str/error.rs b/library/core/src/str/error.rs
index ccf7b20285cb3..aa735a14cbd8f 100644
--- a/library/core/src/str/error.rs
+++ b/library/core/src/str/error.rs
@@ -118,10 +118,9 @@ impl fmt::Display for Utf8Error {
 ///
 /// [`from_str`]: super::FromStr::from_str
 #[derive(Debug, Clone, PartialEq, Eq)]
+#[non_exhaustive]
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct ParseBoolError {
-    pub(super) _priv: (),
-}
+pub struct ParseBoolError;
 
 #[stable(feature = "rust1", since = "1.0.0")]
 impl fmt::Display for ParseBoolError {
diff --git a/library/core/src/str/traits.rs b/library/core/src/str/traits.rs
index 0a2743b1c31e5..12d79a56a527c 100644
--- a/library/core/src/str/traits.rs
+++ b/library/core/src/str/traits.rs
@@ -585,7 +585,7 @@ impl FromStr for bool {
         match s {
             "true" => Ok(true),
             "false" => Ok(false),
-            _ => Err(ParseBoolError { _priv: () }),
+            _ => Err(ParseBoolError),
         }
     }
 }
diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs
index c9079b1cbadc2..7586229504c22 100644
--- a/library/proc_macro/src/lib.rs
+++ b/library/proc_macro/src/lib.rs
@@ -85,14 +85,13 @@ impl !Sync for TokenStream {}
 
 /// Error returned from `TokenStream::from_str`.
 #[stable(feature = "proc_macro_lib", since = "1.15.0")]
+#[non_exhaustive]
 #[derive(Debug)]
-pub struct LexError {
-    _inner: (),
-}
+pub struct LexError;
 
 impl LexError {
     fn new() -> Self {
-        LexError { _inner: () }
+        LexError
     }
 }
 
diff --git a/library/std/src/io/util.rs b/library/std/src/io/util.rs
index f3bff391fb3ea..fd52de7430a20 100644
--- a/library/std/src/io/util.rs
+++ b/library/std/src/io/util.rs
@@ -13,9 +13,8 @@ use crate::io::{
 /// This struct is generally created by calling [`empty()`]. Please see
 /// the documentation of [`empty()`] for more details.
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct Empty {
-    _priv: (),
-}
+#[non_exhaustive]
+pub struct Empty;
 
 /// Constructs a new handle to an empty reader.
 ///
@@ -35,7 +34,7 @@ pub struct Empty {
 #[stable(feature = "rust1", since = "1.0.0")]
 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
 pub const fn empty() -> Empty {
-    Empty { _priv: () }
+    Empty
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
@@ -172,9 +171,8 @@ impl fmt::Debug for Repeat {
 /// This struct is generally created by calling [`sink`]. Please
 /// see the documentation of [`sink()`] for more details.
 #[stable(feature = "rust1", since = "1.0.0")]
-pub struct Sink {
-    _priv: (),
-}
+#[non_exhaustive]
+pub struct Sink;
 
 /// Creates an instance of a writer which will successfully consume all data.
 ///
@@ -195,7 +193,7 @@ pub struct Sink {
 #[stable(feature = "rust1", since = "1.0.0")]
 #[rustc_const_unstable(feature = "const_io_structs", issue = "78812")]
 pub const fn sink() -> Sink {
-    Sink { _priv: () }
+    Sink
 }
 
 #[stable(feature = "rust1", since = "1.0.0")]
diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs
index e62f4440b369c..c53290ec0c7d0 100644
--- a/library/std/src/thread/local.rs
+++ b/library/std/src/thread/local.rs
@@ -324,10 +324,9 @@ macro_rules! __thread_local_inner {
 
 /// An error returned by [`LocalKey::try_with`](struct.LocalKey.html#method.try_with).
 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
+#[non_exhaustive]
 #[derive(Clone, Copy, Eq, PartialEq)]
-pub struct AccessError {
-    _private: (),
-}
+pub struct AccessError;
 
 #[stable(feature = "thread_local_try_with", since = "1.26.0")]
 impl fmt::Debug for AccessError {
@@ -396,7 +395,7 @@ impl<T: 'static> LocalKey<T> {
         F: FnOnce(&T) -> R,
     {
         unsafe {
-            let thread_local = (self.inner)().ok_or(AccessError { _private: () })?;
+            let thread_local = (self.inner)().ok_or(AccessError)?;
             Ok(f(thread_local))
         }
     }