[cfe-dev] Transforming the AST

Douglas Gregor dgregor at apple.com
Tue Jul 6 11:00:30 PDT 2010

On Jul 6, 2010, at 10:46 AM, Zakkak Foivos wrote:

> On 07/06/2010 08:34 PM, John McCall wrote:
>> On Jul 6, 2010, at 8:34 AM, Zakkak Foivos wrote:
>>> i need some help with AST transformations. I searched through the api
>>> but didn't find anything straight forward except some build*type functions.
>>> How can i create a new stmt and insert it in the tree? I don't want to
>>> use the Rewriter for the transformations.
>> If you're interested in producing transformed source code, you should really
>> use the rewriter (and tell us if that's insufficient for some reason).  If you're
>> interested in producing transformed machine code, you can either follow one
>> of Doug's suggestions or, if the code you want to emit is pretty straightforward,
>> you can alter the LLVM IR after CodeGen is done with it.
>> John.
> Thank you both for your replies.
> I am trying to make a source-to-source compiler. The reason i would
> prefer to skip the rewriter is that it supports only text.

If you're writing a source-to-source compiler, use the rewriter. It will preserve comments and code structure so that the resulting source is readable.

> I guess i
> will have to use the prettyprinter to produce the final text.

Oh, don't do that. The pretty printer will not always produce well-formed code and, even if it did, it would produce very ugly code that bears little resemblance to the input source. The pretty printer can be useful for small things, e.g., build a new Stmt or Expr to represent a transformed expression, pretty-print it into a buffer, and then replace the original text with the pretty-printed text using the rewriter.

> Also is it possible for rewriter to create a new file and write in to
> it?

Yes, of course. You can write the results anyway you want.

	- Doug

More information about the cfe-dev mailing list