[cfe-dev] How to use Clang to translate from C++ to another language

Douglas Gregor dgregor at apple.com
Wed Mar 28 08:21:50 PDT 2012


On Mar 28, 2012, at 3:26 AM, David Chisnall wrote:

> On 28 Mar 2012, at 03:37, Tim Stowell wrote:
> 
>> I've recently compiled Clang and LLVM on Windows. My goal is to use it to translate from C++ to another language (specifically Actionscript), but I'm not sure the best way to go about this. For example, if I invoke clang with the -ast-print "pretty print" option, it looks like Clang can get a faithful representation of the original code from its internal AST. Do I need to somehow mimic that code so I get a pretty print in my new language? Or should I walk the AST tree? Thanks for any help! 
> 
> Yes, that's likely to be the best approach - it's what I did to translate Objective-C to JavaScript.  You will probably want to create a clang plugin that subclasses RecursiveASTVisitor.  This should walk the AST and emit code for your target language.  
> 
> You could use the rewriter, but I would strongly recommend against it.  For example, when translating a class with multiple inheritance into ActionScript you will need to create a class that composes them and then turn pointer casts into some fairly complex logic for accessing the relevant class (upcasts, in particular, are going to be especially horrible - no idea how you plan on implementing these) so trying to do simple rewriting is going to involve a lot more pain than simply writing out a new program from the AST.


Right. The rewriter is good when you're just changing from one dialect to another within the same base language---Objective-C to C, C99 to C90, etc.---and want to preserve comments and code structure for all of the common parts. If the two languages are very different (C++ to Actionscript), you should either be transforming IR or walking the AST.

	- Doug



More information about the cfe-dev mailing list