fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <ctype.h>
  5. int yylex();
  6. void yyerror(const char *s);
  7. int yylval;
  8. %}
  9. %token NUMBER
  10. %left '+' '-'
  11. %left '*' '/'
  12. %right UMINUS
  13. %%
  14.  
  15. stmt_list: stmt_list expr '\n' { printf("Result: %d\n", $2); }
  16. | expr '\n' { printf("Result: %d\n", $1); }
  17. ;
  18.  
  19. expr: expr '+' expr { $$ = $1 + $3; }
  20. | expr '-' expr { $$ = $1 - $3; }
  21. | expr '*' expr { $$ = $1 * $3; }
  22. | expr '/' expr {
  23. if ($3 == 0) {
  24. yyerror("Division by zero!");
  25. $$ = 0;
  26. } else {
  27. $$ = $1 / $3;
  28. }
  29. }
  30. | '-' expr %prec UMINUS { $$ = -$2; }
  31. | '(' expr ')' { $$ = $2; }
  32. | NUMBER { $$ = $1; }
  33. ;
  34.  
  35. %%
  36.  
  37. int yylex() {
  38. int c;
  39.  
  40. while ((c = getchar()) == ' ' || c == '\t');
  41. if (isdigit(c)) {
  42. ungetc(c, stdin);
  43. scanf("%d", &yylval);
  44. return NUMBER;
  45. }
  46. if (c == '\n' || c == EOF) return c;
  47. return c;
  48. }
  49.  
  50. void yyerror(const char *s) {
  51. fprintf(stderr, "Error: %s\n", s);
  52. }
  53.  
  54.  
Success #stdin #stdout #stderr 0.03s 6952KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/N7ptDm/prog:53:0: Syntax error: end_of_file_in_quasi_quotation
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit