How to check if a visited node is in if part or else part of IfStatement node in Eclipse JDT parsing?

倖福魔咒の 提交于 2020-01-15 10:17:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!