ob_dev
ob_dev

Reputation: 2838

Who modify the type of $$ in a yacc grammar

I want to change the define $$ as a struct in the following grammar i have declared yylval as str, but i have errors when compile the .c file with gcc

gcc *.c -ly 
tp.l: In function ‘yylex’:
tp.l:12: error: request for member ‘sum’ in something not a structure or union
y.tab.c:1035: error: conflicting types for ‘yylval’
tp.y:11: note: previous declaration of ‘yylval’ was here

the yacc file:

 %{
        #include <ctype.h>
        #include <stdio.h>
        #include <stdlib.h>

        typedef struct {
            int val;
            int cpt;
        } str;

        str yylval;

%}
        %start  start 
        %token  number

%%
    start : number'+'number'\n'
    ;

%%

int main(void)
{
        yyparse();
        return 0;
}

the lex file :

%option noyywrap

%{
    #include<stdio.h>
    #include<stdlib.h>
    #include<ctype.h>
    #include"y.tab.h"
%}

%%
[0-9]+  {
            yylval = atoi(yytext); 
            return number;
        }

"+"     return '+';
\n      return '\n';
" " ;

%%

Upvotes: 0

Views: 1278

Answers (1)

Kaz
Kaz

Reputation: 58617

You cannot define your own yylval. The generated code already defines this. Use the %union directive to define the type indirectly. If that is not suitable, then what you can do is redefine the macro YYSTYPE which expands to arbitrary type specifiers. For instance:

struct my_semantic_attributes {
  int foo;
  /* ... */
};

#define YYSTYPE struct my_semantic_attributes

Upvotes: 3

Related Questions