Skip to content

Commit 85ad8a6

Browse files
committed
Avoid false positives from extension traits
1 parent fbb7fd5 commit 85ad8a6

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

clippy_lints/src/collection_is_never_read.rs

+6
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,16 @@ fn has_no_read_access<'tcx>(cx: &LateContext<'tcx>, id: HirId, block: &'tcx Bloc
9898
// Method call on `id` in a statement ignores any return value, so it's not a read access:
9999
//
100100
// id.foo(...); // Not reading `id`.
101+
//
102+
// Only assuming this for "official" methods defined on the type. For methods defined in extension
103+
// traits (identified as local, based on the orphan rule), pessimistically assume that they might
104+
// have side effects, so consider them a read.
101105
if let Some(Node::Expr(parent)) = get_parent_node(cx.tcx, expr.hir_id)
102106
&& let ExprKind::MethodCall(_, receiver, _, _) = parent.kind
103107
&& path_to_local_id(receiver, id)
104108
&& let Some(Node::Stmt(..)) = get_parent_node(cx.tcx, parent.hir_id)
109+
&& let Some(method_def_id) = cx.typeck_results().type_dependent_def_id(parent.hir_id)
110+
&& !method_def_id.is_local()
105111
{
106112
return ControlFlow::Continue(());
107113
}

tests/ui/collection_is_never_read.rs

+20
Original file line numberDiff line numberDiff line change
@@ -133,3 +133,23 @@ fn not_read_if_return_value_not_used() {
133133
let x = vec![1, 2, 3]; // WARNING
134134
x.is_empty();
135135
}
136+
137+
fn extension_traits() {
138+
trait VecExt<T> {
139+
fn method_with_side_effect(&self);
140+
fn method_without_side_effect(&self);
141+
}
142+
143+
impl<T> VecExt<T> for Vec<T> {
144+
fn method_with_side_effect(&self) {
145+
println!("my length: {}", self.len());
146+
}
147+
fn method_without_side_effect(&self) {}
148+
}
149+
150+
let x = vec![1, 2, 3]; // Ok
151+
x.method_with_side_effect();
152+
153+
let y = vec![1, 2, 3]; // Ok (false negative)
154+
y.method_without_side_effect();
155+
}

0 commit comments

Comments
 (0)