How to check if a visited node is in if part or el

2019-08-21 02:17发布

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条回答
仙女界的扛把子
2楼-- · 2019-08-21 03:07

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
}
查看更多
登录 后发表回答