【问题标题】:checkNewChild throws error when lowering JDT code降低 JDT 代码时 checkNewChild 抛出错误
【发布时间】:2015-04-03 02:20:20
【问题描述】:

所以在我的编译器类中,我们使用 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)
...

所以我最好的猜测是孩子必须是独一无二的。是这样吗?如果是这种情况,降低是如何实施的?如果不是这样,这是怎么回事?

【问题讨论】:

    标签: java compiler-construction compilation eclipse-jdt


    【解决方案1】:

    也遇到过这个问题。很容易发现:

    java.lang.IllegalArgumentException 在 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 要求这样做)。我看到以下方法可以解决这个问题:

    1. 复制节点和它的子树ASTNode.copySubtree(astNode.getAST(), astNode)
    2. 使用astNode.delete() 从树中删除节点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多