Skip to content

Commit 1be4688

Browse files
committed
Auto merge of #120486 - reitermarkus:use-generic-nonzero, r=dtolnay
Use generic `NonZero` internally. Tracking issue: #120257
2 parents 0f806a9 + a90cc05 commit 1be4688

File tree

144 files changed

+641
-633
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

144 files changed

+641
-633
lines changed

compiler/rustc_attr/src/builtin.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use rustc_session::parse::feature_err;
1313
use rustc_session::{RustcVersion, Session};
1414
use rustc_span::hygiene::Transparency;
1515
use rustc_span::{symbol::sym, symbol::Symbol, Span};
16-
use std::num::NonZeroU32;
16+
use std::num::NonZero;
1717

1818
use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause};
1919

@@ -113,7 +113,7 @@ pub enum StabilityLevel {
113113
/// Reason for the current stability level.
114114
reason: UnstableReason,
115115
/// Relevant `rust-lang/rust` issue.
116-
issue: Option<NonZeroU32>,
116+
issue: Option<NonZero<u32>>,
117117
is_soft: bool,
118118
/// If part of a feature is stabilized and a new feature is added for the remaining parts,
119119
/// then the `implied_by` attribute is used to indicate which now-stable feature previously
@@ -442,7 +442,7 @@ fn parse_unstability(sess: &Session, attr: &Attribute) -> Option<(Symbol, Stabil
442442
// is a name/value pair string literal.
443443
issue_num = match issue.unwrap().as_str() {
444444
"none" => None,
445-
issue => match issue.parse::<NonZeroU32>() {
445+
issue => match issue.parse::<NonZero<u32>>() {
446446
Ok(num) => Some(num),
447447
Err(err) => {
448448
sess.dcx().emit_err(

compiler/rustc_attr/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
#![allow(internal_features)]
88
#![feature(rustdoc_internals)]
99
#![doc(rust_logo)]
10+
#![feature(generic_nonzero)]
1011
#![feature(let_chains)]
1112

1213
#[macro_use]

compiler/rustc_const_eval/src/interpret/validity.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
//! to be const-safe.
66
77
use std::fmt::Write;
8-
use std::num::NonZeroUsize;
8+
use std::num::NonZero;
99

1010
use either::{Left, Right};
1111

@@ -785,7 +785,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M>
785785
fn visit_union(
786786
&mut self,
787787
op: &OpTy<'tcx, M::Provenance>,
788-
_fields: NonZeroUsize,
788+
_fields: NonZero<usize>,
789789
) -> InterpResult<'tcx> {
790790
// Special check for CTFE validation, preventing `UnsafeCell` inside unions in immutable memory.
791791
if self.ctfe_mode.is_some_and(|c| !c.allow_immutable_unsafe_cell()) {

compiler/rustc_const_eval/src/interpret/visitor.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_middle::ty;
77
use rustc_target::abi::FieldIdx;
88
use rustc_target::abi::{FieldsShape, VariantIdx, Variants};
99

10-
use std::num::NonZeroUsize;
10+
use std::num::NonZero;
1111

1212
use super::{InterpCx, MPlaceTy, Machine, Projectable};
1313

@@ -43,7 +43,7 @@ pub trait ValueVisitor<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized {
4343
}
4444
/// Visits the given value as a union. No automatic recursion can happen here.
4545
#[inline(always)]
46-
fn visit_union(&mut self, _v: &Self::V, _fields: NonZeroUsize) -> InterpResult<'tcx> {
46+
fn visit_union(&mut self, _v: &Self::V, _fields: NonZero<usize>) -> InterpResult<'tcx> {
4747
Ok(())
4848
}
4949
/// Visits the given value as the pointer of a `Box`. There is nothing to recurse into.

compiler/rustc_const_eval/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ Rust MIR: a lowered representation of Rust.
1111
#![feature(assert_matches)]
1212
#![feature(box_patterns)]
1313
#![feature(decl_macro)]
14+
#![feature(generic_nonzero)]
1415
#![feature(let_chains)]
1516
#![feature(slice_ptr_get)]
1617
#![feature(never_type)]

compiler/rustc_data_structures/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#![feature(cfg_match)]
2121
#![feature(core_intrinsics)]
2222
#![feature(extend_one)]
23+
#![feature(generic_nonzero)]
2324
#![feature(hash_raw_entry)]
2425
#![feature(hasher_prefixfree_extras)]
2526
#![feature(lazy_cell)]

compiler/rustc_data_structures/src/stable_hasher.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::fmt;
66
use std::hash::{BuildHasher, Hash, Hasher};
77
use std::marker::PhantomData;
88
use std::mem;
9+
use std::num::NonZero;
910

1011
#[cfg(test)]
1112
mod tests;
@@ -338,14 +339,14 @@ impl<CTX, T> HashStable<CTX> for PhantomData<T> {
338339
fn hash_stable(&self, _ctx: &mut CTX, _hasher: &mut StableHasher) {}
339340
}
340341

341-
impl<CTX> HashStable<CTX> for ::std::num::NonZeroU32 {
342+
impl<CTX> HashStable<CTX> for NonZero<u32> {
342343
#[inline]
343344
fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
344345
self.get().hash_stable(ctx, hasher)
345346
}
346347
}
347348

348-
impl<CTX> HashStable<CTX> for ::std::num::NonZeroUsize {
349+
impl<CTX> HashStable<CTX> for NonZero<usize> {
349350
#[inline]
350351
fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) {
351352
self.get().hash_stable(ctx, hasher)

compiler/rustc_data_structures/src/sync/worker_local.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use parking_lot::Mutex;
22
use std::cell::Cell;
33
use std::cell::OnceCell;
4-
use std::num::NonZeroUsize;
4+
use std::num::NonZero;
55
use std::ops::Deref;
66
use std::ptr;
77
use std::sync::Arc;
@@ -31,7 +31,7 @@ impl RegistryId {
3131
}
3232

3333
struct RegistryData {
34-
thread_limit: NonZeroUsize,
34+
thread_limit: NonZero<usize>,
3535
threads: Mutex<usize>,
3636
}
3737

@@ -61,7 +61,7 @@ thread_local! {
6161

6262
impl Registry {
6363
/// Creates a registry which can hold up to `thread_limit` threads.
64-
pub fn new(thread_limit: NonZeroUsize) -> Self {
64+
pub fn new(thread_limit: NonZero<usize>) -> Self {
6565
Registry(Arc::new(RegistryData { thread_limit, threads: Mutex::new(0) }))
6666
}
6767

compiler/rustc_data_structures/src/tagged_ptr/copy.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::fmt;
44
use std::hash::{Hash, Hasher};
55
use std::marker::PhantomData;
66
use std::mem::ManuallyDrop;
7-
use std::num::NonZeroUsize;
7+
use std::num::NonZero;
88
use std::ops::{Deref, DerefMut};
99
use std::ptr::NonNull;
1010

@@ -134,7 +134,7 @@ where
134134

135135
ptr.map_addr(|addr| {
136136
// Safety:
137-
// - The pointer is `NonNull` => it's address is `NonZeroUsize`
137+
// - The pointer is `NonNull` => it's address is `NonZero<usize>`
138138
// - `P::BITS` least significant bits are always zero (`Pointer` contract)
139139
// - `T::BITS <= P::BITS` (from `Self::ASSERTION`)
140140
//
@@ -143,14 +143,14 @@ where
143143
// `{non_zero} | packed_tag` can't make the value zero.
144144

145145
let packed = (addr.get() >> T::BITS) | packed_tag;
146-
unsafe { NonZeroUsize::new_unchecked(packed) }
146+
unsafe { NonZero::new_unchecked(packed) }
147147
})
148148
}
149149

150150
/// Retrieves the original raw pointer from `self.packed`.
151151
#[inline]
152152
pub(super) fn pointer_raw(&self) -> NonNull<P::Target> {
153-
self.packed.map_addr(|addr| unsafe { NonZeroUsize::new_unchecked(addr.get() << T::BITS) })
153+
self.packed.map_addr(|addr| unsafe { NonZero::new_unchecked(addr.get() << T::BITS) })
154154
}
155155

156156
/// This provides a reference to the `P` pointer itself, rather than the

compiler/rustc_errors/src/diagnostic_impls.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ into_diagnostic_arg_using_display!(
7979
ast::ParamKindOrd,
8080
std::io::Error,
8181
Box<dyn std::error::Error>,
82-
std::num::NonZeroU32,
82+
std::num::NonZero<u32>,
8383
hir::Target,
8484
Edition,
8585
Ident,

compiler/rustc_errors/src/lib.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#![feature(box_patterns)]
1717
#![feature(error_reporter)]
1818
#![feature(extract_if)]
19+
#![feature(generic_nonzero)]
1920
#![feature(let_chains)]
2021
#![feature(negative_impls)]
2122
#![feature(never_type)]
@@ -77,7 +78,7 @@ use std::error::Report;
7778
use std::fmt;
7879
use std::hash::Hash;
7980
use std::io::Write;
80-
use std::num::NonZeroUsize;
81+
use std::num::NonZero;
8182
use std::ops::DerefMut;
8283
use std::panic;
8384
use std::path::{Path, PathBuf};
@@ -546,7 +547,7 @@ pub struct DiagCtxtFlags {
546547
pub can_emit_warnings: bool,
547548
/// If Some, the Nth error-level diagnostic is upgraded to bug-level.
548549
/// (rustc: see `-Z treat-err-as-bug`)
549-
pub treat_err_as_bug: Option<NonZeroUsize>,
550+
pub treat_err_as_bug: Option<NonZero<usize>>,
550551
/// Eagerly emit delayed bugs as errors, so that the compiler debugger may
551552
/// see all of the errors being emitted at once.
552553
pub eagerly_emit_delayed_bugs: bool,

compiler/rustc_feature/src/lib.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
//! symbol to the `accepted` or `removed` modules respectively.
1313
1414
#![allow(internal_features)]
15+
#![feature(generic_nonzero)]
1516
#![feature(rustdoc_internals)]
1617
#![doc(rust_logo)]
1718
#![feature(lazy_cell)]
@@ -25,13 +26,13 @@ mod unstable;
2526
mod tests;
2627

2728
use rustc_span::symbol::Symbol;
28-
use std::num::NonZeroU32;
29+
use std::num::NonZero;
2930

3031
#[derive(Debug, Clone)]
3132
pub struct Feature {
3233
pub name: Symbol,
3334
pub since: &'static str,
34-
issue: Option<NonZeroU32>,
35+
issue: Option<NonZero<u32>>,
3536
}
3637

3738
#[derive(Copy, Clone, Debug)]
@@ -85,7 +86,7 @@ impl UnstableFeatures {
8586
}
8687
}
8788

88-
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
89+
fn find_lang_feature_issue(feature: Symbol) -> Option<NonZero<u32>> {
8990
// Search in all the feature lists.
9091
if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| f.feature.name == feature) {
9192
return f.feature.issue;
@@ -99,21 +100,21 @@ fn find_lang_feature_issue(feature: Symbol) -> Option<NonZeroU32> {
99100
panic!("feature `{feature}` is not declared anywhere");
100101
}
101102

102-
const fn to_nonzero(n: Option<u32>) -> Option<NonZeroU32> {
103-
// Can be replaced with `n.and_then(NonZeroU32::new)` if that is ever usable
103+
const fn to_nonzero(n: Option<u32>) -> Option<NonZero<u32>> {
104+
// Can be replaced with `n.and_then(NonZero::new)` if that is ever usable
104105
// in const context. Requires https://github.com/rust-lang/rfcs/pull/2632.
105106
match n {
106107
None => None,
107-
Some(n) => NonZeroU32::new(n),
108+
Some(n) => NonZero::new(n),
108109
}
109110
}
110111

111112
pub enum GateIssue {
112113
Language,
113-
Library(Option<NonZeroU32>),
114+
Library(Option<NonZero<u32>>),
114115
}
115116

116-
pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZeroU32> {
117+
pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option<NonZero<u32>> {
117118
match issue {
118119
GateIssue::Language => find_lang_feature_issue(feature),
119120
GateIssue::Library(lib) => lib,

compiler/rustc_hir_analysis/src/check/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ pub mod wfcheck;
7474

7575
pub use check::check_abi;
7676

77-
use std::num::NonZeroU32;
77+
use std::num::NonZero;
7878

7979
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
8080
use rustc_errors::ErrorGuaranteed;
@@ -270,7 +270,7 @@ fn default_body_is_unstable(
270270
item_did: DefId,
271271
feature: Symbol,
272272
reason: Option<Symbol>,
273-
issue: Option<NonZeroU32>,
273+
issue: Option<NonZero<u32>>,
274274
) {
275275
let missing_item_name = tcx.associated_item(item_did).name;
276276
let (mut some_note, mut none_note, mut reason_str) = (false, false, String::new());

compiler/rustc_hir_analysis/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ This API is completely unstable and subject to change.
6363
#![feature(rustdoc_internals)]
6464
#![allow(internal_features)]
6565
#![feature(control_flow_enum)]
66+
#![feature(generic_nonzero)]
6667
#![feature(if_let_guard)]
6768
#![feature(is_sorted)]
6869
#![feature(iter_intersperse)]

compiler/rustc_interface/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#![feature(decl_macro)]
22
#![feature(error_iter)]
3+
#![feature(generic_nonzero)]
34
#![feature(lazy_cell)]
45
#![feature(let_chains)]
56
#![feature(thread_spawn_unchecked)]

compiler/rustc_interface/src/tests.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use rustc_span::{FileName, SourceFileHashAlgorithm};
2020
use rustc_target::spec::{CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, RelocModel};
2121
use rustc_target::spec::{RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TlsModel};
2222
use std::collections::{BTreeMap, BTreeSet};
23-
use std::num::NonZeroUsize;
23+
use std::num::NonZero;
2424
use std::path::{Path, PathBuf};
2525
use std::sync::Arc;
2626

@@ -827,7 +827,7 @@ fn test_unstable_options_tracking_hash() {
827827
tracked!(tls_model, Some(TlsModel::GeneralDynamic));
828828
tracked!(translate_remapped_path_to_local_path, false);
829829
tracked!(trap_unreachable, Some(false));
830-
tracked!(treat_err_as_bug, NonZeroUsize::new(1));
830+
tracked!(treat_err_as_bug, NonZero::new(1));
831831
tracked!(tune_cpu, Some(String::from("abc")));
832832
tracked!(uninit_const_chunk_threshold, 123);
833833
tracked!(unleash_the_miri_inside_of_you, true);

compiler/rustc_interface/src/util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ pub(crate) fn run_in_thread_pool_with_globals<F: FnOnce() -> R + Send, R: Send>(
107107
use rustc_query_impl::QueryCtxt;
108108
use rustc_query_system::query::{deadlock, QueryContext};
109109

110-
let registry = sync::Registry::new(std::num::NonZeroUsize::new(threads).unwrap());
110+
let registry = sync::Registry::new(std::num::NonZero::new(threads).unwrap());
111111

112112
if !sync::is_dyn_thread_safe() {
113113
return run_in_thread_with_globals(edition, || {

compiler/rustc_lint/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#![feature(array_windows)]
3232
#![feature(box_patterns)]
3333
#![feature(control_flow_enum)]
34+
#![feature(generic_nonzero)]
3435
#![feature(if_let_guard)]
3536
#![feature(iter_order_by)]
3637
#![feature(let_chains)]

compiler/rustc_lint/src/lints.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#![allow(rustc::diagnostic_outside_of_impl)]
22
#![allow(rustc::untranslatable_diagnostic)]
3-
4-
use std::num::NonZeroU32;
3+
use std::num::NonZero;
54

65
use crate::errors::RequestedLevel;
76
use crate::fluent_generated as fluent;
@@ -402,7 +401,7 @@ pub struct BuiltinIncompleteFeaturesHelp;
402401
#[derive(Subdiagnostic)]
403402
#[note(lint_note)]
404403
pub struct BuiltinFeatureIssueNote {
405-
pub n: NonZeroU32,
404+
pub n: NonZero<u32>,
406405
}
407406

408407
pub struct BuiltinUnpermittedTypeInit<'a> {

compiler/rustc_metadata/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#![feature(decl_macro)]
66
#![feature(extract_if)]
77
#![feature(coroutines)]
8+
#![feature(generic_nonzero)]
89
#![feature(iter_from_coroutine)]
910
#![feature(let_chains)]
1011
#![feature(if_let_guard)]

compiler/rustc_metadata/src/rmeta/decoder.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
327327
}
328328

329329
#[inline]
330-
fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZeroUsize) -> T) -> T {
330+
fn read_lazy_offset_then<T>(&mut self, f: impl Fn(NonZero<usize>) -> T) -> T {
331331
let distance = self.read_usize();
332332
let position = match self.lazy_state {
333333
LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"),
@@ -338,7 +338,7 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
338338
}
339339
LazyState::Previous(last_pos) => last_pos.get() + distance,
340340
};
341-
let position = NonZeroUsize::new(position).unwrap();
341+
let position = NonZero::new(position).unwrap();
342342
self.lazy_state = LazyState::Previous(position);
343343
f(position)
344344
}
@@ -685,15 +685,15 @@ impl MetadataBlob {
685685
}
686686

687687
pub(crate) fn get_rustc_version(&self) -> String {
688-
LazyValue::<String>::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 8).unwrap())
688+
LazyValue::<String>::from_position(NonZero::new(METADATA_HEADER.len() + 8).unwrap())
689689
.decode(self)
690690
}
691691

692-
fn root_pos(&self) -> NonZeroUsize {
692+
fn root_pos(&self) -> NonZero<usize> {
693693
let offset = METADATA_HEADER.len();
694694
let pos_bytes = self.blob()[offset..][..8].try_into().unwrap();
695695
let pos = u64::from_le_bytes(pos_bytes);
696-
NonZeroUsize::new(pos as usize).unwrap()
696+
NonZero::new(pos as usize).unwrap()
697697
}
698698

699699
pub(crate) fn get_header(&self) -> CrateHeader {

0 commit comments

Comments
 (0)