Skip to content

Commit de59e57

Browse files
committed
Lint ready
1 parent b02cb24 commit de59e57

File tree

5 files changed

+163
-0
lines changed

5 files changed

+163
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5674,6 +5674,7 @@ Released 2018-09-13
56745674
[`non_minimal_cfg`]: https://rust-lang.github.io/rust-clippy/master/index.html#non_minimal_cfg
56755675
[`non_octal_unix_permissions`]: https://rust-lang.github.io/rust-clippy/master/index.html#non_octal_unix_permissions
56765676
[`non_send_fields_in_send_ty`]: https://rust-lang.github.io/rust-clippy/master/index.html#non_send_fields_in_send_ty
5677+
[`non_zero_suggestions`]: https://rust-lang.github.io/rust-clippy/master/index.html#non_zero_suggestions
56775678
[`nonminimal_bool`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonminimal_bool
56785679
[`nonsensical_open_options`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonsensical_open_options
56795680
[`nonstandard_macro_braces`]: https://rust-lang.github.io/rust-clippy/master/index.html#nonstandard_macro_braces

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -556,6 +556,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
556556
crate::non_expressive_names::SIMILAR_NAMES_INFO,
557557
crate::non_octal_unix_permissions::NON_OCTAL_UNIX_PERMISSIONS_INFO,
558558
crate::non_send_fields_in_send_ty::NON_SEND_FIELDS_IN_SEND_TY_INFO,
559+
crate::non_zero_suggestions::NON_ZERO_SUGGESTIONS_INFO,
559560
crate::nonstandard_macro_braces::NONSTANDARD_MACRO_BRACES_INFO,
560561
crate::octal_escapes::OCTAL_ESCAPES_INFO,
561562
crate::only_used_in_recursion::ONLY_USED_IN_RECURSION_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,7 @@ mod non_copy_const;
274274
mod non_expressive_names;
275275
mod non_octal_unix_permissions;
276276
mod non_send_fields_in_send_ty;
277+
mod non_zero_suggestions;
277278
mod nonstandard_macro_braces;
278279
mod octal_escapes;
279280
mod only_used_in_recursion;
@@ -908,6 +909,7 @@ pub fn register_lints(store: &mut rustc_lint::LintStore, conf: &'static Conf) {
908909
store.register_late_pass(|_| Box::new(set_contains_or_insert::HashsetInsertAfterContains));
909910
store.register_early_pass(|| Box::new(byte_char_slices::ByteCharSlice));
910911
store.register_early_pass(|| Box::new(cfg_not_test::CfgNotTest));
912+
store.register_late_pass(|_| Box::new(non_zero_suggestions::NonZeroSuggestions));
911913
// add lints here, do not remove this comment, it's used in `new_lint`
912914
}
913915

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
use clippy_utils::diagnostics::span_lint_and_sugg;
2+
use clippy_utils::source::snippet;
3+
use rustc_errors::Applicability;
4+
use rustc_hir::{Expr, ExprKind};
5+
use rustc_lint::{LateContext, LateLintPass};
6+
use rustc_middle::ty::{self, Ty};
7+
use rustc_session::declare_lint_pass;
8+
use rustc_span::symbol::sym;
9+
10+
declare_clippy_lint! {
11+
/// ### What it does
12+
///
13+
/// ### Why is this bad?
14+
///
15+
/// ### Example
16+
/// ```no_run
17+
/// // example code where clippy issues a warning
18+
/// ```
19+
/// Use instead:
20+
/// ```no_run
21+
/// // example code which does not raise clippy warning
22+
/// ```
23+
#[clippy::version = "1.81.0"]
24+
pub NON_ZERO_SUGGESTIONS,
25+
restriction,
26+
"suggests using `NonZero#` from `u#` or `i#` for more efficient and type-safe conversions"
27+
}
28+
29+
declare_lint_pass!(NonZeroSuggestions => [NON_ZERO_SUGGESTIONS]);
30+
31+
impl<'tcx> LateLintPass<'tcx> for NonZeroSuggestions {
32+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
33+
if let ExprKind::Call(func, [arg]) = expr.kind {
34+
if let ExprKind::Path(qpath) = &func.kind {
35+
if let Some(def_id) = cx.qpath_res(qpath, func.hir_id).opt_def_id() {
36+
let fn_name = cx.tcx.item_name(def_id);
37+
let target_ty = cx.typeck_results().expr_ty(expr);
38+
39+
if let ExprKind::MethodCall(rcv_path, receiver, _, _) = &arg.kind {
40+
let receiver_ty = cx.typeck_results().expr_ty(receiver);
41+
if let ty::Adt(adt_def, _) = receiver_ty.kind() {
42+
if adt_def.is_struct() && cx.tcx.get_diagnostic_name(adt_def.did()) == Some(sym::NonZero) {
43+
if let Some(target_non_zero_type) = get_target_non_zero_type(target_ty) {
44+
let arg_snippet = get_arg_snippet(cx, arg, rcv_path);
45+
suggest_non_zero_conversion(cx, expr, fn_name, target_non_zero_type, &arg_snippet);
46+
}
47+
}
48+
}
49+
}
50+
}
51+
}
52+
}
53+
}
54+
}
55+
56+
fn get_arg_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, rcv_path: &rustc_hir::PathSegment<'_>) -> String {
57+
let arg_snippet = snippet(cx, arg.span, "..");
58+
if let Some(index) = arg_snippet.rfind(&format!(".{}", rcv_path.ident.name)) {
59+
arg_snippet[..index].trim().to_string()
60+
} else {
61+
arg_snippet.to_string()
62+
}
63+
}
64+
65+
fn suggest_non_zero_conversion(
66+
cx: &LateContext<'_>,
67+
expr: &Expr<'_>,
68+
fn_name: rustc_span::Symbol,
69+
target_non_zero_type: &str,
70+
arg_snippet: &str,
71+
) {
72+
let suggestion = format!("{}::{}({})", target_non_zero_type, fn_name, arg_snippet);
73+
span_lint_and_sugg(
74+
cx,
75+
NON_ZERO_SUGGESTIONS,
76+
expr.span,
77+
format!(
78+
"Consider using `{}::{}()` for more efficient and type-safe conversion",
79+
target_non_zero_type, fn_name
80+
),
81+
"Replace with",
82+
suggestion,
83+
Applicability::MachineApplicable,
84+
);
85+
}
86+
87+
fn get_target_non_zero_type(ty: Ty<'_>) -> Option<&'static str> {
88+
match ty.kind() {
89+
ty::Uint(uint_ty) => Some(match uint_ty {
90+
ty::UintTy::U8 => "NonZeroU8",
91+
ty::UintTy::U16 => "NonZeroU16",
92+
ty::UintTy::U32 => "NonZeroU32",
93+
ty::UintTy::U64 => "NonZeroU64",
94+
ty::UintTy::U128 => "NonZeroU128",
95+
ty::UintTy::Usize => "NonZeroUsize",
96+
}),
97+
ty::Int(int_ty) => Some(match int_ty {
98+
ty::IntTy::I8 => "NonZeroI8",
99+
ty::IntTy::I16 => "NonZeroI16",
100+
ty::IntTy::I32 => "NonZeroI32",
101+
ty::IntTy::I64 => "NonZeroI64",
102+
ty::IntTy::I128 => "NonZeroI128",
103+
ty::IntTy::Isize => "NonZeroIsize",
104+
}),
105+
_ => None,
106+
}
107+
}

tests/ui/non_zero_suggestions.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#![warn(clippy::non_zero_suggestions)]
2+
3+
use std::num::{
4+
NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize, NonZeroU128, NonZeroU16, NonZeroU32,
5+
NonZeroU64, NonZeroU8, NonZeroUsize,
6+
};
7+
8+
fn main() {
9+
// Basic cases
10+
let _ = u8::try_from(NonZeroU8::new(5).unwrap().get());
11+
12+
let _ = u16::from(NonZeroU16::new(10).unwrap().get());
13+
14+
// Different integer types
15+
let _ = u32::from(NonZeroU32::new(15).unwrap().get());
16+
17+
let _ = u64::from(NonZeroU64::new(20).unwrap().get());
18+
19+
let _ = u128::from(NonZeroU128::new(25).unwrap().get());
20+
21+
let _ = usize::from(NonZeroUsize::new(30).unwrap().get());
22+
23+
// Signed integer types
24+
let _ = i8::try_from(NonZeroI8::new(-5).unwrap().get());
25+
26+
let _ = i16::from(NonZeroI16::new(-10).unwrap().get());
27+
28+
let _ = i32::from(NonZeroI32::new(-15).unwrap().get());
29+
30+
// Edge cases
31+
32+
// Complex expression
33+
let _ = u8::from(NonZeroU8::new(5).unwrap().get() + 1);
34+
35+
// Function call
36+
fn get_non_zero() -> NonZeroU8 {
37+
NonZeroU8::new(42).unwrap()
38+
}
39+
let _ = u8::from(get_non_zero().get());
40+
41+
// Method chaining
42+
let _ = u16::from(NonZeroU16::new(100).unwrap().get().checked_add(1).unwrap());
43+
// This should not trigger the lint
44+
45+
// Different conversion methods
46+
let _ = u32::try_from(NonZeroU32::new(200).unwrap().get()).unwrap();
47+
48+
// Cases that should not trigger the lint
49+
let _ = u8::from(5);
50+
let _ = u16::from(10u8);
51+
let _ = i32::try_from(40u32).unwrap();
52+
}

0 commit comments

Comments
 (0)