2012-05-11 6 views
6

私はAST(抽象構文木)を持っていますが、今は2つ以上の数値を与えて計算機をテストしたいと思っています。ASTインタープリタ?

私の質問は、インタープリタを構築する最良の方法は何ですか? ASTノードの訪問は再帰的なので、ツリーの最後までカプセル化された計算がいくつあるかわかりません。しかし、これは反復によって反復が行われるので、どのようにして最後まですべての操作を行うことができますか?これはインタプリタの注目点が変更されるため、「後藤」で行うことが迷惑な何

int interpret(tree t) 
{ /* left to right, top down scan of tree */ 
    switch (t->nodetype) { 
    case NodeTypeInt: 
     return t->value; 
    case NodeTypeVariable: 
     return t->symbtable_entry->value 
    case NodeTypeAdd: 
     { int leftvalue= interpret(t->leftchild); 
      int rightvalue= interpret(t->rightchild); 
      return leftvalue+rightvalue; 
     } 
    case NodeTypeMultiply: 
     { int leftvalue= interpret(t->leftchild); 
      int rightvalue= interpret(t->rightchild); 
      return leftvalue*rightvalue; 
     } 
    ... 
    case NodeTypeStatementSequence: // assuming a right-leaning tree 
     { interpret(t->leftchild); 
      interpret(t->rightchild); 
      return 0; 
     } 
    case NodeTypeAssignment: 
     { int right_value=interpret(t->rightchild); 
      assert: t->leftchild->Nodetype==NodeTypeVariable; 
      t->leftchild->symbtable_entry->value=right_value; 
      return right_value; 
     } 
    case NodeTypeCompareForEqual: 
     { int leftvalue= interpret(t->leftchild); 
      int rightvalue= interpret(t->rightchild); 
      return leftvalue==rightvalue; 
     } 
    case NodeTypeIfThenElse 
     { int condition=interpret(t->leftchild); 
      if (condition) interpret(t->secondchild); 
      else intepret(t->thirdchild); 
      return 0; 
    case NodeTypeWhile 
     { int condition; 
      while (condition=interpret(t->leftchild)) 
       interpret(t->rightchild); 
      return 0; 

    ... 
    } 
} 

あなたはASTをしたら

答えて

14

Intepretersは、コードにはかなり簡単ですありがとうございました。 gotoまたは関数呼び出しを実装するには、ラベルまたは関数宣言をツリーで検索し、そこで実行を続行する必要があります。 [ツリーを事前走査し、ルックアップテーブル内のすべてのラベル位置/関数宣言を収集することで、これを高速化できます。これはコンパイラを構築するための第一歩です。]これでさえ十分ではありません。再帰スタックを調整する必要があります。再帰スタックは関数呼び出しに隠れているため、やりにくいです。このコードを明示的に管理された再帰スタックを持つ反復ループに変換すると、スタックを修正するのがずっと簡単になります。

+0

if文があり、その間に演算子を比較するとどうしますか? – Nitrate

+0

CompareForEqual、Assignment、IfThenElseをサポートするためのインタプリタへのパッチを参照 –

+0

ありがとうアイラ! – Nitrate