Search code examples
javaabstract-syntax-treeeclipse-jdt

How to extract a condition in a known line using JDT-AST?


I have a method like this:

public static int calc(int a, int b) {
        if (a >= b)
            return a - b;
        return 0;
}

I want to know the condition that is used on a known line number. In this case my expected result is the name of the condition, something like ">=".

I know how to parse the CompilationUnit of a given ICompilationUnit. But how can I get the condition(s)?


Solution

  • For this you have to create an ASTVisitor which will visit all the infix expressions. In the visitor class the visit method will have the following:

    @Override
    public boolean visit(InfixExpression node) {
        Operator op= node.getOperator();
        if(op.equals(Operator.GREATER) || op.equals(Operator.EQUALS) || ....)
            conditionalInfixExpressionList.add(node);
        return super.visit(node);
    }
    

    In the if statement inside of the visit method, you have to check, if the infix expression is a conditional variables and accordingly add it to the list.