In an AST Visitor, how can I know which node's property I am visiting?
I'm programming an AST Visitor (eclipse JDT).
An EnumDeclaration
node contains the following structural properties:
JAVADOC
, MODIFIERS
, NAME
, SUPER_INTERFACE_TYPES
, ENUM_CONSTANTS
and BODY_DECLARATIONS
.
When I visit a child node of EnumDeclaration
(a SimpleName
node, for instance), is it possible to know which of 开发者_如何学运维the lists of nodes I'm visiting? Is it possible to differentiate?
I'd like to process a node differently, depending on whether I found it in ENUM_CONSTANTS
or BODY_DECLARATIONS
.
I found a solution. Explicitly visiting the nodes in the list (WITH accept()
, not visit()
). Something like (for visiting the super interfaces):
List<Type> superInterfaces = enumDecNode.superInterfaceTypes();
for( Type superInterface: superInterfaces)
superInterface.accept( this);
Note that it is not possible to use:
this.visit( superInterface);
because Type
is an umbrella abstract class for which no visit( Type node)
implementation exists.
This also forces the children of the nodes in the superInterfaces
list to be visited as soon as their parent is visited. Problem solved.
On a side note, if you already process all the children of a node via these lists, you can forbid the visitor from re-visiting its children, by returning false.
Your nodes should invoke corresponding methods.
MODIFIERS -> visitModifiers
NAME -> visitNAME
and so on
Another alternative solution (thanks to Markus Keller @ eclipse JDT forum):
Use "node.getLocationInParent() == EnumDeclaration.NAME_PROPERTY" or other *_PROPERTY constants.
Markus
精彩评论