Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yylval and union

Tags:

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?

like image 796
neuromancer Avatar asked Dec 05 '09 19:12

neuromancer


People also ask

What type is Yylval?

By default, the yylval variable has the int type.

What is the use of Yylval?

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 $$ .

What is Union in bison?

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.

What is Yystype?

The YYSTYPE is a union with a member for each type of token defined within the yacc source file.


1 Answers

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.

like image 104
Jack Avatar answered Sep 21 '22 00:09

Jack