1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
10 use if_chain::if_chain;
12 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use rustc::{declare_tool_lint, lint_array};
14 use rustc_errors::Applicability;
15 use syntax::source_map::Spanned;
17 use crate::consts::{constant, Constant};
18 use crate::utils::paths;
19 use crate::utils::{match_type, snippet_with_applicability, span_lint_and_sugg, walk_ptrs_ty};
21 /// **What it does:** Checks for calculation of subsecond microseconds or milliseconds
22 /// from other `Duration` methods.
24 /// **Why is this bad?** It's more concise to call `Duration::subsec_micros()` or
25 /// `Duration::subsec_millis()` than to calculate them.
27 /// **Known problems:** None.
31 /// let dur = Duration::new(5, 0);
32 /// let _micros = dur.subsec_nanos() / 1_000;
33 /// let _millis = dur.subsec_nanos() / 1_000_000;
35 declare_clippy_lint! {
38 "checks for calculation of subsecond microseconds or milliseconds"
41 #[derive(Copy, Clone)]
42 pub struct DurationSubsec;
44 impl LintPass for DurationSubsec {
45 fn get_lints(&self) -> LintArray {
46 lint_array!(DURATION_SUBSEC)
50 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DurationSubsec {
51 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
53 if let ExprKind::Binary(Spanned { node: BinOpKind::Div, .. }, ref left, ref right) = expr.node;
54 if let ExprKind::MethodCall(ref method_path, _ , ref args) = left.node;
55 if match_type(cx, walk_ptrs_ty(cx.tables.expr_ty(&args[0])), &paths::DURATION);
56 if let Some((Constant::Int(divisor), _)) = constant(cx, cx.tables, right);
58 let suggested_fn = match (method_path.ident.as_str().as_ref(), divisor) {
59 ("subsec_micros", 1_000) | ("subsec_nanos", 1_000_000) => "subsec_millis",
60 ("subsec_nanos", 1_000) => "subsec_micros",
63 let mut applicability = Applicability::MachineApplicable;
68 &format!("Calling `{}()` is more concise than this calculation", suggested_fn),
72 snippet_with_applicability(cx, args[0].span, "_", &mut applicability),