I'm trying to do something like this in Bison...
loop_for: FOR var_name COLONEQUALS expression TO
{printf("%s<=", $2);} expression STEP
{printf("%s+=", $2);} expression {printf(")\n");}
Code ENDFOR
What I'm trying to do is convert a for statement from the fake language's syntax to C's. However, the $2 I've used to grab var_name doesn't seem to work as the program crashes when it reaches there. Is $x supposed to work only for integers?
I even tried adding a union and using char* for a new type, but I still get (null) from the above actions.
EDIT:
I tried to fix it using the hints from the questions that were provided, but I still can't get it perfect.
FLEX rules in question:
"FOR" {printf("for ("); lisnew=0; return FOR;}
"TO" {printf("; "); return TO;}
"STEP" {printf("; "); return STEP;}
"ENDFOR" {printf("\n"); t--; instabs(); printf("}\n"); instabs(); lisnew=1; return ENDFOR;}
[a-zA-Z]+ {printf("%s",yytext); lisnew=0; yylval.strV = yytext; return CHARACTERS;}
":=" {printf("="); lisnew=0; return COLONEQUALS;}
BISON rules:
loop_for: FOR var_name {strcpy(myvar, $<strV>2);} COLONEQUALS expression TO {printf("%s<=", myvar);} expression STEP {printf("%s+=", myvar);} expression {printf(")\n");} Code ENDFOR
var_name: name_first_is_char
name_first_is_char: character | character name2
name2: | character name2 | digit name2
Thing is, for input:
FOR i := 0 TO 10 STEP 1
I get as output:
for ( i = 0 ; i :=<= 10 ; i :=+= 1
Can't I avoid having the := symbols getting in the strV?
EDIT 2:
I tried again, this time with
var_name: name_first_is_char {memset(myvar, '\0', BUFFER_LENGTH); sprintf(myvar, "%s", $<strV>1);}
But still the next few characters get in myvar.