问题
Is there a open source java api that allows to compare two Abstract Syntax Trees of java source code?
I would like to see the differences between the two syntax trees, similar to how it is done in diff tools.
回答1:
Most diff tools compare lines, not syntax trees (see Wikipedia article for discussion).
There are some techical papers that talk about how to do syntax tree compares, e.g., Diff/TS: A Tool for Fine-Grained Structural Change Analysis
There are no APIs for computing tree differences available anywhere as far as I know. The problem is more complex than it first sounds, if you want to get a minimal diff. But the basic technique is to use some variation of Levenstein distance metrics.
We had to roll our own for our line of SmartDifferencers; fortunately, we have really good front ends for many langauges to produce accurate ASTs.
You end up with additional surprises, such as people that want to compare comments in spite of the fact that what you have are ASTs, wanting to compare broken files, to compare language dialects your grammar doesn't match, or codes that contain insertions of other languages, etc.. Do diff by lines doesn't have these issues, which is one reason line-diff is widespread and tree-diff is not.
回答2:
Yes, there are free implementations that output tree diffs:
gumtree(fast, multi languague, integrates with git): http://www.labri.fr/perso/falleri/perso/tools/gumtree/ https://github.com/jrfaller/gumtree
ChangeDistiller (quite mature, built as a self contained library): https://bitbucket.org/sealuzh/tools-changedistiller/wiki/Home
CodingSpectator (ast diffing is hardcoded in the rest of the code): https://github.com/vazexqi/CodingSpectator/tree/codingtracker-ast-inference
回答3:
I wonder if there is an ANTLR extension somewhere that can do this....
http://www.antlr.org/
http://openjdk.java.net/projects/compiler-grammar/antlrworks/Java.g
来源:https://stackoverflow.com/questions/8474046/api-to-compare-ast