构造一个中缀表达式到后缀表达式的翻译器,初步了解递归下降语法分析原理及语法制导翻译的过程。包含+,-,*,/,()
expr ------> expr +
term {print(‘+’)}
| expr - term {print(‘-’)}
| term
term -----> term * factor {print(‘*’)}
| term / factor {print(‘/’)}
| factor
factor ----> ( expr )
| id {print(id.lexeme)}
| num {print(num.value)}
-
#include<stdio.h>
-
#include<ctype.h>
-
void expr();
-
int lookahead;
-
void match(int t)
-
{
-
if (lookahead == t)
-
lookahead = getchar();
-
else {
-
printf("syntax error!");
-
return;
-
}
-
}
-
void factor()
-
{
-
if (isdigit(lookahead)){
-
printf("%c",lookahead);match(lookahead);
-
}else if(lookahead == '('){
-
match('(');expr();match(')');
-
}else if((lookahead >='a'&&lookahead <='z')||(lookahead >='A'&&lookahead <='Z')){
-
printf("%c",lookahead);match(lookahead);factor();
-
}
-
}
-
-
void term()
-
{
-
factor();
-
while(1){
-
if(lookahead == '*'){
-
match('*');factor();printf("*");
-
}else if( lookahead == '/'){
-
match('/');factor();printf("/");
-
}else return;
-
}
-
}
-
void expr(){
-
term();
-
while(1){
-
if(lookahead == '+'){
-
match('+');term();printf("+");
-
}else if(lookahead == '-'){
-
match('-');term();printf("-");
-
}
-
else return;
-
}
-
}
-
int main(){
-
lookahead = getchar();
-
expr();
-
printf("\n");
-
getchar();
-
return 0;
-
}
1. 实验采用递归下降方法,可识别单字符的factor ,未添加下划线等其余变量标识符。
2. 若在factor()函数中递归调用factor()函数,可识别多字符的factor,但识别效果可能会造成二义性,建议加入分割符。
3. 递归调用
factor()在原理上有待商榷,它将多字符
id分割成多个
factor,在形成词法单元时可能出错。
阅读(883) | 评论(0) | 转发(0) |