c - Bison Grammar For Basic Calculator Issue -


so grammar below 'works'. however, has small caveat can stuff

1.0-----------------2.0  

and flip flop between 2 , -2 until gets 1 op 2 evaluate. still new bison , unclear on how best implement fix this. have 1 idea in mind raising error every combination of '+' '-' in increments of 3 8 grammar rules , i'm not sure how throw error in bison. imagine there cleaner more understandable way this.

flex lexer

%option nounistd %option noyywrap  %{ #include <io.h> #include <stdio.h> #include <stdlib.h> #include "parser.tab.h" #define isatty _isatty #define fileno _fileno %}  %% [ \t]+ \n  {return '\n';} [0-9]+(\.[0-9]+)? {yylval.number=atof(yytext); return number;} . {return yytext[0];} %% 

bison grammar

%{     #include <stdio.h>     #include <math.h>     extern int yylex(void);     int yyerror(const char* c) { printf("%s\n",c); return 0;} %}  %union {     double number; }  %type <number> exp %token <number> number  %left '+' '-' %left '*' '/' %right '^'  %start commands %% commands     : /*empty*/     | commands line     ;  line     : '\n'     | exp '\n' {printf("=%f\n",$1);}     | error '\n' {printf("encountered error!\n");}     ;  exp     : number { $$ = $1;}     | exp '+' exp {$$ = $1 + $3;}     | exp '-' exp {$$ = $1 - $3;}     | exp '*' exp {$$ = $1 * $3;}     | exp '/' exp {$$ = $1 / $3;}     | exp '^' exp {$$ = pow($1,$3);}     | '-' exp {$$ = -$2;}     | '+' exp {$$ = $2;}     | '(' exp ')' {$$ = $2;}     ; %% 

this correct , expected behaviour arithmetic evaluation, , find works identically in language doesn't implement -- decrement operator.

if have -- operator, implement in lexer rule like:

"--"  { return decrement; } 

that guarantee a---b lexed "a", "--", "-", "b" , a----b "a", "--", "--", "b". (the latter syntax error.) that's result of "maximal munch" rule, required language standards , implemented scanner generators. (writing code discouraged not forbidden.)

in c, cannot use 2 consecutive post-decrement operators, since post-decrement expression not lvalue. can enforced in grammar requiring argument of pre- , post-decrement , -increment operators lvalue. in c++, cannot determine correctness syntactically; although horrible style, nothing stops overloading operator--(int) type return reference.

if have language without decrement operator want, aesthetic reason, ban expressions 2 consecutive unary operators, can in same way hinted above, eg.:

 value: number | '(' expr ')'  term:  value | '-' value | '+' value  expr:  term | expr '-' expr | expr '+' expr | expr '*' expr | expr '/' expr | ... 

here, cannot have --a (or -+a) because unary operator can applied value , value cannot start unary operator. end user forced use parentheses. should @ least have ready satisfactory answer end user wants know why feel necessary impose restriction.


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -