bison对SysY语⾔进行语法分析 实现代码
时间: 2024-02-11 19:08:49 浏览: 110
以下是一个简单的使用Bison对SysY语言进行语法分析的示例代码:
```c
%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
%}
%token INT ID IF ELSE WHILE RETURN
%token <int> NUM
%%
program:
function_list
;
function_list:
function
| function_list function
;
function:
type_specifier ID '(' parameter_list ')' compound_stmt
;
type_specifier:
INT
;
parameter_list:
parameter_decl
| parameter_list ',' parameter_decl
;
parameter_decl:
type_specifier ID
;
compound_stmt:
'{' local_declarations statement_list '}'
;
local_declarations:
/* empty */
| local_declarations var_declaration
;
var_declaration:
type_specifier ID ';'
;
statement_list:
/* empty */
| statement_list statement
;
statement:
expression_stmt
| compound_stmt
| selection_stmt
| iteration_stmt
| return_stmt
;
expression_stmt:
expression ';'
| ';'
;
selection_stmt:
IF '(' expression ')' statement
| IF '(' expression ')' statement ELSE statement
;
iteration_stmt:
WHILE '(' expression ')' statement
;
return_stmt:
RETURN ';'
| RETURN expression ';'
;
expression:
assignment_expression
;
assignment_expression:
logical_or_expression
| unary_expression '=' assignment_expression
;
logical_or_expression:
logical_and_expression
| logical_or_expression OR_OP logical_and_expression
;
logical_and_expression:
equality_expression
| logical_and_expression AND_OP equality_expression
;
equality_expression:
relational_expression
| equality_expression EQ_OP relational_expression
| equality_expression NE_OP relational_expression
;
relational_expression:
additive_expression
| relational_expression '<' additive_expression
| relational_expression '>' additive_expression
| relational_expression LE_OP additive_expression
| relational_expression GE_OP additive_expression
;
additive_expression:
multiplicative_expression
| additive_expression '+' multiplicative_expression
| additive_expression '-' multiplicative_expression
;
multiplicative_expression:
unary_expression
| multiplicative_expression '*' unary_expression
| multiplicative_expression '/' unary_expression
;
unary_expression:
postfix_expression
| '-' unary_expression
| '!' unary_expression
;
postfix_expression:
primary_expression
| ID '(' argument_list ')'
;
primary_expression:
ID
| NUM
| '(' expression ')'
;
argument_list:
/* empty */
| expression
| argument_list ',' expression
;
%%
int main(int argc, char **argv) {
yyparse();
return 0;
}
void yyerror(const char *msg) {
fprintf(stderr, "Syntax error: %s\n", msg);
exit(1);
}
```
这段代码定义了SysY语言的语法规则,并通过Bison的语法规则定义语言的语法结构。通过在main函数中调用yyparse函数,可以启动语法分析器进行语法分析。当语法分析器遇到错误时,会通过yyerror函数输出错误信息并退出程序。
阅读全文