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
。(基于CDT代码库中ASTRewrite的现有用途,此可选参数的目的似乎是将一组编辑与稍后可在重构UI中显示的描述/标签相关联。)null
IASTComment
节点,您可以迭代全局声明(IASTTranslationUnit
的子项),并找到第一个开始偏移量为(IASTNode.getFileLocation().getNodeOffset()
)已通过注释节点。