replacing Statement/Expression

Is there a facility to replace a statement or an expression with another in the AST? In the scenario that I am looking at, the text replacement strategy doesn't work because after rewriting the child expression, when I rewrite the parent expression it picks the child expressions from the AST which do not reflect the "updated" child expression.



Hi Rajesh,

While we haven't fleshed out the use of setter methods for ASTs, one can indeed replace the AST nodes using Stmt::child_iterator interface. child_iterator (which is a typedef of the class StmtIterator) actually returns a reference to the Stmt* contained within an AST node. For example, here is a snippet from RewriteObjC.cpp:

   // Start by rewriting all children.
   for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
        CI != E; ++CI)
     if (*CI) {
       Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
       if (newStmt)
         *CI = newStmt;

We may gradually add direct setter methods to AST nodes as the refactoring API gets fleshed out (feel free to make suggestions and propose patches). One thing we're still resolving is the memory management model for AST nodes. Right now they are all created using new/malloc, but we've started rolling out changes that Stmt's are allocated using a memory allocator associated with the ASTContext object. I don't think you have to worry about this for now, but it is something to be aware of (i.e., the API is still evolving).


As Ted says, the child iterators make this easy. You might want to look at the objc rewriter, which has similar issues and has a clean solution.