先学习一个最简单的 编译如下代码 " a + 10 + b + c ; ";
关键字为{ "int", "+", "=", ";", "i" }; "i"表示变量或数字
Code
下面的代码一个是产生临时变量,一个是产生四元表达式
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;
}
读入下一个单词
string id;
public void Scaner()
{
sym = CompilerTable.Sym(words[count]);
id = words[count];
count ++ ;
}
采用产生式 E->T{+T}; T->i
则T的函数如下
{
if (sym == " i " )
{
string _id = id;
Scaner();
return _id;
}
return " error " ;
}
E的函数如下
Codepublic 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;
{
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; "
{
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 " ;
}
}