[cfe-dev] Using clang for source to source transformations

Charles Davis cdavis at mymail.mines.edu
Thu Feb 11 23:00:34 PST 2010


Nathan Lawrence wrote:
> Hi,
> 
> I'm trying to use clang as a source-to-source transformer to reorder
> statements in c code.  It is not necessary maintain formatting.
> 
> I've been looking through the documentation, but I can't find an
> obvious way to do this.  I would like to be able to operate on an AST
> and not a token stream.
> 
> How would you recommend doing this?
Take a look at the sample rewriters in lib/Frontend.

What you want to do is create a custom ASTConsumer (by deriving a class
from it). In the ASTConsumer, you hold a reference to a Rewriter object.
Use the InsertXxx(), ReplaceXxx(), and DeleteXxx() methods to manipulate
the AST.

When you're done, you can write the source to disk by grabbing the
RewriteBuffer from the Rewriter. The boundaries are denoted by the
begin() and end() methods.

Chip



More information about the cfe-dev mailing list