Skip to content

Commit b9de4a6

Browse files
committed
Uplift clippy::zero_prefixed_literal as leading_zeros_in_decimal_literals
1 parent 8dac72b commit b9de4a6

File tree

19 files changed

+262
-243
lines changed

19 files changed

+262
-243
lines changed

compiler/rustc_lint/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,10 @@ lint_invalid_reference_casting_note_book = for more information, visit <https://
466466
467467
lint_invalid_reference_casting_note_ty_has_interior_mutability = even for types with interior mutability, the only legal way to obtain a mutable pointer from a shared reference is through `UnsafeCell::get`
468468
469+
lint_leading_zeros_in_decimal_literals = this is a decimal constant
470+
.suggestion_remove_zeros = if you meant to use a decimal constant, remove leading zeros to avoid confusion
471+
.suggestion_prefix_octal = if you meant to use an octal constant, prefix it with `0o` instead
472+
469473
lint_legacy_derive_helpers = derive helper attribute is used before it is introduced
470474
.label = the attribute is introduced here
471475

compiler/rustc_lint/src/builtin.rs

+72-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use rustc_ast::tokenstream::{TokenStream, TokenTree};
2121
use rustc_ast::visit::{FnCtxt, FnKind};
2222
use rustc_ast::{self as ast, *};
2323
use rustc_ast_pretty::pprust::expr_to_string;
24+
use rustc_data_structures::packed::Pu128;
2425
use rustc_errors::{Applicability, LintDiagnostic};
2526
use rustc_feature::{AttributeGate, BuiltinAttribute, GateIssue, Stability, deprecated_attributes};
2627
use rustc_hir as hir;
@@ -57,7 +58,7 @@ use crate::lints::{
5758
BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
5859
BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub,
5960
BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment,
60-
BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel,
61+
BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel, LeadingZeros,
6162
};
6263
use crate::nonstandard_style::{MethodLateContext, method_context};
6364
use crate::{
@@ -3135,3 +3136,73 @@ impl EarlyLintPass for SpecialModuleName {
31353136
}
31363137
}
31373138
}
3139+
3140+
declare_lint! {
3141+
/// The `leading_zeros_in_decimal_literals` lint
3142+
/// detects decimal integral literals with leading zeros.
3143+
///
3144+
/// ### Example
3145+
///
3146+
/// ```rust,no_run
3147+
/// fn is_executable(unix_mode: u32) -> bool {
3148+
/// unix_mode & 0111 != 0
3149+
/// }
3150+
/// ```
3151+
///
3152+
/// {{produces}}
3153+
///
3154+
/// ### Explanation
3155+
/// In some languages (including the infamous C language and most of its family),
3156+
/// a leading zero marks an octal constant. In Rust however, a `0o` prefix is used instead.
3157+
/// Thus, a leading zero can be confusing for both the writer and a reader.
3158+
///
3159+
/// In Rust:
3160+
/// ```rust,no_run
3161+
/// fn main() {
3162+
/// let a = 0123;
3163+
/// println!("{}", a);
3164+
/// }
3165+
/// ```
3166+
///
3167+
/// prints `123`, while in C:
3168+
///
3169+
/// ```c
3170+
/// #include <stdio.h>
3171+
///
3172+
/// int main() {
3173+
/// int a = 0123;
3174+
/// printf("%d\n", a);
3175+
/// }
3176+
/// ```
3177+
///
3178+
/// prints `83` (as `83 == 0o123` while `123 == 0o173`).
3179+
pub LEADING_ZEROS_IN_DECIMAL_LITERALS,
3180+
Warn,
3181+
"leading `0` in decimal integer literals",
3182+
}
3183+
3184+
declare_lint_pass!(LeadingZerosInDecimals => [LEADING_ZEROS_IN_DECIMAL_LITERALS]);
3185+
3186+
impl EarlyLintPass for LeadingZerosInDecimals {
3187+
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
3188+
if let ExprKind::Lit(literal) = expr.kind
3189+
&& let Ok(LitKind::Int(Pu128(10..), _)) = LitKind::from_token_lit(literal)
3190+
&& let s = literal.symbol.as_str()
3191+
&& let Some(tail) = s.strip_prefix('0')
3192+
&& !tail.starts_with(['b', 'o', 'x'])
3193+
&& let nonzero_digits = tail.trim_start_matches(['0', '_'])
3194+
&& !nonzero_digits.contains(['8', '9'])
3195+
{
3196+
let lit_span = expr.span;
3197+
let zeros_offset = s.len() - nonzero_digits.len();
3198+
cx.emit_span_lint(
3199+
LEADING_ZEROS_IN_DECIMAL_LITERALS,
3200+
lit_span,
3201+
LeadingZeros {
3202+
remove_zeros: lit_span.with_hi(lit_span.lo() + BytePos(zeros_offset as u32)),
3203+
prefix_octal: lit_span.with_hi(lit_span.lo() + BytePos(1)),
3204+
},
3205+
);
3206+
}
3207+
}
3208+
}

