]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/duration_subsec.rs
Merge branch 'master' into duration_subsec_pr_2
[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 from
10 /// `Duration::subsec_nanos()`.
11 ///
12 /// **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or
13 /// `Duration::subsec_millis()`.
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 `dur.subsec_nanos() / 1_000` or `dur.subsec_nanos() / 1_000_000`"
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 ExprBinary(Spanned { node: BiDiv, .. }, ref left, ref right) = expr.node;
42             if let ExprMethodCall(ref method_path, _ , ref args) = left.node;
43             if method_path.name == "subsec_nanos";
44             if match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(&args[0])), &paths::DURATION);
45             if let Some((Constant::Int(divisor), _)) = constant(cx, cx.tables, right);
46             then {
47                 let suggested_fn = match divisor {
48                     1_000 => "subsec_micros",
49                     1_000_000 => "subsec_millis",
50                     _ => return,
51                 };
52
53                 span_lint_and_sugg(
54                     cx,
55                     DURATION_SUBSEC,
56                     expr.span,
57                     &format!("Calling `{}()` is more concise than this calculation", suggested_fn),
58                     "try",
59                     format!("{}.{}()", snippet(cx, args[0].span, "_"), suggested_fn),
60                 );
61             }
62         }
63     }
64 }