我有一个AST(抽象语法树),现在我想通过给它2个或更多数字并期望输出数学运算结果(就像计算器一样)来测试我的编译器。
我的问题是,构建解释器的最佳方式是什么? AST节点的访问是递归的,因此在到达树的末尾之前,我不知道存在多少封装的计算。但是由于这是迭代完成的,我该如何使所有操作在结束时进行?
谢谢
我有一个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;
...
}
}