Skip to content

Commit eacb589

Browse files
committed
Uplift clippy::zero_prefixed_literal as leading_zeros_in_decimal_literals
1 parent 7a202a9 commit eacb589

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
@@ -464,6 +464,10 @@ lint_invalid_reference_casting_note_book = for more information, visit <https://
464464
465465
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`
466466
467+
lint_leading_zeros_in_decimal_literals = this is a decimal constant
468+
.suggestion_remove_zeros = if you meant to use a decimal constant, remove leading zeros to avoid confusion
469+
.suggestion_prefix_octal = if you meant to use an octal constant, prefix it with `0o` instead
470+
467471
lint_legacy_derive_helpers = derive helper attribute is used before it is introduced
468472
.label = the attribute is introduced here
469473

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::{self, 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
BuiltinTrivialBounds, BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller,
5960
BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub,
6061
BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub,
61-
BuiltinWhileTrue, InvalidAsmLabel,
62+
BuiltinWhileTrue, InvalidAsmLabel, LeadingZeros,
6263
};
6364
use crate::nonstandard_style::{MethodLateContext, method_context};
6465
use crate::{
@@ -3062,3 +3063,69 @@ impl EarlyLintPass for SpecialModuleName {
30623063
}
30633064
}
30643065
}
3066+
3067+
declare_lint! {
3068+
/// The `leading_zeros_in_decimal_literals` lint
3069+
/// detects decimal integral literals with leading zeros.
3070+
///
3071+
/// ### Example
3072+
///
3073+
/// ```rust,no_run
3074+
/// fn is_executable(unix_mode: u32) -> bool {
3075+
/// unix_mode & 0111 != 0
3076+
/// }
3077+
/// ```
3078+
///
3079+
/// {{produces}}
3080+
///
3081+
/// ### Explanation
3082+
/// In some languages (including the infamous C language and most of its family),
3083+
/// a leading zero marks an octal constant. In Rust however, a `0o` prefix is used instead.
3084+
/// Thus, a leading zero can be confusing for both the writer and a reader.
3085+
///
3086+
/// In Rust:
3087+
/// ```rust,no_run
3088+
/// fn main() {
3089+
/// let a = 0123;
3090+
/// println!("{}", a);
3091+
/// }
3092+
/// ```
3093+
///
3094+
/// prints `123`, while in C:
3095+
///
3096+
/// ```c
3097+
/// #include <stdio.h>
3098+
///
3099+
/// int main() {
3100+
/// int a = 0123;
3101+
/// printf("%d\n", a);
3102+
/// }
3103+
/// ```
3104+
///
3105+
/// prints `83` (as `83 == 0o123` while `123 == 0o173`).
3106+
pub LEADING_ZEROS_IN_DECIMAL_LITERALS,
3107+
Warn,
3108+
"leading `0` in decimal integer literals",
3109+
}
3110+
3111+
declare_lint_pass!(LeadingZerosInDecimals => [LEADING_ZEROS_IN_DECIMAL_LITERALS]);
3112+
3113+
impl EarlyLintPass for LeadingZerosInDecimals {
3114+
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
3115+
if let ExprKind::Lit(literal) = expr.kind
3116+
&& let Ok(LitKind::Int(Pu128(10..), _)) = LitKind::from_token_lit(literal)
3117+
&& let s = literal.symbol.as_str()
3118+
&& let Some(tail) = s.strip_prefix('0')
3119+
&& !tail.starts_with(['b', 'o', 'x'])
3120+
&& let nonzero_digits = tail.trim_start_matches(['0', '_'])
3121+
&& !nonzero_digits.contains(['8', '9'])
3122+
{
3123+
let lit_span = expr.span;
3124+
let zeros_offset = s.len() - nonzero_digits.len();
3125+
cx.emit_span_lint(LEADING_ZEROS_IN_DECIMAL_LITERALS, lit_span, LeadingZeros {
3126+
remove_zeros: lit_span.with_hi(lit_span.lo() + BytePos(zeros_offset as u32)),
3127+
prefix_octal: lit_span.with_hi(lit_span.lo() + BytePos(1)),
3128+
});
3129+
}
3130+
}
3131+
}

compiler/rustc_lint/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,7 @@ early_lint_methods!(
181181
UnusedDocComment: UnusedDocComment,
182182
Expr2024: Expr2024,
183183
Precedence: Precedence,
184+
LeadingZerosInDecimals: LeadingZerosInDecimals,
184185
]
185186
]
186187
);

compiler/rustc_lint/src/lints.rs

+9
Original file line numberDiff line numberDiff line change
@@ -3151,3 +3151,12 @@ pub(crate) struct ReservedMultihash {
31513151
#[suggestion(code = " ", applicability = "machine-applicable")]
31523152
pub suggestion: Span,
31533153
}
3154+
3155+
#[derive(LintDiagnostic)]
3156+
#[diag(lint_leading_zeros_in_decimal_literals)]
3157+
pub(crate) struct LeadingZeros {
3158+
#[suggestion(lint_suggestion_remove_zeros, code = "", applicability = "maybe-incorrect")]
3159+
pub remove_zeros: Span,
3160+
#[suggestion(lint_suggestion_prefix_octal, code = "0o", applicability = "maybe-incorrect")]
3161+
pub prefix_octal: Span,
3162+
}

