Search code examples
parsingcompiler-constructiongrammarbison

Grammar of calculator in a finite field


I have a working calculator apart from one thing: unary operator '-'.

It has to be evaluated and dealt with in 2 difference cases:

  1. When there is some expression further like so -(3+3)
  2. When there isn't: -3

For case 1, I want to get a postfix output 3 3 + - For case 2, I want to get just correct value of this token in this field, so for example in Z10 it's 10-3 = 7.

My current idea:

E:  ...
    |   '-' NUM %prec NEGATIVE      { $$ = correct(-yylval); appendNumber($$);          }
    |   '-' E %prec NEGATIVE        { $$ = correct(P-$2); strcat(rpn, "-");                                 }
    |   NUM     { appendNumber(yylval); $$ = correct(yylval); }

Where NUM is a token, but obviously compiler says there is a confict reduce/reduce as E can also be a NUM in some cases, altough it works I want to get rid of the compilator warning.. and I ran out of ideas.


Solution

  • It has to be evaluated and dealt with in 2 difference cases:

    No it doesn't. The cases are not distinct.

    Both - E and - NUM are incorrect. The correct grammar would be something like:

    primary
        : NUM
        | '-' primary
        | '+' primary /* for completeness */
        | '(' expression ')'
        ;