void main() { p=0; row=1; cout<<endl<<endl<<endl; cout<<"***************************小型词法**********************************"<<endl<<endl; cout<<"请输入一段程序(以#结束):"; do { cin.get(ch); prog[p++]=ch; } while(ch!='#'); p=0; cout<<endl<<"**************************词法分析*********************************"<<endl; cout<<" 种别编码 自身值"<<endl; do { scaner(); switch(syn)
分析结果如器
下
{ case 22 : cout<<" ("<<syn<<" , "<<sum<<")"<<endl; break; case -1: cout<< " Error in row"<<row<<"!"<<endl; break;
default: cout<<" ("<<syn<<" , "<<token<<")"<<endl;break; } } while (syn!=0); }
运行结果:
}
中间代码生成器源程序:
表达式生成四元式 递归子程序法
#include<string> #include <iostream> using namespace std;
#define DEFAULT_SIZE 100
char EMachine(char w); //表达式E的自动机 char TMachine(char w); //表达式T的自动机 char FMachine(char w); //表达式F的自动机 bool ZMachine(); //表达式Z的自动机 string intToString(int a); //整形变成字符串形函数
class stack //栈类定义 {
private: int top;
string *stacka; int maxsize; public:
stack(int size=DEFAULT_SIZE); ~stack(){ delete [] stacka; } void push(const string &item); string pop(void);
string gettop(void) const ;
bool empty(void) const { return (top==-1); }
bool full(void) const { return (top==maxsize-1); } void clear(void) { top=-1; } };
stack::stack(int size) //栈类的构造函数 {
top=-1;
maxsize=size;
stacka=new string[maxsize]; if(!stacka) {
cerr<<"allocate memory failed."<<endl; exit(1); } }
void stack::push(const string &item) //压栈操作 {
if(full()) {
cerr<<"stack full, cannot push."<<endl; return; }
top++;
stacka[top]=item; }
string stack::pop(void) //出栈操作 {
if(empty()) {
cerr<<"stack empty, cannot pop."<<endl; exit(1) ; }
string item=stacka[top]; top--;
return item; }
string stack::gettop(void) const //取栈顶操作 {
if(empty()) {
cerr<<"stack empty, cannot gettop."<<endl; exit(1) ; }
return stacka[top]; }
static stack wordStack; //符号栈 static int noOfQuet=0; //静态四元式个数记录 static int noOfT = 1; //静态状态个数记录
void main(){ //主函数 char yesOrNo; //进行一个循环操作控制 do{ cout<<"请输入算术表达式:"<<endl; noOfT = 1; //每次结束询问 ZMachine(); cout<<endl<<"Continue?Yes or Not:"; cin>>yesOrNo; //输入“Y”则继续 }while(yesOrNo=='y'); //否则程序结束 }
bool ZMachine(){ //Z自动机 char w; cin>>w; w = EMachine(w); //调用E自动机
if(w=='#'){ //遇到“#”则结束 return true; } else{ return false; } }
char EMachine(char w){ //E自动机 string operate,a,b,c; string state[5]; w = TMachine(w); //调用T自动机 while(w=='+'||w=='-'){ //是加或减符号 operate = w; cin>>w; //读入下一字符 w = TMachine(w); //调用T自动机 b = wordStack.pop(); //字符栈弹出 a = wordStack.pop(); //两个操作字符 cout<<"(\""<<operate<<"\","<<a<<","<<b<<",t"<<noOfT<<")"<<endl; c = "t"+intToString(noOfT); //输出四元式 wordStack.push(c); //新状态压栈 noOfT++; //状态计数加一 } return w; }
char TMachine(char w){ string operate,a,b,c; string state[5]; w = FMachine(w); //调用F自动机 while(w=='*'||w=='/'){ //是乘除号 operate = w; cin>>w; //读取下一字符 w = FMachine(w); //调用F自动机 b = wordStack.pop(); //符号栈弹出 a = wordStack.pop(); //两个操作字符 cout<<"(\""<<operate<<"\","<<a<<","<<b<<",t"<<noOfT<<")"<<endl; c = "t"+intToString(noOfT); //输出四元式 wordStack.push(c); //新状态压栈 noOfT++; //状态计数加1 } return w; }