|
| 1 | +use clippy_config::Conf; |
| 2 | +use clippy_utils::consts::{ConstEvalCtxt, Constant}; |
| 3 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 4 | +use clippy_utils::msrvs::{self, Msrv}; |
| 5 | +use clippy_utils::res::MaybeDef; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_hir::{Expr, ExprKind, QPath, RustcVersion}; |
| 8 | +use rustc_lint::{LateContext, LateLintPass}; |
| 9 | +use rustc_session::impl_lint_pass; |
| 10 | +use rustc_span::symbol::sym; |
| 11 | + |
| 12 | +declare_clippy_lint! { |
| 13 | + /// ### What it does |
| 14 | + /// |
| 15 | + /// Checks for instances where a `std::time::Duration` is constructed using a smaller time unit |
| 16 | + /// when the value could be expressed more clearly using a larger unit. |
| 17 | + /// |
| 18 | + /// ### Why is this bad? |
| 19 | + /// |
| 20 | + /// Using a smaller unit for a duration that is evenly divisible by a larger unit reduces |
| 21 | + /// readability. Readers have to mentally convert values, which can be error-prone and makes |
| 22 | + /// the code less clear. |
| 23 | + /// |
| 24 | + /// ### Example |
| 25 | + /// ``` |
| 26 | + /// use std::time::Duration; |
| 27 | + /// |
| 28 | + /// let dur = Duration::from_millis(5_000); |
| 29 | + /// let dur = Duration::from_secs(180); |
| 30 | + /// let dur = Duration::from_mins(10 * 60); |
| 31 | + /// ``` |
| 32 | + /// |
| 33 | + /// Use instead: |
| 34 | + /// ``` |
| 35 | + /// use std::time::Duration; |
| 36 | + /// |
| 37 | + /// let dur = Duration::from_secs(5); |
| 38 | + /// let dur = Duration::from_mins(3); |
| 39 | + /// let dur = Duration::from_hours(10); |
| 40 | + /// ``` |
| 41 | + #[clippy::version = "1.94.0"] |
| 42 | + pub DURATION_SUBOPTIMAL_UNITS, |
| 43 | + pedantic, |
| 44 | + "constructing a `Duration` using a smaller unit when a larger unit would be more readable" |
| 45 | +} |
| 46 | + |
| 47 | +impl_lint_pass!(DurationSuboptimalUnits => [DURATION_SUBOPTIMAL_UNITS]); |
| 48 | + |
| 49 | +pub struct DurationSuboptimalUnits { |
| 50 | + msrv: Msrv, |
| 51 | +} |
| 52 | + |
| 53 | +impl DurationSuboptimalUnits { |
| 54 | + pub fn new(conf: &'static Conf) -> Self { |
| 55 | + Self { msrv: conf.msrv } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +impl LateLintPass<'_> for DurationSuboptimalUnits { |
| 60 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { |
| 61 | + // Check if a function on std::time::Duration is called |
| 62 | + if let ExprKind::Call(func, [arg]) = expr.kind |
| 63 | + && let ExprKind::Path(QPath::TypeRelative(func_ty, func_name)) = func.kind |
| 64 | + && cx |
| 65 | + .typeck_results() |
| 66 | + .node_type(func_ty.hir_id) |
| 67 | + .is_diag_item(cx, sym::Duration) |
| 68 | + { |
| 69 | + // We intentionally don't want to evaluate referenced constants, as we don't want to |
| 70 | + // recommend a literal value over using constants: |
| 71 | + // |
| 72 | + // let dur = Duration::from_secs(SIXTY); |
| 73 | + // ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Duration::from_mins(1)` |
| 74 | + let Some(Constant::Int(value)) = ConstEvalCtxt::new(cx).eval_local(arg, arg.span.ctxt()) else { |
| 75 | + return; |
| 76 | + }; |
| 77 | + // There is no need to promote e.g. 0 seconds to 0 hours |
| 78 | + if value == 0 { |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + let function_name = func_name.ident.name.as_str(); |
| 83 | + let Some((promoted_function_name, promoted_value)) = self.promote(cx, function_name, value) else { |
| 84 | + return; |
| 85 | + }; |
| 86 | + |
| 87 | + span_lint_and_sugg( |
| 88 | + cx, |
| 89 | + DURATION_SUBOPTIMAL_UNITS, |
| 90 | + expr.span, |
| 91 | + "constructing a `Duration` using a smaller unit when a larger unit would be more readable", |
| 92 | + "try", |
| 93 | + format!("Duration::{promoted_function_name}({promoted_value})"), |
| 94 | + Applicability::MachineApplicable, |
| 95 | + ); |
| 96 | + } |
| 97 | + } |
| 98 | +} |
| 99 | + |
| 100 | +impl DurationSuboptimalUnits { |
| 101 | + /// Tries to promote the given function and value to a bigger time unit and returns the promoted |
| 102 | + /// function name and value. |
| 103 | + /// |
| 104 | + /// Returns [`None`] in case no promotion could be done. |
| 105 | + fn promote<'a>(&self, cx: &LateContext<'_>, function_name: &'a str, value: u128) -> Option<(&'a str, u128)> { |
| 106 | + let mut promoted = false; |
| 107 | + let mut promoted_function_name = function_name; |
| 108 | + let mut promoted_value = value; |
| 109 | + |
| 110 | + let bigger_units = UNITS |
| 111 | + .iter() |
| 112 | + .skip_while(|unit| unit.function_name != function_name) |
| 113 | + .skip(1); |
| 114 | + |
| 115 | + for bigger_unit in bigger_units { |
| 116 | + if !self.msrv.meets(cx, bigger_unit.const_support_added) { |
| 117 | + // We have to break early, as we can not skip versions. |
| 118 | + // We can't skip any, as they are needed to correctly calculate the promoted value. |
| 119 | + break; |
| 120 | + } |
| 121 | + |
| 122 | + if promoted_value.is_multiple_of(bigger_unit.factor) { |
| 123 | + promoted = true; |
| 124 | + promoted_value /= bigger_unit.factor; |
| 125 | + promoted_function_name = bigger_unit.function_name; |
| 126 | + } else { |
| 127 | + break; |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + promoted.then_some((promoted_function_name, promoted_value)) |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +struct Unit { |
| 136 | + /// Name of the function on [`Duration`](std::time::Duration) to construct it from the given |
| 137 | + /// unit, e.g. [`Duration::from_secs`](std::time::Duration::from_secs) |
| 138 | + function_name: &'static str, |
| 139 | + |
| 140 | + /// The increase factor over the previous (smaller) unit |
| 141 | + factor: u128, |
| 142 | + |
| 143 | + /// In what rustc version support for this function in const contexts was added |
| 144 | + const_support_added: RustcVersion, |
| 145 | +} |
| 146 | + |
| 147 | +const UNITS: &[Unit] = &[ |
| 148 | + Unit { |
| 149 | + function_name: "from_nanos", |
| 150 | + // The value doesn't matter, as there is no previous unit |
| 151 | + factor: 0, |
| 152 | + const_support_added: msrvs::DURATION_CONSTS, |
| 153 | + }, |
| 154 | + Unit { |
| 155 | + function_name: "from_micros", |
| 156 | + factor: 1_000, |
| 157 | + const_support_added: msrvs::DURATION_CONSTS, |
| 158 | + }, |
| 159 | + Unit { |
| 160 | + function_name: "from_millis", |
| 161 | + factor: 1_000, |
| 162 | + const_support_added: msrvs::DURATION_CONSTS, |
| 163 | + }, |
| 164 | + Unit { |
| 165 | + function_name: "from_secs", |
| 166 | + factor: 1_000, |
| 167 | + const_support_added: msrvs::DURATION_CONSTS, |
| 168 | + }, |
| 169 | + Unit { |
| 170 | + function_name: "from_mins", |
| 171 | + factor: 60, |
| 172 | + const_support_added: msrvs::DURATION_CONSTRUCTORS_LITE, |
| 173 | + }, |
| 174 | + Unit { |
| 175 | + function_name: "from_hours", |
| 176 | + factor: 60, |
| 177 | + const_support_added: msrvs::DURATION_CONSTRUCTORS_LITE, |
| 178 | + }, |
| 179 | + // `from_days` and `from_weeks` are behind the nightly `duration_constructors` feature and can |
| 180 | + // be added once stabilized |
| 181 | +]; |
0 commit comments