Repository navigation
Expand file tree
/
Copy pathAddEmptyStringRule.java
More file actions
50 lines (43 loc) · 1.87 KB
/
Copy pathAddEmptyStringRule.java
File metadata and controls
50 lines (43 loc) · 1.87 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
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.rule.performance;
import net.sourceforge.pmd.lang.java.ast.ASTAnnotation;
import net.sourceforge.pmd.lang.java.ast.ASTAssignableExpr.ASTNamedReferenceExpr;
import net.sourceforge.pmd.lang.java.ast.ASTStringLiteral;
import net.sourceforge.pmd.lang.java.ast.ASTVariableDeclarator;
import net.sourceforge.pmd.lang.java.ast.ASTVariableId;
import net.sourceforge.pmd.lang.java.ast.BinaryOp;
import net.sourceforge.pmd.lang.java.ast.JModifier;
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.ast.internal.JavaAstUtils;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
public class AddEmptyStringRule extends AbstractJavaRulechainRule {
public AddEmptyStringRule() {
super(ASTStringLiteral.class);
}
@Override
public Object visit(ASTStringLiteral node, Object data) {
if (!node.isEmpty()) {
return null;
}
JavaNode parent = node.getParent();
checkExpr(data, parent, node);
if (parent instanceof ASTVariableDeclarator) {
ASTVariableId varId = ((ASTVariableDeclarator) parent).getVarId();
if (varId.hasModifiers(JModifier.FINAL)) {
for (ASTNamedReferenceExpr usage : varId.getLocalUsages()) {
checkExpr(data, usage.getParent(), usage);
}
}
}
return null;
}
private void checkExpr(Object data, JavaNode parent, JavaNode emptyStringNode) {
if (JavaAstUtils.isInfixExprWithOperator(parent, BinaryOp.ADD)
&& parent.ancestors(ASTAnnotation.class).isEmpty()) {
asCtx(data).addViolationWithPosition(parent, parent.getAstInfo(),
emptyStringNode.getReportLocation(), getMessage());
}
}
}