Skip to content

Commit b410dcc

Browse files
committed
Uplift clippy::zero_prefixed_literal as leading_zeros_in_decimal_literals
1 parent aa6f5ab commit b410dcc

File tree

16 files changed

+189
-142
lines changed

16 files changed

+189
-142
lines changed

compiler/rustc_lint/messages.ftl

+4
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,10 @@ lint_invalid_reference_casting_note_book = for more information, visit <https://
469469
470470
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`
471471
472+
lint_leading_zeros_in_decimal_literals = this is a decimal constant
473+
.suggestion_remove_zeros = if you meant to use a decimal constant, remove leading zeros to avoid confusion
474+
.suggestion_prefix_octal = if you meant to use an octal constant, prefix it with `0o` instead
475+
472476
lint_legacy_derive_helpers = derive helper attribute is used before it is introduced
473477
.label = the attribute is introduced here
474478

compiler/rustc_lint/src/builtin.rs

+68-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;
@@ -58,7 +59,7 @@ use crate::lints::{
5859
BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
5960
BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub,
6061
BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment,
61-
BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel,
62+
BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel, LeadingZeros,
6263
};
6364
use crate::nonstandard_style::{MethodLateContext, method_context};
6465
use crate::{
@@ -3101,3 +3102,69 @@ impl EarlyLintPass for SpecialModuleName {
31013102
}
31023103
}
31033104
}
3105+
3106+
declare_lint! {
3107+
/// The `leading_zeros_in_decimal_literals` lint
3108+
/// detects decimal integral literals with leading zeros.
3109+
///
3110+
/// ### Example
3111+
///
3112+
/// ```rust,no_run
3113+
/// fn is_executable(unix_mode: u32) -> bool {
3114+
/// unix_mode & 0111 != 0
3115+
/// }
3116+
/// ```
3117+
///
3118+
/// {{produces}}
3119+
///
3120+
/// ### Explanation
3121+
/// In some languages (including the infamous C language and most of its family),
3122+
/// a leading zero marks an octal constant. In Rust however, a `0o` prefix is used instead.
3123+
/// Thus, a leading zero can be confusing for both the writer and a reader.
3124+
///
3125+
/// In Rust:
3126+
/// ```rust,no_run
3127+
/// fn main() {
3128+
/// let a = 0123;
3129+
/// println!("{}", a);
3130+
/// }
3131+
/// ```
3132+
///
3133+
/// prints `123`, while in C:
3134+
///
3135+
/// ```c
3136+
/// #include <stdio.h>
3137+
///
3138+
/// int main() {
3139+
/// int a = 0123;
3140+
/// printf("%d\n", a);
3141+
/// }
3142+
/// ```
3143+
///
3144+
/// prints `83` (as `83 == 0o123` while `123 == 0o173`).
3145+
pub LEADING_ZEROS_IN_DECIMAL_LITERALS,
3146+
Warn,
3147+
"leading `0` in decimal integer literals",
3148+
}
3149+
3150+
declare_lint_pass!(LeadingZerosInDecimals => [LEADING_ZEROS_IN_DECIMAL_LITERALS]);
3151+
3152+
impl EarlyLintPass for LeadingZerosInDecimals {
3153+
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
3154+
if let ExprKind::Lit(literal) = expr.kind
3155+
&& let Ok(LitKind::Int(Pu128(10..), _)) = LitKind::from_token_lit(literal)
3156+
&& let s = literal.symbol.as_str()
3157+
&& let Some(tail) = s.strip_prefix('0')
3158+
&& !tail.starts_with(['b', 'o', 'x'])
3159+
&& let nonzero_digits = tail.trim_start_matches(['0', '_'])
3160+
&& !nonzero_digits.contains(['8', '9'])
3161+
{
3162+
let lit_span = expr.span;
3163+
let zeros_offset = s.len() - nonzero_digits.len();
3164+
cx.emit_span_lint(LEADING_ZEROS_IN_DECIMAL_LITERALS, lit_span, LeadingZeros {
3165+
remove_zeros: lit_span.with_hi(lit_span.lo() + BytePos(zeros_offset as u32)),
3166+
prefix_octal: lit_span.with_hi(lit_span.lo() + BytePos(1)),
3167+
});
3168+
}
3169+
}
3170+
}

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
@@ -3159,3 +3159,12 @@ pub(crate) struct ReservedMultihash {
31593159
#[suggestion(code = " ", applicability = "machine-applicable")]
31603160
pub suggestion: Span,
31613161
}
3162+
3163+
#[derive(LintDiagnostic)]
3164+
#[diag(lint_leading_zeros_in_decimal_literals)]
3165+
pub(crate) struct LeadingZeros {
3166+
#[suggestion(lint_suggestion_remove_zeros, code = "", applicability = "maybe-incorrect")]
3167+
pub remove_zeros: Span,
3168+
#[suggestion(lint_suggestion_prefix_octal, code = "0o", applicability = "maybe-incorrect")]
3169+
pub prefix_octal: Span,
3170+
}

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
@@ -515,7 +515,6 @@ pub static LINTS: &[&crate::LintInfo] = &[
515515
crate::misc_early::UNNEEDED_FIELD_PATTERN_INFO,
516516
crate::misc_early::UNNEEDED_WILDCARD_PATTERN_INFO,
517517
crate::misc_early::UNSEPARATED_LITERAL_SUFFIX_INFO,
518-
crate::misc_early::ZERO_PREFIXED_LITERAL_INFO,
519518
crate::mismatching_type_param_order::MISMATCHING_TYPE_PARAM_ORDER_INFO,
520519
crate::missing_assert_message::MISSING_ASSERT_MESSAGE_INFO,
521520
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;
@@ -168,45 +167,6 @@ declare_clippy_lint! {
168167
"literals whose suffix is separated by an underscore"
169168
}
170169

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

412371
let lit_kind = LitKind::from_token_lit(lit);
413-
if let Ok(LitKind::Int(value, lit_int_type)) = lit_kind {
372+
if let Ok(LitKind::Int(_value, lit_int_type)) = lit_kind {
414373
let suffix = match lit_int_type {
415374
LitIntType::Signed(ty) => ty.name_str(),
416375
LitIntType::Unsigned(ty) => ty.name_str(),
@@ -419,10 +378,6 @@ impl MiscEarlyLints {
419378
literal_suffix::check(cx, span, &lit_snip, suffix, "integer");
420379
if lit_snip.starts_with("0x") {
421380
mixed_case_hex_literals::check(cx, span, suffix, &lit_snip);
422-
} else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
423-
// nothing to do
424-
} else if value != 0 && lit_snip.starts_with('0') {
425-
zero_prefixed_literal::check(cx, span, &lit_snip);
426381
}
427382
} else if let Ok(LitKind::Float(_, LitFloatType::Suffixed(float_ty))) = lit_kind {
428383
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

+1-5
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,6 @@ fn main() {
3030
//~^ ERROR: integer type suffix should be separated by an underscore
3131
//~| NOTE: `-D clippy::unseparated-literal-suffix` implied by `-D warnings`
3232
//~| ERROR: this is a decimal constant
33-
//~| NOTE: `-D clippy::zero-prefixed-literal` implied by `-D warnings`
3433

3534
let ok9 = 0;
3635
let ok10 = 0_i64;
@@ -66,11 +65,8 @@ fn main() {
6665
}
6766

6867
fn issue9651() {
69-
// lint but octal form is not possible here
68+
// octal form is not possible here
7069
let _ = 08;
71-
//~^ ERROR: this is a decimal constant
7270
let _ = 09;
73-
//~^ ERROR: this is a decimal constant
7471
let _ = 089;
75-
//~^ ERROR: this is a decimal constant
7672
}

0 commit comments

Comments
 (0)