compiler/rustc_lint/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ early_lint_methods!(
183183
Expr2024: Expr2024,
184184
Precedence: Precedence,
185185
DoubleNegations: DoubleNegations,
186+
LeadingZerosInDecimals: LeadingZerosInDecimals,
186187
]
187188
]
188189
);

compiler/rustc_lint/src/lints.rs

+9
Original file line numberDiff line numberDiff line change
@@ -3163,3 +3163,12 @@ pub(crate) struct ReservedMultihash {
31633163
#[suggestion(code = " ", applicability = "machine-applicable")]
31643164
pub suggestion: Span,
31653165
}
3166+
3167+
#[derive(LintDiagnostic)]
3168+
#[diag(lint_leading_zeros_in_decimal_literals)]
3169+
pub(crate) struct LeadingZeros {
3170+
#[suggestion(lint_suggestion_remove_zeros, code = "", applicability = "maybe-incorrect")]
3171+
pub remove_zeros: Span,
3172+
#[suggestion(lint_suggestion_prefix_octal, code = "0o", applicability = "maybe-incorrect")]
3173+
pub prefix_octal: Span,
3174+
}

library/coretests/tests/time.rs

+2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#![cfg_attr(not(bootstrap), allow(leading_zeros_in_decimal_literals))]
2+
13
use core::time::Duration;
24

35
#[test]

src/tools/clippy/clippy_lints/src/declared_lints.rs

