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