calc.y 750 B

123456789101112131415161718192021222324252627282930313233
  1. %{
  2. #define YYSTYPE double
  3. #include <stdio.h>
  4. // yylex() is generated by flex
  5. int yylex(void);
  6. // we have to define yyerror()
  7. int yyerror (char const *);
  8. %}
  9. %token NUMBER
  10. %left '+' '-'
  11. %left '*' '/'
  12. %right '('
  13. %%
  14. stmtlist: statement '\n' stmtlist {
  15. printf("done with statement equal to [%g]\n", $1);
  16. } | // EMPTY RULE i.e. stmtlist -> nil
  17. { printf("DONE\n") ;};
  18. statement: expression { printf("VALUE=%g\n",$1); };
  19. expression: expression '+' expression { $$ = $1 + $3; } |
  20. expression '-' expression { $$ = $1 - $3; } |
  21. expression '*' expression { $$ = $1 * $3; } |
  22. expression '/' expression {
  23. if($3 !=0) { $$ = $1 / $3; } else
  24. { printf("div by zero\n"); $$=0;} } |
  25. '(' expression ')' { $$ = $2; } |
  26. NUMBER { $$ = $1; } ;
  27. %%