Skip to content

Commit c7bf05c

Browse files
committed
Auto merge of rust-lang#11020 - Centri3:tuple_array_conversion, r=llogiq
New lint [`tuple_array_conversions`] Closes rust-lang#10748 PS, the implementation is a bit ugly 😅 ~~I will likely refactor soon enough :)~~ Done :D changelog: New lint [`tuple_array_conversions`]
2 parents 464edbe + 826edd7 commit c7bf05c

10 files changed

+399
-2
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -5263,6 +5263,7 @@ Released 2018-09-13
52635263
[`trivial_regex`]: https://rust-lang.github.io/rust-clippy/master/index.html#trivial_regex
52645264
[`trivially_copy_pass_by_ref`]: https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref
52655265
[`try_err`]: https://rust-lang.github.io/rust-clippy/master/index.html#try_err
5266+
[`tuple_array_conversions`]: https://rust-lang.github.io/rust-clippy/master/index.html#tuple_array_conversions
52665267
[`type_complexity`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_complexity
52675268
[`type_repetition_in_bounds`]: https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds
52685269
[`unchecked_duration_subtraction`]: https://rust-lang.github.io/rust-clippy/master/index.html#unchecked_duration_subtraction

book/src/lint_configuration.md

+1
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ The minimum rust version that the project supports
149149
* [`manual_rem_euclid`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_rem_euclid)
150150
* [`manual_retain`](https://rust-lang.github.io/rust-clippy/master/index.html#manual_retain)
151151
* [`type_repetition_in_bounds`](https://rust-lang.github.io/rust-clippy/master/index.html#type_repetition_in_bounds)
152+
* [`tuple_array_conversions`](https://rust-lang.github.io/rust-clippy/master/index.html#tuple_array_conversions)
152153

153154

154155
## `cognitive-complexity-threshold`

clippy_lints/src/declared_lints.rs

+1
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,7 @@ pub(crate) static LINTS: &[&crate::LintInfo] = &[
623623
crate::transmute::UNSOUND_COLLECTION_TRANSMUTE_INFO,
624624
crate::transmute::USELESS_TRANSMUTE_INFO,
625625
crate::transmute::WRONG_TRANSMUTE_INFO,
626+
crate::tuple_array_conversions::TUPLE_ARRAY_CONVERSIONS_INFO,
626627
crate::types::BORROWED_BOX_INFO,
627628
crate::types::BOX_COLLECTION_INFO,
628629
crate::types::LINKEDLIST_INFO,

clippy_lints/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@ mod to_digit_is_some;
311311
mod trailing_empty_array;
312312
mod trait_bounds;
313313
mod transmute;
314+
mod tuple_array_conversions;
314315
mod types;
315316
mod undocumented_unsafe_blocks;
316317
mod unicode;
@@ -1072,6 +1073,7 @@ pub fn register_plugins(store: &mut rustc_lint::LintStore, sess: &Session, conf:
10721073
});
10731074
store.register_late_pass(|_| Box::new(manual_range_patterns::ManualRangePatterns));
10741075
store.register_early_pass(|| Box::new(visibility::Visibility));
1076+
store.register_late_pass(move |_| Box::new(tuple_array_conversions::TupleArrayConversions { msrv: msrv() }));
10751077
// add lints here, do not remove this comment, it's used in `new_lint`
10761078
}
10771079

+235
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
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+
}

clippy_lints/src/upper_case_acronyms.rs

+1-1
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

+1-1
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

+1
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

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
//@aux-build:proc_macros.rs:proc-macro
2+
#![allow(clippy::no_effect, clippy::useless_vec, unused)]
3+
#![warn(clippy::tuple_array_conversions)]
4+
5+
#[macro_use]
6+
extern crate proc_macros;
7+
8+
fn main() {
9+
let x = [1, 2];
10+
let x = (x[0], x[1]);
11+
let x = [x.0, x.1];
12+
let x = &[1, 2];
13+
let x = (x[0], x[1]);
14+
15+
let t1: &[(u32, u32)] = &[(1, 2), (3, 4)];
16+
let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect();
17+
t1.iter().for_each(|&(a, b)| _ = [a, b]);
18+
let t2: Vec<(u32, u32)> = v1.iter().map(|&[a, b]| (a, b)).collect();
19+
t1.iter().for_each(|&(a, b)| _ = [a, b]);
20+
// Do not lint
21+
let v2: Vec<[u32; 2]> = t1.iter().map(|&t| t.into()).collect();
22+
let t3: Vec<(u32, u32)> = v2.iter().map(|&v| v.into()).collect();
23+
let x = [1; 13];
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+
);
27+
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];
28+
let x = (1, 2);
29+
let x = (x.0, x.1);
30+
let x = [1, 2];
31+
let x = [x[0], x[1]];
32+
let x = vec![1, 2];
33+
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+
let x = [x.0, x.0];
43+
let x = (x[0], x[0]);
44+
external! {
45+
let t1: &[(u32, u32)] = &[(1, 2), (3, 4)];
46+
let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect();
47+
let t2: Vec<(u32, u32)> = v1.iter().map(|&[a, b]| (a, b)).collect();
48+
}
49+
with_span! {
50+
span
51+
let t1: &[(u32, u32)] = &[(1, 2), (3, 4)];
52+
let v1: Vec<[u32; 2]> = t1.iter().map(|&(a, b)| [a, b]).collect();
53+
let t2: Vec<(u32, u32)> = v1.iter().map(|&[a, b]| (a, b)).collect();
54+
}
55+
}
56+
57+
#[clippy::msrv = "1.70.0"]
58+
fn msrv_too_low() {
59+
let x = [1, 2];
60+
let x = (x[0], x[1]);
61+
let x = [x.0, x.1];
62+
let x = &[1, 2];
63+
let x = (x[0], x[1]);
64+
}
65+
66+
#[clippy::msrv = "1.71.0"]
67+
fn msrv_juust_right() {
68+
let x = [1, 2];
69+
let x = (x[0], x[1]);
70+
let x = [x.0, x.1];
71+
let x = &[1, 2];
72+
let x = (x[0], x[1]);
73+
}

0 commit comments

Comments
 (0)