library/core/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
@@ -516,7 +516,6 @@ pub static LINTS: &[&crate::LintInfo] = &[
516516
crate::misc_early::UNNEEDED_FIELD_PATTERN_INFO,
517517
crate::misc_early::UNNEEDED_WILDCARD_PATTERN_INFO,
518518
crate::misc_early::UNSEPARATED_LITERAL_SUFFIX_INFO,
519-
crate::misc_early::ZERO_PREFIXED_LITERAL_INFO,
520519
crate::mismatching_type_param_order::MISMATCHING_TYPE_PARAM_ORDER_INFO,
521520
crate::missing_assert_message::MISSING_ASSERT_MESSAGE_INFO,
522521
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
@@ -179,5 +179,7 @@ declare_with_version! { RENAMED(RENAMED_VERSION): &[(&str, &str)] = &[
179179
("clippy::vtable_address_comparisons", "ambiguous_wide_pointer_comparisons"),
180180
#[clippy::version = ""]
181181
("clippy::reverse_range_loop", "clippy::reversed_empty_ranges"),
182+
#[clippy::version = "CURRENT_RUSTC_VERSION"]
183+
("clippy::zero_prefixed_literal", "leading_zeros_in_decimal_literals"),
182184
// end renamed lints. used by `cargo dev rename_lint`
183185
]}

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

+1-46
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ mod redundant_at_rest_pattern;
66
mod redundant_pattern;
77
mod unneeded_field_pattern;
88
mod unneeded_wildcard_pattern;
9-
mod zero_prefixed_literal;
109

1110
use clippy_utils::diagnostics::span_lint;
1211
use clippy_utils::source::snippet_opt;
@@ -188,45 +187,6 @@ declare_clippy_lint! {
188187
"literals whose suffix is separated by an underscore"
189188
}
190189

191-
declare_clippy_lint! {
192-
/// ### What it does
193-
/// Warns if an integral constant literal starts with `0`.
194-
///
195-
/// ### Why is this bad?
196-
/// In some languages (including the infamous C language
197-
/// and most of its
198-
/// family), this marks an octal constant. In Rust however, this is a decimal
199-
/// constant. This could
200-
/// be confusing for both the writer and a reader of the constant.
201-
///
202-
/// ### Example
203-
///
204-
/// In Rust:
205-
/// ```no_run
206-
/// fn main() {
207-
/// let a = 0123;
208-
/// println!("{}", a);
209-
/// }
210-
/// ```
211-
///
212-
/// prints `123`, while in C:
213-
///
214-
/// ```c
215-
/// #include <stdio.h>
216-
///
217-
/// int main() {
218-
/// int a = 0123;
219-
/// printf("%d\n", a);
220-
/// }
221-
/// ```
222-
///
223-
/// prints `83` (as `83 == 0o123` while `123 == 0o173`).
224-
#[clippy::version = "pre 1.29.0"]
225-
pub ZERO_PREFIXED_LITERAL,
226-
complexity,
227-
"integer literals starting with `0`"
228-
}
229-
230190
declare_clippy_lint! {
231191
/// ### What it does
232192
/// Warns if a generic shadows a built-in type.
@@ -356,7 +316,6 @@ declare_lint_pass!(MiscEarlyLints => [
356316
MIXED_CASE_HEX_LITERALS,
357317
UNSEPARATED_LITERAL_SUFFIX,
358318
SEPARATED_LITERAL_SUFFIX,
359-
ZERO_PREFIXED_LITERAL,
360319
BUILTIN_TYPE_SHADOW,
361320
REDUNDANT_PATTERN,
362321
UNNEEDED_WILDCARD_PATTERN,
@@ -432,7 +391,7 @@ impl MiscEarlyLints {
432391
};
433392

434393
let lit_kind = LitKind::from_token_lit(lit);
435-
if let Ok(LitKind::Int(value, lit_int_type)) = lit_kind {
394+
if let Ok(LitKind::Int(_value, lit_int_type)) = lit_kind {
436395
let suffix = match lit_int_type {
437396
LitIntType::Signed(ty) => ty.name_str(),
438397
LitIntType::Unsigned(ty) => ty.name_str(),
@@ -441,10 +400,6 @@ impl MiscEarlyLints {
441400
literal_suffix::check(cx, span, &lit_snip, suffix, "integer");
442401
if lit_snip.starts_with("0x") {
443402
mixed_case_hex_literals::check(cx, span, suffix, &lit_snip);
444-
} else if lit_snip.starts_with("0b") || lit_snip.starts_with("0o") {
445-
// nothing to do
446-
} else if value != 0 && lit_snip.starts_with('0') {
447-
zero_prefixed_literal::check(cx, span, &lit_snip);
448403
}
449404
} else if let Ok(LitKind::Float(_, LitFloatType::Suffixed(float_ty))) = lit_kind {
450405
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)