可识别C语言语法的bison代码
时间: 2023-12-12 10:05:33 浏览: 95
以下是一个简单的bison代码示例,可识别C语言中的一些基本语法:
```
%{
#include <stdio.h>
%}
%token NUM ID IF ELSE WHILE RETURN
%token ADD SUB MUL DIV
%token LT LE GT GE EQ NE
%token ASSIGN SEMICOLON LPAREN RPAREN LBRACE RBRACE
%%
program: decl_list stmt_list
;
decl_list: /* empty */
| decl_list declaration
;
declaration: type ID SEMICOLON
;
type: INT
| FLOAT
| CHAR
;
stmt_list: /* empty */
| stmt_list statement
;
statement: expression SEMICOLON
| compound_stmt
| selection_stmt
| iteration_stmt
| return_stmt
;
compound_stmt: LBRACE stmt_list RBRACE
;
selection_stmt: IF LPAREN expression RPAREN statement
| IF LPAREN expression RPAREN statement ELSE statement
;
iteration_stmt: WHILE LPAREN expression RPAREN statement
;
return_stmt: RETURN SEMICOLON
| RETURN expression SEMICOLON
;
expression: assignment_expression
;
assignment_expression: ID ASSIGN expression
| equality_expression
;
equality_expression: relational_expression
| equality_expression EQ relational_expression
| equality_expression NE relational_expression
;
relational_expression: additive_expression
| relational_expression LT additive_expression
| relational_expression LE additive_expression
| relational_expression GT additive_expression
| relational_expression GE additive_expression
;
additive_expression: multiplication_expression
| additive_expression ADD multiplication_expression
| additive_expression SUB multiplication_expression
;
multiplication_expression: primary_expression
| multiplication_expression MUL primary_expression
| multiplication_expression DIV primary_expression
;
primary_expression: ID
| NUM
| LPAREN expression RPAREN
;
%%
int main(int argc, char *argv[]) {
yyparse();
return 0;
}
int yyerror(const char *s) {
fprintf(stderr, "%s\n", s);
return 0;
}
```
此示例包括C语言中常见的语法元素,如变量声明、赋值、控制流语句、表达式等。请注意,这只是一个简单的示例,实际上需要更复杂的语法规则才能完全识别C语言的语法。
阅读全文