简单编译器的实现 一

先学习一个最简单的  编译如下代码    " a + 10 + b + c ; ";

关键字为{ "int", "+", "=", ";", "i" };   "i"表示变量或数字
 

ContractedBlock.gifCode

 

下面的代码一个是产生临时变量,一个是产生四元表达式

ContractedBlock.gif ExpandedBlockStart.gif Code static  int  _t  =  0 ;

        
public  string  NewTemp()
        {           
            
return  " T "  +  (_t ++ ).ToString();
        }



        
string  _s  =  "" ;
        
public  void  emit( string  result,  string  arg1,  string  op,  string  arg2)
        {
            _s 
+=  result  +  " = "  +  arg1  +  op  +  arg2;
        }

 

 

读入下一个单词

ContractedBlock.gif ExpandedBlockStart.gif Code string  sym;
        
string  id;
        
public  void  Scaner()
        {
            sym 
=  CompilerTable.Sym(words[count]);

            id 
=  words[count];
            
            count
++ ;

        }

 

采用产生式  E->T{+T};  T->i

则T的函数如下

 

ContractedBlock.gif ExpandedBlockStart.gif Code  string  T()
        {
            
if  (sym  ==  " i " )
            {
                
string  _id  =  id;

                Scaner();
                
return  _id;
            }

            
return  " error " ;
            
        }

 

 

 E的函数如下

 ContractedBlock.gifExpandedBlockStart.gifCodepublic string E()
        {
            
string E1 = T();

            
while (sym == "+"
            {
                Scaner();

                
string E2 = T();

                
string temp = NewTemp();


                emit(temp, E1, 
"+", E2);


                E1 
= temp;
            }

            
return E1;
        }

 

经一个Start函数调用


        public void Start()
        {
            Scaner();
            E();

        }

 

即可产生编译 出的代码 "T0=a+10; T1=T0+b; T2=T1+c; "   其中E 返回的值为T2

 

如此我们加入一个新的产生式 S->T=E;

ContractedBlock.gif ExpandedBlockStart.gif Code  string  S()
        {
            
string  S1  =  T();

            
if  (sym  ==  " = " )
            {
                Scaner();

                emit(S1, E(), 
"" "" );
            }

            
return  S1;
        }

 string code = "a = a + 10 + b + c ; ";


        public void Start()
        {
            Scaner();
            S();

        }

 

产生代码为"T0=a+10; T1=T0+b; T2=T1+c; a=T2; "

 

 

 

 

 


ExpandedBlockStart.gif class  CompilerTable
    {
        
public  static  string [] tables  =  new  string [] {  " int " " + " " = " " ; " " i "  };

        
public  static  string  Sym( string  str)
        {           
            
foreach  ( string  s  in  tables)
            {
                
if  (str  ==  s)  return  s;
            }

            
// if ((str[0] >= '0') && (str[0] <= '9')) return "d";

            
return  " i " ;

        }
    }

转载于:https://www.cnblogs.com/feathersky/archive/2008/12/13/1354391.html

你可能感兴趣的:(简单编译器的实现 一)