表达式语法分析——递归子程序法
Description
递归子程序法是一种确定的自顶向下语法分析方法,要求文法是LL(1)文法。它的实现思想是对应文法中每个非终结符编写一个递归过程,每个过程的功能是识别由该非终结符推出的串,当某非终结符的产生式有多个候选式时能够按LL(1)形式唯一地确定选择某个候选式进行推导。请根据下面的表达式LL(1)文法,构造递归子程序,完成对表达式的语法分析。
表达式文法如下:
E→TG
G→+TG | ε
T→FS
S→*FS | ε
F→(E) | i
#include <stdio.h>
#include <stdlib.h>char str[100];
int num=0;
int cur=0;
void E();
void F();
void G();
void T();
void S();
void S()
{if(str[cur]=='*'){printf("%d S-->*FS\n",num++);cur++;F();S();}else{printf("%d S-->&\n",num++);}
}
void G()
{if(str[cur]=='+'){printf("%d G-->+TG\n",num++);cur++;T();G();}elseprintf("%d G-->&\n",num++);
}
void F()
{if(str[cur]=='i'){printf("%d F-->i\n",num++);cur++;}else if(str[cur]=='('){printf("%d F-->(E)\n",num++);cur++;E();if(str[cur]==')'){cur++;}else{printf("error\n");exit(0);}}else{printf("error\n");exit(0);}
}
void T()
{if(str[cur]=='i'||str[cur]=='('){printf("%d T-->FS\n",num++);F();S();}else{printf("error\n");exit(0);}
}
void E()
{if(str[cur]=='i'||str[cur]=='('){printf("%d E-->TG\n",num++);T();G();}else{printf("error\n");exit(0);}}
int main()
{scanf("%s",str);E();if(str[cur]!='#'){printf("error\n");}elseprintf("accept\n");return 0;
}