%{ /* C DECLARATIONS */ #include #include void yyerror( char *s); int yylex(); #define YYDEBUG 1 #define YYERROR_VERBOSE 1 #define YYINITDEPTH 20 %} /* BISON DECLARATIONS */ %raw %token NUM %% /* GRAMMAR RULES */ A: NUM { printf("%d\n",$$); } | A '+' NUM { $$ = $1 + $3; printf("%d\n",$$); } | A '-' NUM { $$ = $1 - $3; printf("%d\n",$$); }; %% /* ADDITIONAL C CODE */ FILE* input_file; int yylex() { int c; yylex1: switch( c=getc(input_file)) { case EOF: printf("end of file\n"); return 0; case '+': printf("+ returned\n"); return '+'; case '-': printf("- returned\n"); return '-'; case '#': { fscanf(input_file,"%d",&yylval); printf("%d returned\n",yylval); return NUM; } default: break; } goto yylex1; } int main() { #if YYDEBUG != 0 yydebug = -1; #endif if( (input_file=fopen("input.txt","r")) == NULL) {printf("opening file error\n"); return -1;} if( yyparse() != 0 ) printf("unknown error\n"); if( fclose( input_file) == EOF) {printf("closing file error\n"); return -1;} return 0; } void yyerror(char *s) { printf("shit happens: %s\n",s); return; }