Java 在抽象语法树中的节点后插入节点-Eclipse CDT

Java 在抽象语法树中的节点后插入节点-Eclipse CDT,java,c,eclipse-cdt,abstract-syntax-tree,Java,C,Eclipse Cdt,Abstract Syntax Tree,我想在另一个注释后插入节点 /**************/ /* Prototypes */ /**************/ --->want to declare function prototype here int x = 5; 因此,我通过以下代码获得ast中的注释节点 @Override protected int visit(IASTComment comment) { if(comment.getRawSignature().contains("Prototyp

我想在另一个注释后插入节点

/**************/
/* Prototypes */
/**************/
--->want to declare function prototype here
int x = 5;
因此,我通过以下代码获得ast中的注释节点

@Override
protected int visit(IASTComment comment) {
    if(comment.getRawSignature().contains("Prototypes")) {
        prototypeNode = comment;
    }
    return super.visit(comment);
}
然后我想在下面的注释后面插入这个节点

INodeFactory factory = ast.getASTNodeFactory();
IASTSimpleDeclaration simpleDeclaration = factory.newSimpleDeclaration(functionDef.getDeclSpecifier());
simpleDeclaration.addDeclarator(functionDef.getDeclarator());

ASTRewrite rewriter = ASTRewrite.create(ast);
//I want to insert the simpleDeclaration node after the comment node  
**enter code here**


Change c = rewriter.rewriteAST();
try {
    c.perform(new NullProgressMonitor());
} catch (CoreException e) {
    e.printStackTrace();
}

ASTRewrite
有一个
insertBefore(IASTNode parent、IASTNode insertionPoint、IASTNode newNode、TextEditGroup editGroup)
方法可用于此目的

在您的情况下,您希望使用以下名称来称呼它:

  • 您的
    simpleDeclaration
    作为
    newNode
  • intx=5的声明
    (在遍历过程中可以找到)作为插入点的参数
  • 插入点的父项(可能是
    IASTTranslationUnit
    )作为
    父项的参数
  • 您可以为
    editGroup
    参数传递
    null
    。(基于CDT代码库中ASTRewrite的现有用途,此可选参数的目的似乎是将一组编辑与稍后可在重构UI中显示的描述/标签相关联。)

我知道ast write before方法,但我不知道实际的代码可能是int x=5或其他任何东西,x=5只是一个例子。我需要更通用的方式,我知道注释,它是静态的,固定为这样的/***************/***原型*/***************/@MostafaHassan:如果您知道
IASTComment
节点,您可以迭代全局声明(
IASTTranslationUnit
的子项),并找到第一个开始偏移量为(
IASTNode.getFileLocation().getNodeOffset()
)已通过注释节点。