Handling #define macros in yacc/bison lex
-
06-07-2019 - |
Question
How would I implement #define
macros with yacc/bison?
I was thinking all define characters must match a regular variable. Variables are defined as [a-zA-Z_][a-zA-Z0-9_]*
so I figure I can put a check there to see if the variable is a define'd worked or not. Then replace the text with what it should be.
How can i do that? Right now I want to completely ignore the word BAD as if I defined it as #define BAD
in C. Below is the code for that lex rule but I am doing it wrong. Also lex complains about "BA" being in the stream. I know the below is completely wrong and illogical so how do I ignore BAD and then how do I 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 major steps are 1) define the define, 2) detect it in source 3) make lex forget the macro characters 4) insert the new correct characters.
Solution
Put a rule in lex to find the define. Then use unput to insert the replacement text. Note the text is to be inserted backwards
[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;
}