预测分析法的词法分析器

好久没管自己的博客了,今天写了点。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


char row[20]={0};
char col[20]={0};
char table[20][20][5]={0};
char stack[20];
char buffer[20];
int index=0;
int sTop=0;

int getRowIndex(char ch);
int getColIndex(char ch);
void outputTable();
void outputRow();
void outputCol();

void init()
{
	//
	strcpy(row,"a^(),{1}quot;);
	strcpy(col,"STR");
	strcpy(table[0][0],"a");
	strcpy(table[0][1],"^");
	strcpy(table[0][2],"(T)");
	strcpy(table[1][0],"SR");
	strcpy(table[1][1],"SR");
	strcpy(table[1][2],"SR");
	strcpy(table[2][3],"@");// @ 表示空
	strcpy(table[2][4],",SR");
}
void outputTable()
{
	int rowlen=strlen(row);
	int collen=strlen(col);
	for (int i=0;i<collen;i++)
	{
		for (int j=0;j<rowlen;j++)
		{
			if (table[i][j][0]=='\0')
			{
				printf("---\t");
			}
			else
			{
				printf("%c->%s\t",col[i],table[i][j]);
			}
		}
		printf("\n");
	}
}
void outputRow()
{
	int rowlen=strlen(row);
	for (int i=0;i<rowlen;i++)
	{
		printf("%c\t",row[i]);
	}
	printf("\n");
}
void outputCol()
{
	int collen=strlen(col);
	for (int i=0;i<collen;i++)
	{
		printf("%c\t",col[i]);
	}
	printf("\n");
}
int getRowIndex(char ch)
{
	int rowlen=strlen(row);
	for (int i=0;i<rowlen;i++)
	{
		if (row[i]==ch)
		{
			return i;
		}
	}
	return -1;
}
int getColIndex(char ch)
{
	int collen=strlen(col);
	for (int i=0;i<collen;i++)
	{
		if (col[i]==ch)
		{
			return i;
		}
	}
	return -1;
}
bool AnalyzeMachine()
{
	stack[sTop++]='

;stack[sTop++]='S';char a=buffer[index++];char x;char rule[5];start:sTop--;x=stack[sTop];if (-1!=getRowIndex(x))//属于非终结{if (x==a){a=buffer[index++];goto start;}elsereturn false;}else{if (x=='
){if (x==a)return true;elsereturn false;}else{strcpy(rule,table[getColIndex(x)][getRowIndex(a)]);if (rule[0]=='\0'){return false;}else{if (rule[0]!='@'){int len=strlen(rule);while (len!=0){stack[sTop++]=rule[--len];}goto start;}}}}}void main(){init();outputTable();outputRow();outputCol();// printf("%s\n",table[getRowIndex('(')][getColIndex('T')]);// printf("%c->%s\n",col[getColIndex('T')],table[getColIndex('T')][getRowIndex('(')]);// printf("%d\n",getRowIndex('('));// printf("%d\n",getColIndex('T'));// printf("%s\n",table[1][2]);strcpy(buffer,"(a,a,^){1}quot;);if(AnalyzeMachine()){printf("Success\n");}else{printf("Failing\n");}}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值