John Assymptoth
John Assymptoth

Reputation: 8507

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.

Upvotes: 4

Views: 882

Answers (3)

John Assymptoth
John Assymptoth

Reputation: 8507

Another alternative solution (thanks to Markus Keller @ eclipse JDT forum):

Use "node.getLocationInParent() == EnumDeclaration.NAME_PROPERTY" or other *_PROPERTY constants.

Markus

Upvotes: 0

John Assymptoth
John Assymptoth

Reputation: 8507

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.

Upvotes: 2

Stan Kurilin
Stan Kurilin

Reputation: 15792

Your nodes should invoke corresponding methods.

MODIFIERS -> visitModifiers 
NAME -> visitNAME

and so on

Upvotes: 1

Related Questions