Skip to content

Commit 9fd7478

Browse files
committed
unified: Add unused variable query
1 parent f69f365 commit 9fd7478

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* @name Unused variable
3+
* @description Unused variables may be an indication that the code is incomplete or has a typo.
4+
* @kind problem
5+
* @problem.severity recommendation
6+
* @id unified/unused-variable
7+
* @precision high
8+
*/
9+
10+
private import unified
11+
12+
private predicate isUnusedLocal(LocalName local) {
13+
local.getABinding().fromSource() and // ignore unused implicit locals, and ignore locals in built-ins
14+
not ignoreDeclaration(local.getABinding().getDeclaration()) and // ignore fields, method, etc
15+
not local.getName().regexpMatch("_.*") and
16+
not exists(LocalNameAccess access |
17+
access = local.getAnAccess() and
18+
not access instanceof NameBinding
19+
) and
20+
not local = any(UnqualifiedMemberAccess access).getImplicitQualifierVariable()
21+
}
22+
23+
private predicate ignoreDeclaration(AstNode n) {
24+
// ignore fields and methods etc
25+
n = any(ClassLikeDeclaration cls).getAMember()
26+
or
27+
// ignore top-level statements, which are often exported
28+
n = any(TopLevel t).getBody().getAStmt()
29+
or
30+
// Parameters are often needed to satisfy an interface
31+
n instanceof Parameter
32+
}
33+
34+
string getKind(LocalName local) {
35+
if local instanceof LocalVariable then result = "local variable" else result = "declaration"
36+
}
37+
38+
from LocalName local
39+
where isUnusedLocal(local)
40+
select local, "Unused " + getKind(local) + " '" + local.getName() + "'"

0 commit comments

Comments
 (0)