Skip to content

Commit 15a539a

Browse files
committed
Uplift clippy::zero_prefixed_literal as leading_zeros_in_decimal_literals
1 parent ab5b1be commit 15a539a

File tree

19 files changed

+295
-285
lines changed

19 files changed

+295
-285
lines changed

compiler/rustc_lint/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -475,6 +475,10 @@ lint_invalid_reference_casting_note_book = for more information, visit <https://
475475
476476
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`
477477
478+
lint_leading_zeros_in_decimal_literals = this is a decimal constant
479+
.suggestion_remove_zeros = if you meant to use a decimal constant, remove leading zeros to avoid confusion
480+
.suggestion_prefix_octal = if you meant to use an octal constant, prefix it with `0o` instead
481+
478482
lint_legacy_derive_helpers = derive helper attribute is used before it is introduced
479483
.label = the attribute is introduced here
480484

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::{
@@ -3140,3 +3141,73 @@ impl EarlyLintPass for SpecialModuleName {
31403141
}
31413142
}
31423143
}
3144+
3145+
declare_lint! {
3146+
/// The `leading_zeros_in_decimal_literals` lint
3147+
/// detects decimal integral literals with leading zeros.
3148+
///
3149+
/// ### Example
3150+
///
3151+
/// ```rust,no_run
3152+
/// fn is_executable(unix_mode: u32) -> bool {
3153+
/// unix_mode & 0111 != 0
3154+
/// }
3155+
/// ```
3156+
///
3157+
/// {{produces}}
3158+
///
3159+
/// ### Explanation
3160+
/// In some languages (including the infamous C language and most of its family),
3161+
/// a leading zero marks an octal constant. In Rust however, a `0o` prefix is used instead.
3162+
/// Thus, a leading zero can be confusing for both the writer and a reader.
3163+
///
3164+
/// In Rust:
3165+
/// ```rust,no_run
3166+
/// fn main() {
3167+
/// let a = 0123;
3168+
/// println!("{}", a);
3169+
/// }
3170+
/// ```
3171+
///
3172+
/// prints `123`, while in C:
3173+
///
3174+
/// ```c
3175+
/// #include <stdio.h>
3176+
///
3177+
/// int main() {
3178+
/// int a = 0123;
3179+
/// printf("%d\n", a);
3180+
/// }
3181+
/// ```
3182+
///
3183+
/// prints `83` (as `83 == 0o123` while `123 == 0o173`).
3184+
pub LEADING_ZEROS_IN_DECIMAL_LITERALS,
3185+
Warn,
3186+
"leading `0` in decimal integer literals",
3187+
}
3188+
3189+
declare_lint_pass!(LeadingZerosInDecimals => [LEADING_ZEROS_IN_DECIMAL_LITERALS]);
3190+
3191+
impl EarlyLintPass for LeadingZerosInDecimals {
3192+
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
3193+
if let ExprKind::Lit(literal) = expr.kind
3194+
&& let Ok(LitKind::Int(Pu128(10..), _)) = LitKind::from_token_lit(literal)
3195+
&& let s = literal.symbol.as_str()
3196+
&& let Some(tail) = s.strip_prefix('0')
3197+
&& !tail.starts_with(['b', 'o', 'x'])
3198+
&& let nonzero_digits = tail.trim_start_matches(['0', '_'])
3199+
&& !nonzero_digits.contains(['8', '9'])
3200+
{
3201+
let lit_span = expr.span;
3202+
let zeros_offset = s.len() - nonzero_digits.len();
3203+
cx.emit_span_lint(
3204+
LEADING_ZEROS_IN_DECIMAL_LITERALS,
3205+
lit_span,
3206+
LeadingZeros {
3207+
remove_zeros: lit_span.with_hi(lit_span.lo() + BytePos(zeros_offset as u32)),
3208+
prefix_octal: lit_span.with_hi(lit_span.lo() + BytePos(1)),
3209+
},
3210+
);
3211+
}
3212+
}
3213+
}

compiler/rustc_lint/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ early_lint_methods!(
182182
Expr2024: Expr2024,
183183
Precedence: Precedence,
184184
DoubleNegations: DoubleNegations,
185+
LeadingZerosInDecimals: LeadingZerosInDecimals,
185186
]
186187
]
187188
);

compiler/rustc_lint/src/lints.rs

+9
Original file line numberDiff line numberDiff line change
@@ -3184,3 +3184,12 @@ pub(crate) struct ReservedMultihash {
31843184
#[suggestion(code = " ", applicability = "machine-applicable")]
31853185
pub suggestion: Span,
31863186
}
3187+
3188+
#[derive(LintDiagnostic)]
3189+
#[diag(lint_leading_zeros_in_decimal_literals)]
3190+
pub(crate) struct LeadingZeros {
3191+
#[suggestion(lint_suggestion_remove_zeros, code = "", applicability = "maybe-incorrect")]
3192+
pub remove_zeros: Span,
3193+
#[suggestion(lint_suggestion_prefix_octal, code = "0o", applicability = "maybe-incorrect")]
3194+
pub prefix_octal: Span,
3195+
}

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
@@ -530,7 +530,6 @@ pub static LINTS: &[&crate::LintInfo] = &[
530530
crate::misc_early::UNNEEDED_FIELD_PATTERN_INFO,
531531
crate::misc_early::UNNEEDED_WILDCARD_PATTERN_INFO,
532532
crate::misc_early::UNSEPARATED_LITERAL_SUFFIX_INFO,
533-
crate::misc_early::ZERO_PREFIXED_LITERAL_INFO,
534533
crate::mismatching_type_param_order::MISMATCHING_TYPE_PARAM_ORDER_INFO,
535534
crate::missing_assert_message::MISSING_ASSERT_MESSAGE_INFO,
536535
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
@@ -185,5 +185,7 @@ declare_with_version! { RENAMED(RENAMED_VERSION): &[(&str, &str)] = &[
185185
("clippy::vtable_address_comparisons", "ambiguous_wide_pointer_comparisons"),
186186
#[clippy::version = ""]
187187
("clippy::reverse_range_loop", "clippy::reversed_empty_ranges"),
188+
#[clippy::version = "CURRENT_RUSTC_VERSION"]
189+
("clippy::zero_prefixed_literal", "leading_zeros_in_decimal_literals"),
188190
// end renamed lints. used by `cargo dev rename_lint`
189191
]}

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

+3-11
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,9 @@
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)]
8-
#![allow(dead_code, overflowing_literals)]
7+
#![allow(dead_code, overflowing_literals, leading_zeros_in_decimal_literals)]
98

109
fn main() {
1110
let ok1 = 0xABCD;
@@ -36,14 +35,12 @@ fn main() {
3635

3736
let fail_multi_zero = 000_123usize;
3837
//~^ unseparated_literal_suffix
39-
//~| zero_prefixed_literal
4038

4139
let ok9 = 0;
4240
let ok10 = 0_i64;
4341
//~^ separated_literal_suffix
4442

45-
let fail8 = 0123;
46-
//~^ zero_prefixed_literal
43+
let ok10andhalf = 0123;
4744

4845
let ok11 = 0o123;
4946
let ok12 = 0b10_1010;
@@ -75,13 +72,8 @@ fn main() {
7572
}
7673

7774
fn issue9651() {
78-
// lint but octal form is not possible here
75+
// octal form is not possible here
7976
let _ = 08;
80-
//~^ zero_prefixed_literal
81-
8277
let _ = 09;
83-
//~^ zero_prefixed_literal
84-
8578
let _ = 089;
86-
//~^ zero_prefixed_literal
8779
}

0 commit comments

Comments
 (0)