-1
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,6 @@ pub static LINTS: &[&crate::LintInfo] = &[
523523
crate::misc_early::UNNEEDED_FIELD_PATTERN_INFO,
524524
crate::misc_early::UNNEEDED_WILDCARD_PATTERN_INFO,
525525
crate::misc_early::UNSEPARATED_LITERAL_SUFFIX_INFO,
526-
crate::misc_early::ZERO_PREFIXED_LITERAL_INFO,
527526
crate::mismatching_type_param_order::MISMATCHING_TYPE_PARAM_ORDER_INFO,
528527
crate::missing_assert_message::MISSING_ASSERT_MESSAGE_INFO,
529528
crate::missing_asserts_for_indexing::MISSING_ASSERTS_FOR_INDEXING_INFO,

src/tools/clippy/clippy_lints/src/deprecated_lints.rs

+2
Original file line numberDiff line numberDiff line change
@@ -181,5 +181,7 @@ declare_with_version! { RENAMED(RENAMED_VERSION): &[(&str, &str)] = &[
181181
("clippy::vtable_address_comparisons", "ambiguous_wide_pointer_comparisons"),
182182
#[clippy::version = ""]
183183
("clippy::reverse_range_loop", "clippy::reversed_empty_ranges"),
184+
#[clippy::version = "CURRENT_RUSTC_VERSION"]
185+
("clippy::zero_prefixed_literal", "leading_zeros_in_decimal_literals"),
184186
// end renamed lints. used by `cargo dev rename_lint`
185187
]}

src/tools/clippy/clippy_lints/src/misc_early/mod.rs

+1-46
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ mod redundant_at_rest_pattern;
55
mod redundant_pattern;
66
mod unneeded_field_pattern;
77
mod unneeded_wildcard_pattern;
8-
mod zero_prefixed_literal;
98

109
use clippy_utils::diagnostics::span_lint;
1110
use clippy_utils::source::snippet_opt;
@@ -167,45 +166,6 @@ declare_clippy_lint! {
167166
"literals whose suffix is separated by an underscore"
168167
}
169168

170-
declare_clippy_lint! {
171-
/// ### What it does
172-
/// Warns if an integral constant literal starts with `0`.
173-
///
174-
/// ### Why is this bad?
175-
/// In some languages (including the infamous C language
176-
/// and most of its
177-
/// family), this marks an octal constant. In Rust however, this is a decimal
178-
/// constant. This could
179-
/// be confusing for both the writer and a reader of the constant.
180-
///
181-
/// ### Example
182-
///
183-
/// In Rust:
184-
/// ```no_run
185-
/// fn main() {
186-
/// let a = 0123;
187-
/// println!("{}", a);
188-
/// }
189-
/// ```
190-
///
191-
/// prints `123`, while in C:
192-
///
193-
/// ```c
194-
/// #include <stdio.h>
195-
///
196-
/// int main() {
197-
/// int a = 0123;
198-
/// printf("%d\n", a);
199-
/// }
200-
/// ```
201-
///
202-
/// prints `83` (as `83 == 0o123` while `123 == 0o173`).
203-
#[clippy::version = "pre 1.29.0"]
204-
pub ZERO_PREFIXED_LITERAL,
205-
complexity,
206-
"integer literals starting with `0`"
207-
}
208-
209169
declare_clippy_lint! {
210170
/// ### What it does
211171
/// Warns if a generic shadows a built-in type.
@@ -334,7 +294,6 @@ declare_lint_pass!(MiscEarlyLints => [
334294
MIXED_CASE_HEX_LITERALS,
335295
UNSEPARATED_LITERAL_SUFFIX,
336296
SEPARATED_LITERAL_SUFFIX,
337-
ZERO_PREFIXED_LITERAL,
338297
BUILTIN_TYPE_SHADOW,
339298
REDUNDANT_PATTERN,
340299
UNNEEDED_WILDCARD_PATTERN,
@@ -409,7 +368,7 @@ impl MiscEarlyLints {
409368
};
410369

411370
let lit_kind = LitKind::from_token_lit(lit);
412-
if let Ok(LitKind::Int(value, lit_int_type)) = lit_kind {
371+
if let Ok(LitKind::Int(_value, lit_int_type)) = lit_kind {
413372
let suffix = match lit_int_type {
414373
LitIntType::Signed(ty) => ty.name_str(),
415374
LitIntType::Unsigned(ty) => ty.name_str(),
@@ -418,10 +377,6 @@ impl MiscEarlyLints {
418377
literal_suffix::check(cx, span, &lit_snip, suffix, "integer");
419378
if lit_snip.starts_with("0x") {
420379
mixed_case_hex_literals::check(cx, span, suffix, &lit_snip);
421-
} else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
422-
// nothing to do
423-
} else if value != 0 && lit_snip.starts_with('0') {
424-
zero_prefixed_literal::check(cx, span, &lit_snip);
425380
}
426381
} else if let Ok(LitKind::Float(_, LitFloatType::Suffixed(float_ty))) = lit_kind {
427382
let suffix = float_ty.name_str();

src/tools/clippy/clippy_lints/src/misc_early/zero_prefixed_literal.rs

-33
This file was deleted.

src/tools/clippy/tests/ui/literals.rs

-15
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// does not test any rustfixable lints
33

44
#![warn(clippy::mixed_case_hex_literals)]
5-
#![warn(clippy::zero_prefixed_literal)]
65
#![warn(clippy::unseparated_literal_suffix)]
76
#![warn(clippy::separated_literal_suffix)]
87
#![allow(dead_code, overflowing_literals)]
@@ -29,14 +28,10 @@ fn main() {
2928
let fail_multi_zero = 000_123usize;
3029
//~^ ERROR: integer type suffix should be separated by an underscore
3130
//~| NOTE: `-D clippy::unseparated-literal-suffix` implied by `-D warnings`
32-
//~| ERROR: this is a decimal constant
33-
//~| NOTE: `-D clippy::zero-prefixed-literal` implied by `-D warnings`
3431

3532
let ok9 = 0;
3633
let ok10 = 0_i64;
3734
//~^ ERROR: integer type suffix should not be separated by an underscore
38-
let fail8 = 0123;
39-
//~^ ERROR: this is a decimal constant
4035

4136
let ok11 = 0o123;
4237
let ok12 = 0b10_1010;
@@ -64,13 +59,3 @@ fn main() {
6459
let ok26 = 0x6_A0_BF;
6560
let ok27 = 0b1_0010_0101;
6661
}
67-
68-
fn issue9651() {
69-
// lint but octal form is not possible here
70-
let _ = 08;
71-
//~^ ERROR: this is a decimal constant
72-
let _ = 09;
73-
//~^ ERROR: this is a decimal constant
74-
let _ = 089;
75-
//~^ ERROR: this is a decimal constant
76-
}

0 commit comments

Comments
 (0)