fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int yylex(void);
  6. void yyerror(char *s);
  7. %}
  8.  
  9. %token NUMBER
  10. %left '+' '-'
  11. %left '*' '/'
  12. %left NEG
  13.  
  14. %%
  15.  
  16. expr:
  17. expr '+' expr { $$ = $1 + $3; }
  18. | expr '-' expr { $$ = $1 - $3; }
  19. | expr '*' expr { $$ = $1 * $3; }
  20. | expr '/' expr {
  21. if ($3 == 0) {
  22. yyerror("Error: Division by zero.");
  23. YYABORT;
  24. }
  25. $$ = $1 / $3;
  26. }
  27. | '(' expr ')' { $$ = $2; }
  28. | NUMBER { $$ = $1; }
  29. ;
  30.  
  31. %%
  32.  
  33. /* Lexical Analyzer (Flex section) */
  34.  
  35. %{
  36. #include "y.tab.h"
  37. %}
  38.  
  39. %%
  40. [0-9]+ { yylval = atoi(yytext); return NUMBER; }
  41. "+" { return '+'; }
  42. "-" { return '-'; }
  43. "*" { return '*'; }
  44. "/" { return '/'; }
  45. "(" { return '('; }
  46. ")" { return ')'; }
  47. [ \t\n] { /* Ignore whitespace */ }
  48. . { printf("Unexpected character: %s\n", yytext); return 0; }
  49. %%
  50.  
  51. /* Error handling */
  52. void yyerror(char *s) {
  53. fprintf(stderr, "%s\n", s);
  54. }
  55.  
  56. int main(void) {
  57. printf("Enter an arithmetic expression: ");
  58. if (yyparse() == 0) {
  59. printf("Valid arithmetic expression\n");
  60. } else {
  61. printf("Invalid arithmetic expression\n");
  62. }
  63. return 0;
  64. }
  65.  
Success #stdin #stdout #stderr 0.03s 6872KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/FsxVFU/prog:2:1: Syntax error: Operator expected
ERROR: /home/FsxVFU/prog:64:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit