Skip to content

Commit e34e49f

Browse files
committed
useless_conversion: don't lint if ty param has multiple bounds
1 parent 3de0f19 commit e34e49f

File tree

4 files changed

+127
-26
lines changed

4 files changed

+127
-26
lines changed

clippy_lints/src/useless_conversion.rs

Lines changed: 81 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,19 @@
1+
use std::ops::ControlFlow;
2+
13
use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
24
use clippy_utils::source::{snippet, snippet_with_applicability, snippet_with_context};
35
use clippy_utils::sugg::Sugg;
46
use clippy_utils::ty::{is_copy, is_type_diagnostic_item, same_type_and_consts};
5-
use clippy_utils::{get_parent_expr, is_trait_method, is_ty_alias, match_def_path, path_to_local, paths};
7+
use clippy_utils::{
8+
get_parent_expr, is_diag_trait_item, is_trait_method, is_ty_alias, match_def_path, path_to_local, paths,
9+
};
610
use if_chain::if_chain;
711
use rustc_errors::Applicability;
812
use rustc_hir::def::DefKind;
913
use rustc_hir::def_id::DefId;
1014
use rustc_hir::{BindingAnnotation, Expr, ExprKind, HirId, MatchSource, Node, PatKind};
1115
use rustc_lint::{LateContext, LateLintPass};
12-
use rustc_middle::ty;
16+
use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor};
1317
use rustc_session::{declare_tool_lint, impl_lint_pass};
1418
use rustc_span::{sym, Span};
1519

@@ -61,22 +65,83 @@ impl MethodOrFunction {
6165
}
6266
}
6367

64-
/// Returns the span of the `IntoIterator` trait bound in the function pointed to by `fn_did`
65-
fn into_iter_bound(cx: &LateContext<'_>, fn_did: DefId, into_iter_did: DefId, param_index: u32) -> Option<Span> {
66-
cx.tcx
67-
.predicates_of(fn_did)
68-
.predicates
69-
.iter()
70-
.find_map(|&(ref pred, span)| {
71-
if let ty::ClauseKind::Trait(tr) = pred.kind().skip_binder()
72-
&& tr.def_id() == into_iter_did
73-
&& tr.self_ty().is_param(param_index)
68+
/// Returns the span of the `IntoIterator` trait bound in the function pointed to by `fn_did`,
69+
/// iff the `IntoIterator` bound is the only bound on the type parameter.
70+
///
71+
/// This last part is important because it might be that the type the user is calling `.into_iter()`
72+
/// on might not satisfy those other bounds and would result in compile errors:
73+
/// ```ignore
74+
/// pub fn foo<I>(i: I)
75+
/// where I: IntoIterator<Item=i32> + ExactSizeIterator
76+
/// ^^^^^^^^^^^^^^^^^ this extra bound stops us from suggesting to remove `.into_iter()` ...
77+
/// {
78+
/// assert_eq!(i.len(), 3);
79+
/// }
80+
///
81+
/// pub fn bar() {
82+
/// foo([1, 2, 3].into_iter());
83+
/// ^^^^^^^^^^^^ ... here, because `[i32; 3]` is not `ExactSizeIterator`
84+
/// }
85+
/// ```
86+
fn exclusive_into_iter_bound(
87+
cx: &LateContext<'_>,
88+
fn_did: DefId,
89+
into_iter_did: DefId,
90+
param_index: u32,
91+
) -> Option<Span> {
92+
#[derive(Clone)]
93+
struct ExplicitlyUsedTyParam<'a, 'tcx> {
94+
cx: &'a LateContext<'tcx>,
95+
param_index: u32,
96+
}
97+
98+
impl<'a, 'tcx> TypeVisitor<TyCtxt<'tcx>> for ExplicitlyUsedTyParam<'a, 'tcx> {
99+
type BreakTy = ();
100+
fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
101+
// Ignore implicit `T: Sized` bound
102+
if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr)) = p.kind().skip_binder()
103+
&& let Some(sized_trait_did) = self.cx.tcx.lang_items().sized_trait()
104+
&& sized_trait_did == tr.def_id()
74105
{
75-
Some(span)
106+
return ControlFlow::Continue(());
107+
}
108+
109+
// Ignore `<T as IntoIterator>::Item` projection, this use of the ty param specifically is fine
110+
// because it's what we're already looking for
111+
if let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) = p.kind().skip_binder()
112+
&& is_diag_trait_item(self.cx,proj.projection_ty.def_id, sym::IntoIterator)
113+
{
114+
return ControlFlow::Continue(());
115+
}
116+
117+
p.super_visit_with(self)
118+
}
119+
120+
fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
121+
if t.is_param(self.param_index) {
122+
ControlFlow::Break(())
76123
} else {
77-
None
124+
ControlFlow::Continue(())
78125
}
79-
})
126+
}
127+
}
128+
129+
let mut into_iter_span = None;
130+
131+
for (pred, span) in cx.tcx.explicit_predicates_of(fn_did).predicates {
132+
if let ty::ClauseKind::Trait(tr) = pred.kind().skip_binder()
133+
&& tr.def_id() == into_iter_did
134+
&& tr.self_ty().is_param(param_index)
135+
{
136+
into_iter_span = Some(*span);
137+
} else if pred.visit_with(&mut ExplicitlyUsedTyParam { cx, param_index }).is_break() {
138+
// Found another reference of the type parameter; conservatively assume
139+
// that we can't remove the bound.
140+
return None;
141+
}
142+
}
143+
144+
into_iter_span
80145
}
81146

