[英]In an AST Visitor, how can I know which node's property I am visiting?
I'm programming an AST Visitor (eclipse JDT). 我正在编程AST访问者(eclipse JDT)。
An EnumDeclaration
node contains the following structural properties: EnumDeclaration
节点包含以下结构属性:
JAVADOC
, MODIFIERS
, NAME
, SUPER_INTERFACE_TYPES
, ENUM_CONSTANTS
and BODY_DECLARATIONS
. JAVADOC
, MODIFIERS
, NAME
, SUPER_INTERFACE_TYPES
, ENUM_CONSTANTS
和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? 当我访问
EnumDeclaration
的子节点(例如,一个SimpleName
节点)时,是否可以知道我正在访问哪些节点列表? 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
. 我想以不同的方式处理节点,具体取决于我是在
ENUM_CONSTANTS
还是BODY_DECLARATIONS
找到它。
I found a solution. 我找到了解决方案。 Explicitly visiting the nodes in the list (WITH
accept()
, not visit()
). 显式访问列表中的节点(WITH
accept()
,而不是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. 因为
Type
是一个伞形抽象类,不存在visit( Type node)
实现。
This also forces the children of the nodes in the superInterfaces
list to be visited as soon as their parent is visited. 这也会强制访问其父级时访问
superInterfaces
列表中的节点的子节点。 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. 另外,如果您已经通过这些列表处理了节点的所有子节点,则可以通过返回false来禁止访问者重新访问其子节点。
Your nodes should invoke corresponding methods. 您的节点应该调用相应的方法。
MODIFIERS -> visitModifiers
NAME -> visitNAME
and so on 等等
Another alternative solution (thanks to Markus Keller @ eclipse JDT forum): 另一种替代解决方案(感谢Markus Keller @ eclipse JDT论坛):
Use "node.getLocationInParent() == EnumDeclaration.NAME_PROPERTY" or other *_PROPERTY constants.
使用“node.getLocationInParent()== EnumDeclaration.NAME_PROPERTY”或其他* _PROPERTY常量。
Markus
马库斯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.