编译原理实验二语法分析器LL(1)实现 下载本文

内容发布更新时间 : 2024/5/18 2:32:32星期一 下面是文章的全部内容请认真阅读。

{

if(ch==bound[i]) {

return i+1; } } return 0; }

int Isoperate(char ch) //判断是否为运算符 { int i;

for(i=0;i<4;i++) {

if(ch==operate[i]) {

return i+3; } } return 0; }

int main() { {

printf(\文件未找到!\\n\ } else{

while(!feof(fp)){

if(isspace(ch=fgetc(fp))); else{

sour[q]=ch; q++; } } } int p=0;

printf(\输入句子为:\\n\ for(p;p<=q;p++)

FILE *fp; int q=0,m=0; char sour[200]=\

printf(\请将源文件置于以下位置并按以下方式命名:F:\\\\2.txt\\n\

if((fp=fopen(\

{

printf(\ }

printf(\ int state=0,nowlen=0;

BOOLEAN OK=TRUE,ERR=FALSE; int i,flagpoint=0; for(i=0;i

if(sour[i]=='#')

tokenlist[m].code=='#'; switch(state) { case 0: ch=sour[i]; if(Isbound(ch)) {

if(ERR) {

printf(\无法识别\\n\ ERR=FALSE; OK=TRUE; }

else if(!OK) {

printf(\标识符\\n\ tokentemp.code=10;

tokentemp.ch[10]=nowword[10]; tokenlist[m]=tokentemp; m++; OK=TRUE; } state=4; }

else if(IsDigit(ch)) {

if(OK) {

memset(nowword,0,strlen(nowword)); nowlen=0;

nowword[nowlen]=ch; nowlen++; state=3; OK=FALSE;

break; }else {

nowword[nowlen]=ch; nowlen++; } }

else if(IsLetter(ch)) {

if(OK) {

memset(nowword,0,strlen(nowword)); nowlen=0;

nowword[nowlen]=ch; nowlen++; OK=FALSE; }else {

nowword[nowlen]=ch; nowlen++; } }

else if(Isoperate(ch)) {

if(!OK) {

printf(\标识符\\n\ tokentemp.code=10;

tokentemp.ch[10]=nowword[10]; tokenlist[m]=tokentemp; m++; OK=TRUE; }

printf(\运算符\\n\ tokentemp.code=Isoperate(ch); tokentemp.ch[10]=ch; tokenlist[m]=tokentemp; m++; } break; case 3:

if(IsLetter(ch)) {

printf(\错误\\n\

nowword[nowlen]=ch; nowlen++; ERR=FALSE; state=0; break; }

if(IsDigit(ch=sour[i])) {

nowword[nowlen]=ch; nowlen++; }

else if(sour[i]=='.'&&flagpoint==0) {

flagpoint=1;

nowword[nowlen]=ch; nowlen++; } else {

printf(\数字\\n\ i--; state=0; OK=TRUE; tokentemp.code=20;

tokentemp.ch[10]=nowword[10]; tokenlist[m]=tokentemp; m++; } break; case 4: i--;

printf(\界符\\n\ tokentemp.code=Isbound(ch); tokentemp.ch[10]=ch; tokenlist[m]=tokentemp; m++; state=0; OK=TRUE; break; } }

printf(\值为%d\\n\ int t=0;

tokenlist[m+1].code='r';

m++; for(t;t

printf(\值为%d\\n\ } LL1();

printf(\值为%d\\n\ if(op+1==m) printf(\ else

printf(\ return 0; }

void LL1() {

STack s; init(&s); push(&s,'#'); push(&s,'E'); char ch; int flag=1; do {

pop(&s,&ch);

printf(\输出栈顶为%c\\n\ printf(\输出栈顶为%d\\n\ printf(\当前p值为%d\\n\

if((ch=='(')||(ch==')')||(ch=='+')||(ch=='-')||(ch=='*')||(ch=='/')||(ch==10)||(ch==20)) {

if(tokenlist[op].code==1||tokenlist[op].code==20||tokenlist[op].code==10||tokenlist[op].code==2||tokenlist[op].code==3||tokenlist[op].code==4||tokenlist[op].code==5||tokenlist[op].code==6) op++; else {

printf(\ exit(0); } }

else if(ch=='#') {

if(tokenlist[op].code==0) flag=0;