1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| chunli@blog:~$ cat eval.y %define api.pure full %locations %param { yyscan_t scanner }
%code top { #include <stdio.h> } %code requires { typedef void* yyscan_t; } %code { #define YY_EXTRA_TYPE void*
int yylex(YYSTYPE* yylvalp, YYLTYPE* yyllocp, yyscan_t scanner); void yyerror(YYLTYPE* yyllocp, yyscan_t unused, const char* msg);
char *yyget_text ( yyscan_t scanner ); int yyget_leng ( yyscan_t scanner ); FILE *yyget_in ( yyscan_t scanner ); FILE *yyget_out ( yyscan_t scanner ); int yyget_lineno ( yyscan_t scanner ); int yyget_debug ( yyscan_t scanner ); YY_EXTRA_TYPE yyget_extra ( yyscan_t scanner );
void yyset_debug ( int flag, yyscan_t scanner ); void yyset_in ( FILE * in_str , yyscan_t scanner ); void yyset_out ( FILE * out_str , yyscan_t scanner ); void yyset_lineno ( int line_number , yyscan_t scanner ); void yyset_extra ( YY_EXTRA_TYPE user_defined , yyscan_t scanner ); }
%token NUMBER UNOP %left '+' '-' %left '*' '/' '%' %precedence UNOP %% input: %empty | input expr '\n' { fprintf(yyget_out(scanner), "[%d]: %d\n", @2.first_line, $2); } | input '\n' | input error '\n' { yyerrok; } expr : NUMBER | '(' expr ')' { printf("Bison File:%s 规约识别()\n", (const char*)yyget_extra(scanner)); $$ = $2; } | '-' expr %prec UNOP { printf("Bison File:%s 规约识别 -\n", (const char*)yyget_extra(scanner)); $$ = -$2; } | expr '+' expr { printf("Bison File:%s 规约识别 +\n", (const char*)yyget_extra(scanner)); $$ = $1 + $3; } | expr '-' expr { printf("Bison File:%s 规约识别 -\n", (const char*)yyget_extra(scanner)); $$ = $1 - $3; } | expr '*' expr { printf("Bison File:%s 规约识别 *\n", (const char*)yyget_extra(scanner)); $$ = $1 * $3; } | expr '/' expr { printf("Bison File:%s 规约识别 /\n", (const char*)yyget_extra(scanner)); $$ = $1 / $3; } | expr '%' expr { printf("Bison File:%s 规约识别%%\n", (const char*)yyget_extra(scanner)); $$ = $1 % $3; }
%%
void yyerror(YYLTYPE* yyllocp, yyscan_t scanner, const char* msg) { fprintf(stderr, "Bison File:%s [%d:%d]: %s\n", (const char*)yyget_extra(scanner), yyllocp->first_line, yyllocp->first_column, msg); }
chunli@blog:~$
|