#include <stdio.h> #include <string.h> #include <stdlib.h> char prog[80],token[8]; char ch; int syn=-1,p,t; void scanner(); void statement(); void expression_r(); void term(); void factor(); void getcha() { ch=prog[p++]; } void getbc() { while(prog[p]==' ') p++; getcha(); } void concat() { token[t++]=ch; } bool letter(char ch) { if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) return true; return false; } bool digit(char ch) { if(ch>='0'&&ch<='9') return true; return false; } int reserve() { token[t++]='\0'; if(strcmp(token,"begin")==0) return 1; if(strcmp(token,"end")==0) return 6; if(strcmp(token,"if")==0) return 2; if(strcmp(token,"then")==0) return 3; if(strcmp(token,"else")==0) return 7; if(strcmp(token,"while")==0) return 4; if(strcmp(token,"do")==0) return 5; return 10; } void retract() { p--; } int dtb() { token[t++]='\0'; int i=atoi(token); return i; } void Irparse() { scanner(); statement(); while(syn==26)//; { scanner(); statement(); } } void statement() { if(syn==10) { scanner(); if(syn==18) { scanner(); expression_r(); } else { printf("语法分析出错! 请检查表达式是否含:=\n");return ; } } else { //printf("语法分析出错! 请检查语句是否正确\n");return 0; } } void expression_r() { term(); while(syn==13||syn==14)//+ - { scanner(); term(); } } void term() { factor(); while(syn==15||syn==16)//* / { scanner(); factor(); } } void factor() { if(syn==10||syn==11) { scanner(); } else if(syn==27) { scanner(); expression_r(); if(syn==28) { scanner(); } else {printf("语法分析出错! 请检查是否缺少')'\n");return;} } else {printf("语法分析出错! 请检查是否输入非法字符\n");return;} } void scanner() { t=0; //getcha(); getbc(); if(letter(ch)) { while(letter(ch)||digit(ch)) { concat(); getcha(); } retract(); syn=reserve(); if(syn==10) syn=10; } else if(digit(ch)) { while(digit(ch)) { concat(); getcha(); } retract(); syn=11; } else switch(ch) { case'+': syn=13;token[0]=ch;break; case'-': syn=14;token[0]=ch;break; case'*': syn=15;token[0]=ch;break; case'/': syn=16;token[0]=ch;break; case'<': token[0]=ch; getcha(); if(ch=='=') {syn=22;token[1]=ch;} else if(ch=='>') {syn=21;token[1]=ch;} else {retract(); syn=20;} break; case'>': token[0]=ch; getcha(); if(ch=='=') {syn=24;token[1]=ch;} else {retract(); syn=23;} break; case'=': syn=25;token[0]=ch;break; case':': token[0]=ch; getcha(); if(ch=='=') {syn=18;token[1]=ch;} else {retract(); syn=17;} break; case';': syn=26;token[0]=ch;break; case'(': syn=27;token[0]=ch;break; case')': syn=28;token[0]=ch;break; case'#': syn=0;token[0]=ch;break; default: syn=-1;break; } } int main() { p=0; printf("please input string: \n"); char c; while(1) {c=getchar(); if(c=='\n') break; prog[p++]=c; } p=0; scanner(); if(syn==1) {Irparse();}//begin else {printf("语法分析出错! 请检查begin关键字\n");return 0;} if(syn==6)//end { scanner(); if(syn==0) { printf("success!\n"); } else {printf("语法分析出错! 请检查是否缺少'#'\n");} } else{printf("语法分析出错! 请检查是否缺少'end'\n");} return 0; }