Repository navigation
Expand file tree
/
Copy pathLiteralsFirstInComparisonsRule.java
More file actions
66 lines (53 loc) · 2.41 KB
/
Copy pathLiteralsFirstInComparisonsRule.java
File metadata and controls
66 lines (53 loc) · 2.41 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
66
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.bestpractices;
import static net.sourceforge.pmd.util.CollectionUtil.listOf;
import static net.sourceforge.pmd.util.CollectionUtil.setOf;
import java.util.Set;
import org.checkerframework.checker.nullness.qual.Nullable;
import net.sourceforge.pmd.lang.java.ast.ASTExpression;
import net.sourceforge.pmd.lang.java.ast.ASTMethodCall;
import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
import net.sourceforge.pmd.lang.java.types.TypeTestUtil;
import net.sourceforge.pmd.reporting.RuleContext;
public class LiteralsFirstInComparisonsRule extends AbstractJavaRulechainRule {
private static final Set<String> STRING_COMPARISONS =
setOf("equalsIgnoreCase",
"compareTo",
"compareToIgnoreCase",
"contentEquals");
public LiteralsFirstInComparisonsRule() {
super(ASTMethodCall.class);
}
@Override
public Object visit(ASTMethodCall call, Object data) {
RuleContext ctx = (RuleContext) data;
if ("equals".equals(call.getMethodName())
&& call.getArguments().size() == 1
&& isEqualsObjectAndNotAnOverload(call)) {
checkArgs(ctx, call);
} else if (STRING_COMPARISONS.contains(call.getMethodName())
&& call.getArguments().size() == 1
&& TypeTestUtil.isDeclaredInClass(String.class, call.getMethodType())) {
checkArgs(ctx, call);
}
return null;
}
private boolean isEqualsObjectAndNotAnOverload(ASTMethodCall call) {
return call.getOverloadSelectionInfo().isFailed() // failed selection is considered probably equals(Object)
|| call.getMethodType().getFormalParameters().equals(listOf(call.getTypeSystem().OBJECT));
}
private boolean isConstantString(@Nullable ASTExpression node) {
return node instanceof ASTStringLiteral
|| node != null && node.getConstValue() instanceof String;
}
private void checkArgs(RuleContext ctx, ASTMethodCall call) {
ASTExpression arg = call.getArguments().get(0);
@Nullable ASTExpression qualifier = call.getQualifier();
if (qualifier != null && !isConstantString(qualifier) && isConstantString(arg)) {
ctx.addViolation(call);
}
}
}