我應該使用解釋或訪問者設計模式?
我覺得名字給出提示;-)
遊客有利於對AST的一般操作,但用於執行單一功能(執行/解釋),你只需要一個方法,從而解釋模式。
這裏是一個非常簡單的例子(但它確實沒有變得更加複雜,重要的是,即使是複雜的翻譯):
// Holds function scope etc.
class Context { … }
abstract class Node {
public abstract object Execute(Context ctx);
}
class Number {
private readonly int x;
public Number(int x) { this.x = x; }
public object Execute(Context ctx) { return x; }
}
class Addition {
private readonly Node left, right;
public Addition(Node left, Node right) {
this.left = left;
this.right = right;
}
public object Execute(Context ctx) {
// Verification omitted: do the nested expressions evaluate to a number?
return ((int) (left.Execute(ctx)) + ((int) (right.Execute(ctx))
}
}
...和你有它。一個簡單的解釋器,知道加法。下面是一個使用示例:
var ast = new Addition(new Number(23), new Number(42));
Console.WriteLine("Result = {0}", ast.Execute(new Context()));
最佳做法是將編譯與解釋相結合。 AST通常不太適合高效的解釋,因此將它降低到更簡單的表示,擴展所有語法糖,儘可能解析標識符(如果有詞法範圍界定)是有意義的。然後纔可以開始翻譯。 下面答案中的「解釋者」模式是一個很好的起點,雖然有很多有趣的優化。請參閱SISC的靈感。 –