0

I'm having some problems with operator management increase and decrease (prefixes and postfixes) using Flex / Bison, below is another answer :

How to fix YACC shift/reduce conflicts from post-increment operator?

I have read that the best solution seems to be to declare them as %nonassoc or in some cases use %right, I'm a little confused:

inserting these parameters I expect these results :

 1 + ++1 ;  // 3
 1 + 1++ ;  // 2
 1 + --1 ;  // 1
 1 + 1-- ;  // 2

however I receive this as an output :

1-3
2-3
2-3
2-3

I'll post the source I use :

...

%right  tplus tmin 
%nonassoc tINC tDEC      

...

%type<integer> expr program

%%

program: expr tPV           {printf ( "1-%d\n",$$); }
    | program expr tPV      {printf ( "2-%d\n",$$); }
    ;


expr: tINTEGER               { $$ = $1; }
    | expr tPLUS expr           { $$ = $1 + $3; }
    | expr tMIN expr            { $$ = $1 - $3; }
    | expr tMUL expr            { $$ = $1 * $3; }
    | expr tDIV expr            { $$ = $1 / $3; }
    | expr tMOD expr            { $$ = $1 % $3; }

    | tPLUS expr  %prec tplus     { $$ =  $2; }
    | tMIN  expr  %prec tmin      { $$ = -$2; }

    | tINC expr                   { $$ = ++$2;    }
    | expr tINC                   { $$ =  $1++;   }
    | tDEC expr                   { $$ = --$2;    }
    | expr tDEC                   { $$ =  $1--;   }

    | tP0 expr tP1                { $$ =  $2; }
    ;

%%

can you give me some suggestions? Thanks in advance Claudio

Solution :

program: line
    | program line
    ;
line: tPV { } 
    | expr tPV { printf("\n[%d]\n", $1); }
    ;

the error was not in grammar, but in non-terminal !

output :

main.exe < prova.txt

[3]

[2]

[1]

[2]
Stephan
  • 531
  • 3
  • 16
  • 3
    My suggestion is that you think carefully about what `$$` means in `program expr tPV {printf ( "2-%d\n",$$); }`. Even with the application of the preaction `$$ = $1;` that's not going to print the value of `expr`. – rici Oct 30 '18 at 21:00
  • Found Error : you are right. –  Oct 30 '18 at 21:04

0 Answers0