我正在使用javaparser解析以下代码的内容,并确定语句序列:
class X {
void x() {
int x = 1;
if (x>4) {
x=21;
} else {
if (x>1) {
x=3;
} else {
x=212;
}
}
if (x==4) {
x=3;
}
}}
我用来解析上述示例的代码:
private static void statements(BlockStmt block, State beforeState, State afterState) {
List<State> states = new ArrayList<>();
for (Statement statement : block.getStatements()) {
states.add(new State(statement));
}
beforeState.nextStates.add(states.get(0));
for (int i = 0; i < states.size(); i++) {
State currentState = states.get(i);
State nextState;
if (i == states.size() - 1) {
nextState = afterState;
} else {
nextState = states.get(i + 1);
}
currentState.statement.accept(new VoidVisitorWithDefaults<Void>() {
@Override
public void visit(ExpressionStmt n, Void arg) {
currentState.nextStates.add(nextState);
}
@Override
public void visit(IfStmt n, Void arg) {
statements(n.getThenStmt().asBlockStmt(), currentState, nextState);
n.getElseStmt().ifPresent(elseStmt ->
statements(elseStmt.asBlockStmt(), currentState, nextState));
}
}, null);
} }
我还想做的是确定当前语句是否是表达式语句(即赋值),如果是,则查找它是否是if/else语句的then块中包含的最后一条语句。在上面的例子中,这就是 x=3;
. 然而,我不知道如何做到这一点。
到目前为止,我的想法是这样的:
ExpressionStmt exprStmt = (ExpressionStmt) currentState.statement;
Node exprStmtParent = exprStmt.getParent();
List<Node> exprStmtSibilings = exprStmtParent.getChildNodes();
Node lastNode = exprStmtSiblings.get(exprStmtSiblings.size() - 1);
boolean exprStmtIsLast = lastNode == ifStmt;
它适用于if语句,但不适用于赋值。关于如何处理这个问题有什么建议吗?
暂无答案!
目前还没有任何答案,快来回答吧!