Skip to content

Commit b1acbde

Browse files
committed
Add msrv check and make test pass
1 parent bfcc8ba commit b1acbde

File tree

7 files changed

+188
-64
lines changed

7 files changed

+188
-64
lines changed

clippy_lints/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1073,7 +1073,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10731073
});
10741074
store.register_late_pass(|_| Box::new(manual_range_patterns::ManualRangePatterns));
10751075
store.register_early_pass(|| Box::new(visibility::Visibility));
1076-
store.register_late_pass(|_| Box::new(tuple_array_conversions::TupleArrayConversions));
1076+
store.register_late_pass(move |_| Box::new(tuple_array_conversions::TupleArrayConversions { msrv: msrv() }));
10771077
// add lints here, do not remove this comment, it's used in `new_lint`
10781078
}
10791079

clippy_lints/src/tuple_array_conversions.rs

Lines changed: 102 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
1-
use clippy_utils::{diagnostics::span_lint_and_help, is_from_proc_macro, path_to_local};
2-
use rustc_hir::*;
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 itertools::Itertools;
8+
use rustc_hir::{Expr, ExprKind, Node, Pat};
39
use rustc_lint::{LateContext, LateLintPass, LintContext};
410
use rustc_middle::{lint::in_external_macro, ty};
5-
use rustc_session::{declare_lint_pass, declare_tool_lint};
11+
use rustc_session::{declare_tool_lint, impl_lint_pass};
12+
use std::iter::once;
613

714
declare_clippy_lint! {
815
/// ### What it does
16+
/// Checks for tuple<=>array conversions that are not done with `.into()`.
917
///
1018
/// ### Why is this bad?
19+
/// It's overly complex. `.into()` works for tuples<=>arrays with less than 13 elements and
20+
/// conveys the intent a lot better, while also leaving less room for bugs!
1121
///
1222
/// ### Example
1323
/// ```rust,ignore
@@ -22,16 +32,23 @@ declare_clippy_lint! {
2232
#[clippy::version = "1.72.0"]
2333
pub TUPLE_ARRAY_CONVERSIONS,
2434
complexity,
25-
"default lint description"
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,
2642
}
27-
declare_lint_pass!(TupleArrayConversions => [TUPLE_ARRAY_CONVERSIONS]);
2843

2944
impl LateLintPass<'_> for TupleArrayConversions {
3045
fn check_expr<'tcx>(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) {
31-
if !in_external_macro(cx.sess(), expr.span) {
46+
if !in_external_macro(cx.sess(), expr.span) && self.msrv.meets(msrvs::TUPLE_ARRAY_CONVERSIONS) {
3247
_ = check_array(cx, expr) || check_tuple(cx, expr);
3348
}
3449
}
50+
51+
extract_msrv_attr!(LateContext);
3552
}
3653

3754
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 {
4259
return false;
4360
}
4461

