Skip to content

Commit 915bfa8

Browse files
authored
Merge pull request #22994 from riemenschneider/java/unread-local-unnamed-variables
Java: Exclude unnamed variables from `java/local-variable-is-never-read`
2 parents 9e8089e + f12b7a2 commit 915bfa8

4 files changed

Lines changed: 52 additions & 0 deletions

File tree

‎java/ql/src/Violations of Best Practice/Dead Code/UnreadLocal.ql‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,5 +32,7 @@ where
3232
f.getVariable().getVariable() = v and
3333
f.getExpr().getType().(RefType).hasQualifiedName("kotlin.ranges", ["IntRange", "LongRange"])
3434
) and
35+
// Unnamed variables (`_`) cannot be read.
36+
not v.getDeclExpr().isAnonymous() and
3537
not readImplicitly(v)
3638
select v, "Variable '" + v + "' is never read."
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
---
2+
category: minorAnalysis
3+
---
4+
* The `java/local-variable-is-never-read` query no longer reports unnamed variables (`_`), for example in `case Foo _ ->` patterns, `for (var _ : items)` loops, and `var _ = ...;` declarations.
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package test;
2+
3+
import java.util.List;
4+
5+
public class UnnamedVariables
6+
{
7+
sealed interface Shape permits Circle, Square {}
8+
record Circle(double radius) implements Shape {}
9+
record Square(double side) implements Shape {}
10+
record Pair(Object left, Object right) {}
11+
12+
// Not flagged: unnamed variables cannot be read
13+
static int side(Shape shape)
14+
{
15+
return switch (shape) {
16+
case Circle _ -> 0;
17+
case Square s -> (int) s.side();
18+
};
19+
}
20+
21+
static Object left(Object o)
22+
{
23+
if (o instanceof Pair(var left, _)) {
24+
return left;
25+
}
26+
return switch (o) {
27+
case Pair(Object left, Object _) -> left;
28+
default -> null;
29+
};
30+
}
31+
32+
static int count(List<String> items)
33+
{
34+
int n = 0;
35+
for (String _ : items) {
36+
n++;
37+
}
38+
return n;
39+
}
40+
41+
static void removeFirst(List<String> items)
42+
{
43+
var _ = items.remove(0);
44+
}
45+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
//semmle-extractor-options: --javac-args --release 22

0 commit comments

Comments
 (0)