使用Eclipse AST在特定位置将元素添加到AST中



更新2:再次感谢@deepak azad,我成功地解决了我的问题:这是主代码的链接:https://gist.github.com/1714641

更新:多亏了@deepak-azad,我补充了代码,但仍然无法工作。

我正在尝试使用EclipseJDT在Java中插入一个源文件。我的主要目标是在每个变量声明下面放一些语句"x();"。

例如:由此:

int a = 10;

到此:

int a = 10;
method();

我能够创建ast,并创建了一个类来扩展visit方法,以获得代码中的所有变量声明:

import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
public class VDS extends ASTVisitor {
List<VariableDeclarationStatement> vds = new ArrayList<VariableDeclarationStatement>();
    @Override
    public boolean visit(VariableDeclarationStatement node) {
        vds.add(node);
        return super.visit(node);
    }   
    public List<VariableDeclarationStatement> getVDS() {
        return vds;
    }
}

我测试了它,它可以很好地捕获每个变量,但不能插入新节点,使用类似这样的东西:

VDS vds = new VDS();
unit2.accept(vds); // unit2 is the compilation unit
System.out.println("Variables :" + vds.getVDS().size());
for(VariableDeclarationStatement vds_p : vds.getVDS()){
    System.out.println(vds_p.toString()) 
    List<Statement> a = ((Block) vds_.getParent()).statements();
     a.add(e);//e is the artificial statement 
        ListRewrite lrw = astRewrite.getListRewrite(vds_p.getParent().BLock.STATEMENTS_PROPERTY);
lrw.insertAfter(e,vds_p,null);
    }

实际写下的代码是(我用任意注释测试了这一部分)

IDocument document2;
ITextFileBufferManager bufferManager = FileBuffers.getTextFileBufferManager(); // get the buffer manager
IPath path = unit2.getJavaElement().getPath(); // unit: instance of CompilationUnit
try {
    bufferManager.connect(path, null); 
    ITextFileBuffer textFileBuffer = bufferManager.getTextFileBuffer(path);
    // retrieve the buffer
    document2 = textFileBuffer.getDocument(); 
    textFileBuffer.commit(null /* ProgressMonitor */, false /* Overwrite */); 
} finally{ bufferManager.disconnect(path, null);}
TextEdit edits = unit2.rewrite(document2, null);
edits.apply(document2);
write2File(document2);  

我对层次结构是如何工作的有点困惑,我是基于每个变量语句都属于一个块,每个块都属于一种方法这一事实得出这个想法的,但我仍然不知道如何在ListRewrite元素中处理这个问题。

我一直在eclipse中阅读有关ast的内容,但所有问题都与代码的创建有关,但与的编辑过程无关

当我执行此操作时,我得到一个非法的参数异常,如下所示:

java.lang.IllegalArgumentException
    at org.eclipse.jdt.core.dom.ASTNode.checkNewChild(ASTNode.java:1905)
    at org.eclipse.jdt.core.dom.ASTNode$NodeList.add(ASTNode.java:1269)
    at java.util.AbstractList.add(AbstractList.java:91)
    at plugin.astsimple.handlers.SampleHandler.execute(SampleHandler.java:109)
    at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:293)
    at org.eclipse.core.commands.Command.executeWithChecks(Command.java:476)
        ...

其中,我的代码的第109行是将e添加到的行

a.add(e);

谢谢!

每个"块"都由语句的"列表"组成,因此您需要使用"org.eclipse.jdt.core.dom.rewrite.ListRewrite.insertAfter(ASTNode,ASTNode,TextEditGroup)"。您可以在org.eclipse.jdt.ui插件中查找此方法的用法示例。

为了更好地理解AST中的层次结构是如何工作的,您应该使用AST视图插件-http://www.eclipse.org/jdt/ui/astview/index.php

最新更新