Skip to content

Commit 7c82ae1

Browse files
committed
Auto merge of #8213 - paolobarbolini:size-of-as-bits, r=flip1995
Add `manual_bits` lint Closes #6670 --- changelog: new lint: [`manual_bits`]
2 parents b9cae79 + 166737f commit 7c82ae1

10 files changed

+364
-1
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -3071,6 +3071,7 @@ Released 2018-09-13
30713071
[`main_recursion`]: https://rust-lang.github.io/rust-clippy/master/index.html#main_recursion
30723072
[`manual_assert`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_assert
30733073
[`manual_async_fn`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_async_fn
3074+
[`manual_bits`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_bits
30743075
[`manual_filter_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_filter_map
30753076
[`manual_find_map`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_find_map
30763077
[`manual_flatten`]: https://rust-lang.github.io/rust-clippy/master/index.html#manual_flatten

clippy_lints/src/lib.register_all.rs

+1
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ store.register_group(true, "clippy::all", Some("clippy_all"), vec![
115115
LintId::of(loops::WHILE_LET_ON_ITERATOR),
116116
LintId::of(main_recursion::MAIN_RECURSION),
117117
LintId::of(manual_async_fn::MANUAL_ASYNC_FN),
118+
LintId::of(manual_bits::MANUAL_BITS),
118119
LintId::of(manual_map::MANUAL_MAP),
119120
LintId::of(manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
120121
LintId::of(manual_strip::MANUAL_STRIP),

clippy_lints/src/lib.register_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ store.register_lints(&[
226226
main_recursion::MAIN_RECURSION,
227227
manual_assert::MANUAL_ASSERT,
228228
manual_async_fn::MANUAL_ASYNC_FN,
229+
manual_bits::MANUAL_BITS,
229230
manual_map::MANUAL_MAP,
230231
manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE,
231232
manual_ok_or::MANUAL_OK_OR,

clippy_lints/src/lib.register_style.rs

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ store.register_group(true, "clippy::style", Some("clippy_style"), vec![
4343
LintId::of(loops::WHILE_LET_ON_ITERATOR),
4444
LintId::of(main_recursion::MAIN_RECURSION),
4545
LintId::of(manual_async_fn::MANUAL_ASYNC_FN),
46+
LintId::of(manual_bits::MANUAL_BITS),
4647
LintId::of(manual_map::MANUAL_MAP),
4748
LintId::of(manual_non_exhaustive::MANUAL_NON_EXHAUSTIVE),
4849
LintId::of(map_clone::MAP_CLONE),

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,7 @@ mod macro_use;
261261
mod main_recursion;
262262
mod manual_assert;
263263
mod manual_async_fn;
264+
mod manual_bits;
264265
mod manual_map;
265266
mod manual_non_exhaustive;
266267
mod manual_ok_or;
@@ -858,6 +859,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
858859
store.register_late_pass(|| Box::new(init_numbered_fields::NumberedFields));
859860
store.register_early_pass(|| Box::new(single_char_lifetime_names::SingleCharLifetimeNames));
860861
store.register_late_pass(move || Box::new(borrow_as_ptr::BorrowAsPtr::new(msrv)));
862+
store.register_late_pass(move || Box::new(manual_bits::ManualBits::new(msrv)));
861863
// add lints here, do not remove this comment, it's used in `new_lint`
862864
}
863865

clippy_lints/src/manual_bits.rs

+107
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_opt;
3+
use clippy_utils::{match_def_path, meets_msrv, msrvs, paths};
4+
use rustc_ast::ast::LitKind;
5+
use rustc_errors::Applicability;
6+
use rustc_hir::{BinOpKind, Expr, ExprKind, GenericArg, QPath};
7+
use rustc_lint::{LateContext, LateLintPass};
8+
use rustc_middle::ty::{self, Ty};
9+
use rustc_semver::RustcVersion;
10+
use rustc_session::{declare_tool_lint, impl_lint_pass};
11+
12+
declare_clippy_lint! {
13+
/// ### What it does
14+
/// Checks for uses of `std::mem::size_of::<T>() * 8` when
15+
/// `T::BITS` is available.
16+
///
17+
/// ### Why is this bad?
18+
/// Can be written as the shorter `T::BITS`.
19+
///
20+
/// ### Example
21+
/// ```rust
22+
/// std::mem::size_of::<usize>() * 8;
23+
/// ```
24+
/// Use instead:
25+
/// ```rust
26+
/// usize::BITS;
27+
/// ```
28+
#[clippy::version = "1.60.0"]
29+
pub MANUAL_BITS,
30+
style,
31+
"manual implementation of `size_of::<T>() * 8` can be simplified with `T::BITS`"
32+
}
33+
34+
#[derive(Clone)]
35+
pub struct ManualBits {
36+
msrv: Option<RustcVersion>,
37+
}
38+
39+
impl ManualBits {
40+
#[must_use]
41+
pub fn new(msrv: Option<RustcVersion>) -> Self {
42+
Self { msrv }
43+
}
44+
}
45+
46+
impl_lint_pass!(ManualBits => [MANUAL_BITS]);
47+
48+
impl<'tcx> LateLintPass<'tcx> for ManualBits {
49+
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
50+
if !meets_msrv(self.msrv.as_ref(), &msrvs::MANUAL_BITS) {
51+
return;
52+
}
53+
54+
if_chain! {
55+
if let ExprKind::Binary(bin_op, left_expr, right_expr) = expr.kind;
56+
if let BinOpKind::Mul = &bin_op.node;
57+
if let Some((real_ty, resolved_ty, other_expr)) = get_one_size_of_ty(cx, left_expr, right_expr);
58+
if matches!(resolved_ty.kind(), ty::Int(_) | ty::Uint(_));
59+
if let ExprKind::Lit(lit) = &other_expr.kind;
60+
if let LitKind::Int(8, _) = lit.node;
61+
62+
then {
63+
span_lint_and_sugg(
64+
cx,
65+
MANUAL_BITS,
66+
expr.span,
67+
"usage of `mem::size_of::<T>()` to obtain the size of `T` in bits",
68+
"consider using",
69+
format!("{}::BITS", snippet_opt(cx, real_ty.span).unwrap()),
70+
Applicability::MachineApplicable,
71+
);
72+
}
73+
}
74+
}
75+
}
76+
77+
fn get_one_size_of_ty<'tcx>(
78+
cx: &LateContext<'tcx>,
79+
expr1: &'tcx Expr<'_>,
80+
expr2: &'tcx Expr<'_>,
81+
) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>, &'tcx Expr<'tcx>)> {
82+
match (get_size_of_ty(cx, expr1), get_size_of_ty(cx, expr2)) {
83+
(Some((real_ty, resolved_ty)), None) => Some((real_ty, resolved_ty, expr2)),
84+
(None, Some((real_ty, resolved_ty))) => Some((real_ty, resolved_ty, expr1)),
85+
_ => None,
86+
}
87+
}
88+
89+
fn get_size_of_ty<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(&'tcx rustc_hir::Ty<'tcx>, Ty<'tcx>)> {
90+
if_chain! {
91+
if let ExprKind::Call(count_func, _func_args) = expr.kind;
92+
if let ExprKind::Path(ref count_func_qpath) = count_func.kind;
93+
94+
if let QPath::Resolved(_, count_func_path) = count_func_qpath;
95+
if let Some(segment_zero) = count_func_path.segments.get(0);
96+
if let Some(args) = segment_zero.args;
97+
if let Some(GenericArg::Type(real_ty)) = args.args.get(0);
98+
99+
if let Some(def_id) = cx.qpath_res(count_func_qpath, count_func.hir_id).opt_def_id();
100+
if match_def_path(cx, def_id, &paths::MEM_SIZE_OF);
101+
then {
102+
cx.typeck_results().node_substs(count_func.hir_id).types().next().map(|resolved_ty| (real_ty, resolved_ty))
103+
} else {
104+
None
105+
}
106+
}
107+
}

