summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/clippy_lints/src/instant_subtraction.rs
blob: 668110c7cc081c1e9da0fd1e62897c9d9d1dc757 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
use clippy_utils::diagnostics::{self, span_lint_and_sugg};
use clippy_utils::msrvs::{self, Msrv};
use clippy_utils::source;
use clippy_utils::sugg::Sugg;
use clippy_utils::ty;
use rustc_errors::Applicability;
use rustc_hir::{BinOpKind, Expr, ExprKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::{source_map::Spanned, sym};

declare_clippy_lint! {
    /// ### What it does
    /// Lints subtraction between `Instant::now()` and another `Instant`.
    ///
    /// ### Why is this bad?
    /// It is easy to accidentally write `prev_instant - Instant::now()`, which will always be 0ns
    /// as `Instant` subtraction saturates.
    ///
    /// `prev_instant.elapsed()` also more clearly signals intention.
    ///
    /// ### Example
    /// ```rust
    /// use std::time::Instant;
    /// let prev_instant = Instant::now();
    /// let duration = Instant::now() - prev_instant;
    /// ```
    /// Use instead:
    /// ```rust
    /// use std::time::Instant;
    /// let prev_instant = Instant::now();
    /// let duration = prev_instant.elapsed();
    /// ```
    #[clippy::version = "1.65.0"]
    pub MANUAL_INSTANT_ELAPSED,
    pedantic,
    "subtraction between `Instant::now()` and previous `Instant`"
}

declare_clippy_lint! {
    /// ### What it does
    /// Lints subtraction between an [`Instant`] and a [`Duration`].
    ///
    /// ### Why is this bad?
    /// Unchecked subtraction could cause underflow on certain platforms, leading to
    /// unintentional panics.
    ///
    /// ### Example
    /// ```rust
    /// # use std::time::{Instant, Duration};
    /// let time_passed = Instant::now() - Duration::from_secs(5);
    /// ```
    ///
    /// Use instead:
    /// ```rust
    /// # use std::time::{Instant, Duration};
    /// let time_passed = Instant::now().checked_sub(Duration::from_secs(5));
    /// ```
    ///
    /// [`Duration`]: std::time::Duration
    /// [`Instant::now()`]: std::time::Instant::now;
    #[clippy::version = "1.67.0"]
    pub UNCHECKED_DURATION_SUBTRACTION,
    pedantic,
    "finds unchecked subtraction of a 'Duration' from an 'Instant'"
}

pub struct InstantSubtraction {
    msrv: Msrv,
}

impl InstantSubtraction {
    #[must_use]
    pub fn new(msrv: Msrv) -> Self {
        Self { msrv }
    }
}

impl_lint_pass!(InstantSubtraction => [MANUAL_INSTANT_ELAPSED, UNCHECKED_DURATION_SUBTRACTION]);

impl LateLintPass<'_> for InstantSubtraction {
    fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) {
        if let ExprKind::Binary(
            Spanned {
                node: BinOpKind::Sub, ..
            },
            lhs,
            rhs,
        ) = expr.kind
        {
            if_chain! {
                if is_instant_now_call(cx, lhs);

                if is_an_instant(cx, rhs);
                if let Some(sugg) = Sugg::hir_opt(cx, rhs);

                then {
                    print_manual_instant_elapsed_sugg(cx, expr, sugg)
                } else {
                    if_chain! {
                        if !expr.span.from_expansion();
                        if self.msrv.meets(msrvs::TRY_FROM);

                        if is_an_instant(cx, lhs);
                        if is_a_duration(cx, rhs);

                        then {
                            print_unchecked_duration_subtraction_sugg(cx, lhs, rhs, expr)
                        }
                    }
                }
            }
        }
    }

    extract_msrv_attr!(LateContext);
}

fn is_instant_now_call(cx: &LateContext<'_>, expr_block: &'_ Expr<'_>) -> bool {
    if let ExprKind::Call(fn_expr, []) = expr_block.kind
        && let Some(fn_id) = clippy_utils::path_def_id(cx, fn_expr)
        && clippy_utils::match_def_path(cx, fn_id, &clippy_utils::paths::INSTANT_NOW)
    {
        true
    } else {
        false
    }
}

fn is_an_instant(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
    let expr_ty = cx.typeck_results().expr_ty(expr);

    match expr_ty.kind() {
        rustc_middle::ty::Adt(def, _) => clippy_utils::match_def_path(cx, def.did(), &clippy_utils::paths::INSTANT),
        _ => false,
    }
}

fn is_a_duration(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
    let expr_ty = cx.typeck_results().expr_ty(expr);
    ty::is_type_diagnostic_item(cx, expr_ty, sym::Duration)
}

fn print_manual_instant_elapsed_sugg(cx: &LateContext<'_>, expr: &Expr<'_>, sugg: Sugg<'_>) {
    span_lint_and_sugg(
        cx,
        MANUAL_INSTANT_ELAPSED,
        expr.span,
        "manual implementation of `Instant::elapsed`",
        "try",
        format!("{}.elapsed()", sugg.maybe_par()),
        Applicability::MachineApplicable,
    );
}

fn print_unchecked_duration_subtraction_sugg(
    cx: &LateContext<'_>,
    left_expr: &Expr<'_>,
    right_expr: &Expr<'_>,
    expr: &Expr<'_>,
) {
    let mut applicability = Applicability::MachineApplicable;

    let left_expr =
        source::snippet_with_applicability(cx, left_expr.span, "std::time::Instant::now()", &mut applicability);
    let right_expr = source::snippet_with_applicability(
        cx,
        right_expr.span,
        "std::time::Duration::from_secs(1)",
        &mut applicability,
    );

    diagnostics::span_lint_and_sugg(
        cx,
        UNCHECKED_DURATION_SUBTRACTION,
        expr.span,
        "unchecked subtraction of a 'Duration' from an 'Instant'",
        "try",
        format!("{left_expr}.checked_sub({right_expr}).unwrap()"),
        applicability,
    );
}