Skip to content

Commit b66aa09

Browse files
committed
Add [manual_slice_size_calculation]
1 parent 26e245d commit b66aa09

6 files changed

+151
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4674,6 +4674,7 @@ Released 2018-09-13
46744674
[`manual_rem_euclid`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_rem_euclid
46754675
[`manual_retain`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_retain
46764676
[`manual_saturating_arithmetic`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_saturating_arithmetic
4677+
[`manual_slice_size_calculation`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_slice_size_calculation
46774678
[`manual_split_once`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_split_once
46784679
[`manual_str_repeat`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_str_repeat
46794680
[`manual_string_new`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_string_new

clippy_lints/src/declared_lints.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
269269
crate::manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE_INFO,
270270
crate::manual_rem_euclid::MANUAL_REM_EUCLID_INFO,
271271
crate::manual_retain::MANUAL_RETAIN_INFO,
272+
crate::manual_slice_size_calculation::MANUAL_SLICE_SIZE_CALCULATION_INFO,
272273
crate::manual_string_new::MANUAL_STRING_NEW_INFO,
273274
crate::manual_strip::MANUAL_STRIP_INFO,
274275
crate::map_unit_fn::OPTION_MAP_UNIT_FN_INFO,

clippy_lints/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ mod manual_main_separator_str;
186186
mod manual_non_exhaustive;
187187
mod manual_rem_euclid;
188188
mod manual_retain;
189+
mod manual_slice_size_calculation;
189190
mod manual_string_new;
190191
mod manual_strip;
191192
mod map_unit_fn;
@@ -957,6 +958,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
957958
});
958959
store.register_late_pass(|_| Box::new(lines_filter_map_ok::LinesFilterMapOk));
959960
store.register_late_pass(|_| Box::new(tests_outside_test_module::TestsOutsideTestModule));
961+
store.register_late_pass(|_| Box::new(manual_slice_size_calculation::ManualSliceSizeCalculation));
960962
// add lints here, do not remove this comment, it's used in `new_lint`
961963
}
962964

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
use clippy_utils::diagnostics::span_lint_and_help;
2+
use clippy_utils::in_constant;
3+
use rustc_hir::{BinOpKind, Expr, ExprKind};
4+
use rustc_lint::{LateContext, LateLintPass};
5+
use rustc_middle::ty;
6+
use rustc_session::{declare_lint_pass, declare_tool_lint};
7+
use rustc_span::symbol::sym;
8+
9+
declare_clippy_lint! {
10+
/// ### What it does
11+
/// When `a` is `&[T]`, detect `a.len() * size_of::<T>()` and suggest `size_of_val(a)`
12+
/// instead.
13+
///
14+
/// ### Why is this better?
15+
/// * Shorter to write
16+
/// * Removes the need for the human and the compiler to worry about overflow in the
17+
/// multiplication
18+
/// * Potentially faster at runtime as rust emits special no-wrapping flags when it
19+
/// calculates the byte length
20+
/// * Less turbofishing
21+
///
22+
/// ### Example
23+
/// ```rust
24+
/// # let data : &[i32] = &[1, 2, 3];
25+
/// let newlen = data.len() * std::mem::size_of::<i32>();
26+
/// ```
27+
/// Use instead:
28+
/// ```rust
29+
/// # let data : &[i32] = &[1, 2, 3];
30+
/// let newlen = std::mem::size_of_val(data);
31+
/// ```
32+
#[clippy::version = "1.70.0"]
33+
pub MANUAL_SLICE_SIZE_CALCULATION,
34+
complexity,
35+
"manual slice size calculation"
36+
}
37+
declare_lint_pass!(ManualSliceSizeCalculation => [MANUAL_SLICE_SIZE_CALCULATION]);
38+
39+
impl<'tcx> LateLintPass<'tcx> for ManualSliceSizeCalculation {
40+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
41+
// Does not apply inside const because size_of_value is not cost in stable.
42+
if !in_constant(cx, expr.hir_id)
43+
&& let ExprKind::Binary(ref op, left, right) = expr.kind
44+
&& BinOpKind::Mul == op.node
45+
&& let Some(_receiver) = simplify(cx, left, right)
46+
{
47+
span_lint_and_help(
48+
cx,
49+
MANUAL_SLICE_SIZE_CALCULATION,
50+
expr.span,
51+
"manual slice size calculation",
52+
None,
53+
"consider using std::mem::size_of_value instead");
54+
}
55+
}
56+
}
57+
58+
fn simplify<'tcx>(
59+
cx: &LateContext<'tcx>,
60+
expr1: &'tcx Expr<'tcx>,
61+
expr2: &'tcx Expr<'tcx>,
62+
) -> Option<&'tcx Expr<'tcx>> {
63+
simplify_half(cx, expr1, expr2).or_else(|| simplify_half(cx, expr2, expr1))
64+
}
65+
66+
fn simplify_half<'tcx>(
67+
cx: &LateContext<'tcx>,
68+
expr1: &'tcx Expr<'tcx>,
69+
expr2: &'tcx Expr<'tcx>,
70+
) -> Option<&'tcx Expr<'tcx>> {
71+
if
72+
// expr1 is `[T1].len()`?
73+
let ExprKind::MethodCall(method_path, receiver, _, _) = expr1.kind
74+
&& method_path.ident.name == sym::len
75+
&& let receiver_ty = cx.typeck_results().expr_ty(receiver)
76+
&& let ty::Slice(ty1) = receiver_ty.peel_refs().kind()
77+
// expr2 is `size_of::<T2>()`?
78+
&& let ExprKind::Call(func, _) = expr2.kind
79+
&& let ExprKind::Path(ref func_qpath) = func.kind
80+
&& let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
81+
&& cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id)
82+
&& let Some(ty2) = cx.typeck_results().node_substs(func.hir_id).types().next()
83+
// T1 == T2?
84+
&& *ty1 == ty2
85+
{
86+
Some(receiver)
87+
} else {
88+
None
89+
}
90+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
#![allow(unused)]
2+
#![warn(clippy::manual_slice_size_calculation)]
3+
4+
use core::mem::{align_of, size_of};
5+
6+
fn main() {
7+
let v_i32 = Vec::<i32>::new();
8+
let s_i32 = v_i32.as_slice();
9+
10+
// True positives:
11+
let _ = s_i32.len() * size_of::<i32>(); // WARNING
12+
let _ = size_of::<i32>() * s_i32.len(); // WARNING
13+
let _ = size_of::<i32>() * s_i32.len() * 5; // WARNING
14+
15+
// True negatives:
16+
let _ = size_of::<i32>() + s_i32.len(); // Ok, not a multiplication
17+
let _ = size_of::<i32>() * s_i32.partition_point(|_| true); // Ok, not len()
18+
let _ = size_of::<i32>() * v_i32.len(); // Ok, not a slice
19+
let _ = align_of::<i32>() * s_i32.len(); // Ok, not size_of()
20+
let _ = size_of::<u32>() * s_i32.len(); // Ok, different types
21+
22+
// False negatives:
23+
let _ = 5 * size_of::<i32>() * s_i32.len(); // Ok (MISSED OPPORTUNITY)
24+
let _ = size_of::<i32>() * 5 * s_i32.len(); // Ok (MISSED OPPORTUNITY)
25+
}
26+
27+
const fn _const(s_i32: &[i32]) {
28+
// True negative:
29+
let _ = s_i32.len() * size_of::<i32>(); // Ok, can't use size_of_val in const
30+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
error: manual slice size calculation
2+
--> $DIR/manual_slice_size_calculation.rs:11:13
3+
|
4+
LL | let _ = s_i32.len() * size_of::<i32>(); // WARNING
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
6+
|
7+
= help: consider using std::mem::size_of_value instead
8+
= note: `-D clippy::manual-slice-size-calculation` implied by `-D warnings`
9+
10+
error: manual slice size calculation
11+
--> $DIR/manual_slice_size_calculation.rs:12:13
12+
|
13+
LL | let _ = size_of::<i32>() * s_i32.len(); // WARNING
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15+
|
16+
= help: consider using std::mem::size_of_value instead
17+
18+
error: manual slice size calculation
19+
--> $DIR/manual_slice_size_calculation.rs:13:13
20+
|
21+
LL | let _ = size_of::<i32>() * s_i32.len() * 5; // WARNING
22+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
23+
|
24+
= help: consider using std::mem::size_of_value instead
25+
26+
error: aborting due to 3 previous errors
27+

0 commit comments

Comments
 (0)