Shode AAA Shode AAA - 2 years ago 62
Java Question

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

I want to write a custom

rule that uses two

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 Source

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">
    <property name="xpath">
//Expression[.//AdditiveExpression and .//MultiplicativeExpression]

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download