What is the purpose of union in the yacc file? Is it directly related to yylval in the flex file? If you don't use yylval, then you don't need to use union?
By default, the yylval variable has the int type.
The yylval global variable is used to pass the semantic value associated with a token from the lexer to the parser. The semantic values of symbols are accessed in yacc actions as $1 , $2 , etc and are set for non-terminals by assigning to $$ .
The %union declaration specifies the entire collection of possible data types for semantic values. The keyword %union is followed by braced code containing the same thing that goes inside a union in C.
The YYSTYPE is a union with a member for each type of token defined within the yacc source file.
The purpose of the union
is to allow storing different kind of objects into nodes emitted by flex.
To explain better you can have for example:
%union { int intValue; float floatValue; char *stringValue; }
in .y
if you want to provide basic support for int
, float
and string
types. What can you do with this?
Two things:
First, you can automatically set right values when generating tokens. Think about .l
file of the previous example, you can have:
[a-zA-Z][a-zA-Z0-9]* { yylval.stringValue = strdup(yytext); return IDENTIFIER; } [0-9]+ { yylval.intValue = atoi(yytext); return INTEGER; } [0-9]*\.[0-9]+"f"? { yylval.floatValue = new atof(yytext); return FLOAT; }
In addition you can use value directly in your flex grammar:
nexp: nexp '+' nexp { $<floatValue>$ = $<floatValue>1 + $<floatValue>3 }
Finally if you plan to use an OOP syntax tree you can define union as
%union { class ASTNode *node; }
in which ASTNode
is the ancestor class of any kind of syntax node.
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