preferred way to translate and output source code?

Hi,

I’m writing a source to source translation tool which accepts Clang AST and outputs source code of another language. My original plan was to traverse the AST of a translation unit and outputs corresponding source code of the target language, but I’ve noticed that there is a Rewriter and I’m not sure if the Rewriter works for my purpose.

I’ve just started using Clang AST, and I appreciate any suggestion and example.

The Rewriter is useful if you want to make small changes and keep the
remaining untouched (formatting, whitespace, ...). If you target a
different language, you probably do not want/need to preserve
anything, so a recursive traversal is the right thing to do. It also
saves you from having to handle #include and forward declarations,
which probably do not have the same semantics in your target language.

"Probably", because there are two language rewriters in clang:
RewriteObjC/RewriteModernObjC (Objective C -> C) and HTMLRewriter
(ObjC/C/C++ -> HTML)

Michael

Hi Michael,

I looked into two methods of traversing the AST. One is using libClang and its CXCursor, and the other using libTooling. From the document, it seems that libClang is good enough to traverse the AST, but when I started doing it, it isn’t easy to get the content of a node. For example, there is no interface that gives the content of a binary operator directly. For this reason, I prefer to use the libTooling library. Do you have any suggestions about which way to go?