问题
When I visit a MethodInvocation node during AST traversal, I want to know if it lies in the IfStatement then part or else part or in the expression part. The then part can be a complete block of code but I think my code is handling only a single then statement.
Here is the code snippet for visiting a method invocation
@Override
public boolean visit(MethodInvocation node)
{
StructuralPropertyDescriptor location = node.getLocationInParent();
setNodeRegion(location);
Here is how I want to set flags for each region of IfStatement
private void setNodeRegion(StructuralPropertyDescriptor location) {
if(location == IfStatement.EXPRESSION_PROPERTY ||
location == IfStatement.THEN_STATEMENT_PROPERTY)
{
ParseContextAction.ifBlockRegion = true;
}
else
{
if(location == IfStatement.ELSE_STATEMENT_PROPERTY)
{
ParseContextAction.elseBlockRegion = true;
}
else
{
if(location == CatchClause.BODY_PROPERTY)
{
ParseContextAction.catchBlockRegion = true;
}
else
{
ParseContextAction.basicBlockRegion = true;
}
}
}
}
回答1:
If you use visit(IfStatement node)
instead of visit(MethodInvocation node)
, you can visit both the then (getThenStatement()
) and the else (getElseStatement()
) branch with a separate visitor:
@Override
public boolean visit(IfStatement node) {
Statement thenBranch = node.getThenStatement();
if (thenBranch != null) {
thenBranch.accept(new ASTVisitor(false) {
@Override
public boolean visit(MethodInvocation node) {
// handle method invocation in the then branch
return true; // false, if nested method invocations should be ignored
}
}
}
Statement elseBranch = node.getElseStatement();
if (elseBranch != null) {
elseBranch.accept(new ASTVisitor(false) {
@Override
public boolean visit(MethodInvocation node) {
// handle method invocation in the else branch
return true; // false, if nested method invocations should be ignored
}
}
}
return true; // false, if nested if statements should be ignored
}
来源:https://stackoverflow.com/questions/50484559/how-to-check-if-a-visited-node-is-in-if-part-or-else-part-of-ifstatement-node-in