|
| 1 | +use std::ops::ControlFlow; |
| 2 | + |
| 3 | +use clippy_config::Conf; |
| 4 | +use clippy_utils::consts::{ConstEvalCtxt, Constant}; |
| 5 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 6 | +use clippy_utils::msrvs::{self, Msrv}; |
| 7 | +use clippy_utils::res::MaybeDef; |
| 8 | +use clippy_utils::sym; |
| 9 | +use rustc_errors::Applicability; |
| 10 | +use rustc_hir::{Expr, ExprKind, QPath, RustcVersion}; |
| 11 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 12 | +use rustc_middle::ty::TyCtxt; |
| 13 | +use rustc_session::impl_lint_pass; |
| 14 | +use rustc_span::Symbol; |
| 15 | + |
| 16 | +declare_clippy_lint! { |
| 17 | + /// ### What it does |
| 18 | + /// |
| 19 | + /// Checks for instances where a `std::time::Duration` is constructed using a smaller time unit |
| 20 | + /// when the value could be expressed more clearly using a larger unit. |
| 21 | + /// |
| 22 | + /// ### Why is this bad? |
| 23 | + /// |
| 24 | + /// Using a smaller unit for a duration that is evenly divisible by a larger unit reduces |
| 25 | + /// readability. Readers have to mentally convert values, which can be error-prone and makes |
| 26 | + /// the code less clear. |
| 27 | + /// |
| 28 | + /// ### Example |
| 29 | + /// ``` |
| 30 | + /// use std::time::Duration; |
| 31 | + /// |
| 32 | + /// let dur = Duration::from_millis(5_000); |
| 33 | + /// let dur = Duration::from_secs(180); |
| 34 | + /// let dur = Duration::from_mins(10 * 60); |
| 35 | + /// ``` |
| 36 | + /// |
| 37 | + /// Use instead: |
| 38 | + /// ``` |
| 39 | + /// use std::time::Duration; |
| 40 | + /// |
| 41 | + /// let dur = Duration::from_secs(5); |
| 42 | + /// let dur = Duration::from_mins(3); |
| 43 | + /// let dur = Duration::from_hours(10); |
| 44 | + /// ``` |
| 45 | + #[clippy::version = "1.94.0"] |
| 46 | + pub DURATION_SUBOPTIMAL_UNITS, |
| 47 | + pedantic, |
| 48 | + "constructing a `Duration` using a smaller unit when a larger unit would be more readable" |
| 49 | +} |
| 50 | + |
| 51 | +impl_lint_pass!(DurationSuboptimalUnits => [DURATION_SUBOPTIMAL_UNITS]); |
| 52 | + |
| 53 | +pub struct DurationSuboptimalUnits { |
| 54 | + msrv: Msrv, |
| 55 | + units: Vec<Unit>, |
| 56 | +} |
| 57 | + |
| 58 | +impl DurationSuboptimalUnits { |
| 59 | + pub fn new(tcx: TyCtxt<'_>, conf: &'static Conf) -> Self { |
| 60 | + // The order of the units matters, as they are walked top to bottom |
| 61 | + let mut units = UNITS.to_vec(); |
| 62 | + if tcx.features().enabled(sym::duration_constructors) { |
| 63 | + units.extend(EXTENDED_UNITS.iter().copied()); |
| 64 | + } |
| 65 | + Self { msrv: conf.msrv, units } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +impl LateLintPass<'_> for DurationSuboptimalUnits { |
| 70 | + fn check_expr(&mut self, cx: &LateContext<'_>, expr: &'_ Expr<'_>) { |
| 71 | + if !expr.span.in_external_macro(cx.sess().source_map()) |
| 72 | + // Check if a function on std::time::Duration is called |
| 73 | + && let ExprKind::Call(func, [arg]) = expr.kind |
| 74 | + && let ExprKind::Path(QPath::TypeRelative(func_ty, func_name)) = func.kind |
| 75 | + && cx |
| 76 | + .typeck_results() |
| 77 | + .node_type(func_ty.hir_id) |
| 78 | + .is_diag_item(cx, sym::Duration) |
| 79 | + // We intentionally don't want to evaluate referenced constants, as we don't want to |
| 80 | + // recommend a literal value over using constants: |
| 81 | + // |
| 82 | + // let dur = Duration::from_secs(SIXTY); |
| 83 | + // ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `Duration::from_mins(1)` |
| 84 | + && let Some(Constant::Int(value)) = ConstEvalCtxt::new(cx).eval_local(arg, expr.span.ctxt()) |
| 85 | + && let value = u64::try_from(value).expect("All Duration::from_<time-unit> constructors take a u64") |
| 86 | + // There is no need to promote e.g. 0 seconds to 0 hours |
| 87 | + && value != 0 |
| 88 | + && let Some((promoted_constructor, promoted_value)) = self.promote(cx, expr, func_name.ident.name, value) |
| 89 | + { |
| 90 | + span_lint_and_sugg( |
| 91 | + cx, |
| 92 | + DURATION_SUBOPTIMAL_UNITS, |
| 93 | + expr.span, |
| 94 | + "constructing a `Duration` using a smaller unit when a larger unit would be more readable", |
| 95 | + "try", |
| 96 | + format!("Duration::{promoted_constructor}({promoted_value})"), |
| 97 | + Applicability::MachineApplicable, |
| 98 | + ); |
| 99 | + } |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +impl DurationSuboptimalUnits { |
| 104 | + /// Tries to promote the given constructor and value to a bigger time unit and returns the |
| 105 | + /// promoted constructor name and value. |
| 106 | + /// |
| 107 | + /// Returns [`None`] in case no promotion could be done. |
| 108 | + fn promote( |
| 109 | + &self, |
| 110 | + cx: &LateContext<'_>, |
| 111 | + expr: &'_ Expr<'_>, |
| 112 | + constructor_name: Symbol, |
| 113 | + value: u64, |
| 114 | + ) -> Option<(Symbol, u64)> { |
| 115 | + let in_const = cx.tcx.hir_is_inside_const_context(expr.hir_id); |
| 116 | + |
| 117 | + let (best_unit, best_value) = self |
| 118 | + .units |
| 119 | + .iter() |
| 120 | + .skip_while(|unit| unit.constructor_name != constructor_name) |
| 121 | + .skip(1) |
| 122 | + .try_fold( |
| 123 | + (constructor_name, value), |
| 124 | + |(current_unit, current_value), bigger_unit| { |
| 125 | + if let Some(bigger_value) = current_value.div_exact(u64::from(bigger_unit.factor)) |
| 126 | + && bigger_unit |
| 127 | + .stable_since(in_const) |
| 128 | + .is_none_or(|v| self.msrv.meets(cx, v)) |
| 129 | + { |
| 130 | + ControlFlow::Continue((bigger_unit.constructor_name, bigger_value)) |
| 131 | + } else { |
| 132 | + // We have to break early, as we can't skip versions, as they are needed to |
| 133 | + // correctly calculate the promoted value. |
| 134 | + ControlFlow::Break((current_unit, current_value)) |
| 135 | + } |
| 136 | + }, |
| 137 | + ) |
| 138 | + .into_value(); |
| 139 | + (best_unit != constructor_name).then_some((best_unit, best_value)) |
| 140 | + } |
| 141 | +} |
| 142 | + |
| 143 | +#[derive(Clone, Copy)] |
| 144 | +struct Unit { |
| 145 | + /// Name of the constructor on [`Duration`](std::time::Duration) to construct it from the given |
| 146 | + /// unit, e.g. [`Duration::from_secs`](std::time::Duration::from_secs) |
| 147 | + constructor_name: Symbol, |
| 148 | + |
| 149 | + /// The increase factor over the previous (smaller) unit |
| 150 | + factor: u16, |
| 151 | + |
| 152 | + /// In what rustc version stable support for this constructor was added. |
| 153 | + stable_since: Option<RustcVersion>, |
| 154 | + |
| 155 | + /// In what rustc version stable support for this constructor in const contexts was added. |
| 156 | + const_stable_since: Option<RustcVersion>, |
| 157 | +} |
| 158 | + |
| 159 | +impl Unit { |
| 160 | + /// In what rustc version stable support was added. This depends if the constructor call is in |
| 161 | + /// a const context or not. |
| 162 | + /// |
| 163 | + /// If [`None`] is returned, there is no rustc version restriction (e.g. because it actually |
| 164 | + /// depends on a feature). |
| 165 | + pub fn stable_since(&self, in_const: bool) -> Option<RustcVersion> { |
| 166 | + if in_const { |
| 167 | + self.const_stable_since |
| 168 | + } else { |
| 169 | + self.stable_since |
| 170 | + } |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +/// Time unit constructors available on stable. The order matters! |
| 175 | +const UNITS: [Unit; 6] = [ |
| 176 | + Unit { |
| 177 | + constructor_name: sym::from_nanos, |
| 178 | + // The value doesn't matter, as there is no previous unit |
| 179 | + factor: 0, |
| 180 | + stable_since: Some(msrvs::DURATION_FROM_NANOS_MICROS), |
| 181 | + const_stable_since: Some(msrvs::DURATION_CONST_FROM_NANOS_MICROS_MILLIS_SECS), |
| 182 | + }, |
| 183 | + Unit { |
| 184 | + constructor_name: sym::from_micros, |
| 185 | + factor: 1_000, |
| 186 | + stable_since: Some(msrvs::DURATION_FROM_NANOS_MICROS), |
| 187 | + const_stable_since: Some(msrvs::DURATION_CONST_FROM_NANOS_MICROS_MILLIS_SECS), |
| 188 | + }, |
| 189 | + Unit { |
| 190 | + constructor_name: sym::from_millis, |
| 191 | + factor: 1_000, |
| 192 | + stable_since: Some(msrvs::DURATION_FROM_MILLIS_SECS), |
| 193 | + const_stable_since: Some(msrvs::DURATION_CONST_FROM_NANOS_MICROS_MILLIS_SECS), |
| 194 | + }, |
| 195 | + Unit { |
| 196 | + constructor_name: sym::from_secs, |
| 197 | + factor: 1_000, |
| 198 | + stable_since: Some(msrvs::DURATION_FROM_MILLIS_SECS), |
| 199 | + const_stable_since: Some(msrvs::DURATION_CONST_FROM_NANOS_MICROS_MILLIS_SECS), |
| 200 | + }, |
| 201 | + Unit { |
| 202 | + constructor_name: sym::from_mins, |
| 203 | + factor: 60, |
| 204 | + stable_since: Some(msrvs::DURATION_FROM_MINUTES_HOURS), |
| 205 | + const_stable_since: Some(msrvs::DURATION_FROM_MINUTES_HOURS), |
| 206 | + }, |
| 207 | + Unit { |
| 208 | + constructor_name: sym::from_hours, |
| 209 | + factor: 60, |
| 210 | + stable_since: Some(msrvs::DURATION_FROM_MINUTES_HOURS), |
| 211 | + const_stable_since: Some(msrvs::DURATION_FROM_MINUTES_HOURS), |
| 212 | + }, |
| 213 | +]; |
| 214 | + |
| 215 | +/// Time unit constructors behind the `duration_constructors` feature. The order matters! |
| 216 | +const EXTENDED_UNITS: [Unit; 2] = [ |
| 217 | + Unit { |
| 218 | + constructor_name: sym::from_days, |
| 219 | + factor: 24, |
| 220 | + stable_since: None, |
| 221 | + const_stable_since: None, |
| 222 | + }, |
| 223 | + Unit { |
| 224 | + constructor_name: sym::from_weeks, |
| 225 | + factor: 7, |
| 226 | + stable_since: None, |
| 227 | + const_stable_since: None, |
| 228 | + }, |
| 229 | +]; |
0 commit comments