Muli Ben-Yehuda's journal

August 29, 2003

enumerating enums

Filed under: Uncategorized — Muli Ben-Yehuda @ 6:36 PM

Yesterday I spent a few hours working on a python script to parse C source code and automagically generate “print functions”[0] for each enum it finds. At first, I tried parsing out enums using regexps, but that turned out to be non trivial. Now I’m thinking it’ll need real parsing, with tokenizing and lexing and the whole shebang. Good chance to play with lex and yacc and their ilk, and someone already wrote a grammar file for C, but if I go that route, there’s not much point in doing it in python and I might as well stick to C. We’ll see.

[0] for example, for

enum someenum { E1 = 3, E2 } 

We would want to generate

static void print_someenum(const someenum e) 
{ 
        const char* name;
        switch(e) { 
        case E1: name = "E1"; 
                 break; 
        case E2: name = "E2"; 
                 break; 
        default: name = "eek, unkown value";
                 break;
        }

        fprintf(stdout, "%s - %d", name, (int)e); 
} 

4 Comments »

  1. Python doesn’t have something like C::Scan?
    (sorry, I’m a Perl weenie ๐Ÿ™‚

    Comment by geekosaur — August 29, 2003 @ 8:46 AM | Reply

    • I didn’t know perl had that… interesting, very interesting. I prefer to use python over perl whenever possible, but if this module does what it sounds like it does, I’ll just use it. Especially since the person I’m writing this for prefers perl over python anyway. Thanks for the tip!

      Comment by mulix — August 29, 2003 @ 1:23 PM | Reply

  2. #define
    I think I understand what you need it for. But can’t it be done with C’s “stringize” capability of macros (# and ##) ?

    Comment by Anonymous — August 31, 2003 @ 8:42 AM | Reply

    • Re: #define
      It can, but that way leads to incredibly ugly code, worthy of nomination for “best abuse of macros” at the next IOCCC. It was the first thing I did, and it was horrible.

      Comment by mulix — August 31, 2003 @ 8:48 AM | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: