|
| 1 | +use clippy_utils::diagnostics::span_lint; |
| 2 | +use clippy_utils::fn_has_unsatisfiable_preds; |
| 3 | +use clippy_utils::source::snippet_opt; |
| 4 | +use itertools::Itertools; |
| 5 | +use rustc_const_eval::interpret::Scalar; |
| 6 | +use rustc_data_structures::fx::FxHashMap; |
| 7 | +use rustc_hir::def_id::LocalDefId; |
| 8 | +use rustc_hir::{intravisit::FnKind, Body, FnDecl}; |
| 9 | +use rustc_lint::{LateContext, LateLintPass}; |
| 10 | +use rustc_middle::mir::{ |
| 11 | + self, interpret::ConstValue, visit::Visitor, Constant, Location, Operand, Rvalue, Statement, StatementKind, |
| 12 | +}; |
| 13 | +use rustc_session::{declare_lint_pass, declare_tool_lint}; |
| 14 | +use rustc_span::Span; |
| 15 | + |
| 16 | +declare_clippy_lint! { |
| 17 | + /// ### What it does |
| 18 | + /// Checks for locals that are always assigned the same value. |
| 19 | + /// |
| 20 | + /// ### Why is this bad? |
| 21 | + /// It's almost always a typo. If not, it can be made immutable, or turned into a constant. |
| 22 | + /// |
| 23 | + /// ### Example |
| 24 | + /// ```rust |
| 25 | + /// let mut x = 1; |
| 26 | + /// x = 1; |
| 27 | + /// ``` |
| 28 | + /// Use instead: |
| 29 | + /// ```rust |
| 30 | + /// let x = 1; |
| 31 | + /// ``` |
| 32 | + #[clippy::version = "1.72.0"] |
| 33 | + pub LOCAL_ASSIGNED_SINGLE_VALUE, |
| 34 | + correctness, |
| 35 | + "disallows assigning locals many times with the same value" |
| 36 | +} |
| 37 | +declare_lint_pass!(LocalAssignedSingleValue => [LOCAL_ASSIGNED_SINGLE_VALUE]); |
| 38 | + |
| 39 | +impl LateLintPass<'_> for LocalAssignedSingleValue { |
| 40 | + fn check_fn( |
| 41 | + &mut self, |
| 42 | + cx: &LateContext<'_>, |
| 43 | + _: FnKind<'_>, |
| 44 | + _: &FnDecl<'_>, |
| 45 | + _: &Body<'_>, |
| 46 | + _: Span, |
| 47 | + def_id: LocalDefId, |
| 48 | + ) { |
| 49 | + // Building MIR for `fn`s with unsatisfiable preds results in ICE. |
| 50 | + if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) { |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + let mir = cx.tcx.optimized_mir(def_id.to_def_id()); |
| 55 | + let mut v = V { |
| 56 | + body: mir, |
| 57 | + cx, |
| 58 | + local_usage: mir |
| 59 | + .local_decls |
| 60 | + .iter_enumerated() |
| 61 | + .map(|(local, _)| (local, LocalUsageValues::default())) |
| 62 | + .collect(), |
| 63 | + }; |
| 64 | + v.visit_body(mir); |
| 65 | + |
| 66 | + for (local, usage) in &v.local_usage { |
| 67 | + if should_lint(&v.local_usage, *local, usage) { |
| 68 | + let LocalUsageValues { |
| 69 | + usage, |
| 70 | + mut_ref_acquired: _, |
| 71 | + assigned_non_const: _, |
| 72 | + } = usage; |
| 73 | + |
| 74 | + if let Some(local_decl) = mir.local_decls.get(*local) |
| 75 | + && let [dbg_info] = &*mir |
| 76 | + .var_debug_info |
| 77 | + .iter() |
| 78 | + .filter(|info| info.source_info.span == local_decl.source_info.span) |
| 79 | + .collect_vec() |
| 80 | + // Don't handle function arguments. |
| 81 | + && dbg_info.argument_index.is_none() |
| 82 | + // Ignore anything from a procedural macro, or locals we cannot prove aren't |
| 83 | + // temporaries |
| 84 | + && let Some(snippet) = snippet_opt(cx, dbg_info.source_info.span) |
| 85 | + && snippet.ends_with(dbg_info.name.as_str()) |
| 86 | + { |
| 87 | + span_lint( |
| 88 | + cx, |
| 89 | + LOCAL_ASSIGNED_SINGLE_VALUE, |
| 90 | + usage.iter().map(|(span, _)| *span).collect_vec(), |
| 91 | + "local only ever assigned single value", |
| 92 | + ); |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +type LocalUsage = FxHashMap<mir::Local, LocalUsageValues>; |
| 100 | + |
| 101 | +/// Holds the data we have for the usage of a local. |
| 102 | +#[derive(Default)] |
| 103 | +struct LocalUsageValues { |
| 104 | + /// Where and what this local is assigned. |
| 105 | + usage: Vec<(Span, Scalar)>, |
| 106 | + /// Whether it's mutably borrowed, ever. We should not lint this. |
| 107 | + mut_ref_acquired: bool, |
| 108 | + /// Whether it's assigned a value we cannot prove is constant, ever. We should not lint this. |
| 109 | + assigned_non_const: bool, |
| 110 | +} |
| 111 | + |
| 112 | +struct V<'a, 'tcx> { |
| 113 | + #[allow(dead_code)] |
| 114 | + body: &'a mir::Body<'tcx>, |
| 115 | + cx: &'a LateContext<'tcx>, |
| 116 | + local_usage: LocalUsage, |
| 117 | +} |
| 118 | + |
| 119 | +impl<'a, 'tcx> Visitor<'tcx> for V<'a, 'tcx> { |
| 120 | + fn visit_statement(&mut self, stmt: &Statement<'tcx>, _: Location) { |
| 121 | + let Self { |
| 122 | + body: _, |
| 123 | + cx, |
| 124 | + local_usage, |
| 125 | + } = self; |
| 126 | + |
| 127 | + if stmt.source_info.span.from_expansion() { |
| 128 | + return; |
| 129 | + } |
| 130 | + |
| 131 | + if let StatementKind::Assign(assign) = &stmt.kind { |
| 132 | + let (place, rvalue) = &**assign; |
| 133 | + // Do not lint if there are any mutable borrows to a local |
| 134 | + if let Rvalue::Ref(_, mir::BorrowKind::Unique | mir::BorrowKind::Mut { .. }, place) = rvalue |
| 135 | + && let Some(other) = local_usage.get_mut(&place.local) |
| 136 | + { |
| 137 | + other.assigned_non_const = true; |
| 138 | + return; |
| 139 | + } |
| 140 | + let Some(usage) = local_usage.get_mut(&place.local) else { |
| 141 | + return; |
| 142 | + }; |
| 143 | + |
| 144 | + if let Rvalue::Use(Operand::Constant(constant)) = rvalue |
| 145 | + && let Constant { literal, .. } = **constant |
| 146 | + && let Some(ConstValue::Scalar(val)) = literal.try_to_value(cx.tcx) |
| 147 | + { |
| 148 | + usage.usage.push((stmt.source_info.span, val)); |
| 149 | + } else if let Rvalue::Use(Operand::Copy(place)) = rvalue |
| 150 | + && let [_base_proj, ..] = place.projection.as_slice() |
| 151 | + { |
| 152 | + // While this could be `let [x, y] = [1, 1]` or `let (x, y) = (1, 1)`, which should |
| 153 | + // indeed be considered a constant, handling such a case would overcomplicate this |
| 154 | + // lint. |
| 155 | + // |
| 156 | + // TODO(Centri3): Let's do the above as a follow-up, in the future! In particular, |
| 157 | + // we need to handle `ProjectionElem::Field` and `ProjectionElem::Index`. |
| 158 | + usage.assigned_non_const = true; |
| 159 | + } else { |
| 160 | + // We can also probably handle stuff like `x += 1` here, maybe. But this would be |
| 161 | + // very very complex. Let's keep it simple enough. |
| 162 | + usage.assigned_non_const = true; |
| 163 | + } |
| 164 | + } |
| 165 | + } |
| 166 | +} |
| 167 | + |
| 168 | +fn should_lint(_local_usage: &LocalUsage, _local: mir::Local, usage: &LocalUsageValues) -> bool { |
| 169 | + let LocalUsageValues { |
| 170 | + usage, |
| 171 | + mut_ref_acquired, |
| 172 | + assigned_non_const, |
| 173 | + } = usage; |
| 174 | + |
| 175 | + if usage.len() > 1 |
| 176 | + && !mut_ref_acquired |
| 177 | + && !assigned_non_const |
| 178 | + && let [(_, head), tail @ ..] = &**usage |
| 179 | + && tail.iter().all(|(_, i)| i == head) |
| 180 | + { |
| 181 | + return true; |
| 182 | + } |
| 183 | + |
| 184 | + false |
| 185 | +} |
0 commit comments