私は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をしたら
if文があり、その間に演算子を比較するとどうしますか? – Nitrate
CompareForEqual、Assignment、IfThenElseをサポートするためのインタプリタへのパッチを参照 –
ありがとうアイラ! – Nitrate