LL(1)语法分析

#include <iostream>
#include <iomanip>
#include <string>
#include <stack>
using namespace std;


int searchVn(string Vx[], string ch){//寻找非终结符
int i;
for (i = 0; i < 5; i++){
if (Vx[i] == ch)break;
}
return i==6?-1:i;
}


int searchVt(string Vx[], string ch){//寻找终结符
int i;
for (i = 0; i < 6; i++){
if (Vx[i] == ch)break;
}
return i==6?-1:i;
}


void Init(string** p,string* Vn,string* Vt){//初始化预测分析表
for (int i = 0; i < 5; i++){
for (int j = 0; j < 6; j++){
p[i][j] = "error";
}
}
p[0][0] = "E' T";
p[0][3] = "E' T";
p[1][1] = "E' T +";
p[1][4] = "ε";
p[1][5] = "ε";
p[2][0] = "T' F";
p[2][3] = "T' F";
p[3][1] = "ε";
p[3][2] = "T' F *";
p[3][4] = "ε";
p[3][5] = "ε";
p[4][0] = "i";
p[4][3] = ") E (";
//打印预测分析表
for (int i = 0; i < 6; i++){
for (int j = 0; j < 7; j++){
if (i == 0){
if (j == 0){
cout << setw(10)<< " ";
}
else{
cout << setw(10) << Vt[j - 1];
}
}
else{
if (j == 0){
cout << setw(10) << Vn[i - 1];
}
else{
cout << setw(10) << p[i - 1][j - 1];
}
}
}
cout << endl;
}
}


bool function(string inputString,string** p,string* Vn,string* Vt){
bool flag = false;//判断是否为终结符
int count = 1;//步骤
/*将输入串入栈*/
string::iterator it_input = inputString.end()-1;
stack<string> sta_input;
sta_input.push("#");
while (it_input != inputString.begin()){
string tend;
tend = *it_input;
sta_input.push(tend);
it_input--;
}
string tend;
tend = *it_input;
sta_input.push(tend);
/*初始化分析栈*/
stack<string> sta_analysis;
sta_analysis.push("#");
sta_analysis.push("E");
string str_analysis;//分析串
//开始推导
while (1){
str_analysis = p[searchVn(Vn, sta_analysis.top())][searchVt(Vt,sta_input.top())];//查表
sta_analysis.pop();


if (str_analysis == "error")return false;//预测分析表生空的位置
/*推导入栈*/
string::iterator itfx = str_analysis.begin();
string tend;
while (itfx != str_analysis.end()){
if (*itfx == ' '){
sta_analysis.push(tend);
tend = "";
}
else{
tend = tend + *itfx;
}
itfx++;
}
if (tend != "ε"){
sta_analysis.push(tend);
}
/*匹配终结符*/
if (searchVt(Vt,sta_analysis.top())!=-1){
if (sta_analysis.top()==sta_input.top()){
sta_analysis.pop();
sta_input.pop();
}
else{
return false;//匹配不上就结束
}
}
if (sta_analysis.empty())break;//栈空结束
}
return true;
}


int main(){
string Vn[] = { "E", "E'", "T", "T'", "F" };
string Vt[] = { "i", "+", "*", "(", ")", "#" };
string** p = new string*[5];
for (int i = 0; i < 5; i++){
p[i] = new string[6];
}

string inputString = "(i)";//输入的字符串

Init(p,Vn,Vt);



if (function(inputString,p,Vn,Vt)){
cout << "是一条产生式" << endl;
}
else{
cout << "有词法错误" <<endl;
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值