Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[cdt-dev] Difficulties with rewriting initializers


I use the ASTRewrite API to refactor C++ Code in a headless eclipse application. It seems to me that some trivial examples are not rewritten correctly. For example, the following code should replace "int i = 1+2;" with "int i = 3". The actual result is: "int i =  = 3;". An extra "=" is also added for "int main(){int i = 1+2;}". On the other hand, "int main(){int i; i = 1+2;}" is rewritten correctly.

Am I doing something wrong? If this is a bug, can I work around it? My version of cdt.core is 5.2.0. I also tried the current head, but the problem remains.

Here's my code:

public Object start(...){
    IASTTranslationUnit translationUnit = MyLanguage.getDefault().getASTTranslationUnit(reader, config, fileCreator, index, options, log);
    IASTTranslationUnit mutableAST = translationUnit.copy();
    ASTRewrite rewriter = ASTRewrite.create(mutableAST);
    MyASTVisitor visitor = new MyAstVisitor(rewriter);
    Change changes = rewriter.rewriteAST();
    changes.perform(new NullProgressMonitor());

class MyASTVisitor extends ASTVisitor{
    private ASTRewrite rewriter;
    public MyAstVisitor(ASTRewrite rewriter){
        this.rewriter = rewriter;
    public int visit(IASTExpression expr){
        if(expr instanceof IASTBinaryExpression){
            IASTBinaryExpression bexpr = (IASTBinaryExpression) expr;
            if(bexpr.getOperator() == IASTBinaryExpression.op_plus){
                rewriter.replace(bexpr, rewriter.createLiteralNode("3"), null);
        return ASTVisitor.PROCESS_CONTINUE;

Alexander Christ

Back to the top