Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse C++ to create an AST?

I'm trying to parse C++ code, and create an AST. What I want to do is extract some simple reflection information(class names, member variables and their types, etc..). I don't need to compile the code, or generate binaries. I am looking for the simplest possible way to do this. Ideally, I would like a small parser, in a single static library, with no dependencies.

I've been looking around, and it appears that a Bison parser may be able to do this for me. I've tried to find an open source parser, but all google will give me is C++ wrappers for bison, and not a bison parser for C++. Typing "C++ parser" also fails, by giving results for parsers for everything else, that are written in C++.

Is there an open source project that will do what I need?

like image 630
CuriousGeorge Avatar asked Dec 12 '22 04:12

CuriousGeorge


2 Answers

clang can do this:

clang -Xclang -ast-dump -fsyntax-only test.cc

also see the docs.

like image 151
perreal Avatar answered Dec 21 '22 03:12

perreal


You can use GCC-XML to generate a fairly easy to parse XML representation of most (but not all) C++ code.

like image 35
John Zwinck Avatar answered Dec 21 '22 04:12

John Zwinck