in reply to Lexing C++

I think this approach is bound to fail.

C++ is a very complex language; e.g. here is an example program (scroll down to the first comment) that's syntactically valid if and only if the integer in the main function is a prime.

Writing a full C++ parser would be a large undertaking, especially if you start with a simple approach like the ones above, and try to add support for new language features gradually. It would be an uphill battle. At some point you'd have to stop and live with the risk that for certain inputs your incomplete parser would silently produce broken output.

So why not use the one program that is known to be able to parse C++: a C++ compiler?

Clang, for example, has options to dump the tokens it encounters:

clang foo.cpp -Xclang -dump-tokens clang foo.cpp -Xclang -dump-raw-tokens

or the full AST:

clang foo.cpp -Xclang -ast-dump

Parsing or make sense of the latter is still not trivial, but not as hopeless as writing a full C++ parser on your own.

Replies are listed 'Best First'.
Re^2: Lexing C++
by Random_Walk (Prior) on Sep 03, 2019 at 17:59 UTC


    I am actually 'only' after parsing out some details of the function signatures, some info on variable types and classes. Parsing the code to the level of execution is not my goal. Having said that I like the idea of handing it to an existing parser and getting the AST back. And I just found there is a package for Clang in the standard Ubuntu repos.



    Pereant, qui ante nos nostra dixerunt!