Lucas Meijer Lucas Meijer - 2 months ago 14
C++ Question

get human readable AST from c++ code

In order to get a better understanding of some of the details of the C++ language and grammer, I would love to be able to write a small C++ program, and see the AST that a compiler generates from that.

It looks like clang had this feature in the past (-emit-asm), but it has removed.

Is there an easy way to do this today?


clang still has that functionality:

The commands are -ast-dump and -ast-dump-xml

Note: -ast-dump-xml will only work when you build clang in debug mode.

For example:

## cat test.cpp 
int main()
return 0;

##clang++ -cc1 -ast-dump-xml test.cpp                                       
<TranslationUnit ptr="0x4e42660">
 <Typedef ptr="0x4e42bd0" name="__builtin_va_list" typeptr="0x0">
  <PointerType ptr="0x4e42b90" canonical="0x4e42b90">
   <BuiltinType ptr="0x4e426f0" canonical="0x4e426f0"/>
 <Function ptr="0x4e42c70" name="main" returnzero="true" prototype="true">
  <FunctionProtoType ptr="0x4e42c20" canonical="0x4e42c20">
   <BuiltinType ptr="0x4e42750" canonical="0x4e42750"/>
CompoundStmt 0x4e42d78 <test.cpp:2:1, line:4:1>
`-ReturnStmt 0x4e42d58 <line:3:1, col:8>
  `-IntegerLiteral 0x4e42d38 <col:8> 'int' 0