나는 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