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
10 /// from other `Duration` methods.
12 /// **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or
13 /// `Duration::subsec_millis()` than to calculate them.
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 calculation of subsecond microseconds or milliseconds"
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 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);
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",
56 &format!("Calling `{}()` is more concise than this calculation", suggested_fn),
58 format!("{}.{}()", snippet(cx, args[0].span, "_"), suggested_fn),