|
| 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 | +import codeql_ql.ast.internal.Builtins |
| 14 | + |
| 15 | +class PrefixPredicate extends BuiltinPredicate { |
| 16 | + PrefixPredicate() { this = any(StringClass sc).getClassPredicate("prefix", 1) } |
| 17 | +} |
| 18 | + |
| 19 | +class SuffixPredicate extends BuiltinPredicate { |
| 20 | + SuffixPredicate() { this = any(StringClass sc).getClassPredicate("suffix", 1) } |
| 21 | +} |
| 22 | + |
| 23 | +class PrefixPredicateCall extends Call { |
| 24 | + PrefixPredicateCall() { this.getTarget() instanceof PrefixPredicate } |
| 25 | +} |
| 26 | + |
| 27 | +class SuffixPredicateCall extends Call { |
| 28 | + SuffixPredicateCall() { this.getTarget() instanceof SuffixPredicate } |
| 29 | +} |
| 30 | + |
| 31 | +class EqFormula extends ComparisonFormula { |
| 32 | + EqFormula() { this.getSymbol() = "=" } |
| 33 | +} |
| 34 | + |
| 35 | +bindingset[s] |
| 36 | +string escape(string s) { result = s.replaceAll("_", "\\\\_").replaceAll("%", "\\\\%") } |
| 37 | + |
| 38 | +pragma[inline] |
| 39 | +string getMessage(FixPredicateCall call, String literal) { |
| 40 | + call instanceof PrefixPredicateCall and |
| 41 | + result = ".matches(\"" + escape(literal.getValue()) + "%\")" |
| 42 | + or |
| 43 | + call instanceof SuffixPredicateCall and |
| 44 | + result = ".matches(\"%" + escape(literal.getValue()) + "\")" |
| 45 | +} |
| 46 | + |
| 47 | +class FixPredicateCall extends Call { |
| 48 | + FixPredicateCall() { this instanceof PrefixPredicateCall or this instanceof SuffixPredicateCall } |
| 49 | +} |
| 50 | + |
| 51 | +from EqFormula eq, FixPredicateCall call, String literal |
| 52 | +where eq.getAnOperand() = call and eq.getAnOperand() = literal |
| 53 | +select eq, "Use " + getMessage(call, literal) + " instead." |
0 commit comments