diff --git a/clippy_lints/src/lib.rs b/clippy_lints/src/lib.rs index 39301b5344a..87329ee5e14 100644 --- a/clippy_lints/src/lib.rs +++ b/clippy_lints/src/lib.rs @@ -1073,7 +1073,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf: }); store.register_late_pass(|_| Box::new(manual_range_patterns::ManualRangePatterns)); store.register_early_pass(|| Box::new(visibility::Visibility)); - store.register_late_pass(|_| Box::new(tuple_array_conversions::TupleArrayConversions)); + store.register_late_pass(move |_| Box::new(tuple_array_conversions::TupleArrayConversions { msrv: msrv() })); // add lints here, do not remove this comment, it's used in `new_lint` } diff --git a/clippy_lints/src/tuple_array_conversions.rs b/clippy_lints/src/tuple_array_conversions.rs index 9640083f764..9d5e872bd78 100644 --- a/clippy_lints/src/tuple_array_conversions.rs +++ b/clippy_lints/src/tuple_array_conversions.rs @@ -1,13 +1,23 @@ -use clippy_utils::{diagnostics::span_lint_and_help, is_from_proc_macro, path_to_local}; -use rustc_hir::*; +use clippy_utils::{ + diagnostics::span_lint_and_help, + is_from_proc_macro, + msrvs::{self, Msrv}, + path_to_local, +}; +use itertools::Itertools; +use rustc_hir::{Expr, ExprKind, Node, Pat}; use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_middle::{lint::in_external_macro, ty}; -use rustc_session::{declare_lint_pass, declare_tool_lint}; +use rustc_session::{declare_tool_lint, impl_lint_pass}; +use std::iter::once; declare_clippy_lint! { /// ### What it does + /// Checks for tuple<=>array conversions that are not done with `.into()`. /// /// ### Why is this bad? + /// It's overly complex. `.into()` works for tuples<=>arrays with less than 13 elements and + /// conveys the intent a lot better, while also leaving less room for bugs! /// /// ### Example /// ```rust,ignore @@ -22,16 +32,23 @@ declare_clippy_lint! { #[clippy::version = "1.72.0"] pub TUPLE_ARRAY_CONVERSIONS, complexity, - "default lint description" + "checks for tuple<=>array conversions that are not done with `.into()`" +} +impl_lint_pass!(TupleArrayConversions => [TUPLE_ARRAY_CONVERSIONS]); + +#[derive(Clone)] +pub struct TupleArrayConversions { + pub msrv: Msrv, } -declare_lint_pass!(TupleArrayConversions => [TUPLE_ARRAY_CONVERSIONS]); impl LateLintPass<'_> for TupleArrayConversions { fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { - if !in_external_macro(cx.sess(), expr.span) { + if !in_external_macro(cx.sess(), expr.span) && self.msrv.meets(msrvs::TUPLE_ARRAY_CONVERSIONS) { _ = check_array(cx, expr) || check_tuple(cx, expr); } } + + extract_msrv_attr!(LateContext); } fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { @@ -42,15 +59,22 @@ fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { return false; } - if let Some(locals) = path_to_locals(cx, elements) - && locals.iter().all(|local| { - matches!( - local, - Node::Pat(pat) if matches!( - cx.typeck_results().pat_ty(backtrack_pat(cx, pat)).peel_refs().kind(), - ty::Tuple(_), - ), - ) + if let Some(locals) = path_to_locals(cx, &elements.iter().collect_vec()) + && let [first, rest @ ..] = &*locals + && let Node::Pat(first_pat) = first + && let first_id = parent_pat(cx, first_pat).hir_id + && rest.iter().chain(once(first)).all(|local| { + if let Node::Pat(pat) = local + && let parent = parent_pat(cx, pat) + && parent.hir_id == first_id + { + return matches!( + cx.typeck_results().pat_ty(parent).peel_refs().kind(), + ty::Tuple(len) if len.len() == elements.len() + ); + } + + false }) { return emit_lint(cx, expr, ToType::Array); @@ -66,15 +90,22 @@ fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { None }) .collect::>>>() - && let Some(locals) = path_to_locals(cx, elements) - && locals.iter().all(|local| { - matches!( - local, - Node::Pat(pat) if matches!( - cx.typeck_results().pat_ty(backtrack_pat(cx, pat)).peel_refs().kind(), - ty::Tuple(_), - ), - ) + && let Some(locals) = path_to_locals(cx, &elements) + && let [first, rest @ ..] = &*locals + && let Node::Pat(first_pat) = first + && let first_id = parent_pat(cx, first_pat).hir_id + && rest.iter().chain(once(first)).all(|local| { + if let Node::Pat(pat) = local + && let parent = parent_pat(cx, pat) + && parent.hir_id == first_id + { + return matches!( + cx.typeck_results().pat_ty(parent).peel_refs().kind(), + ty::Tuple(len) if len.len() == elements.len() + ); + } + + false }) { return emit_lint(cx, expr, ToType::Array); @@ -83,6 +114,7 @@ fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { false } +#[expect(clippy::cast_possible_truncation)] fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { let ExprKind::Tup(elements) = expr.kind else { return false; @@ -90,15 +122,23 @@ fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { if !(1..=12).contains(&elements.len()) { return false; }; - if let Some(locals) = path_to_locals(cx, elements) - && locals.iter().all(|local| { - matches!( - local, - Node::Pat(pat) if matches!( - cx.typeck_results().pat_ty(backtrack_pat(cx, pat)).peel_refs().kind(), - ty::Array(_, _), - ), - ) + + if let Some(locals) = path_to_locals(cx, &elements.iter().collect_vec()) + && let [first, rest @ ..] = &*locals + && let Node::Pat(first_pat) = first + && let first_id = parent_pat(cx, first_pat).hir_id + && rest.iter().chain(once(first)).all(|local| { + if let Node::Pat(pat) = local + && let parent = parent_pat(cx, pat) + && parent.hir_id == first_id + { + return matches!( + cx.typeck_results().pat_ty(parent).peel_refs().kind(), + ty::Array(_, len) if len.eval_target_usize(cx.tcx, cx.param_env) as usize == elements.len() + ); + } + + false }) { return emit_lint(cx, expr, ToType::Tuple); @@ -114,15 +154,22 @@ fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { None }) .collect::>>>() - && let Some(locals) = path_to_locals(cx, elements.clone()) - && locals.iter().all(|local| { - matches!( - local, - Node::Pat(pat) if cx.typeck_results() - .pat_ty(backtrack_pat(cx, pat)) - .peel_refs() - .is_array() - ) + && let Some(locals) = path_to_locals(cx, &elements) + && let [first, rest @ ..] = &*locals + && let Node::Pat(first_pat) = first + && let first_id = parent_pat(cx, first_pat).hir_id + && rest.iter().chain(once(first)).all(|local| { + if let Node::Pat(pat) = local + && let parent = parent_pat(cx, pat) + && parent.hir_id == first_id + { + return matches!( + cx.typeck_results().pat_ty(parent).peel_refs().kind(), + ty::Array(_, len) if len.eval_target_usize(cx.tcx, cx.param_env) as usize == elements.len() + ); + } + + false }) { return emit_lint(cx, expr, ToType::Tuple); @@ -132,7 +179,7 @@ fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { } /// Walks up the `Pat` until it's reached the final containing `Pat`. -fn backtrack_pat<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Pat<'tcx>) -> &'tcx Pat<'tcx> { +fn parent_pat<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Pat<'tcx>) -> &'tcx Pat<'tcx> { let mut end = start; for (_, node) in cx.tcx.hir().parent_iter(start.hir_id) { if let Node::Pat(pat) = node { @@ -144,12 +191,9 @@ fn backtrack_pat<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Pat<'tcx>) -> &'tcx end } -fn path_to_locals<'tcx>( - cx: &LateContext<'tcx>, - exprs: impl IntoIterator>, -) -> Option>> { +fn path_to_locals<'tcx>(cx: &LateContext<'tcx>, exprs: &[&'tcx Expr<'tcx>]) -> Option>> { exprs - .into_iter() + .iter() .map(|element| path_to_local(element).and_then(|local| cx.tcx.hir().find(local))) .collect() } @@ -161,12 +205,19 @@ enum ToType { } impl ToType { - fn help(self) -> &'static str { + fn msg(self) -> &'static str { match self { ToType::Array => "it looks like you're trying to convert a tuple to an array", ToType::Tuple => "it looks like you're trying to convert an array to a tuple", } } + + fn help(self) -> &'static str { + match self { + ToType::Array => "use `.into()` instead, or `<[T; N]>::from` if type annotations are needed", + ToType::Tuple => "use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed", + } + } } fn emit_lint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, to_type: ToType) -> bool { @@ -175,9 +226,9 @@ fn emit_lint<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, to_type: ToTy cx, TUPLE_ARRAY_CONVERSIONS, expr.span, - to_type.help(), + to_type.msg(), None, - "use `.into()` instead", + to_type.help(), ); return true; diff --git a/clippy_lints/src/upper_case_acronyms.rs b/clippy_lints/src/upper_case_acronyms.rs index 1d2d3eb12e1..4df1e3299ed 100644 --- a/clippy_lints/src/upper_case_acronyms.rs +++ b/clippy_lints/src/upper_case_acronyms.rs @@ -65,7 +65,7 @@ fn correct_ident(ident: &str) -> String { let mut ident = fragments.clone().next().unwrap(); for (ref prev, ref curr) in fragments.tuple_windows() { - if [prev, curr] + if <[&String; 2]>::from((prev, curr)) .iter() .all(|s| s.len() == 1 && s.chars().next().unwrap().is_ascii_uppercase()) { diff --git a/clippy_lints/src/utils/conf.rs b/clippy_lints/src/utils/conf.rs index 972e24aac51..89063964622 100644 --- a/clippy_lints/src/utils/conf.rs +++ b/clippy_lints/src/utils/conf.rs @@ -294,7 +294,7 @@ define_Conf! { /// /// Suppress lints whenever the suggested change would cause breakage for other crates. (avoid_breaking_exported_api: bool = true), - /// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, OPTION_MAP_UNWRAP_OR, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS. + /// Lint: MANUAL_SPLIT_ONCE, MANUAL_STR_REPEAT, CLONED_INSTEAD_OF_COPIED, REDUNDANT_FIELD_NAMES, OPTION_MAP_UNWRAP_OR, REDUNDANT_STATIC_LIFETIMES, FILTER_MAP_NEXT, CHECKED_CONVERSIONS, MANUAL_RANGE_CONTAINS, USE_SELF, MEM_REPLACE_WITH_DEFAULT, MANUAL_NON_EXHAUSTIVE, OPTION_AS_REF_DEREF, MAP_UNWRAP_OR, MATCH_LIKE_MATCHES_MACRO, MANUAL_STRIP, MISSING_CONST_FOR_FN, UNNESTED_OR_PATTERNS, FROM_OVER_INTO, PTR_AS_PTR, IF_THEN_SOME_ELSE_NONE, APPROX_CONSTANT, DEPRECATED_CFG_ATTR, INDEX_REFUTABLE_SLICE, MAP_CLONE, BORROW_AS_PTR, MANUAL_BITS, ERR_EXPECT, CAST_ABS_TO_UNSIGNED, UNINLINED_FORMAT_ARGS, MANUAL_CLAMP, MANUAL_LET_ELSE, UNCHECKED_DURATION_SUBTRACTION, COLLAPSIBLE_STR_REPLACE, SEEK_FROM_CURRENT, SEEK_REWIND, UNNECESSARY_LAZY_EVALUATIONS, TRANSMUTE_PTR_TO_REF, ALMOST_COMPLETE_RANGE, NEEDLESS_BORROW, DERIVABLE_IMPLS, MANUAL_IS_ASCII_CHECK, MANUAL_REM_EUCLID, MANUAL_RETAIN, TYPE_REPETITION_IN_BOUNDS, TUPLE_ARRAY_CONVERSIONS. /// /// The minimum rust version that the project supports (msrv: Option = None), diff --git a/clippy_utils/src/msrvs.rs b/clippy_utils/src/msrvs.rs index 5aacca45146..1f70f11bd67 100644 --- a/clippy_utils/src/msrvs.rs +++ b/clippy_utils/src/msrvs.rs @@ -19,6 +19,7 @@ macro_rules! msrv_aliases { // names may refer to stabilized feature flags or library items msrv_aliases! { + 1,71,0 { TUPLE_ARRAY_CONVERSIONS } 1,70,0 { OPTION_IS_SOME_AND } 1,68,0 { PATH_MAIN_SEPARATOR_STR } 1,65,0 { LET_ELSE, POINTER_CAST_CONSTNESS } diff --git a/tests/ui/tuple_array_conversions.rs b/tests/ui/tuple_array_conversions.rs index 061c05e98d0..64aaa53be5c 100644 --- a/tests/ui/tuple_array_conversions.rs +++ b/tests/ui/tuple_array_conversions.rs @@ -1,5 +1,5 @@ //@aux-build:proc_macros.rs:proc-macro -#![allow(clippy::useless_vec, unused)] +#![allow(clippy::no_effect, clippy::useless_vec, unused)] #![warn(clippy::tuple_array_conversions)] #[macro_use] @@ -21,7 +21,9 @@ fn main() { let v2: Vec<[u32; 2]> = t1.iter().map(|&t| t.into()).collect(); let t3: Vec<(u32, u32)> = v2.iter().map(|&v| v.into()).collect(); let x = [1; 13]; - let x = (x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12]); + let x = ( + x[0], x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12], + ); let x = [x.0, x.1, x.2, x.3, x.4, x.5, x.6, x.7, x.8, x.9, x.10, x.11, x.12]; let x = (1, 2); let x = (x.0, x.1); @@ -29,6 +31,18 @@ fn main() { let x = [x[0], x[1]]; let x = vec![1, 2]; let x = (x[0], x[1]); + let x = [1; 3]; + let x = (x[0],); + let x = (1, 2, 3); + let x = [x.0]; + let x = (1, 2); + let y = (1, 2); + [x.0, y.0]; + [x.0, y.1]; + // FP + let x = [x.0, x.0]; + let x = (x[0], x[0]); + // How can this be fixed? external! { let t1: &[(u32, u32)] = &[(1, 2), (3, 4)]; let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect(); @@ -41,3 +55,21 @@ fn main() { let t2: Vec<(u32, u32)> = v1.iter().map(|&[a, b]| (a, b)).collect(); } } + +#[clippy::msrv = "1.70.0"] +fn msrv_too_low() { + let x = [1, 2]; + let x = (x[0], x[1]); + let x = [x.0, x.1]; + let x = &[1, 2]; + let x = (x[0], x[1]); +} + +#[clippy::msrv = "1.71.0"] +fn msrv_juust_right() { + let x = [1, 2]; + let x = (x[0], x[1]); + let x = [x.0, x.1]; + let x = &[1, 2]; + let x = (x[0], x[1]); +} diff --git a/tests/ui/tuple_array_conversions.stderr b/tests/ui/tuple_array_conversions.stderr index aba461e51f7..d9d59a611a0 100644 --- a/tests/ui/tuple_array_conversions.stderr +++ b/tests/ui/tuple_array_conversions.stderr @@ -4,7 +4,7 @@ error: it looks like you're trying to convert an array to a tuple LL | let x = (x[0], x[1]); | ^^^^^^^^^^^^ | - = help: use `.into()` instead + = help: use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed = note: `-D clippy::tuple-array-conversions` implied by `-D warnings` error: it looks like you're trying to convert a tuple to an array @@ -13,7 +13,7 @@ error: it looks like you're trying to convert a tuple to an array LL | let x = [x.0, x.1]; | ^^^^^^^^^^ | - = help: use `.into()` instead + = help: use `.into()` instead, or `<[T; N]>::from` if type annotations are needed error: it looks like you're trying to convert an array to a tuple --> $DIR/tuple_array_conversions.rs:13:13 @@ -21,7 +21,7 @@ error: it looks like you're trying to convert an array to a tuple LL | let x = (x[0], x[1]); | ^^^^^^^^^^^^ | - = help: use `.into()` instead + = help: use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed error: it looks like you're trying to convert a tuple to an array --> $DIR/tuple_array_conversions.rs:16:53 @@ -29,7 +29,7 @@ error: it looks like you're trying to convert a tuple to an array LL | let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect(); | ^^^^^^ | - = help: use `.into()` instead + = help: use `.into()` instead, or `<[T; N]>::from` if type annotations are needed error: it looks like you're trying to convert a tuple to an array --> $DIR/tuple_array_conversions.rs:17:38 @@ -37,7 +37,7 @@ error: it looks like you're trying to convert a tuple to an array LL | t1.iter().for_each(|&(a, b)| _ = [a, b]); | ^^^^^^ | - = help: use `.into()` instead + = help: use `.into()` instead, or `<[T; N]>::from` if type annotations are needed error: it looks like you're trying to convert an array to a tuple --> $DIR/tuple_array_conversions.rs:18:55 @@ -45,7 +45,7 @@ error: it looks like you're trying to convert an array to a tuple LL | let t2: Vec<(u32, u32)> = v1.iter().map(|&[a, b]| (a, b)).collect(); | ^^^^^^ | - = help: use `.into()` instead + = help: use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed error: it looks like you're trying to convert a tuple to an array --> $DIR/tuple_array_conversions.rs:19:38 @@ -53,7 +53,47 @@ error: it looks like you're trying to convert a tuple to an array LL | t1.iter().for_each(|&(a, b)| _ = [a, b]); | ^^^^^^ | - = help: use `.into()` instead + = help: use `.into()` instead, or `<[T; N]>::from` if type annotations are needed -error: aborting due to 7 previous errors +error: it looks like you're trying to convert a tuple to an array + --> $DIR/tuple_array_conversions.rs:43:13 + | +LL | let x = [x.0, x.0]; + | ^^^^^^^^^^ + | + = help: use `.into()` instead, or `<[T; N]>::from` if type annotations are needed + +error: it looks like you're trying to convert an array to a tuple + --> $DIR/tuple_array_conversions.rs:44:13 + | +LL | let x = (x[0], x[0]); + | ^^^^^^^^^^^^ + | + = help: use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed + +error: it looks like you're trying to convert an array to a tuple + --> $DIR/tuple_array_conversions.rs:71:13 + | +LL | let x = (x[0], x[1]); + | ^^^^^^^^^^^^ + | + = help: use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed + +error: it looks like you're trying to convert a tuple to an array + --> $DIR/tuple_array_conversions.rs:72:13 + | +LL | let x = [x.0, x.1]; + | ^^^^^^^^^^ + | + = help: use `.into()` instead, or `<[T; N]>::from` if type annotations are needed + +error: it looks like you're trying to convert an array to a tuple + --> $DIR/tuple_array_conversions.rs:74:13 + | +LL | let x = (x[0], x[1]); + | ^^^^^^^^^^^^ + | + = help: use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed + +error: aborting due to 12 previous errors