Skip to content

Commit f86a827

Browse files
authored
QL: QL: Add query to find uses of .prefix or .suffix when comparing against literals.
1 parent fbb58f1 commit f86a827

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* @name Prefix or suffix predicate calls when comparing with literal
3+
* @description Using 'myString.prefix(n) = "..."' instead of 'myString.matches("...%")'
4+
* @kind problem
5+
* @problem.severity error
6+
* @id ql/prefix-or-suffix-equality-check
7+
* @tags performance
8+
* @precision high
9+
*/
10+
11+
import ql
12+
import codeql_ql.ast.internal.Predicate
13+
14+
class StringClass extends PrimitiveType {
15+
StringClass() { this.getName() = "string" }
16+
}
17+
18+
class PrefixPredicate extends BuiltinPredicate {
19+
PrefixPredicate() { this = any(StringClass sc).getClassPredicate("prefix", 1) }
20+
}
21+
22+
class SuffixPredicate extends BuiltinPredicate {
23+
SuffixPredicate() { this = any(StringClass sc).getClassPredicate("suffix", 1) }
24+
}
25+
26+
class PrefixPredicateCall extends Call {
27+
PrefixPredicateCall() { this.getTarget() instanceof PrefixPredicate }
28+
}
29+
30+
class SuffixPredicateCall extends Call {
31+
SuffixPredicateCall() { this.getTarget() instanceof SuffixPredicate }
32+
}
33+
34+
class EqFormula extends ComparisonFormula {
35+
EqFormula() { this.getSymbol() = "=" }
36+
}
37+
38+
pragma[inline]
39+
string getMessage(Call call, String literal) {
40+
call instanceof PrefixPredicateCall and result = ".matches(\"" + literal.getValue() + "%\")"
41+
or
42+
call instanceof SuffixPredicateCall and result = ".matches(\"%" + literal.getValue() + "\")"
43+
}
44+
45+
from EqFormula eq, PrefixPredicateCall call, String literal
46+
where eq.getAnOperand() = call and eq.getAnOperand() = literal
47+
select eq,
48+
"Use " + getMessage(call, literal) + " instead (but be sure to escape " + literal.getValue() +
49+
")."

0 commit comments

Comments
 (0)