clippy_utils/src/msrvs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ macro_rules! msrv_aliases {
1212

1313
// names may refer to stabilized feature flags or library items
1414
msrv_aliases! {
15-
1,53,0 { OR_PATTERNS }
15+
1,53,0 { OR_PATTERNS, MANUAL_BITS }
1616
1,52,0 { STR_SPLIT_ONCE }
1717
1,51,0 { BORROW_AS_PTR }
1818
1,50,0 { BOOL_THEN }

tests/ui/manual_bits.fixed

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::manual_bits)]
4+
#![allow(clippy::no_effect, path_statements, unused_must_use, clippy::unnecessary_operation)]
5+
6+
use std::mem::{size_of, size_of_val};
7+
8+
fn main() {
9+
i8::BITS;
10+
i16::BITS;
11+
i32::BITS;
12+
i64::BITS;
13+
i128::BITS;
14+
isize::BITS;
15+
16+
u8::BITS;
17+
u16::BITS;
18+
u32::BITS;
19+
u64::BITS;
20+
u128::BITS;
21+
usize::BITS;
22+
23+
i8::BITS;
24+
i16::BITS;
25+
i32::BITS;
26+
i64::BITS;
27+
i128::BITS;
28+
isize::BITS;
29+
30+
u8::BITS;
31+
u16::BITS;
32+
u32::BITS;
33+
u64::BITS;
34+
u128::BITS;
35+
usize::BITS;
36+
37+
size_of::<usize>() * 4;
38+
4 * size_of::<usize>();
39+
size_of::<bool>() * 8;
40+
8 * size_of::<bool>();
41+
42+
size_of_val(&0u32) * 8;
43+
44+
type Word = u32;
45+
Word::BITS;
46+
type Bool = bool;
47+
size_of::<Bool>() * 8;
48+
}

