How to get string value of token in flex and bison?

I have this token in my .lex file:

[a-zA-Z0-9]+ { yylval = yytext; return ALPHANUM; } 

and this code in my .y file:

 Sentence: "Sphere(" ALPHANUM ")." { FILE* file = fopen("C:/test.txt", "a+"); char st1[] = "polySphere -name "; strcat(st1, $2); strcat(st1, ";"); fprintf(file,"%s", st1); fclose(file); } 

I get this error when I try to compile:

warning: passing argument 2 of 'strcat makes a pointer from an integer without cast

So, $ 2 is an int, how can I make it a string?

For example: "Sphere (worldGlobe)." I want $ 2 to have the string worldGlobe value here.

Thanks for any help

+4
source share
1 answer

In the absence of a declaration, %union bison defines YYSTYPE as int, so all Character Values ​​are integers. In fact, you have several solutions for this problem:

1) yylval solution | union (RECOMMENDED):
As you know, yylval is a global variable used by lexer to store the yytext variable ( yylval = yytext; ), so you must tell your lexer which types you want to store. You can simply add this line to the heading of your YACC grammar:

 #define YYSTYPE char * 

you only save string values ​​here.

By the way, if you want to store different types, you must specify yacc in your file:

 %union { char *a; double d; int fn; } 

then in your lex you will have

 [a-zA-Z0-9]+ { **yylval.a** = yytext; return ALPHANUM; } 

2) Using yytext:

Tip: for callbacks after the rules in yacc, I personally prefer to use functions. not all code like you :)

this solution is really simple. Sentence: "Sphere("{callback_your_function(yytext);} ALPHANUM ")."

yytext here will have the value of your ALPHANUM token, because this is the next token.

+7
source

Source: https://habr.com/ru/post/1387976/


All Articles