|
1 | 1 | use clippy_utils::diagnostics::span_lint; |
2 | 2 | use rustc_ast::BinOpKind; |
3 | | -use rustc_hir::{Expr, ExprKind}; |
4 | | -use rustc_lint::{LateContext, LateLintPass}; |
| 3 | +use rustc_hir::Expr; |
| 4 | +use rustc_lint::LateContext; |
5 | 5 | use rustc_middle::ty::{self}; |
6 | | -use rustc_session::declare_lint_pass; |
7 | 6 |
|
8 | | -declare_clippy_lint! { |
9 | | - /// ### What it does |
10 | | - /// Checks for the usage of division (`/`) and remainder (`%`) operations |
11 | | - /// when performed on any integer types using the default `Div` and `Rem` trait implementations. |
12 | | - /// |
13 | | - /// ### Why restrict this? |
14 | | - /// In cryptographic contexts, division can result in timing sidechannel vulnerabilities, |
15 | | - /// and needs to be replaced with constant-time code instead (e.g. Barrett reduction). |
16 | | - /// |
17 | | - /// ### Example |
18 | | - /// ```no_run |
19 | | - /// let my_div = 10 / 2; |
20 | | - /// ``` |
21 | | - /// Use instead: |
22 | | - /// ```no_run |
23 | | - /// let my_div = 10 >> 1; |
24 | | - /// ``` |
25 | | - #[clippy::version = "1.79.0"] |
26 | | - pub INTEGER_DIVISION_REMAINDER_USED, |
27 | | - restriction, |
28 | | - "use of disallowed default division and remainder operations" |
29 | | -} |
30 | | - |
31 | | -declare_lint_pass!(IntegerDivisionRemainderUsed => [INTEGER_DIVISION_REMAINDER_USED]); |
| 7 | +use super::INTEGER_DIVISION_REMAINDER_USED; |
32 | 8 |
|
33 | | -impl LateLintPass<'_> for IntegerDivisionRemainderUsed { |
34 | | - fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { |
35 | | - if let ExprKind::Binary(op, lhs, rhs) = &expr.kind |
36 | | - && let BinOpKind::Div | BinOpKind::Rem = op.node |
37 | | - && let lhs_ty = cx.typeck_results().expr_ty(lhs) |
38 | | - && let rhs_ty = cx.typeck_results().expr_ty(rhs) |
39 | | - && let ty::Int(_) | ty::Uint(_) = lhs_ty.peel_refs().kind() |
40 | | - && let ty::Int(_) | ty::Uint(_) = rhs_ty.peel_refs().kind() |
41 | | - { |
42 | | - span_lint( |
43 | | - cx, |
44 | | - INTEGER_DIVISION_REMAINDER_USED, |
45 | | - expr.span.source_callsite(), |
46 | | - format!("use of `{}` has been disallowed in this context", op.node.as_str()), |
47 | | - ); |
48 | | - } |
| 9 | +pub(super) fn check(cx: &LateContext<'_>, expr: &Expr<'_>, op: BinOpKind, lhs: &Expr<'_>, rhs: &Expr<'_>) { |
| 10 | + if let BinOpKind::Div | BinOpKind::Rem = op |
| 11 | + && let lhs_ty = cx.typeck_results().expr_ty(lhs) |
| 12 | + && let rhs_ty = cx.typeck_results().expr_ty(rhs) |
| 13 | + && let ty::Int(_) | ty::Uint(_) = lhs_ty.peel_refs().kind() |
| 14 | + && let ty::Int(_) | ty::Uint(_) = rhs_ty.peel_refs().kind() |
| 15 | + { |
| 16 | + span_lint( |
| 17 | + cx, |
| 18 | + INTEGER_DIVISION_REMAINDER_USED, |
| 19 | + expr.span.source_callsite(), |
| 20 | + format!("use of `{}` has been disallowed in this context", op.as_str()), |
| 21 | + ); |
49 | 22 | } |
50 | 23 | } |
0 commit comments