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); 
} 

Blog at WordPress.com.