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

99封情书 提交于 2019-12-06 05:50:10

问题


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 pointer from integer without a cast

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

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

Thanks for any help


回答1:


In the absence of a %union declaration, bison defines YYSTYPE to be int, so all of the symbol values are integers. In fact you have a few solutions for this problem:

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

#define YYSTYPE char *

you will store here only string values.

By the way if you want to store different types you should specify in your yacc 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:

Advice: for callbacks after rules in yacc i,personally prefer to use functions. not the whole code as you do :)

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

the yytext here will have the value of your ALPHANUM token because it's the next token.



来源:https://stackoverflow.com/questions/8632516/how-to-get-string-value-of-token-in-flex-and-bison

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!