tags:

views:

122

answers:

4

Is there a library for Python that will allow me to parse c++ code?

For example, let's say I want to parse some c++ code and find the names of all classes and their member functions/variables.

I can think of a few ways to hack it together using regular expressions, but if there is an existing library it would be more helpful.

A: 

How about pyparsing?

Tuomas Pelkonen
From that site: "The pyparsing module is an alternative approach to creating and executing simple grammars". 1) c++ doesn't have a "simple" grammar. 2) Most people attempting to build a C++ parser simply fail; its a much bigger job that you might imagine.
Ira Baxter
I know it's impossible to parse C++ correctly with pyparsing, but the author of the question is not building a complier for C++ as far as I know, so pyparsing might be enough for him. Let him be the judge.
Tuomas Pelkonen
that wouldn't be helpful because i would have to write the simple grammar myself. thanks for the suggestion
Mike
... and we don't know what he really wants to really do. He clearly said, "parse C++". He also said, "...find names..." but is it limited to that? I responded to the headline question.
Ira Baxter
+3  A: 

Parsing C++ accurately is light-years from something you can do with a regular expression. You need a full C++ parser, and they're pretty hard to build. I've been involved in building one over several years, and track who is doing it; I don't know of any being attempted in Python.

The one I work on is DMS C++ Front End. It provides not only parsing, but full name and type resolution. After parsing, you can basically extract detailed information about the code at whatever level of detail you like, including arbittary details about function content.

You might consider using GCCXML, which does contain a parser, and will produce, I believe, the names of all classes, functions, and top-level variables. GCCXML won't give you any information about what's inside a function.

Ira Baxter
+1 for gccxml ... looking to be exactly what i need.
Mike
+3  A: 

In the past I've used for such purposes gccxml (a C++ parser that emits easily-parseable XML) -- I hacked up my own Python interfaces to it, but now there's a pygccxml which should package that up nicely for you.

Alex Martelli
pygccxml looks great, i hadn't noticed it before.
Georg Fritzsche
+1  A: 

This is a little outside your question's scope perhaps... but depending on what you're trying to achieve, perhaps Exuberant Ctags is worth looking at.

Craig McQueen
good suggestion, it would be even more helpful if there was a library that could parse the ctags output
Mike