先上cal.l代码:
%{
#include <string.h>
#include "cal.tab.h"
#define YY_SKIP_YYWRAP
extern int yylval;
int yylex(void);
%}
numbers ([0-9])+
plus "+"
minus "-"
times "*"
divide "/"
lp "("
rp ")"
delim [ \n\t]
ws {delim}*
%%
{numbers} {
sscanf(yytext, "%d", &yylval);
return INTEGER;
}
{plus} {
return PLUS;
}
{minus} {
return MINUS;
}
{times} {
return TIMES;
}
{divide} {
return DIVIDE;
}
{lp} {
return LP;
}
{rp} {
return RP;
}
{ws} {
}
. {
}
%%
再上cal.y代码:
%{
#include <stdio.h>
#include "lex.yy.c"
#define YYSTYPE int
int yyparse(void);
void yyerror(char* s);
%}
%token PLUS MINUS TIMES DIVIDE INTEGER LP RP
%%
command: exp {printf("%d\n", $1);}
exp: exp PLUS term {$$ = $1 + $3;}
| exp MINUS term {$$ = $1 - $3;}
| term {$$ = $1;}
;
term: term TIMES factor {$$ = $1 * $3;}
| term DIVIDE factor {$$ = $1 / $3;}
| factor {$$ = $1;}
;
factor: INTEGER {$$ = $1;}
| LP exp RP {$$ = $2;}
;
%%
int main(int argc, char *argv[]) {
return yyparse();
}
int yywrap() {
return 1;
}
void yyerror(char* s) {
printf("error: %s\n", s);
}
编译出c代码:
bison.exe -d cal.y
flex cal.l
再编译cal.tab.c得到exe文件,测试:
离线