82147
/// Extracts the receiver of a `.into_iter()` method call.
@@ -175,7 +240,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion {
175240
&& let Some(arg_pos) = args.iter().position(|x| x.hir_id == e.hir_id)
176241
&& let Some(&into_iter_param) = sig.inputs().get(kind.param_pos(arg_pos))
177242
&& let ty::Param(param) = into_iter_param.kind()
178-
&& let Some(span) = into_iter_bound(cx, parent_fn_did, into_iter_did, param.index)
243+
&& let Some(span) = exclusive_into_iter_bound(cx, parent_fn_did, into_iter_did, param.index)
179244
&& self.expn_depth == 0
180245
{
181246
// Get the "innermost" `.into_iter()` call, e.g. given this expression:

tests/ui/useless_conversion.fixed

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ fn main() {
151151
let _ = s3;
152152
let s4: Foo<'a'> = Foo;
153153
let _ = vec![s4, s4, s4].into_iter();
154+
155+
issue11300::bar();
154156
}
155157

156158
#[allow(dead_code)]
@@ -196,6 +198,22 @@ fn explicit_into_iter_fn_arg() {
196198
b(macro_generated!());
197199
}
198200

201+
mod issue11300 {
202+
pub fn foo<I>(i: I)
203+
where
204+
I: IntoIterator<Item = i32> + ExactSizeIterator,
205+
{
206+
assert_eq!(i.len(), 3);
207+
}
208+
209+
pub fn bar() {
210+
// This should not trigger the lint:
211+
// `[i32, 3]` does not satisfy the `ExactSizeIterator` bound, so the into_iter call cannot be
212+
// removed and is not useless.
213+
foo([1, 2, 3].into_iter());
214+
}
215+
}
216+
199217
#[derive(Copy, Clone)]
200218
struct Foo<const C: char>;
201219

tests/ui/useless_conversion.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ fn main() {
151151
let _ = Foo::<'a'>::from(s3);
152152
let s4: Foo<'a'> = Foo;
153153
let _ = vec![s4, s4, s4].into_iter().into_iter();
154+
155+
issue11300::bar();
154156
}
155157

156158
#[allow(dead_code)]
@@ -196,6 +198,22 @@ fn explicit_into_iter_fn_arg() {
196198
b(macro_generated!());
197199
}
198200

201+
mod issue11300 {
202+
pub fn foo<I>(i: I)
203+
where
204+
I: IntoIterator<Item = i32> + ExactSizeIterator,
205+
{
206+
assert_eq!(i.len(), 3);
207+
}
208+
209+
pub fn bar() {
210+
// This should not trigger the lint:
211+
// `[i32, 3]` does not satisfy the `ExactSizeIterator` bound, so the into_iter call cannot be
212+
// removed and is not useless.
213+
foo([1, 2, 3].into_iter());
214+
}
215+
}
216+
199217
#[derive(Copy, Clone)]
200218
struct Foo<const C: char>;
201219

tests/ui/useless_conversion.stderr

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -119,61 +119,61 @@ LL | let _ = vec![s4, s4, s4].into_iter().into_iter();
119119
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing `.into_iter()`: `vec![s4, s4, s4].into_iter()`
120120

121121
error: explicit call to `.into_iter()` in function argument accepting `IntoIterator`
122-
--> $DIR/useless_conversion.rs:183:7
122+
--> $DIR/useless_conversion.rs:185:7
123123
|
124124
LL | b(vec![1, 2].into_iter());
125125
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider removing the `.into_iter()`: `vec![1, 2]`
126126
|
127127
note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()`
128-
--> $DIR/useless_conversion.rs:173:13
128+
--> $DIR/useless_conversion.rs:175:13
129129
|
130130
LL | fn b<T: IntoIterator<Item = i32>>(_: T) {}
131131
| ^^^^^^^^^^^^^^^^^^^^^^^^
132132

133133
error: explicit call to `.into_iter()` in function argument accepting `IntoIterator`
134-
--> $DIR/useless_conversion.rs:184:7
134+
--> $DIR/useless_conversion.rs:186:7
135135
|
136136
LL | c(vec![1, 2].into_iter());
137137
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider removing the `.into_iter()`: `vec![1, 2]`
138138
|
139139
note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()`
140-
--> $DIR/useless_conversion.rs:174:18
140+
--> $DIR/useless_conversion.rs:176:18
141141
|
142142
LL | fn c(_: impl IntoIterator<Item = i32>) {}
143143
| ^^^^^^^^^^^^^^^^^^^^^^^^
144144

145145
error: explicit call to `.into_iter()` in function argument accepting `IntoIterator`
146-
--> $DIR/useless_conversion.rs:185:7
146+
--> $DIR/useless_conversion.rs:187:7
147147
|
148148
LL | d(vec![1, 2].into_iter());
149149
| ^^^^^^^^^^^^^^^^^^^^^^ help: consider removing the `.into_iter()`: `vec![1, 2]`
150150
|
151151
note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()`
152-
--> $DIR/useless_conversion.rs:177:12
152+
--> $DIR/useless_conversion.rs:179:12
153153
|
154154
LL | T: IntoIterator<Item = i32>,
155155
| ^^^^^^^^^^^^^^^^^^^^^^^^
156156

157157
error: explicit call to `.into_iter()` in function argument accepting `IntoIterator`
158-
--> $DIR/useless_conversion.rs:188:7
158+
--> $DIR/useless_conversion.rs:190:7
159159
|
160160
LL | b(vec![1, 2].into_iter().into_iter());
161161
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing the `.into_iter()`s: `vec![1, 2]`
162162
|
163163
note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()`
164-
--> $DIR/useless_conversion.rs:173:13
164+
--> $DIR/useless_conversion.rs:175:13
165165
|
166166
LL | fn b<T: IntoIterator<Item = i32>>(_: T) {}
167167
| ^^^^^^^^^^^^^^^^^^^^^^^^
168168

169169
error: explicit call to `.into_iter()` in function argument accepting `IntoIterator`
170-
--> $DIR/useless_conversion.rs:189:7
170+
--> $DIR/useless_conversion.rs:191:7
171171
|
172172
LL | b(vec![1, 2].into_iter().into_iter().into_iter());
173173
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider removing the `.into_iter()`s: `vec![1, 2]`
174174
|
175175
note: this parameter accepts any `IntoIterator`, so you don't need to call `.into_iter()`
176-
--> $DIR/useless_conversion.rs:173:13
176+
--> $DIR/useless_conversion.rs:175:13
177177
|
178178
LL | fn b<T: IntoIterator<Item = i32>>(_: T) {}
179179
| ^^^^^^^^^^^^^^^^^^^^^^^^

0 commit comments

Comments
 (0)