问题
So in my compilers class we are using JDT to represent our subset of Java. I already have assignment working and so I thought it would be a good idea to implement increment/decrement by lowering it to assignment. I realized while typing this that because the expression being incremented might have an effect this is not 100% valid. Still I want to do something like this for for loops as well.
So I have this code
@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);
}
but when it executes I get an error as soon as I try to set the left operand of the infix expression.
the error is
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)
...
So my best guess is that children are required to be unique. Is this the case? If this is the case, how is lowering implemented? If this is not the case, what is going on here?
回答1:
Also faced this issue. It was simple to find out:
java.lang.IllegalArgumentException at org.eclipse.jdt.core.dom.ASTNode.checkNewChild(ASTNode.java:2087)
Go to sources and check for line 2087.
if (newChild.getParent() != null) {
// new child currently has a different parent
throw new IllegalArgumentException();
}
The problem is you cannot add node to tree if node is already there (this is required by tree structure). I see the following ways to solve this problem:
- Copy node and it's subtree with
ASTNode.copySubtree(astNode.getAST(), astNode) - Delete node from tree with
astNode.delete()
来源:https://stackoverflow.com/questions/29425345/checknewchild-throws-error-when-lowering-jdt-code