我正在使用由Joel Pobar编写的这个示例项目。我得到这个来自:如何实现if和else语句?当编写一个语言编译器
http://msdn.microsoft.com/en-us/magazine/cc136756.aspx
好了,所以要实现一个简单的打印命令我需要:
首先声明在Ast.cs类:
// print <expr>
public class Print : Stmt
{
public Expr Expr;
}
其次我将该方法应用到Parser.cs:
// <stmt> := print <expr>
// <expr> := <string>
// | <int>
// | <arith_expr>
// | <ident>
if (this.tokens[this.index].Equals("Printl"))
{
this.index++;
Print print = new Print();
print.Expr = this.ParseExpr();
result = print;
}
最后我实现了在CodeGen.cs检查:
else if (stmt is Print)
{
// the "print" statement is an alias for System.Console.WriteLine.
// it uses the string case
this.GenExpr(((Print)stmt).Expr, typeof(string));
this.il.Emit(Emit.OpCodes.Call, typeof(System.Console).GetMethod("WriteLine", new System.Type[] { typeof(string) }));
}
现在,这允许我创建了一个翻译,编译一个文件,如果它的语法匹配。该解释器支持变量,循环和基本打印文本和变量值。然而,我对如何实现if和else语句有些困惑。
我编辑了自己的冠军。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –
你说你有循环工作? 'if-else'非常像循环控制表达式。 –