把以上文法消除左递归
时间: 2024-02-16 17:05:08 浏览: 65
消除左递归后的C语言文法如下:
```
<program> ::= <declaration-list>
<declaration-list> ::= <declaration> <declaration-list-tail>
<declaration-list-tail> ::= ε
| <declaration> <declaration-list-tail>
<declaration> ::= <type-specifier> <declaration-tail>;
<declaration-tail> ::= <var-declaration-tail>
| <fun-declaration-tail>
<var-declaration-tail> ::= <id-list>
| <id-list> = <expression>
<fun-declaration-tail> ::= <identifier> (<params>) <compound-stmt>
<params> ::= <param-list>
| void
<param-list> ::= <param> <param-list-tail>
<param-list-tail> ::= ε
| , <param> <param-list-tail>
<param> ::= <type-specifier> <identifier>
<compound-stmt> ::= { <local-declarations> <statement-list> }
<local-declarations> ::= ε
| <var-declaration> <local-declarations>
<statement-list> ::= ε
| <statement> <statement-list>
<statement> ::= <expression-stmt>
| <compound-stmt>
| <selection-stmt>
| <iteration-stmt>
| <return-stmt>
<expression-stmt> ::= <expression> ;
| ;
<selection-stmt> ::= if ( <expression> ) <statement> <else>
<else> ::= ε
| else <statement>
<iteration-stmt> ::= while ( <expression> ) <statement>
<return-stmt> ::= return <return-stmt-tail>
<return-stmt-tail> ::= ε
| <expression> ;
<expression> ::= <var> = <expression-tail>
| <simple-expression>
<expression-tail> ::= <expression>
| <simple-expression>
<var> ::= <identifier> <var-tail>
<var-tail> ::= ε
| [ <expression> ]
<simple-expression> ::= <additive-expression> <simple-expression-tail>
<simple-expression-tail> ::= <relop> <additive-expression>
| ε
<additive-expression> ::= <term> <additive-expression-tail>
<additive-expression-tail> ::= <additive-operator> <term> <additive-expression-tail>
| ε
<additive-operator> ::= +
| -
<term> ::= <factor> <term-tail>
<term-tail> ::= <mulop> <factor> <term-tail>
| ε
<mulop> ::= *
| /
<factor> ::= ( <expression> )
| <var>
| <call>
| <number>
<call> ::= <identifier> (<args>)
<args> ::= ε
| <arg-list>
<arg-list> ::= <expression> <arg-list-tail>
<arg-list-tail> ::= ε
| , <expression> <arg-list-tail>
<relop> ::= <=
| <
| >=
| >
| ==
| !=
```
其中,`<declaration-list-tail>`、`<var-declaration-tail>`和`<fun-declaration-tail>`是为了消除左递归而引入的辅助符号;`<else>`表示if语句的else部分,可以为空;`<expression-tail>`用于消除赋值语句的左递归;`<var-tail>`用于表示数组下标;`<simple-expression-tail>`用于判断是否有关系运算符;`<additive-expression-tail>`和`<term-tail>`用于表示加减和乘除运算符。
阅读全文