0

I am using javaparser to parse the AST for Java source files.

I would like to get all binary subexpressions in the source code as individual nodes. Here is the source code I am parsing:

class MyClass {
  public MyClass() {
    double x = (4 / 10.0) + 15;
  }
}

I implemented a Visitor that accepts the built-in BinaryExp type, but the only node that it finds contains the binary expression:

(4 / 10.0) + 15

Is there a way to visit the subexpression "(4 / 10.0)" as well? I tried getting the full expression's "left operand", but it is of type Expression, and not BinaryExpr as I expected.

Any help would be appreciated.

jem
  • 130
  • 8

1 Answers1

0

The left operand cannot be of actual type Expression because Expression is an abstract class.

  • You can check the actual type by checking binEx.getLeft() instanceof BinaryExp.If this evaluates true, you can cast to BinaryExpression.
  • But probably it evaluates false and the node is of type EnclosedExpr (parentheses). Then the binary expression is the child of the left node

This will probably not solve the whole problem. I think you missed to apply the visitor to the child nodes. You have to adjust visit(BinaryExpr n, A arg):

  • if you use a GenericVisitorAdaptor you will have to call super.visit(n,arg)
  • if you wrote your own adaptor you will have to call accept(this, arg) on each child.
CoronA
  • 7,717
  • 2
  • 26
  • 53