This isn't particularly hard if you pick the right approach. I think the easiest way it to tokenize the language you are parsing and then build a simple state machine to parse just enough of the tokens to get the information you want.

Since type declarations can contain parens (though usually don't) I settled on considering ") {" as the start of a function body. I think that can't happen elsewhere in valid C code. I didn't check my POD syntax and the code is very imcomplete, intentionally.

=for state_machine START \n -> {flush} START ws -> START else -> DECL DECL ; -> {flush} START ) -> CLOSE CLOSE { -> {block=1} FUNC else -> DECL FUNC { -> {++block} FUNC } -> { --block ? FUNC : END } END ws -> END \n -> {save} START else -> {save} DECL =end use enum qw( START DECL CLOSE FUNC END ); my $state= START(); my $part= ''; while( $code =~ m{ \G( \n # newline | [^\S\n]+ # horizontal whitespace | [a-z]\w* # identifier | \d+ # digit string | "(?:[^\\"]+|\\[^\n])*" | '(?:[^\\']+|\\[^\n])*' | /\*.*?\*/ # C comment | //[^\n]*\n # C++ comment | [^\w\s] # punctuation mark ) }xsg ) { my $token= $1; if( START() == $state ) { if( $token eq "\n" ) { $token= $part= ''; } elsif( $token =~ /\S/ ) { $state= DECL(); } ... } elsif( END() == $state ) { if( $token =~ /\S/ ) { push @func, $part; $part= ''; ... } } $part .= $token; }

And it is pretty easy to extend the state machine to track nesting of parens so you can extract the identifier before the last outer open paren before the body of the function is detected, for example (which would be the name of the function).

- tye        


In reply to Re: Parsing C Functions.. (tokens) by tye
in thread Parsing C Functions.. by jmmistrot

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.