3 use syntax::codemap::Spanned;
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};
9 /// **What it does:** Checks for calculation of subsecond microseconds or milliseconds from
10 /// `Duration::subsec_nanos()`.
12 /// **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or
13 /// `Duration::subsec_millis()`.
15 /// **Known problems:** None.
19 /// let dur = Duration::new(5, 0);
20 /// let _micros = dur.subsec_nanos() / 1_000;
21 /// let _millis = dur.subsec_nanos() / 1_000_000;
23 declare_clippy_lint! {
26 "checks for `dur.subsec_nanos() / 1_000` or `dur.subsec_nanos() / 1_000_000`"
29 #[derive(Copy, Clone)]
30 pub struct DurationSubsec;
32 impl LintPass for DurationSubsec {
33 fn get_lints(&self) -> LintArray {
34 lint_array!(DURATION_SUBSEC)
38 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DurationSubsec {
39 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
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);
47 let suggested_fn = match divisor {
48 1_000 => "subsec_micros",
49 1_000_000 => "subsec_millis",
57 &format!("Calling `{}()` is more concise than this calculation", suggested_fn),
59 format!("{}.{}()", snippet(cx, args[0].span, "_"), suggested_fn),