Search code examples
eclipse-pluginstatic-analysisabstract-syntax-treeeclipse-jdt

Comparing ASTNodes in Eclipse


I'm writing a plugin for Eclipse that periodically walks the Abstract Syntax Tree provided by Eclipse JDT and places IMarkers on certain nodes - for example, a printStackTrace() is highlighted for removal (Youtube Demo). For each subsequent walk I want to avoid placing a 2nd (or 3rd or 4th or...) marker.

The position of these nodes can change (if the document is edited between walks) but the IMarkers do not (IMarker positions do not update until the document has been saved), so I can't use char_start and char_end comparisons on these objects.

I also can't use the .equals method of ASTNode, as a stored copy of an ASTNode won't update these charstart and charend positions. I've also tried comparing getParent() nodes but this has its own issues (ie two printStackTraces, in separate catch blocks, will have a common TryStatement parent)

Right now I'm looking at extending ASTMatcher and overriding the various matches() methods, but to call each matches() I'll need to cast one of the nodes from ASTNode to the appropriate subclass.

Before trying to write that up with a massive switch statement and a lot of casting, is there a more elegant solution for checking if two ASTNodes are the same without relying on .equals()?


Solution

  • Generally validators and builders will remove all of the markers on a file before going back and adding their own for that particular validation or build. I suspect they did it that way instead of taking your approach because it was easier that way. I'd take that approach unless there is a serious performance reason not to.

    If you do need to do a comparison between old and new, you'll need to write a switch statement and do a lot of casting, although you can at least make it look elegant with a factory pattern of some sort.