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.


In reply to Re: Lexing C++ by kikuchiyo
in thread Lexing C++ by Random_Walk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.