#Define macro handling in yacc / bison lex

How do I implement macros #define

with yacc / bison?

I thought that all defining characters should match a regular variable. Variables are defined as [a-zA-Z_][a-zA-Z0-9_]*

, so I figure I can put a check in there to check if the variable is define'd or not. Then replace the text with what it should be.

How can i do this? Right now, I want to completely ignore the word BAD as if I had defined it as #define BAD

in C. Below is the code for this lex rule, but I am doing it wrong. Also lex complains about "BA" being in the stream. I know below is all wrong and illogical since I am ignoring BAD and then how to replace it with something like float

    if(strcmp(yytext, "BAD")==0) {
        int i, l = strlen(yytext);
        for(i=0; i<l; i++) { REJECT }
        return;
    }
    return VAR; }

      

I know the basic steps are 1) define the definition, 2) find it in the source 3) make lex forget macros; 4) insert new correct symbols.

+2


source to share


1 answer


Put the rule in lex to find the definition. Then use unput to insert the replacement text. Please note that the text should be pasted back



[a-zA-Z0-9_]* {
        if(strcmp(yytext, "HARDCODED_DEFINE")==0) {
            const char s[]="int replacement_text";
            int z;
            for(z=strlen(s)-1; z>=0; z--)
                unput(s[z]);
        }
        else
            return VAR_TOK; 
        }

      

+2


source







All Articles