Question about printing abstract syntax tree in Clang

Hello everyone,

This is Yang Ye, a new researcher working on Clang. I want to use
clang to print out the abstract syntax tree in a human readable, not
getting the binary bytecode one.
Can anyone show me how to use the API to do it?

Another question, I found some sample code on the website about
dumping the CFG, it uses:

Stmt* FooBody = ...
CFG* FooCFG = CFG::buildCFG(FooBody);

This is also helpful, but how can I construct a statement from give code?

Thanks a lot

Another question please, can anyone help describe, if I have a class
definition in C++, what will it be like in the parsed result ----
abstract syntax tree?

Say for the class definition:

class A{
   int a;
   int b;
   bool c;

what will it be like in the parsed resulted AST?

Thank you!

Currently you can use ‘clang -cc1 -ast-dump’ to get this. The code is driven from ASTPrinter defined here:

However, if you’re interested in this type of walk, I’d suggest you consider the RecursiveASTVisitor:

It’s not complete yet, so it misses a few parts of the AST, but it’s being actively developed by several folks who are interested in similar walks of the AST.


The CFG is just a layer on top of the ASTs. The basic blocks consist of CFGElements, which is a discriminated union to represent references to statements, etc. Currently CFGElements only wrap Stmt*, but in the near future they will also represent destructor calls, etc. Going back to the AST is as simple as iterating over the CFG.

To pretty-print the AST, there are a variety of dumpers. The Stmt class has a dumpPretty() and dumpMethod(), for example. The dumpPretty() method is not intended, however, to reprint the original code as it was written.

Thanks! So can anyone show me a full tool chain of functions using the
Clang API, and a c++ file as input, then get the output of AST or CFG?
(not using clang -cc1 -ast-dump xx.cpp)