Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Lexing C++

by kikuchiyo (Hermit)
on Sep 02, 2019 at 21:24 UTC ( [id://11105475]=note: print w/replies, xml ) Need Help??


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

    kikuchiyo++

    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.

    Thanks!

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11105475]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-19 17:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found