umx_compiler

UMX virtual machine "Monkey" interpreter / bytecode compiler
git clone git://bsandro.tech/umx_compiler
Log | Files | Refs

commit ca13c7ec05c2e8aee27f5545d05abe993851ba57
parent 4469a343e5eb7af7b7ec8fb3a348630b159b60fc
Author: bsandro <email@bsandro.tech>
Date:   Fri, 24 Jun 2022 00:01:04 +0300

eval integer infix expressions: + - * /

Diffstat:
Meval/eval.go | 28++++++++++++++++++++++++++++
Meval/eval_test.go | 4++++
2 files changed, 32 insertions(+), 0 deletions(-)

diff --git a/eval/eval.go b/eval/eval.go @@ -32,6 +32,10 @@ func Eval(node ast.Node) object.Object { case *ast.PrefixExpression: right := Eval(node.Right) return evalPrefixExpression(node.Operator, right) + case *ast.InfixExpression: + left := Eval(node.Left) + right := Eval(node.Right) + return evalInfixExpression(node.Operator, left, right) } return nil } @@ -75,3 +79,27 @@ func evalMinusPrefixOperatorExpression(right object.Object) object.Object { value := right.(*object.Integer).Value return &object.Integer{Value: -value} } + +func evalInfixExpression(operator string, left, right object.Object) object.Object { + if left.Type() == object.INTEGER_OBJ && right.Type() == object.INTEGER_OBJ { + return evalIntegerInfixExpression(operator, left, right) + } + return NULL +} + +func evalIntegerInfixExpression(operator string, left, right object.Object) object.Object { + leftValue := left.(*object.Integer).Value + rightValue := right.(*object.Integer).Value + switch operator { + case "+": + return &object.Integer{Value: leftValue + rightValue} + case "-": + return &object.Integer{Value: leftValue - rightValue} + case "*": + return &object.Integer{Value: leftValue * rightValue} + case "/": + return &object.Integer{Value: leftValue / rightValue} + default: + return NULL + } +} diff --git a/eval/eval_test.go b/eval/eval_test.go @@ -16,6 +16,10 @@ func TestEvalIntegerExpression(t *testing.T) { {"-8", -8}, {"10", 10}, {"-256", -256}, + {"1+2*3", 7}, + {"10/5", 2}, + {"3*3*3+10", 37}, + {"(5+10*2+15/3)*2+-10", 50}, } for _, tt := range tests { evaluated := testEval(tt.input)