You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Eclipse CDT抽象语法树中指定注释节点后插入新节点

如何使用ASTRewrite在目标注释节点后插入函数原型

需求回顾

你需要在包含Prototypes的注释节点后插入预先创建好的函数原型声明节点,目前已经拿到了目标IASTComment节点和待插入的IASTSimpleDeclaration节点,接下来只需要补充ASTRewrite的插入逻辑即可。

已完成的前置代码

先确认你已经完成的两项关键工作:

  1. 获取目标注释节点的访问器实现:
@Override
protected int visit(IASTComment comment) {
    if(comment.getRawSignature().contains("Prototypes")) {
        prototypeNode = comment;
    }
    return super.visit(comment);
}
  1. 创建待插入的函数声明节点:
INodeFactory factory = ast.getASTNodeFactory();
IASTSimpleDeclaration simpleDeclaration = factory.newSimpleDeclaration(functionDef.getDeclSpecifier());
simpleDeclaration.addDeclarator(functionDef.getDeclarator());

补充AST插入的核心代码

下面是完整的ASTRewrite改写代码,重点是insertAfter方法的使用:

ASTRewrite rewriter = ASTRewrite.create(ast);

// 核心操作:将函数声明节点插入到目标注释节点的后方
rewriter.insertAfter(simpleDeclaration, prototypeNode, null);

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

关键代码解释

  • rewriter.insertAfter(newNode, referenceNode, editGroup):这是Eclipse AST框架提供的标准插入方法,它会自动处理节点的位置关系,不需要手动计算父节点的索引:
    • simpleDeclaration:你已经创建好的函数原型声明节点
    • prototypeNode:之前找到的包含Prototypes的注释节点
    • 第三个参数传null即可,若需要跟踪编辑操作组,可以传入自定义的ASTEditGroup

运行这段代码后,函数原型就会被准确插入到目标注释的后方,完成AST的改写。

内容的提问来源于stack exchange,提问作者Mostafa Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:38:29