Back: Nodes Parsing | Chapters | Next: Conclusion
Add a method def eval(self, variables) to every AST node and
recursively call eval until you reach the terminal leaves.
For now we will disregard all runtime errors.
Value
class Value(AST):
...
def eval(self, variables):
return self.valueVariable
class Variable(AST):
...
def eval(self, variables):
return variables[self.name]FuncCall
class FuncCall(AST):
...
def eval(self, variables):
args = [arg.eval(variables) for arg in self.args]
return variables[self.name](args)BinaryOp
class BinaryOp(AST):
...
def eval(self, variables):
left = self.left.eval(variables)
right = self.right.eval(variables)
if self.op == '+':
return left + right
if self.op == '-':
return left - right
if self.op == '*':
return left * right
if self.op == '/':
return left / right
if self.op == '%':
return left % rightUnaryOp
class UnaryOp(AST):
...
def eval(self, variables):
item = self.item.eval(variables)
if self.op == '+':
return +item # redundant, but ey why not
if self.op == '-':
return -itemAnd we are done!
%>py main.py
2.2704074859237844