Search code examples
javacompiler-constructionautomated-testsabstract-syntax-tree

How to make Abstract Syntax Tree of few line of code not a complete file or class in java?


I am trying to compare CFGs using AST comparison. I have tried the Eclipse AST Parser, it's great. But I'm using IntelliJ IDE so can't use it. I explored the Java parser but it returns compilation unit and work on complete Java files. Please suggest a way or APIs to get the Abstract Syntax Trees of basic blocks (few lines of code), further in I should be able to compare generated ASTs.


Solution

  • I've never done this but what about taking the text of the basic block and putting a trivial wrapper around it:

    class AST {
        void method() {
            // basic block here
        }
    }
    

    And passing that to the parser? It would give you more than you wanted, but you could navigate a couple of nodes down in the AST and the entire subtree below that would be the AST you wanted.