|
| 1 | +use clippy_utils::{ |
| 2 | + diagnostics::span_lint_and_help, |
| 3 | + is_from_proc_macro, |
| 4 | + msrvs::{self, Msrv}, |
| 5 | + path_to_local, |
| 6 | +}; |
| 7 | +use rustc_ast::LitKind; |
| 8 | +use rustc_hir::{Expr, ExprKind, HirId, Node, Pat}; |
| 9 | +use rustc_lint::{LateContext, LateLintPass, LintContext}; |
| 10 | +use rustc_middle::{lint::in_external_macro, ty}; |
| 11 | +use rustc_session::{declare_tool_lint, impl_lint_pass}; |
| 12 | +use std::iter::once; |
| 13 | + |
| 14 | +declare_clippy_lint! { |
| 15 | + /// ### What it does |
| 16 | + /// Checks for tuple<=>array conversions that are not done with `.into()`. |
| 17 | + /// |
| 18 | + /// ### Why is this bad? |
| 19 | + /// It's unnecessary complexity. `.into()` works for tuples<=>arrays at or below 12 elements and |
| 20 | + /// conveys the intent a lot better, while also leaving less room for hard to spot bugs! |
| 21 | + /// |
| 22 | + /// ### Example |
| 23 | + /// ```rust,ignore |
| 24 | + /// let t1 = &[(1, 2), (3, 4)]; |
| 25 | + /// let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect(); |
| 26 | + /// ``` |
| 27 | + /// Use instead: |
| 28 | + /// ```rust,ignore |
| 29 | + /// let t1 = &[(1, 2), (3, 4)]; |
| 30 | + /// let v1: Vec<[u32; 2]> = t1.iter().map(|&t| t.into()).collect(); |
| 31 | + /// ``` |
| 32 | + #[clippy::version = "1.72.0"] |
| 33 | + pub TUPLE_ARRAY_CONVERSIONS, |
| 34 | + complexity, |
| 35 | + "checks for tuple<=>array conversions that are not done with `.into()`" |
| 36 | +} |
| 37 | +impl_lint_pass!(TupleArrayConversions => [TUPLE_ARRAY_CONVERSIONS]); |
| 38 | + |
| 39 | +#[derive(Clone)] |
| 40 | +pub struct TupleArrayConversions { |
| 41 | + pub msrv: Msrv, |
| 42 | +} |
| 43 | + |
| 44 | +impl LateLintPass<'_> for TupleArrayConversions { |
| 45 | + fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { |
| 46 | + if !in_external_macro(cx.sess(), expr.span) && self.msrv.meets(msrvs::TUPLE_ARRAY_CONVERSIONS) { |
| 47 | + match expr.kind { |
| 48 | + ExprKind::Array(elements) if (1..=12).contains(&elements.len()) => check_array(cx, expr, elements), |
| 49 | + ExprKind::Tup(elements) if (1..=12).contains(&elements.len()) => check_tuple(cx, expr, elements), |
| 50 | + _ => {}, |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + extract_msrv_attr!(LateContext); |
| 56 | +} |
| 57 | + |
| 58 | +#[expect( |
| 59 | + clippy::blocks_in_if_conditions, |
| 60 | + reason = "not a FP, but this is much easier to understand" |
| 61 | +)] |
| 62 | +fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, elements: &'tcx [Expr<'tcx>]) { |
| 63 | + if should_lint( |
| 64 | + cx, |
| 65 | + elements, |
| 66 | + // This is cursed. |
| 67 | + Some, |
| 68 | + |(first_id, local)| { |
| 69 | + if let Node::Pat(pat) = local |
| 70 | + && let parent = parent_pat(cx, pat) |
| 71 | + && parent.hir_id == first_id |
| 72 | + { |
| 73 | + return matches!( |
| 74 | + cx.typeck_results().pat_ty(parent).peel_refs().kind(), |
| 75 | + ty::Tuple(len) if len.len() == elements.len() |
| 76 | + ); |
| 77 | + } |
| 78 | + |
| 79 | + false |
| 80 | + }, |
| 81 | + ) || should_lint( |
| 82 | + cx, |
| 83 | + elements, |
| 84 | + |(i, expr)| { |
| 85 | + if let ExprKind::Field(path, field) = expr.kind && field.as_str() == i.to_string() { |
| 86 | + return Some((i, path)); |
| 87 | + }; |
| 88 | + |
| 89 | + None |
| 90 | + }, |
| 91 | + |(first_id, local)| { |
| 92 | + if let Node::Pat(pat) = local |
| 93 | + && let parent = parent_pat(cx, pat) |
| 94 | + && parent.hir_id == first_id |
| 95 | + { |
| 96 | + return matches!( |
| 97 | + cx.typeck_results().pat_ty(parent).peel_refs().kind(), |
| 98 | + ty::Tuple(len) if len.len() == elements.len() |
| 99 | + ); |
| 100 | + } |
| 101 | + |
| 102 | + false |
| 103 | + }, |
| 104 | + ) { |
| 105 | + emit_lint(cx, expr, ToType::Array); |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +#[expect( |
| 110 | + clippy::blocks_in_if_conditions, |
| 111 | + reason = "not a FP, but this is much easier to understand" |
| 112 | +)] |
| 113 | +#[expect(clippy::cast_possible_truncation)] |
| 114 | +fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, elements: &'tcx [Expr<'tcx>]) { |
| 115 | + if should_lint(cx, elements, Some, |(first_id, local)| { |
| 116 | + if let Node::Pat(pat) = local |
| 117 | + && let parent = parent_pat(cx, pat) |
| 118 | + && parent.hir_id == first_id |
| 119 | + { |
| 120 | + return matches!( |
| 121 | + cx.typeck_results().pat_ty(parent).peel_refs().kind(), |
| 122 | + ty::Array(_, len) if len.eval_target_usize(cx.tcx, cx.param_env) as usize == elements.len() |
| 123 | + ); |
| 124 | + } |
| 125 | + |
| 126 | + false |
| 127 | + }) || should_lint( |
| 128 | + cx, |
| 129 | + elements, |
| 130 | + |(i, expr)| { |
| 131 | + if let ExprKind::Index(path, index) = expr.kind |
| 132 | + && let ExprKind::Lit(lit) = index.kind |
| 133 | + && let LitKind::Int(val, _) = lit.node |
| 134 | + && val as usize == i |
| 135 | + { |
| 136 | + return Some((i, path)); |
| 137 | + }; |
| 138 | + |
| 139 | + None |
| 140 | + }, |
| 141 | + |(first_id, local)| { |
| 142 | + if let Node::Pat(pat) = local |
| 143 | + && let parent = parent_pat(cx, pat) |
| 144 | + && parent.hir_id == first_id |
| 145 | + { |
| 146 | + return matches!( |
| 147 | + cx.typeck_results().pat_ty(parent).peel_refs().kind(), |
| 148 | + ty::Array(_, len) if len.eval_target_usize(cx.tcx, cx.param_env) as usize == elements.len() |
| 149 | + ); |
| 150 | + } |
| 151 | + |
| 152 | + false |
| 153 | + }, |
| 154 | + ) { |
| 155 | + emit_lint(cx, expr, ToType::Tuple); |
| 156 | + } |
| 157 | +} |
| 158 | + |
| 159 | +/// Walks up the `Pat` until it's reached the final containing `Pat`. |
| 160 | +fn parent_pat<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Pat<'tcx>) -> &'tcx Pat<'tcx> { |
| 161 | + let mut end = start; |
| 162 | + for (_, node) in cx.tcx.hir().parent_iter(start.hir_id) { |
| 163 | + if let Node::Pat(pat) = node { |
| 164 | + end = pat; |
| 165 | + } else { |
| 166 | + break; |
| 167 | + } |
| 168 | + } |
| 169 | + end |
| 170 | +} |
| 171 | + |
| 172 | +#[derive(Clone, Copy)] |
| 173 | +enum ToType { |
| 174 | + Array, |
| 175 | + Tuple, |
| 176 | +} |
| 177 | + |
| 178 | +impl ToType { |
| 179 | + fn msg(self) -> &'static str { |
| 180 | + match self { |
| 181 | + ToType::Array => "it looks like you're trying to convert a tuple to an array", |
| 182 | + ToType::Tuple => "it looks like you're trying to convert an array to a tuple", |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + fn help(self) -> &'static str { |
| 187 | + match self { |
| 188 | + ToType::Array => "use `.into()` instead, or `<[T; N]>::from` if type annotations are needed", |
| 189 | + ToType::Tuple => "use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed", |
| 190 | + } |
| 191 | + } |
| 192 | +} |
| 193 | + |
| 194 | +fn emit_lint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, to_type: ToType) -> bool { |
| 195 | + if !is_from_proc_macro(cx, expr) { |
| 196 | + span_lint_and_help( |
| 197 | + cx, |
| 198 | + TUPLE_ARRAY_CONVERSIONS, |
| 199 | + expr.span, |
| 200 | + to_type.msg(), |
| 201 | + None, |
| 202 | + to_type.help(), |
| 203 | + ); |
| 204 | + |
| 205 | + return true; |
| 206 | + } |
| 207 | + |
| 208 | + false |
| 209 | +} |
| 210 | + |
| 211 | +fn should_lint<'tcx>( |
| 212 | + cx: &LateContext<'tcx>, |
| 213 | + elements: &'tcx [Expr<'tcx>], |
| 214 | + map: impl FnMut((usize, &'tcx Expr<'tcx>)) -> Option<(usize, &Expr<'_>)>, |
| 215 | + predicate: impl FnMut((HirId, &Node<'tcx>)) -> bool, |
| 216 | +) -> bool { |
| 217 | + if let Some(elements) = elements |
| 218 | + .iter() |
| 219 | + .enumerate() |
| 220 | + .map(map) |
| 221 | + .collect::<Option<Vec<_>>>() |
| 222 | + && let Some(locals) = elements |
| 223 | + .iter() |
| 224 | + .map(|(_, element)| path_to_local(element).and_then(|local| cx.tcx.hir().find(local))) |
| 225 | + .collect::<Option<Vec<_>>>() |
| 226 | + && let [first, rest @ ..] = &*locals |
| 227 | + && let Node::Pat(first_pat) = first |
| 228 | + && let parent = parent_pat(cx, first_pat).hir_id |
| 229 | + && rest.iter().chain(once(first)).map(|i| (parent, i)).all(predicate) |
| 230 | + { |
| 231 | + return true; |
| 232 | + } |
| 233 | + |
| 234 | + false |
| 235 | +} |
0 commit comments