作为学习龙书前4章一个总结,做一个计算器,支持+-*/(),*/优先,lex采用flex2.5.37,yacc采用bison2.7
最后的效果是可以连续输入表达式进行计算,比如3.2+5.3*(6.2+3.3)
首先构建可以单独运行的可以识别浮点数的词法分析器和可以处理单个数字的语法分析器,然后进行修改并将两者结合起来
首先构建独立词法分析器,参考龙书中图4-60
%{
#include "stdio.h"
float yylval;
float NUMBER;
%}
number [0-9]+\.?|[0-9]*\.[0-9]+
%%
[ ] { /* skip blanks */ }
{number} { sscanf(yytext, "%f", &yylval);
return NUMBER; }
\n|. { return yytext[0]; }
%%
int yywrap()
{
return 1;
}
void main()
{
yylex();
printf("output:%f\n", yylval);
}
然后构建词法分析器
%{
#include <ctype.h>
%}
%token NUMBER
%%
line : expr '\n' { printf("output:%f\n", $1); }
;
expr : expr '+' term { $$ = $1 + $3; printf("expr%f=%f+%f