Skip to content

Commit b78ba71

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

File tree

6 files changed

+149
-0
lines changed

6 files changed

+149
-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: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
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 newlen = data.len() * mem::size_of::<i32>();
25+
/// ```
26+
/// Use instead:
27+
/// ```rust
28+
/// let newlen = mem::size_of_val(data);
29+
/// ```
30+
#[clippy::version = "1.70.0"]
31+
pub MANUAL_SLICE_SIZE_CALCULATION,
32+
complexity,
33+
"manual slice size calculation"
34+
}
35+
declare_lint_pass!(ManualSliceSizeCalculation => [MANUAL_SLICE_SIZE_CALCULATION]);
36+
37+
impl<'tcx> LateLintPass<'tcx> for ManualSliceSizeCalculation {
38+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
39+
// Does not apply inside const because size_of_value is not cost in stable.
40+
if !in_constant(cx, expr.hir_id)
41+
&& let ExprKind::Binary(ref op, left, right) = expr.kind
42+
&& BinOpKind::Mul == op.node
43+
&& let Some(_receiver) = simplify(cx, left, right)
44+
{
45+
span_lint_and_help(
46+
cx,
47+
MANUAL_SLICE_SIZE_CALCULATION,
48+
expr.span,
49+
"manual slice size calculation",
50+
None,
51+
"consider using std::mem::size_of_value instead");
52+
}
53+
}
54+
}
55+
56+
fn simplify<'tcx>(
57+
cx: &LateContext<'tcx>,
58+
expr1: &'tcx Expr<'tcx>,
59+
expr2: &'tcx Expr<'tcx>,
60+
) -> Option<&'tcx Expr<'tcx>> {
61+
simplify_half(cx, expr1, expr2).or_else(|| simplify_half(cx, expr2, expr1))
62+
}
63+
64+
fn simplify_half<'tcx>(
65+
cx: &LateContext<'tcx>,
66+
expr1: &'tcx Expr<'tcx>,
67+
expr2: &'tcx Expr<'tcx>,
68+
) -> Option<&'tcx Expr<'tcx>> {
69+
if
70+
// expr1 is `[T1].len()`?
71+
let ExprKind::MethodCall(method_path, receiver, _, _) = expr1.kind
72+
&& method_path.ident.name == sym::len
73+
&& let receiver_ty = cx.typeck_results().expr_ty(receiver)
74+
&& let ty::Slice(ty1) = receiver_ty.peel_refs().kind()
75+
// expr2 is `size_of::<T2>()`?
76+
&& let ExprKind::Call(func, _) = expr2.kind
77+
&& let ExprKind::Path(ref func_qpath) = func.kind
78+
&& let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
79+
&& cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id)
80+
&& let Some(ty2) = cx.typeck_results().node_substs(func.hir_id).types().next()
81+
// T1 == T2?
82+
&& *ty1 == ty2
83+
{
84+
Some(receiver)
85+
} else {
86+
None
87+
}
88+
}
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)