|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::source::snippet; |
| 3 | +use rustc_ast::ast::BinOpKind; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::{Expr, ExprKind}; |
| 6 | +use rustc_lint::{LateContext, LateLintPass}; |
| 7 | +use rustc_middle::ty::{self, Ty}; |
| 8 | +use rustc_session::declare_lint_pass; |
| 9 | +use rustc_span::symbol::sym; |
| 10 | + |
| 11 | +declare_clippy_lint! { |
| 12 | + /// ### What it does |
| 13 | + /// Checks for conversions from `NonZero` types to regular integer types, |
| 14 | + /// and suggests using `NonZero` types for the target as well. |
| 15 | + /// |
| 16 | + /// ### Why is this bad? |
| 17 | + /// Converting from `NonZero` types to regular integer types and then back to `NonZero` |
| 18 | + /// types is less efficient and loses the type-safety guarantees provided by `NonZero` types. |
| 19 | + /// Using `NonZero` types consistently can lead to more optimized code and prevent |
| 20 | + /// certain classes of errors related to zero values. |
| 21 | + /// |
| 22 | + /// ### Example |
| 23 | + /// ```no_run |
| 24 | + /// use std::num::{NonZeroU32, NonZeroU64}; |
| 25 | + /// |
| 26 | + /// fn example(x: u64, y: NonZeroU32) { |
| 27 | + /// // Bad: Converting NonZeroU32 to u64 unnecessarily |
| 28 | + /// let r1 = x / u64::from(y.get()); |
| 29 | + /// let r2 = x % u64::from(y.get()); |
| 30 | + /// } |
| 31 | + /// ``` |
| 32 | + /// Use instead: |
| 33 | + /// ```no_run |
| 34 | + /// use std::num::{NonZeroU32, NonZeroU64}; |
| 35 | + /// |
| 36 | + /// fn example(x: u64, y: NonZeroU32) { |
| 37 | + /// // Good: Preserving the NonZero property |
| 38 | + /// let r1 = x / NonZeroU64::from(y); |
| 39 | + /// let r2 = x % NonZeroU64::from(y); |
| 40 | + /// } |
| 41 | + /// ``` |
| 42 | + #[clippy::version = "1.81.0"] |
| 43 | + pub NON_ZERO_SUGGESTIONS, |
| 44 | + restriction, |
| 45 | + "suggests using `NonZero#` from `u#` or `i#` for more efficient and type-safe conversions" |
| 46 | +} |
| 47 | + |
| 48 | +declare_lint_pass!(NonZeroSuggestions => [NON_ZERO_SUGGESTIONS]); |
| 49 | + |
| 50 | +impl<'tcx> LateLintPass<'tcx> for NonZeroSuggestions { |
| 51 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { |
| 52 | + if let ExprKind::Binary(op, _, rhs) = expr.kind |
| 53 | + && matches!(op.node, BinOpKind::Div | BinOpKind::Rem) |
| 54 | + { |
| 55 | + check_non_zero_conversion(cx, rhs, Applicability::MachineApplicable); |
| 56 | + } else { |
| 57 | + // Check if the parent expression is a binary operation |
| 58 | + let parent_is_binary = cx.tcx.hir().parent_iter(expr.hir_id).any(|(_, node)| { |
| 59 | + matches!(node, rustc_hir::Node::Expr(parent_expr) if matches!(parent_expr.kind, ExprKind::Binary(..))) |
| 60 | + }); |
| 61 | + |
| 62 | + if !parent_is_binary { |
| 63 | + check_non_zero_conversion(cx, expr, Applicability::MaybeIncorrect); |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +fn check_non_zero_conversion(cx: &LateContext<'_>, expr: &Expr<'_>, applicability: Applicability) { |
| 70 | + // Check if the expression is a function call with one argument |
| 71 | + if let ExprKind::Call(func, [arg]) = expr.kind |
| 72 | + && let ExprKind::Path(qpath) = &func.kind |
| 73 | + && let Some(def_id) = cx.qpath_res(qpath, func.hir_id).opt_def_id() |
| 74 | + && let ExprKind::MethodCall(rcv_path, receiver, _, _) = &arg.kind |
| 75 | + && rcv_path.ident.name.as_str() == "get" |
| 76 | + { |
| 77 | + let fn_name = cx.tcx.item_name(def_id); |
| 78 | + let target_ty = cx.typeck_results().expr_ty(expr); |
| 79 | + let receiver_ty = cx.typeck_results().expr_ty(receiver); |
| 80 | + |
| 81 | + // Check if the receiver type is a NonZero type |
| 82 | + if let ty::Adt(adt_def, _) = receiver_ty.kind() |
| 83 | + && adt_def.is_struct() |
| 84 | + && cx.tcx.get_diagnostic_name(adt_def.did()) == Some(sym::NonZero) |
| 85 | + { |
| 86 | + if let Some(target_non_zero_type) = get_target_non_zero_type(target_ty) { |
| 87 | + let arg_snippet = get_arg_snippet(cx, arg, rcv_path); |
| 88 | + suggest_non_zero_conversion(cx, expr, fn_name, target_non_zero_type, &arg_snippet, applicability); |
| 89 | + } |
| 90 | + } |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +fn get_arg_snippet(cx: &LateContext<'_>, arg: &Expr<'_>, rcv_path: &rustc_hir::PathSegment<'_>) -> String { |
| 95 | + let arg_snippet = snippet(cx, arg.span, ".."); |
| 96 | + if let Some(index) = arg_snippet.rfind(&format!(".{}", rcv_path.ident.name)) { |
| 97 | + arg_snippet[..index].trim().to_string() |
| 98 | + } else { |
| 99 | + arg_snippet.to_string() |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +fn suggest_non_zero_conversion( |
| 104 | + cx: &LateContext<'_>, |
| 105 | + expr: &Expr<'_>, |
| 106 | + fn_name: rustc_span::Symbol, |
| 107 | + target_non_zero_type: &str, |
| 108 | + arg_snippet: &str, |
| 109 | + applicability: Applicability, |
| 110 | +) { |
| 111 | + let suggestion = format!("{target_non_zero_type}::{fn_name}({arg_snippet})"); |
| 112 | + span_lint_and_sugg( |
| 113 | + cx, |
| 114 | + NON_ZERO_SUGGESTIONS, |
| 115 | + expr.span, |
| 116 | + format!("consider using `{target_non_zero_type}::{fn_name}()` for more efficient and type-safe conversion"), |
| 117 | + "replace with", |
| 118 | + suggestion, |
| 119 | + applicability, |
| 120 | + ); |
| 121 | +} |
| 122 | + |
| 123 | +fn get_target_non_zero_type(ty: Ty<'_>) -> Option<&'static str> { |
| 124 | + match ty.kind() { |
| 125 | + ty::Uint(uint_ty) => Some(match uint_ty { |
| 126 | + ty::UintTy::U8 => "NonZeroU8", |
| 127 | + ty::UintTy::U16 => "NonZeroU16", |
| 128 | + ty::UintTy::U32 => "NonZeroU32", |
| 129 | + ty::UintTy::U64 => "NonZeroU64", |
| 130 | + ty::UintTy::U128 => "NonZeroU128", |
| 131 | + ty::UintTy::Usize => "NonZeroUsize", |
| 132 | + }), |
| 133 | + ty::Int(int_ty) => Some(match int_ty { |
| 134 | + ty::IntTy::I8 => "NonZeroI8", |
| 135 | + ty::IntTy::I16 => "NonZeroI16", |
| 136 | + ty::IntTy::I32 => "NonZeroI32", |
| 137 | + ty::IntTy::I64 => "NonZeroI64", |
| 138 | + ty::IntTy::I128 => "NonZeroI128", |
| 139 | + ty::IntTy::Isize => "NonZeroIsize", |
| 140 | + }), |
| 141 | + _ => None, |
| 142 | + } |
| 143 | +} |
0 commit comments