递归下降分析分析法
用递归下降法编写一个语法分析程序,使之与词法分析器结合,能够根据语言的上下文无关文法,识别输入的单词序列是否文法的句子。
对下列文法,用递归下降分析法对任意输入的符号串进行分析:
E->TG G->+TG|-TG G->ε
T->FS S->*FS|/FS S->ε
F->(E) F->i
源程序
#include<iostream>
#include<string>
using namespace std;
void E(); //E->TG
void G(); // G->+TG|-TG G->ε
void T(); //T->FS
void S(); // S->*FS | / FS S->ε
void F(); //F->(E) | i
string str;
string strC;
void main()
{
cout << "请输入字符串(#号结束):" << endl;
cin >> str;
strC = str;
cout << "文法 分析串 分析字符 剩余串" << endl;
E();
}
void E()
{
cout << "E->TG " << strC.substr(0, strC.length() - str.length() + 1) << " " << str[0] << " " << str << endl;
T();
G();
}
void T()
{
cout << "T->FS " << strC.substr(0, strC.length() - str.length() + 1) << " " << str[0] << " " << str << endl;
F();
S();
}
void G()
{
if (str[0] == '+')
{
cout << "G->+TG " << strC.substr(0, strC.length()-str.length()+1) << " " << str[0] << " " << str << endl;
str = str.substr(1, str.length());
T();
G();
}
else if (str[0] == '-')
{
cout << "G->-TG " << strC.substr(0, strC.length() - str.length()+1) << " " << str[0] << " " << str << endl;
str = str.substr(1, str.length());
T();
G();
}
else
{
cout << "G->ε " << strC.substr(0, strC.length() - str.length() + 1) << " " << str << endl;
}
}
void F()
{
if (str[0] == 'i') {
cout << "F->i " << strC.substr(0, strC.length() - str.length() + 1) << " " << str[0] << " " << str << endl;
str = str.substr(1, str.length());
}
else if (str[0] == '(') {
cout << "F->(E) " << strC.substr(0, strC.length() - str.length() + 1) << " " << str[0] << " " << str << endl;
str = str.substr(1, str.length());
E();
if (str[0] == ')') {
cout << "F->(E) " << strC.substr(0, strC.length() - str.length() + 1) << " " << str[0] << " " << str << endl;
str = str.substr(1, str.length());
}
else {
printf("\n非法的符号串!\n");
exit(0);
}
}
else {
printf("非法的符号串!\n");
exit(0);
}
}
void S()
{
if (str[0] == '*') {
cout << "S->*FS " << strC.substr(0, strC.length() - str.length() + 1) << " " << str[0] << " " << str << endl;
str = str.substr(1, str.length());
F();
S();
}
else if (str[0] == '/')
{
cout << "S->/FS " << strC.substr(0, strC.length() - str.length() + 1) << " " + str[0] << " " << str << endl;
str = str.substr(1, str.length());
F();
S();
}
else{
cout << "S->ε " << strC.substr(0, strC.length() - str.length() + 1) << " " << str[0] << " " << str << endl;
}
}