accessing clang's AST

Hi,

I would like to use the AST already generated by clang to perform some transformations. I am new to clang & llvm and I was wondering if I could get a couple of pointers. Is there a good example which initializes the parser and traverser the AST?

Thank!

– Octav

Octav Chipara wrote:

Hi,

I would like to use the AST already generated by clang to perform some
transformations. I am new to clang & llvm and I was wondering if I could
get a couple of pointers. Is there a good example which initializes the
parser and traverser the AST?

Yes! Take a look at lib/Frontend/RewriteObjC.cpp. It uses the Rewriter
library to take a fully-parsed AST for an ObjC program and turn it into C++.

Also, have a look at the CompilerInstance and CompilerInvocation classes
from the Frontend library. They will really come in handy for setting up
your environment.

Chip

Dear Chip,

Thanks for the info. Is there an plug-in the exports the AST? I tried the ast-dump, however, it crashes:

0x10490e360 Assertion failed: (0 && “Unexpected decl”), function DumpDeclarator, file StmtDumper.cpp, line 263.

Thanks,
– Octav

Octav Chipara wrote:

Dear Chip,

Thanks for the info. Is there an plug-in the exports the AST?

No. However, it's really not necessary. If you derive a class from
ASTConsumer (from the AST library), you will be fed each top-level
declaration from the AST as the parser builds it up (see
ASTConsumer::HandleTopLevelDecl()). Or, you can traverse the AST all at
once by implementing the HandleTranslationUnit() method (also in
ASTConsumer), which receives a translation unit decl from which you can
get every other node in the AST.

I tried
the ast-dump, however, it crashes:

0x10490e360 Assertion failed: (0 && "Unexpected decl"), function
DumpDeclarator, file StmtDumper.cpp, line 263.

That's not supposed to happen.

Can we see the source that caused this? Put it up on pastebin or some such.

Chip

The AST dumper does not handle all decl kinds (nor does the AST printer, IIRC). It would be helpful if someone were to contribute a patch dumping the remaining decl kinds.

Sure. Here it is http://pastebin.com/mgMyzuTb

– Octav

Dear Charles,

To make things easier, below is a much simpler program that crashes the adt-dump:

#include
int main() {
}

– Octav

In lib/FrontEnd there is quite a bit of code for printing the AST to XML. Does that work and if so how can you invoke it?

Thanks a bunch,
– Octav

Octav Chipara schrieb:

In lib/FrontEnd there is quite a bit of code for printing the AST to XML. Does that work and if so how can you invoke it?

-ast-print-xml is the option to invoke xml export. Leave me a note if
it's not working properly.

Best Olaf