hi im confusing about how to get a char* when i read a specific token... I look in various sites and they provide suggestions but not complete, i mean, for example yylval and yytext declaration is missing or how to transform the types, etc
What is need in .l file? What is need in .y file?
What I have
in the .l file:
{WORD} { yylval = strdup(yytext);return T_ValidWord;}
in the .y file:
%union{
char *str;
}
%token<str> T_ValidWord
%%
element:
T_OpenTag T_ValidWord ele1 {printf("%s", $2);}
;
The error:
xml.lex: In function ‘yylex’:
xml.lex:34: error: incompatible types when assigning to type ‘YYSTYPE’ from type ‘char *’
Other thing more that confused me: In some places i see
yylval->something = yytext
yylval.something = yytext
yylval = yytext
In the manual of bison tell that yylval is a macro, I understand that a macro is text replaced for other text, but in this situation i really don't get it.
yylval is a union type YYSTYPE. Change your assignment in the scanner to yylval. str = strdup(yytext) . yylval is a union which you can either declare or the bison will declare automatically.
extern yylval; means that yylval is defined somewhere else. So you have to do that. Usually it is defined in the yacc/bison generated parser, so the name can be resolved when you link the scanner and the parser. If you aren't using bison/yacc, you will have to define yylval yourself. (If you actually need it.
yylval is a union type YYSTYPE. Change your assignment in the scanner to yylval.str = strdup(yytext)
.
yylval is a union which you can either declare or the bison will declare automatically. Bison's default yylval is essentially useless. You declare yylval using %union { ... }
in your parser because you may need to return other values from the scanner to the parser. For example, when you match a number in your scanner, you'll want to return a token like T_NUM
. But you most probably also want the value of that number, which is where yylval comes handy. Using yylval, if you have an integer field, you could simply do yylval.num = atoi(yytext)
inside your scanner, and then use that num field in the parser.
yytext is an array of characters, which acts as a buffer for the input currently being parsed. You cannot declare yytext, and neither should you.
When you use bison to compile the parser into a .tab.c file, use the flags bison -d -t
for debugging symbols and the header file. The header file will be called *.tab.h. Include that in your scanner so you only need to declare token names once and have proper use of yylval.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With