tests/ui/manual_bits.rs

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// run-rustfix
2+
3+
#![warn(clippy::manual_bits)]
4+
#![allow(clippy::no_effect, path_statements, unused_must_use, clippy::unnecessary_operation)]
5+
6+
use std::mem::{size_of, size_of_val};
7+
8+
fn main() {
9+
size_of::<i8>() * 8;
10+
size_of::<i16>() * 8;
11+
size_of::<i32>() * 8;
12+
size_of::<i64>() * 8;
13+
size_of::<i128>() * 8;
14+
size_of::<isize>() * 8;
15+
16+
size_of::<u8>() * 8;
17+
size_of::<u16>() * 8;
18+
size_of::<u32>() * 8;
19+
size_of::<u64>() * 8;
20+
size_of::<u128>() * 8;
21+
size_of::<usize>() * 8;
22+
23+
8 * size_of::<i8>();
24+
8 * size_of::<i16>();
25+
8 * size_of::<i32>();
26+
8 * size_of::<i64>();
27+
8 * size_of::<i128>();
28+
8 * size_of::<isize>();
29+
30+
8 * size_of::<u8>();
31+
8 * size_of::<u16>();
32+
8 * size_of::<u32>();
33+
8 * size_of::<u64>();
34+
8 * size_of::<u128>();
35+
8 * size_of::<usize>();
36+
37+
size_of::<usize>() * 4;
38+
4 * size_of::<usize>();
39+
size_of::<bool>() * 8;
40+
8 * size_of::<bool>();
41+
42+
size_of_val(&0u32) * 8;
43+
44+
type Word = u32;
45+
size_of::<Word>() * 8;
46+
type Bool = bool;
47+
size_of::<Bool>() * 8;
48+
}

0 commit comments

Comments
 (0)