gpt4 book ai didi

java - 在抽象语法树中一个接一个地插入节点 - Eclipse CDT

转载 作者:行者123 更新时间:2023-11-30 16:31:27 25 4
gpt4 key购买 nike

我想在另一条评论之后插入节点

/**************/
/* 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 insertPoint, IASTNode newNode, TextEditGroup editGroup) 方法,您可以将其用于此目的。

就您而言,您需要使用以下方式调用它:

  • 您的 simpleDeclaration 作为 newNode 的参数
  • int x = 5; 的声明(您将在遍历过程中找到)作为 insertionPoint 的参数
  • insertionPoint 的父级(可能是 IASTTranslationUnit)作为 parent 的参数
  • 您可以为 editGroup 参数传递 null。 (根据 CDT 代码库中 ASTRewrite 的现有使用,这个可选参数的目的似乎是将一组编辑与稍后可以在重构 UI 等中显示的描述/标签相关联。)

关于java - 在抽象语法树中一个接一个地插入节点 - Eclipse CDT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50569221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com