所以在我的编译器类中,我们使用JDT来表示我们的Java子集。我已经完成了作业,因此我认为通过将其降低到赋值来实现递增/递减是个好主意。我在输入时意识到,因为增加的表达式可能会产生影响,这不是100%有效。我仍然想为for循环做这样的事情。
所以我有这个代码
@Override
public boolean visit(final PostfixExpression node) {
//in this we lower an inc/dec expression to an assignment
NumberLiteral one = node.getAST().newNumberLiteral();
one.setToken(new Integer(1).toString());
InfixExpression ie = node.getAST().newInfixExpression();
ie.setLeftOperand(node.getOperand());
ie.setRightOperand(one);
if(node.getOperator() == PostfixExpression.Operator.INCREMENT) {
ie.setOperator(InfixExpression.Operator.PLUS);
} else {
ie.setOperator(InfixExpression.Operator.MINUS);
}
Assignment a = node.getAST().newAssignment();
a.setLeftHandSide(node.getOperand());
a.setRightHandSide(ie);
//finally just lower the increment to the assignment
return this.visit(a);
}
但是当它执行时,一旦我尝试设置中缀表达式的左操作数,我就会收到错误。
错误是
java.lang.IllegalArgumentException
at org.eclipse.jdt.core.dom.ASTNode.checkNewChild(ASTNode.java:2087)
at org.eclipse.jdt.core.dom.ASTNode.preReplaceChild(ASTNode.java:2149)
at org.eclipse.jdt.core.dom.InfixExpression.setLeftOperand(InfixExpression.java:437)
...
所以我最好的猜测是孩子们必须是独一无二的。是这样的吗?如果是这种情况,如何实施降低?如果不是这样,那么这里发生了什么?
答案 0 :(得分:0)
也面临这个问题。很容易找到:
java.lang.IllegalArgumentException at org.eclipse.jdt.core.dom.ASTNode.checkNewChild(ASTNode.java:2087)
转到sources并检查第2087行。
if (newChild.getParent() != null) {
// new child currently has a different parent
throw new IllegalArgumentException();
}
问题是,如果节点已经存在,则无法将节点添加到树(这是tree structure所要求的)。我看到以下方法来解决这个问题:
ASTNode.copySubtree(astNode.getAST(), astNode)
astNode.delete()