45-
if let Some(locals) = path_to_locals(cx, elements)
46-
&& locals.iter().all(|local| {
47-
matches!(
48-
local,
49-
Node::Pat(pat) if matches!(
50-
cx.typeck_results().pat_ty(backtrack_pat(cx, pat)).peel_refs().kind(),
51-
ty::Tuple(_),
52-
),
53-
)
62+
if let Some(locals) = path_to_locals(cx, &elements.iter().collect_vec())
63+
&& let [first, rest @ ..] = &*locals
64+
&& let Node::Pat(first_pat) = first
65+
&& let first_id = parent_pat(cx, first_pat).hir_id
66+
&& rest.iter().chain(once(first)).all(|local| {
67+
if let Node::Pat(pat) = local
68+
&& let parent = parent_pat(cx, pat)
69+
&& parent.hir_id == first_id
70+
{
71+
return matches!(
72+
cx.typeck_results().pat_ty(parent).peel_refs().kind(),
73+
ty::Tuple(len) if len.len() == elements.len()
74+
);
75+
}
76+
77+
false
5478
})
5579
{
5680
return emit_lint(cx, expr, ToType::Array);
@@ -66,15 +90,22 @@ fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
6690
None
6791
})
6892
.collect::<Option<Vec<&Expr<'_>>>>()
69-
&& let Some(locals) = path_to_locals(cx, elements)
70-
&& locals.iter().all(|local| {
71-
matches!(
72-
local,
73-
Node::Pat(pat) if matches!(
74-
cx.typeck_results().pat_ty(backtrack_pat(cx, pat)).peel_refs().kind(),
75-
ty::Tuple(_),
76-
),
77-
)
93+
&& let Some(locals) = path_to_locals(cx, &elements)
94+
&& let [first, rest @ ..] = &*locals
95+
&& let Node::Pat(first_pat) = first
96+
&& let first_id = parent_pat(cx, first_pat).hir_id
97+
&& rest.iter().chain(once(first)).all(|local| {
98+
if let Node::Pat(pat) = local
99+
&& let parent = parent_pat(cx, pat)
100+
&& parent.hir_id == first_id
101+
{
102+
return matches!(
103+
cx.typeck_results().pat_ty(parent).peel_refs().kind(),
104+
ty::Tuple(len) if len.len() == elements.len()
105+
);
106+
}
107+
108+
false
78109
})
79110
{
80111
return emit_lint(cx, expr, ToType::Array);
@@ -83,22 +114,31 @@ fn check_array<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
83114
false
84115
}
85116

117+
#[expect(clippy::cast_possible_truncation)]
86118
fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
87119
let ExprKind::Tup(elements) = expr.kind else {
88120
return false;
89121
};
90122
if !(1..=12).contains(&elements.len()) {
91123
return false;
92124
};
93-
if let Some(locals) = path_to_locals(cx, elements)
94-
&& locals.iter().all(|local| {
95-
matches!(
96-
local,
97-
Node::Pat(pat) if matches!(
98-
cx.typeck_results().pat_ty(backtrack_pat(cx, pat)).peel_refs().kind(),
99-
ty::Array(_, _),
100-
),
101-
)
125+
126+
if let Some(locals) = path_to_locals(cx, &elements.iter().collect_vec())
127+
&& let [first, rest @ ..] = &*locals
128+
&& let Node::Pat(first_pat) = first
129+
&& let first_id = parent_pat(cx, first_pat).hir_id
130+
&& rest.iter().chain(once(first)).all(|local| {
131+
if let Node::Pat(pat) = local
132+
&& let parent = parent_pat(cx, pat)
133+
&& parent.hir_id == first_id
134+
{
135+
return matches!(
136+
cx.typeck_results().pat_ty(parent).peel_refs().kind(),
137+
ty::Array(_, len) if len.eval_target_usize(cx.tcx, cx.param_env) as usize == elements.len()
138+
);
139+
}
140+
141+
false
102142
})
103143
{
104144
return emit_lint(cx, expr, ToType::Tuple);
@@ -114,15 +154,22 @@ fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
114154
None
115155
})
116156
.collect::<Option<Vec<&Expr<'_>>>>()
117-
&& let Some(locals) = path_to_locals(cx, elements.clone())
118-
&& locals.iter().all(|local| {
119-
matches!(
120-
local,
121-
Node::Pat(pat) if cx.typeck_results()
122-
.pat_ty(backtrack_pat(cx, pat))
123-
.peel_refs()
124-
.is_array()
125-
)
157+
&& let Some(locals) = path_to_locals(cx, &elements)
158+
&& let [first, rest @ ..] = &*locals
159+
&& let Node::Pat(first_pat) = first
160+
&& let first_id = parent_pat(cx, first_pat).hir_id
161+
&& rest.iter().chain(once(first)).all(|local| {
162+
if let Node::Pat(pat) = local
163+
&& let parent = parent_pat(cx, pat)
164+
&& parent.hir_id == first_id
165+
{
166+
return matches!(
167+
cx.typeck_results().pat_ty(parent).peel_refs().kind(),
168+
ty::Array(_, len) if len.eval_target_usize(cx.tcx, cx.param_env) as usize == elements.len()
169+
);
170+
}
171+
172+
false
126173
})
127174
{
128175
return emit_lint(cx, expr, ToType::Tuple);
@@ -132,7 +179,7 @@ fn check_tuple<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool {
132179
}
133180

134181
/// Walks up the `Pat` until it's reached the final containing `Pat`.
135-
fn backtrack_pat<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Pat<'tcx>) -> &'tcx Pat<'tcx> {
182+
fn parent_pat<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Pat<'tcx>) -> &'tcx Pat<'tcx> {
136183
let mut end = start;
137184
for (_, node) in cx.tcx.hir().parent_iter(start.hir_id) {
138185
if let Node::Pat(pat) = node {
@@ -144,12 +191,9 @@ fn backtrack_pat<'tcx>(cx: &LateContext<'tcx>, start: &'tcx Pat<'tcx>) -> &'tcx
144191
end
145192
}
146193

147-
fn path_to_locals<'tcx>(
148-
cx: &LateContext<'tcx>,
149-
exprs: impl IntoIterator<Item = &'tcx Expr<'tcx>>,
150-
) -> Option<Vec<Node<'tcx>>> {
194+
fn path_to_locals<'tcx>(cx: &LateContext<'tcx>, exprs: &[&'tcx Expr<'tcx>]) -> Option<Vec<Node<'tcx>>> {
151195
exprs
152-
.into_iter()
196+
.iter()
153197
.map(|element| path_to_local(element).and_then(|local| cx.tcx.hir().find(local)))
154198
.collect()
155199
}
@@ -161,12 +205,19 @@ enum ToType {
161205
}
162206

163207
impl ToType {
164-
fn help(self) -> &'static str {
208+
fn msg(self) -> &'static str {
165209
match self {
166210
ToType::Array => "it looks like you're trying to convert a tuple to an array",
167211
ToType::Tuple => "it looks like you're trying to convert an array to a tuple",
168212
}
169213
}
214+
215+
fn help(self) -> &'static str {
216+
match self {
217+
ToType::Array => "use `.into()` instead, or `<[T; N]>::from` if type annotations are needed",
218+
ToType::Tuple => "use `.into()` instead, or `<(T0, T1, ..., Tn)>::from` if type annotations are needed",
219+
}
220+
}
170221
}
171222

172223
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
175226
cx,
176227
TUPLE_ARRAY_CONVERSIONS,
177228
expr.span,
178-
to_type.help(),
229+
to_type.msg(),
179230
None,
180-
"use `.into()` instead",
231+
to_type.help(),
181232
);
182233

183234
return true;

clippy_lints/src/upper_case_acronyms.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ fn correct_ident(ident: &str) -> String {
6565

6666
let mut ident = fragments.clone().next().unwrap();
6767
for (ref prev, ref curr) in fragments.tuple_windows() {
68-
if [prev, curr]
68+
if <[&String; 2]>::from((prev, curr))
6969
.iter()
7070
.all(|s| s.len() == 1 && s.chars().next().unwrap().is_ascii_uppercase())
7171
{

clippy_lints/src/utils/conf.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ define_Conf! {
294294
///
295295
/// Suppress lints whenever the suggested change would cause breakage for other crates.
296296
(avoid_breaking_exported_api: bool = true),
297-
/// 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.
297+
/// 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.
298298
///
299299
/// The minimum rust version that the project supports
300300
(msrv: Option<String> = None),

clippy_utils/src/msrvs.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ macro_rules! msrv_aliases {
1919

2020
// names may refer to stabilized feature flags or library items
2121
msrv_aliases! {
22+
1,71,0 { TUPLE_ARRAY_CONVERSIONS }
2223
1,70,0 { OPTION_IS_SOME_AND }
2324
1,68,0 { PATH_MAIN_SEPARATOR_STR }
2425
1,65,0 { LET_ELSE, POINTER_CAST_CONSTNESS }

tests/ui/tuple_array_conversions.rs

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
//@aux-build:proc_macros.rs:proc-macro
2-
#![allow(clippy::useless_vec, unused)]
2+
#![allow(clippy::no_effect, clippy::useless_vec, unused)]
33
#![warn(clippy::tuple_array_conversions)]
44

55
#[macro_use]
@@ -21,14 +21,28 @@ fn main() {
2121
let v2: Vec<[u32; 2]> = t1.iter().map(|&t| t.into()).collect();
2222
let t3: Vec<(u32, u32)> = v2.iter().map(|&v| v.into()).collect();
2323
let x = [1; 13];
24-
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]);
24+
let x = (
25+
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],
26+
);
2527
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];
2628
let x = (1, 2);
2729
let x = (x.0, x.1);
2830
let x = [1, 2];
2931
let x = [x[0], x[1]];
3032
let x = vec![1, 2];
3133
let x = (x[0], x[1]);
34+
let x = [1; 3];
35+
let x = (x[0],);
36+
let x = (1, 2, 3);
37+
let x = [x.0];
38+
let x = (1, 2);
39+
let y = (1, 2);
40+
[x.0, y.0];
41+
[x.0, y.1];
42+
// FP
43+
let x = [x.0, x.0];
44+
let x = (x[0], x[0]);
45+
// How can this be fixed?
3246
external! {
3347
let t1: &[(u32, u32)] = &[(1, 2), (3, 4)];
3448
let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect();
@@ -41,3 +55,21 @@ fn main() {
4155
let t2: Vec<(u32, u32)> = v1.iter().map(|&[a, b]| (a, b)).collect();
4256
}
4357
}
58+
59+
#[clippy::msrv = "1.70.0"]
60+
fn msrv_too_low() {
61+
let x = [1, 2];
62+
let x = (x[0], x[1]);
63+
let x = [x.0, x.1];
64+
let x = &[1, 2];
65+
let x = (x[0], x[1]);
66+
}
67+
68+
#[clippy::msrv = "1.71.0"]
69+
fn msrv_juust_right() {
70+
let x = [1, 2];
71+
let x = (x[0], x[1]);
72+
let x = [x.0, x.1];
73+
let x = &[1, 2];
74+
let x = (x[0], x[1]);
75+
}

0 commit comments

Comments
 (0)