计算器主要实现了整数的加、减、乘、除、括号以及绝对值运算。其中,绝对值符号用|
表示。
FLex词法分析
calculator.l
%{
#include "calculator.tab.h"
%}
%option noyywrap
%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
"(" { return OP; }
")" { return CP; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
"//".*
[ \t] { /* ignore white space */ }
. { fprintf(stderr, "Mystery character %c\n", *yytext); }
%%
Bison语法分析
calculator.y
%{
#include <stdio.h>
int yylex (void);
void yyerror (const char *);
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token OP CP
%token EOL
%%
calclist: /* nothing */
| calclist exp EOL { printf("= %d\n> ", $2); }
| calclist EOL { printf("> "); } /* blank line or a comment */
;
exp: factor
| exp ADD exp { $$ = $1 + $3; }
| exp SUB factor { $$ = $1 - $3; }
| exp ABS factor { $$ = $1 | $3; }
;
factor: term
| factor MUL term { $$ = $1 * $3; }
| factor DIV term { $$ = $1 / $3; }
;
term: NUMBER
| ABS term { $$ = $2 >= 0? $2 : - $2; }
| OP exp CP { $$ = $2; }
;
%%
int main()
{
printf("> ");
return yyparse();
}
void yyerror(const char *s)
{
fprintf(stderr, "error: %s\n", s);
}
gcc编译
bison -d calculator.y
flex calculator.l
gcc -o calculator lex.yy.c calculator.tab.c
计算器测试
参考资料:flex与bison(中文版)