Skip to content

Commit ee732e9

Browse files
committed
Add StringBuilder-append-String-repeat.ql
1 parent 70e7567 commit ee732e9

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Finds code which first repeats a String using `String#repeat` and then appends it to
3+
* a `StringBuilder` or `StringBuffer`.
4+
*
5+
* Since Java 21 `StringBuilder` and `StringBuffer` have new `repeat` methods, which can
6+
* be used instead and likely provide better performance.
7+
*
8+
* @id TODO
9+
* @kind problem
10+
*/
11+
12+
import java
13+
14+
from MethodAccess stringRepeatCall, Method stringRepeatMethod, MethodAccess stringBuilderAppendCall
15+
where
16+
stringRepeatCall.getMethod() = stringRepeatMethod and
17+
stringRepeatMethod.getDeclaringType() instanceof TypeString and
18+
stringRepeatMethod.hasStringSignature("repeat(int)") and
19+
stringBuilderAppendCall.getReceiverType() instanceof StringBuildingType and
20+
stringBuilderAppendCall.getMethod().hasName("append") and
21+
// For now only cover `repeat` result directly being used as argument for `append`; that already has
22+
// a lot of findings. Could instead use local dataflow, but this causes false positives then if `repeat`
23+
// result is used multiple times and cannot be replaced with `StringBuilder#repeat`.
24+
stringRepeatCall = stringBuilderAppendCall.getAnArgument()
25+
select stringRepeatCall,
26+
"Can instead use " + stringBuilderAppendCall.getReceiverType().getName() + "#repeat"

0 commit comments

Comments
 (0)