views:

446

answers:

2

Given the following code in Eclipse:

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;

public class Question {
    public static void main(String[] args) {
        String source = "class Bob {}";
        ASTParser parser = ASTParser.newParser(AST.JLS3); 
        parser.setSource(source.toCharArray());
        CompilationUnit result = (CompilationUnit) parser.createAST(null);

        String source2 = "class Bob {public void MyMethod(){}}";
        ASTParser parser2 = ASTParser.newParser(AST.JLS3); 
        parser2.setSource(source2.toCharArray());
        CompilationUnit result2 = (CompilationUnit) parser2.createAST(null);
    }
}

How do you use the Eclipse Compare API (org.eclipse.compare) to find the AST difference? (And can this be done outside of a plugin?)

I'm looking at the following APIs

http://kickjava.com/src/org/eclipse/compare/structuremergeviewer/Differencer.java.htm http://kickjava.com/src/org/eclipse/jdt/internal/ui/compare/JavaStructureCreator.java.htm http://kickjava.com/src/org/eclipse/compare/CompareUI.java.htm

Can anyone point to example code (or an API - but the code is preferred).

A: 

You don't have two different ASTs in your example. But beside of that, I don't know of any simple way to compare two ASTs.

The package "org.eclipse.compare" is used for comparing two files and showing the compare view to the user of eclipse. If you are interested in that, you could look at the tests of this package. (Can be found under: http://dev.eclipse.org/viewsvn/index.cgi/org.eclipse.compare.tests/) I haven't had time to look into them myself but most times the eclipse tests are really helpful.

hoess_c
The code in the original poster's question clearly builds two ASTs.
Ira Baxter
Thanks for the link - it looks like eclipse only does the difference by line number - not actual AST matching.
hawkeye
+1  A: 

Given that Eclipse doesn't do AST differencing, perhaps what the OP wanted to find differences between two files in terms of the langauge constructs ignoring white spaces and comments. The Smart Differencer tool compares two source files in terms of the langauge constructs (variables, expressions, statements, blocks, methods, ...) and describes the differences in terms of abstract editing operations over these elements (delete, copy, move, rename identifier in region, ...)

Ira Baxter