Shode AAA Shode AAA - 7 months ago 11
Java Question

How to use two AST node in one rule in pmd?

I want to write a custom

PMD
rule that uses two
AST
nodes.

My custom rule scans the source code to find mathematical operators.

I want my rule to find more than one operators from these

+,*,/, and -


in the same expression.

I have tried some solutions but they did not work, for example:

public class OperatorPrecednece extends AbstractJavaRule {

Public Object visit(ASTMultiplicativeExpression node, Object data) {


Object tvisi(ASTAdditiveExpression node2, Object data2){
addViolation(data2, node2);


}

return super.visit(node, data);

}
}


How to do that?

Answer

I chose XPath instead of Java. Put this rule into your pmd ruleset configuration xml:

<rule name="MultipleOperatorsInExpression" language="java" message="More than one different operator used in expression" class="net.sourceforge.pmd.lang.rule.XPathRule">
  <properties>
    <property name="xpath">
      <value>
        <![CDATA[
//Expression[.//AdditiveExpression and .//MultiplicativeExpression]
        ]]>
      </value>
    </property>
  </properties>
</rule>

But it's not a complete solution yet... I'm looking into a possible pmd bug: looks like that an expression like 1+2-3+4 gets a single AdditiveExpression:+ node instead of 3 distinct nodes with their respective operators, so detecting an expression that uses just + and - or just * and / will not be detected. But it will detect expressions with mixed additive and multiplicative operators.

I will update the answer if I figure this out, but I hope the rule is of some use.