From 378683d25bdae89fa446b2b82f8dda5d6b34ea33 Mon Sep 17 00:00:00 2001 From: Marc Vertes Date: Thu, 14 Mar 2024 14:37:32 +0100 Subject: feat: initial support of closures Also detection and automatic execution of main function. Make sure that all debug is output to stderr. --- vm/type.go | 3 +++ vm/vm.go | 2 +- vm/vm_test.go | 8 ++++---- 3 files changed, 8 insertions(+), 5 deletions(-) (limited to 'vm') diff --git a/vm/type.go b/vm/type.go index d29de48..16e3733 100644 --- a/vm/type.go +++ b/vm/type.go @@ -26,6 +26,9 @@ type Value struct { // NewValue returns an addressable zero value for the specified type. func NewValue(typ *Type) Value { + if typ.Rtype.Kind() == reflect.Func { + typ = TypeOf(0) // Function value is its index in the code segment. + } return Value{Type: typ, Data: reflect.New(typ.Rtype).Elem()} } diff --git a/vm/vm.go b/vm/vm.go index a8c1f28..6472dae 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -145,7 +145,7 @@ func (m *Machine) Run() (err error) { case Calli: mem = append(mem, ValueOf(ip+1), ValueOf(fp)) fp = sp + 2 - ip += int(op[2]) + ip = int(op[2]) continue case CallX: // Should be made optional. l := int(op[2]) diff --git a/vm/vm_test.go b/vm/vm_test.go index fb71176..8fa8e71 100644 --- a/vm/vm_test.go +++ b/vm/vm_test.go @@ -75,7 +75,7 @@ var tests = []struct { {0, Push, 3}, // 1 {0, Return, 1, 1}, // 2 {0, Push, 1}, // 3 - {0, Calli, -3}, // 4 + {0, Calli, 1}, // 4 {0, Exit}, // 5 }, start: 0, end: 1, mem: "[3]", @@ -138,16 +138,16 @@ var tests = []struct { {0, JumpTrue, 9}, // 3 [], goto 12 {0, Fdup, -2}, // 4 [i] {0, Subi, 2}, // 5 [(i-2)] - {0, Calli, -5}, // 6 [fib(i-2)] + {0, Calli, 1}, // 6 [fib(i-2)] {0, Fdup, -2}, // 7 [fib(i-2) i] {0, Subi, 1}, // 8 [(i-2) (i-1)] - {0, Calli, -8}, // 9 [fib(i-2) fib(i-1)], call 1 + {0, Calli, 1}, // 9 [fib(i-2) fib(i-1)], call 1 {0, Add}, // 10 [fib(i-2)+fib(i-1)] {0, Return, 1, 1}, // 11 return i {0, Fdup, -2}, // 12 [i] {0, Return, 1, 1}, // 13 return i {0, Push, 6}, // 14 [1] - {0, Calli, -14}, // 15 [fib(*1)], call 1 + {0, Calli, 1}, // 15 [fib(*1)], call 1 {0, Exit}, // 16 }, start: 0, end: 1, mem: "[8]", -- cgit v1.2.3