非常简单的汇编翻译器

来源:互联网 发布:热传导 软件 编辑:程序博客网 时间:2024/05/21 01:45

上周一直在做一个学校的比赛,题目就是写一个翻译器把C代码翻译为汇编代码。
我设计思路是把C代码读入后,按“;”分割为语句然后识别关键词来分别变量和变量的赋值。最后发现我整个都在做对字符串的处理。也发现了自己很多原来忽略的地方。
函数关系图
这里写图片描述
思路图
这里写图片描述

因为学校要求只提供一个源文件所以我所有代码都写一起了比较丑陋。而且其中越写脑洞越大很多代码都是无用的- -。真正完成题目估计300行即可。

//将C代码翻译成汇编代码(c++实现)//编译器2.0 加入代码每行的分割 //3.0加入char变量的识别并加入符号表  注:输入代码定义时只能每行只能定义两个变量 //请确保输入文件中无中文字符 //char 一行最多定义2个变量//printf一行只能输出一个变量 #include<iostream>#include<new>#include<fstream>#include<string> #include<vector>#include<math.h>#include <sstream>using namespace std;template <typename T> struct Node{    T data;    Node * next;}; template <typename T> class Queue//队列类 {    public:        typedef Node<T> * PtrToQueue;    private:        PtrToQueue first;        PtrToQueue last;    public:        bool IsEmpty()        {            return first->next == NULL;        }        void MakeEmpty()        {            if( !IsEmpty() )                while( !IsEmpty() )                    Dequeue();        }        void Enqueue( T x )        {            PtrToQueue tmp;            tmp = new Node<T>;            tmp->data = x;            tmp->next = NULL;            last->next = tmp;            last = tmp;        }        T Front()        {            return first->next->data;        }        void Dequeue()        {            PtrToQueue tmp;            tmp = first;            first = first->next;            delete tmp;         }        T FrontAndDequeue()        {            T d = Front();            Dequeue();            return d;        }        int length()        {            int i;            Node<T> * p = first;            for(i=0;p!=last;i++,p=p->next);            return i;        }        Queue(  )        {            first = new Node<T>;            first->data = 0;            first->next = NULL;            last = first;        }        ~Queue()        {            MakeEmpty();            delete first;        }};class  Morpheme{ //词素类 每个变量都会归入该类     private:        string id;//变量ID         string attribute; //变量属性    public:        Morpheme()        {        }        Morpheme( string a , string b )        {            id = a;            attribute = b;        }        Morpheme( const Morpheme &m)        {            this->id = m.id;            this->attribute = m.attribute;        }        string getid()        {            return id;        }        string getatt()        {            return attribute;        }        void setid(string a)        {            id = a;        }        void setatt( string a )        {            attribute = a;          }        ~Morpheme()        {        }};vector<Morpheme> symbol;//符号表存储变量 vector<string> DivisionCodes;//分割代码后存储vector<string> huibiaoCodes;//需要输出的汇编代码保存vector<Morpheme> putsymbol;//需要输出的符号void DivisionPrint()//分割后的代码输出 {    for( int i = 0 ; i < DivisionCodes.size() ; i++ )    {        cout<<DivisionCodes[i]<<endl;    } } void division( string ReadCodes )//分割函数 {    int i,j;    int num=0,z=0;    string tmpst;/*for( i = 0 ; i <= ReadCodes.length() ; i++ )    {        if(  ReadCodes[i] == ';')        {            cout<<i<<endl;              for( j = 0 ; j <= i-z ; j++ )            {                tmp[j] = ReadCodes[j+z];            }            z = i;            tmpst = tmp;            DivisionCodes.push_back(tmpst);        }    }*/    Queue<char> queue;//  cout<<ReadCodes[ReadCodes.length()-1];    for( i = 0 ; i < ReadCodes.length() ; i++)    {        if( ReadCodes[i] != ';')        {            queue.Enqueue(ReadCodes[i]);        }        else        {            char tmp[queue.length()];        //  cout<<queue.length()<<endl;            for( j=0; !queue.IsEmpty() ; j++)            {                tmp[j] = queue.FrontAndDequeue();            }            tmp[j]=0;            tmpst = tmp;            for(int i = 0 ; i < j ; i++)            {                tmp[i] = 0;            }            string::iterator p;            for( p = tmpst.begin(); p != tmpst.end() ; p++ )//删除字符串中的空格和回车             {                if(*p == ' '|| *p == '\n')                    tmpst.erase(p);            }            DivisionCodes.push_back(tmpst);        }    } //   DivisionPrint();/*  vector<string>::iterator p = DivisionCodes.begin();    for(;p!=DivisionCodes.end();p++)    {        cout<<*p<<endl;     } */ }void ReadCode( char codes[] )//读入文件中的C代码并保存入ReadCodes数组 {    fstream f( "shuru.txt" );    while( !f.eof() )    {        f.read(codes,1000);    }    f.close();} void symbolPrint()//符号表输出 {    for( int i= 0 ; i < symbol.size() ; i++ )    {        cout<<symbol[i].getid()<<" "<<symbol[i].getatt()<<endl;    }}void addSymbol( Morpheme a )//符号表增加 {        int flag=0;        for( int i= 0 ; i < symbol.size() ; i++ )        {            if( symbol[i].getid() == a.getid() )                flag = 1;        }        if( flag != 1)            symbol.push_back(a); } void addPutSymbol( Morpheme a )//输出符号表增加 {    int flag=0;    for( int i= 0 ; i < putsymbol.size() ; i++ )    {        if( putsymbol[i].getid() == a.getid() )            flag = 1;    }    //cout<<flag<<endl;    if( flag != 1)        putsymbol.push_back(a); } void ConsturtVar ( string s , int count)//char关键字分析 {    if(count == 0)    {        string t;        char tmp[s.length()-3-s.find("char")]={0};        for( int i = 0 , j = s.find("char")+4 ; i < s.length()-s.find("char")-4 ; i++)        {            tmp[i] = s[j++];        }        t = tmp;        for( int i = 0 ; i < 10 ;i++)        {            tmp[i] = 0;         }    //  cout<<tmp<<endl;        Morpheme mtmp( t , "char");        addSymbol(mtmp);    }    else if(count == 1)    {        string tmpst;        char tmp[ s.find(",") - s.find("char")]={0};        for( int i = 0 ,  j = s.find("char")+4 ; i < s.find(",")-s.find("char")-4 ; i++)        {            tmp[i] = s[j++];        }        tmpst = tmp;        for( int i = 0 ; i < 10 ;i++)        {            tmp[i] = 0;         }        //  cout<<tmpst<<endl;        Morpheme mtmp( tmpst , "char");        addSymbol(mtmp);        string tmpst2;        char tmp2[s.length() - s.find(",")]={0};        for( int i = 0 , j = s.find(",")+1 ; i < s.length() - s.find(",") - 1 ; i++)        {            tmp2[i] = s[j++];        }        tmpst2 = tmp2;        for( int i = 0 ; i < 10 ;i++)        {            tmp2[i] = 0;         }    //  cout<<tmpst2<<endl;        Morpheme mtmp2( tmpst2 , "char");        addSymbol(mtmp2);    }//  cout<<symbol[0].getid()<<endl; //  cout<<symbol[1].getid()<<endl;} string FindValue( string s )//把变量值赋予变量 {//  cout<<s<<endl;    string tmps;    if(s.find("'")!=-1)    {        int x , y ;        x=s.find("'");        y=s.find("'",x+1);    //  cout<<x<<endl;    //  cout<<y<<endl;        char tmp[y-x];        int j = 0;        for(int i = x+1, j = 0  ; i < y ; i++,j++ )        {            tmp[j] = s[i];        }        tmp[j+1]=0;        tmps = tmp;    //  cout<<tmp<<endl;    //  cout<<tmps.length()<<endl;     }    if(s.find("'") == -1)    {        int x , y ;        x=s.find("=");        y=s.length();    //  cout<<x<<endl;    //  cout<<y<<endl;        char tmp[y-x];        int j = 0;        for(int i = x+1, j = 0  ; i < y ; i++,j++ )        {            tmp[j] = s[i];        }        tmp[j+1]=0;        tmps = tmp;    }     return tmps; }void NameValue( string s ) {//  cout<<s<<endl;//  cout<<FindValue(s)<<endl;      for( int i= 0 ; i < symbol.size() ; i++ )    {        if( s.find(symbol[i].getid()) != -1 )        {        //  cout<<s<<endl;         //  cout<<symbol[i].getid()<<endl;        //  cout<<FindValue(s)<<endl;            symbol[i].setatt( FindValue( s ) );        }    }//  cout<<"ok"<<endl;}void finddou( string s , int count )//找此句中 {//  cout<<count<<endl;    if( count == 1)    {        int x,y,z;        int m;        x = s.find("\"");        y = s.find("\"", x+1);        z = s.find(",");        m = s.find(")");    //  cout<<s<<endl;    //  cout<<x<<endl;    //  cout<<y<<endl;    //  cout<<z<<endl;    //  cout<<m<<endl;         string tmps;        if( m-z-1 == 1)        {            char tmp;            for(int i = z+1, j = 0 ; i < m ; i++ , j++ )            {                tmp = s[i];             }            tmps = tmp;        }        else        {            char tmp[m-z-1]={0};            for(int i = z+1, j = 0 ; i < m ; i++ , j++ )            {                tmp[j] = s[i];              }            tmps = tmp;        }       //  cout<<tmps<<endl;        int flag = -1;    //  cout<<symbol.size()<<endl;        for(int i = 0 ; i < symbol.size() ; i++ )        {            if( symbol[i].getid() == tmps )            {                flag = i;            }        }     //  string tmps ;    //  tmps = tmp;    //  cout<<tmps<<endl;     //  cout<<symbol[flag].getatt()<<endl;    //  cout<<flag<<endl;        if ( flag != -1 )        {            Morpheme p(symbol[flag]);            addPutSymbol( p );         }    }    if( count == 2)    {         int x,y,m,n;        x = s.find(",");        y = s.find(",", x+1);    //  cout<<x<<" "<<y<<endl;        m = s.find(")");    //  cout<<m<<endl;        string tmps;        if( y-x-1 == 1)        {            char tmp;            for(int i = x+1, j = 0 ; i < y ; i++ , j++ )            {                tmp = s[i];             }            tmps = tmp;        }        else        {            char tmp[y-x-1]={0};            for(int i = x+1, j = 0 ; i < y ; i++ , j++ )            {                tmp[j] = s[i];              }            tmps = tmp;        }           int flag = -1;    //  cout<<symbol.size()<<endl;        for(int i = 0 ; i < symbol.size() ; i++ )        {            if( symbol[i].getid() == tmps )            {                flag = i;            }        }     //  cout<<flag<<endl;        if ( flag != -1 )        {            Morpheme p(symbol[flag]);            addPutSymbol( p );         }        flag = -1;    //  cout<<tmps<<endl;        if( m-y-1 == 1)        {            char tmp;            for(int i = y+1, j = 0 ; i < m ; i++ , j++ )            {                tmp = s[i];             }            tmps = tmp;        }        else        {            char tmp[m-y-1]={0};            for(int i = y+1, j = 0 ; i < m ; i++ , j++ )            {                tmp[j] = s[i];              }            tmps = tmp;        }               for(int i = 0 ; i < symbol.size() ; i++ )        {            if( symbol[i].getid() == tmps )            {                flag = i;            }        }         if ( flag != -1 )        {            Morpheme p(symbol[flag]);            addPutSymbol( p );         }    //  cout<<tmps<<endl;    }}void toprint( string s  )//发现printf后的操作 {    int x=0;        basic_string<char>::size_type y = 0;    while( (y=s.find(",",y)) != string::npos)//找到该句中有几个“,”         {            x++;            y++;        }     if(x==0)    {            int x;            int y;            string tmps;        //  cout<<s.find("\"");            if( s.find("\"") != -1 )            {                x=s.find("\"");                y=s.find("\"",x+1);            //  cout<<x<<" "<<y<<endl;          //  cout<<y-x-1<<endl;                if( y-x-1 == 1)                {                    //cout<<"1"<<endl;                    char tmp = s[x+1];                    tmps = tmp;                }                else                {                    char tmp[y-x-1];                    for(int i = 0 ; i < 3 ;i++ )                    {                        tmp[i] = 0;                    }                        tmps = tmp;                    for( int i = x+1,j = 0 ; i < y ; i++,j++ )                    {                    //  cout<<j<<endl;                        tmp[j] = s[i];                    //  cout<<s[i]<<endl;                    //  cout<<tmp[j]<<endl;                    }                    tmp[y-x-1]=0;                    //cout<<tmp<<endl;                    tmps = tmp;                }            Morpheme p("zifu",tmps);                addSymbol( p );             addPutSymbol( p );        //  cout<<p.getid()<<endl;        //  cout<<p.getatt()<<endl;         }    }    finddou( s , x );}/*void fanyi(){    ofstream f;    string s1 = "data segment\n";    string s2;    s2 = "tab db '";    for (int i = 0 ; i < putsymbol.size() ; i++ )    {//      cout<<putsymbol[i].getatt()<<endl;        s2 = s2 +  putsymbol[i].getatt() ;    }//  cout<<s2<<endl;    s2 = s2 + "$" + "'"+"\n";    string s3 = "data ends\n code segment \n assume cs:code, ds:data \n start:\n mov ax,data\nmov ds,ax\n lea dx,tab\nmov ah,9h\n int 21h\n mov ah,4ch\n int 21h\ncode ends\nend start\n";    string s;    s = s1+s2+s3;    f.open("shuchu.txt");    f<<s;    cout<<s<<endl;    f.close();}*/int charToInt( char a[] , int n)//char变量转换为int {    int num = 0;    for( int i = 0 ; i < n ; i++)    {        num = num + a[i]*pow(10,n-i-1);     }    return num;}void getValue( string s , string fuhao)//只支持两个数的操作{    if( fuhao == "+")    {        int x , y , m , n;        int num1 , num2 ;        x = s.find( " = " );        y = s.find( " + " );        char tmp[y-x+1];        int j = 0;        for(int i = x ; i < y ; i++ , j++ )        {            tmp[j] = s[i];        }        num1 = charToInt(tmp , j);        m = s.length();        for(int i = y , j = 0 ; i < m ; i++ , j++ )        {            tmp[j] = s[i];        }        num2 = charToInt( tmp , j);        int num3;        num3 = num1 + num2;        int flag = 0;        for( int i = 0 ; i < symbol.size() ; i++ )        {            if( s.find( symbol[i].getid() ) != -1 )            {                flag = i;            }        }        string tmps;        tmps = num3;        symbol[flag].setatt(tmps);    }    if( fuhao == "-")    {        int x , y , m , n;        int num1 , num2 ;        x = s.find( " = " );        y = s.find( " + " );        char tmp[y-x+1];        int j;        for(int i = x , j = 0 ; i < y ; i++ , j++ )        {            tmp[j] = s[i];        }        num1 = charToInt( tmp ,j ) ;        m = s.length();        for(int i = y , j = 0 ; i < m ; i++ , j++ )        {            tmp[j] = s[i];        }        num2 = charToInt( tmp , j);        int num3;        num3 = num1 - num2;        int flag = 0;        for( int i = 0 ; i < symbol.size() ; i++ )        {            if( s.find( symbol[i].getid() ) != -1 )            {                flag = i;            }        }        string tmps;        stringstream ss;        ss << num3;        ss >> tmps;        symbol[flag].setatt(tmps);    }    if( fuhao == "*")    {        int x , y , m , n;        int num1 , num2 ;        x = s.find( " = " );        y = s.find( " + " );        char tmp[y-x+1];        int j;        for(int i = x , j = 0 ; i < y ; i++ , j++ )        {            tmp[j] = s[i];        }        num1 = charToInt( tmp , j);        m = s.length();        for(int i = y , j = 0 ; i < m ; i++ , j++ )        {            tmp[j] = s[i];        }        num2 = charToInt( tmp , j);        int num3;        num3 = num1 * num2;        int flag = 0;        for( int i = 0 ; i < symbol.size() ; i++ )        {            if( s.find( symbol[i].getid() ) != -1 )            {                flag = i;            }        }        string tmps;        stringstream ss;        ss << num3;        ss >> tmps;        symbol[flag].setatt(tmps);    }    {        int x , y , m , n;        int num1 , num2 ;        x = s.find( " = " );        y = s.find( " + " );        char tmp[y-x+1];        int j;        for(int i = x , j = 0 ; i < y ; i++ , j++ )        {            tmp[j] = s[i];        }        num1 = charToInt( tmp , j);        m = s.length();        for(int i = y , j = 0 ; i < m ; i++ , j++ )        {            tmp[j] = s[i];        }        num2 = charToInt( tmp , j);        int num3;        num3 = num1 / num2;        int flag = 0;        for( int i = 0 ; i < symbol.size() ; i++ )        {            if( s.find( symbol[i].getid() ) != -1 )            {                flag = i;            }        }        string tmps;        stringstream ss;        ss << num3;        ss >> tmps;        symbol[flag].setatt(tmps);    }}void ConsturtVarofint(string s, int count)//{    if(count == 0)    {        string t;        char tmp[s.length()-2-s.find("int")]={0};        for( int i = 0 , j = s.find("int")+3 ; i < s.length()-s.find("int")-3 ; i++)        {            tmp[i] = s[j++];        }        t = tmp;        for( int i = 0 ; i < 10 ;i++)        {            tmp[i] = 0;         }    //  cout<<tmp<<endl;        Morpheme mtmp( t , "int");        addSymbol(mtmp);    }    else if(count == 1)    {        string tmpst;        char tmp[ s.find(",") - s.find("int")]={0};        for( int i = 0 ,  j = s.find("int")+3 ; i < s.find(",")-s.find("int")-3 ; i++)        {            tmp[i] = s[j++];        }        tmpst = tmp;    //  cout<<tmpst<<endl;        for( int i = 0 ; i < 10 ;i++)        {            tmp[i] = 0;         }        Morpheme mtmp( tmpst , "int");        addSymbol(mtmp);        string tmpst2;        char tmp2[s.length() - s.find(",")]={0};        for( int i = 0 , j = s.find(",")+1 ; i < s.length() - s.find(",") - 1 ; i++)        {            tmp2[i] = s[j++];        }        tmpst2 = tmp2;        for( int i = 0 ; i < 10 ;i++)        {            tmp2[i] = 0;         }    //  cout<<tmpst2<<endl;        Morpheme mtmp2( tmpst2 , "int");        addSymbol(mtmp2);    }}void FindVariableId( string s )//找变量 {    string a;//  cout<<DivisionCodes.size()<<endl;    for( int i = 0 ; i < DivisionCodes.size() ; i++)    {//    cout<<DivisionCodes.size()<<endl;        if( s.find("char")!= -1 )        {        //  cout<<s<<endl;        /*  if(s.find(","))            {                string tmpst;                char tmp[ s.find(",") - s.find("char")];                for( int i = 0 ,  j = s.find("char")+4 ; i < s.find(",")-s.find("char")-4 ; i++)                {                    tmp[i] = s[j++];                }            //  cout<<s.find(",") - s.find("char")<<endl;                tmpst = tmp;                cout<<tmpst<<endl;                 Morpheme mtmp( tmpst , "char");                symbol.push_back(mtmp);            //  if(s.find(","),s.find(",")+1);            }*/             int x=0;                basic_string<char>::size_type y = 0;            while( (y=s.find(",",y)) != string::npos)//找到该句中有几个“,”             {                x++;                y++;            }         //  cout<<s<<endl;            ConsturtVar(s,x);//找到这一句中的变量并放到符号表中         }        if( s.find( "=" ) != -1 )        {            NameValue( s );        }     //  cout<<"find="<<s.find("=")<<endl;    //  cout<<"findp"<<s.find("printf")<<endl;        if( s.find("printf") != -1 )        {        //  cout<<s<<endl;            toprint( s );        }        if( s.find("int") != -1 && s.find("printf") == -1)        {            int x=0;                basic_string<char>::size_type y = 0;            while( (y=s.find(",",y)) != string::npos)//找到该句中有几个“,”             {                x++;                y++;            }         //  cout<<s<<endl;            ConsturtVarofint(s,x);//找到这一句中的变量并放到符号表中         }        if( s.find("+") != -1 )        {        //  getValue( s , " + " );        }        if( s.find("-") != -1 )        {        //  getValue( s , " - " );        }        if( s.find("*") != -1 )        {        //  getValue( s , " * " );        }        if( s.find("/") != -1 )        {        //  getValue( s , " / " );        }    } //  cout<<"ok"<<endl;}void lexical()//遍历分割代码 {    string a;    vector<string>::iterator p = DivisionCodes.begin();    for(;p!=DivisionCodes.end();p++)    {    //  cout<<*p<<endl;        FindVariableId(*p);    } }/*bool PushJudge( char c )//判断是否入队 {    if( c != ' ' && c != ';' && c != ',' && c!='(' && c != ')' )        return true;    else        return false; } */void transducer()//翻译器 {    string datacode ="data segment\n";    string codecode ="code segment\nassume cs:code, ds:data\nstart:\nmov ax,data\nmov ds,ax\n";    if( symbol.size() != 0)    {        string s;        for( int i = 0 ; i < symbol.size() ; i++ )        {            s = symbol[i].getid()+" "+"db"+" "+"'"+symbol[i].getatt()+"$"+"'"+"\n";            datacode = datacode+s;        }    //  cout<<datacode<<endl;    }    if( putsymbol.size() != 0 )    {        string s;        for( int i = 0 ; i < putsymbol.size() ; i++ )        {            s = "lea dx,"+putsymbol[i].getid()+"\n"+"mov ah,9h\nint 21h\n";            codecode = codecode+s;        }    //  cout<<codecode<<endl;    }    string huibiancode;    huibiancode = datacode + codecode +"mov ah,4ch\nint 21h\ncode ends\n end start\n";    cout<<huibiancode<<endl;    ofstream f;    f.open("shuchu.txt");    f<<huibiancode;    f.close();}int main(){    string ReadCodes;//输入代码     string outputCodes;//输出代码     char ReadCodesArray[1000];    ReadCode(ReadCodesArray);    //string a = "hello world";//  cout<<ReadCodesArray<<endl;    ReadCodes = ReadCodesArray;//现在我们有一个输入代码的字符数组和一个字符串     division( ReadCodes );    lexical();/*  for( int i = 0 ; i < DivisionCodes.size() ; i++ )    {        cout<<DivisionCodes[i]<<endl;    }    for( int i = 0 ; i < symbol.size() ; i++  )    {        cout<<"id:"<<symbol[i].getid()<<endl;        cout<<"att:"<<symbol[i].getatt()<<endl;     }*/ //  cout<<symbol.size()<<endl;//  symbolPrint();//  cout<<putsymbol.size()<<endl;/*  for(int i = 0 ; i < putsymbol.size();i++)    {        cout<<putsymbol[i].getid()<<endl;        cout<<putsymbol[i].getatt()<<endl;    }*/    //fanyi();    transducer();    cout<<"转化成功"<<endl;     //cout<<ReadCodes[1]<<endl;//  cout<<PushJudge( ' ')<<endl;//pushJudege没问题 //  outputCodes=Convert( a );//  for( int i=0 ; i< ReadCodes.length() ; i++)//  {//      cout<<ReadCodesArray[i]<<endl; //  }     return 0;}
0 0