Search code examples
javanetbeansabstract-syntax-treenetbeans-platform

Parse if else statement using Compiler Tree API


I am trying to find a way to parse java code source in netbeans using the Tree API, I learned through this guide how I can access high level language elements (classes,methods,fields ..).

what I'm looking for is a way to parse if else statements (for a start) since I'm trying to apply replace type code with state strategy refactoring afterwards. it is very important for me to get the if condition. Any help would be deeply appreciated.


Solution

  • After diving into the Compiler Tree API doc I found how to access low level code the condition of a selected if statement in my case, here is a code snippet

      @Override
        public Void visitIf(IfTree node, Void p) {
            try {
                JTextComponent editor = EditorRegistry.lastFocusedComponent();
                if (editor.getDocument() == info.getDocument()) {
                    InputOutput io = IOProvider.getDefault().getIO("Analysis of " + info.getFileObject().getName(),
                            true);
                    ExpressionTree exTree = node.getCondition();
                    if (exTree.getKind() == Tree.Kind.PARENTHESIZED) {
                        ParenthesizedTree parTree = (ParenthesizedTree) exTree;
                        BinaryTree conditionTree = (BinaryTree) parTree.getExpression();
                        ExpressionTree identTree = conditionTree.getLeftOperand();
                        if (identTree.getKind() == Tree.Kind.IDENTIFIER) {
                            Name name = ((IdentifierTree) identTree).getName();
                            io.getOut().println("Hurray, this is the name of the identifier in the left operand: " + name.toString());
                        }
    
    
               io.getOut().close();
                    }
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
                return null;        
    }
    

    Thankfully the code naming is intuitive otherwise the documentation doesn't help much. debugging using println is very useful to know what kind of tree to deal with next.