编写相应的Lex和Yacc程序,计算整数表达式的值, 整数表达式中可能含有 + - * / ( ) 和整数值。 1. 设计整数表达式的正规式词法 2. 设计整数表达式的文法 3. 用Flex和Bison生成整数表达式的计算程序
时间: 2024-06-06 22:10:29 浏览: 15
1. 整数表达式的正规式词法:
整数:数字(一位或多位),例如:0, 123, 9999。
运算符:+,-,*,/,(,),例如:+,-,*,/,(,)。
空格:空格字符,例如:空格。
2. 整数表达式的文法:
<expr> → <term> | <expr> + <term> | <expr> - <term>
<term> → <factor> | <term> * <factor> | <term> / <factor>
<factor> → <integer> | ( <expr> )
<integer> → <digit> | <integer> <digit>
<digit> → 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
3. 用Flex和Bison生成整数表达式的计算程序:
Flex用来生成词法分析器,通过正规式词法分析输入的字符串,生成token,用于Bison进行分析。
Bison用来生成语法分析器,通过文法分析token串,生成抽象语法树,根据计算规则计算表达式的值。
代码示例:
Lexer.lex
%{
#include "Parser.tab.h"
%}
%%
[0-9]+ {yylval.ival = atoi(yytext); return INTEGER;}
[-+*/()] {return *yytext;}
[ \t\n] {/* ignore */}
Parser.y
%{
#include <stdio.h>
%}
%token INTEGER
%%
expr: term
| expr '+' term { $$ = $1 + $3; }
| expr '-' term { $$ = $1 - $3; }
term: factor
| term '*' factor { $$ = $1 * $3; }
| term '/' factor { $$ = $1 / $3; }
factor: INTEGER
| '(' expr ')' { $$ = $2; }
%%
int main()
{
yyparse();
return 0;
}
注意:在编译之前需要把上述两个文件进行合并,生成的命令方式如下:
flex Lexer.lex
bison -d Parser.y
gcc Lexer.lex.c Parser.tab.c -o calculator
编译后就可以测试整数表达式的计算程序了。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)