forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInefficientKeySetIterator.ql
More file actions
65 lines (58 loc) · 1.8 KB
/
InefficientKeySetIterator.ql
File metadata and controls
65 lines (58 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* @name Inefficient use of key set iterator
* @description Iterating through the values of a map using the key set is inefficient.
* @kind problem
* @problem.severity recommendation
* @precision high
* @id java/inefficient-key-set-iterator
* @tags efficiency
* maintainability
*/
import java
/** A local variable that is initialized using a key-set iterator. */
class KeySetIterator extends LocalVariableDecl {
KeySetIterator() {
exists(LocalVariableDeclExpr lvde, MethodAccess init |
lvde.getVariable() = this and
lvde.getInit() = init and
init.getMethod().hasName("iterator") and
init.getQualifier().(MethodAccess).getMethod().hasName("keySet")
)
}
LocalVariableDecl getBase() {
exists(LocalVariableDeclExpr lvde, MethodAccess init |
lvde.getVariable() = this and
lvde.getInit() = init and
init.getQualifier().(MethodAccess).getQualifier().(VarAccess).getVariable() = result
)
}
}
predicate isKeyNext(Expr e, KeySetIterator it) {
exists(MethodAccess ma | ma = e |
ma.getMethod().hasName("next") and
ma.getQualifier().(VarAccess).getVariable() = it
)
or
isKeyNext(e.(CastExpr).getExpr(), it)
}
class Key extends LocalVariableDecl {
Key() {
exists(LocalVariableDeclExpr lvde, KeySetIterator it |
lvde.getVariable() = this and
isKeyNext(lvde.getInit(), it)
)
}
KeySetIterator getBase() {
exists(LocalVariableDeclExpr lvde |
lvde.getVariable() = this and
isKeyNext(lvde.getInit(), result)
)
}
}
from MethodAccess ma, Method get
where
ma.getMethod() = get and
get.hasName("get") and
ma.getAnArgument().(VarAccess).getVariable().(Key).getBase().getBase() =
ma.getQualifier().(VarAccess).getVariable()
select ma, "Inefficient use of key set iterator instead of entry set iterator."