%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
void yyerror(const char *s);
%}
%token NUM
%left '+' '-'
%left '*' '/'
%%
expr:
expr '+' expr { printf("%d\n", $1 + $3); }
| expr '-' expr { printf("%d\n", $1 - $3); }
| expr '*' expr { printf("%d\n", $1 * $3); }
| expr '/' expr {
if ($3 == 0) {
yyerror("Division by zero!");
} else {
printf("%d\n", $1 / $3);
}
}
| '(' expr ')' { $$ = $2; }
| NUM { $$ = $1; }
;
%%
void yyerror(const char *s) {
fprintf(stderr, "Error: %s\n", s);
}
int main() {
printf("Enter an arithmetic expression:\n");
yyparse();
return 0;
}
JXsKI2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KCmludCB5eWxleCh2b2lkKTsKdm9pZCB5eWVycm9yKGNvbnN0IGNoYXIgKnMpOwolfQoKJXRva2VuIE5VTQolbGVmdCAnKycgJy0nCiVsZWZ0ICcqJyAnLycKCiUlCgpleHByOgogICAgICBleHByICcrJyBleHByICB7IHByaW50ZigiJWRcbiIsICQxICsgJDMpOyB9CiAgICB8IGV4cHIgJy0nIGV4cHIgIHsgcHJpbnRmKCIlZFxuIiwgJDEgLSAkMyk7IH0KICAgIHwgZXhwciAnKicgZXhwciAgeyBwcmludGYoIiVkXG4iLCAkMSAqICQzKTsgfQogICAgfCBleHByICcvJyBleHByICB7IAogICAgICAgICAgICAgICAgICAgICAgICBpZiAoJDMgPT0gMCkgewogICAgICAgICAgICAgICAgICAgICAgICAgICAgeXllcnJvcigiRGl2aXNpb24gYnkgemVybyEiKTsKICAgICAgICAgICAgICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgICAgICAgICAgICAgIHByaW50ZigiJWRcbiIsICQxIC8gJDMpOwogICAgICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICAgICAgICB9CiAgICB8ICcoJyBleHByICcpJyAgICB7ICQkID0gJDI7IH0KICAgIHwgTlVNICAgICAgICAgICAgIHsgJCQgPSAkMTsgfQogICAgOwoKJSUKCnZvaWQgeXllcnJvcihjb25zdCBjaGFyICpzKSB7CiAgICBmcHJpbnRmKHN0ZGVyciwgIkVycm9yOiAlc1xuIiwgcyk7Cn0KCmludCBtYWluKCkgewogICAgcHJpbnRmKCJFbnRlciBhbiBhcml0aG1ldGljIGV4cHJlc3Npb246XG4iKTsKICAgIHl5cGFyc2UoKTsKICAgIHJldHVybiAwOwp9Cg==