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;
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};
11 /// **What it does:** Checks for calculation of subsecond microseconds or milliseconds
12 /// from other `Duration` methods.
14 /// **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or
15 /// `Duration::subsec_millis()` than to calculate them.
17 /// **Known problems:** None.
21 /// let dur = Duration::new(5, 0);
22 /// let _micros = dur.subsec_nanos() / 1_000;
23 /// let _millis = dur.subsec_nanos() / 1_000_000;
25 declare_clippy_lint! {
28 "checks for calculation of subsecond microseconds or milliseconds"
31 #[derive(Copy, Clone)]
32 pub struct DurationSubsec;
34 impl LintPass for DurationSubsec {
35 fn get_lints(&self) -> LintArray {
36 lint_array!(DURATION_SUBSEC)
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DurationSubsec {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
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);
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",
58 &format!("Calling `{}()` is more concise than this calculation", suggested_fn),
60 format!("{}.{}()", snippet(cx, args[0].span, "_"), suggested_fn),