eval.y 998 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. Syntax analyser
  3. for `bison`
  4. */
  5. %{
  6. #include <stdio.h>
  7. /* Prototypes */
  8. int yylex (void);
  9. void yyerror (const char *);
  10. /* Variable from lexical analysis */
  11. extern char* yytext;
  12. %}
  13. %defines /* Geneates eval.tab.h */
  14. %token number
  15. %start EXPR_CALCS /* Axiom */
  16. %%
  17. EXPR_CALCS : EXPR_CALC
  18. | EXPR_CALCS EXPR_CALC
  19. ;
  20. EXPR_CALC : EXPR '=' { printf("%d\n", $1); }
  21. ;
  22. EXPR : EXPR '+' FACTOR {$$ = $1 + $3;}
  23. | EXPR '-' FACTOR {$$ = $1 - $3;}
  24. | FACTOR
  25. ;
  26. FACTOR : FACTOR '*' ATOM {$$ = $1 * $3;}
  27. | FACTOR '/' ATOM {if ($3 == 0) $$ = $1; else $$ = $1 / $3;}
  28. | ATOM
  29. ;
  30. ATOM : number {$$ = $1;}
  31. | '(' EXPR ')' {$$ = $2;}
  32. ;
  33. %%
  34. #include <stdio.h>
  35. #include "eval.tab.h"
  36. void yyerror (const char * error)
  37. {
  38. fprintf (stderr, "Error detected : %s\n for expression\n%s\n", error, yytext);
  39. }
  40. int main() {
  41. if ( yyparse() != 0 ) {
  42. fprintf(stderr, "Error detected : syntax error\n");
  43. return 1;
  44. }
  45. else
  46. return 0;
  47. }