0

I am getting an error in my parser for a toy language I am making. Here is some of my parser code:

%union {
  char* <sval>;
}

%token INTEGER
%token INTDEC FLODEC AS
%token <sval> VARIABLE
%token POINT LBRACKET RBRACKET
%token SHOW ESC
%left '+' '-'
%left '*' '/' MODULO FACTORIAL FLOOR
%left '^'

%code requires {
  #define YYSTYPE float
}

And some of my lexer code:

    as                         {return AS;}
float                      {return FLODEC;}
show                       {return SHOW;}
int                        {return INTDEC;}
esc                        {return ESC;}
\.                         {return POINT;}
{integer}                  {yylval = atoi(yytext); return INTEGER;}
[a-zA-Z]+                  {yylval.sval = strdup(yytext); return VARIABLE;}
["\\"]                     {return FLOOR;}
[-+/=*^\n]                 {return *yytext;}
["("]                      {return LBRACKET;}
[")"]                      {return RBRACKET;}
["!"]                      {return FACTORIAL;}
["%%"]                     {return MODULO;}
[" \t\n"]
.                          {printf("Syntax error");}

How do I fix this as I think this is actually in a union but I am not sure what to do.

  • You cannot have both `yylval = atoi(yytext);` and `yylval.sval = strdup(yytext);` It is either a union or an integer, not both things at the same time. – n. m. could be an AI Aug 19 '20 at 16:54

1 Answers1

0
char* <sval>;

is not a valid C member declaration, and %union members are just C member declarations. (Yacc/bison copies them literally into a union declaration.) So attempting to compile that code is bound to produce a compile-time error message in the declaration of the union YYSTYPE. Subsequent code will not be able to use union YYSTYPE because it has not been correctly declared, and therefore will produce the error message shown.

Moreover, once you have declared that the semantic type is a union, your lexical scanner actions need to be adjusted accordingly. You will not be able to compile

yylval = strdup(yytext);

because yylval has type union YYSTYPE and a union can only be assigned to from another union variable of the same type. You'll need to change that to

yylval.sval = strdup(yytext);

Your other yylval assignment will need to be dealt with in the same way, but you don't seem to have appropriate union members for them in your %union declaration, so you'll have to start by fixing that.

rici
  • 234,347
  • 28
  • 237
  • 341