]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/duration_subsec.rs
Adapt codebase to the tool_lints
[rust.git] / clippy_lints / src / duration_subsec.rs
1 use rustc::hir::*;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use if_chain::if_chain;
5 use syntax::source_map::Spanned;
6
7 use crate::consts::{constant, Constant};
8 use crate::utils::paths;
9 use crate::utils::{match_type, snippet, span_lint_and_sugg, walk_ptrs_ty};
10
11 /// **What it does:** Checks for calculation of subsecond microseconds or milliseconds
12 /// from other `Duration` methods.
13 ///
14 /// **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or
15 /// `Duration::subsec_millis()` than to calculate them.
16 ///
17 /// **Known problems:** None.
18 ///
19 /// **Example:**
20 /// ```rust
21 /// let dur = Duration::new(5, 0);
22 /// let _micros = dur.subsec_nanos() / 1_000;
23 /// let _millis = dur.subsec_nanos() / 1_000_000;
24 /// ```
25 declare_clippy_lint! {
26     pub DURATION_SUBSEC,
27     complexity,
28     "checks for calculation of subsecond microseconds or milliseconds"
29 }
30
31 #[derive(Copy, Clone)]
32 pub struct DurationSubsec;
33
34 impl LintPass for DurationSubsec {
35     fn get_lints(&self) -> LintArray {
36         lint_array!(DURATION_SUBSEC)
37     }
38 }
39
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DurationSubsec {
41     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
42         if_chain! {
43             if let ExprKind::Binary(Spanned { node: BinOpKind::Div, .. }, ref left, ref right) = expr.node;
44             if let ExprKind::MethodCall(ref method_path, _ , ref args) = left.node;
45             if match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(&args[0])), &paths::DURATION);
46             if let Some((Constant::Int(divisor), _)) = constant(cx, cx.tables, right);
47             then {
48                 let suggested_fn = match (method_path.ident.as_str().as_ref(), divisor) {
49                     ("subsec_micros", 1_000) => "subsec_millis",
50                     ("subsec_nanos", 1_000) => "subsec_micros",
51                     ("subsec_nanos", 1_000_000) => "subsec_millis",
52                     _ => return,
53                 };
54                 span_lint_and_sugg(
55                     cx,
56                     DURATION_SUBSEC,
57                     expr.span,
58                     &format!("Calling `{}()` is more concise than this calculation", suggested_fn),
59                     "try",
60                     format!("{}.{}()", snippet(cx, args[0].span, "_"), suggested_fn),
61                 );
62             }
63         }
64     }
65 }