سؤال

in my final project left me several codes, one of them is this for flex & bison. The problem is that gcc returns me the message "request for member 'db' in something not a structure or union" in bison file ... I do not know how to fix this, I find examples of solutions but none works for me. I hope I can help, thanks in advance.

Flex file:

%{
 #include <stdlib.h>
 #include "y.tab.h"
 #include <stdio.h>
 #include <string.h>
 #include <ctype.h>
%}
%option noyywrap
%option yylineno
digit   [0-9]
blank   [\t]
sign    [+-/*]
other   .

%%

{digit}+            { sscanf(yytext, "%lf", &yylval.db); return NUMBER;}
{digit}+\.{digit}*  { sscanf(yytext, "%lf", &yylval.db); return NUMBER;}
\.{digit}+          { sscanf(yytext, "%lf", &yylval.db); return NUMBER;} 
sign                return *yytext;
{blank}+            ; 
{other}             return yytext[0];


%%

int main()
{
 if (yyparse()==0){
 printf("\n NO ERROR");}
 return 0;
}

int yyerror(char * mensaje)
{
 printf("\n AND STOP");
 printf("\n ERROR: %s",mensaje);
 printf("\n ERROR LINE: %d",yylineno);
 return 0;
}

Bison File:

%{
    #include <stdio.h>
    #include <stdlib.h> 
    char result[100];
%}

%union { double db; int i; }
%token NUMBER
%left '-' '+'
%left '*' '/'
%left '(' ')'
%nonassoc UMINUS 
%type<db> list NUMBER
%type<i> expression
%start list

%%

list    : expression { printf("\nResultado: %5g\n",$$.db);} 
        ;
expression  : expression '+' expression { $$.db = $1.db + $3.db; }
            | expression '-' expression { $$.db = $1.db - $3.db; }
            | expression '*' expression { $$.db = $1.db * $3.db; }
            | expression '/' expression {  if ($3.db==(double)0) yyerror("Division por cero\n");    
                                           else  $$.db = $1.db / $3.db; }
            | '-' expression %prec UMINUS { $$.db = -$2.db; }
            | '(' expression ')'                   { $$.db = $2.db; }
            | NUMBER                            { $$.db = $1.db; } 
            ;
هل كانت مفيدة؟

المحلول

When you declare that expression has type i (%type<i> expression), you're telling bison that wherever you've put an expression, the stack value should be the .i variant. So in all of the expression productions, $$ already represents the .i union member; if you write an explicit .db, then you end up generating yylval.i.db. But yylval.i is an int, which is not a strut or a union and therefore cannot have any members.

I strongly suspect that you intended the type of expression to be db, but whatever it is, you don't have to (and in fact cannot) explicitly specify the union member in your action.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top