Skip to content

Commit b8cbce8

Browse files
committed
Auto merge of #10601 - schubart:manual_slice_size_calculation, r=llogiq
Add [`manual_slice_size_calculation`] Fixes: #10518 --- changelog: new lint [`manual_slice_size_calculation`]
2 parents 9408d01 + b1c784d commit b8cbce8

6 files changed

+184
-0
lines changed

CHANGELOG.md

+1
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

+1
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

+2
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ mod manual_main_separator_str;
185185
mod manual_non_exhaustive;
186186
mod manual_rem_euclid;
187187
mod manual_retain;
188+
mod manual_slice_size_calculation;
188189
mod manual_string_new;
189190
mod manual_strip;
190191
mod map_unit_fn;
@@ -956,6 +957,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
956957
});
957958
store.register_late_pass(|_| Box::new(lines_filter_map_ok::LinesFilterMapOk));
958959
store.register_late_pass(|_| Box::new(tests_outside_test_module::TestsOutsideTestModule));
960+
store.register_late_pass(|_| Box::new(manual_slice_size_calculation::ManualSliceSizeCalculation));
959961
// add lints here, do not remove this comment, it's used in `new_lint`
960962
}
961963

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
use clippy_utils::diagnostics::span_lint_and_help;
2+
use clippy_utils::{expr_or_init, 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+
let expr1 = expr_or_init(cx, expr1);
64+
let expr2 = expr_or_init(cx, expr2);
65+
66+
simplify_half(cx, expr1, expr2).or_else(|| simplify_half(cx, expr2, expr1))
67+
}
68+
69+
fn simplify_half<'tcx>(
70+
cx: &LateContext<'tcx>,
71+
expr1: &'tcx Expr<'tcx>,
72+
expr2: &'tcx Expr<'tcx>,
73+
) -> Option<&'tcx Expr<'tcx>> {
74+
if
75+
// expr1 is `[T1].len()`?
76+
let ExprKind::MethodCall(method_path, receiver, _, _) = expr1.kind
77+
&& method_path.ident.name == sym::len
78+
&& let receiver_ty = cx.typeck_results().expr_ty(receiver)
79+
&& let ty::Slice(ty1) = receiver_ty.peel_refs().kind()
80+
// expr2 is `size_of::<T2>()`?
81+
&& let ExprKind::Call(func, _) = expr2.kind
82+
&& let ExprKind::Path(ref func_qpath) = func.kind
83+
&& let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id()
84+
&& cx.tcx.is_diagnostic_item(sym::mem_size_of, def_id)
85+
&& let Some(ty2) = cx.typeck_results().node_substs(func.hir_id).types().next()
86+
// T1 == T2?
87+
&& *ty1 == ty2
88+
{
89+
Some(receiver)
90+
} else {
91+
None
92+
}
93+
}
+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
let len = s_i32.len();
16+
let size = size_of::<i32>();
17+
let _ = len * size_of::<i32>(); // WARNING
18+
let _ = s_i32.len() * size; // WARNING
19+
let _ = len * size; // WARNING
20+
21+
// True negatives:
22+
let _ = size_of::<i32>() + s_i32.len(); // Ok, not a multiplication
23+
let _ = size_of::<i32>() * s_i32.partition_point(|_| true); // Ok, not len()
24+
let _ = size_of::<i32>() * v_i32.len(); // Ok, not a slice
25+
let _ = align_of::<i32>() * s_i32.len(); // Ok, not size_of()
26+
let _ = size_of::<u32>() * s_i32.len(); // Ok, different types
27+
28+
// False negatives:
29+
let _ = 5 * size_of::<i32>() * s_i32.len(); // Ok (MISSED OPPORTUNITY)
30+
let _ = size_of::<i32>() * 5 * s_i32.len(); // Ok (MISSED OPPORTUNITY)
31+
}
32+
33+
const fn _const(s_i32: &[i32]) {
34+
// True negative:
35+
let _ = s_i32.len() * size_of::<i32>(); // Ok, can't use size_of_val in const
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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: manual slice size calculation
27+
--> $DIR/manual_slice_size_calculation.rs:17:13
28+
|
29+
LL | let _ = len * size_of::<i32>(); // WARNING
30+
| ^^^^^^^^^^^^^^^^^^^^^^
31+
|
32+
= help: consider using std::mem::size_of_value instead
33+
34+
error: manual slice size calculation
35+
--> $DIR/manual_slice_size_calculation.rs:18:13
36+
|
37+
LL | let _ = s_i32.len() * size; // WARNING
38+
| ^^^^^^^^^^^^^^^^^^
39+
|
40+
= help: consider using std::mem::size_of_value instead
41+
42+
error: manual slice size calculation
43+
--> $DIR/manual_slice_size_calculation.rs:19:13
44+
|
45+
LL | let _ = len * size; // WARNING
46+
| ^^^^^^^^^^
47+
|
48+
= help: consider using std::mem::size_of_value instead
49+
50+
error: aborting due to 6 previous errors
51+

0 commit comments

Comments
 (0)