Skip to content

Commit

Permalink
Extend and test minimal example.
Browse files Browse the repository at this point in the history
  • Loading branch information
eigenhombre committed Jul 29, 2023
1 parent 3e82c59 commit 1cad80c
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 16 deletions.
8 changes: 6 additions & 2 deletions chunk.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@ type chunk struct {
index int
}

func newChunk() *chunk {
return &chunk{[]Entry{}, 0}
func newChunk(entries ...Entry) *chunk {
c := &chunk{}
if len(entries) > 0 {
c.entries = entries
}
return c
}

func (c *chunk) add(e Entry) {
Expand Down
12 changes: 12 additions & 0 deletions chunk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,15 @@ func TestChunk(t *testing.T) {
t.Error("chunk should have more")
}
}

func TestChunkVariadic(t *testing.T) {
c := newChunk(opEntry(op_ret), constantEntry(1))
if !c.hasMore() {
t.Error("chunk should have more")
}
c.next()
c.next()
if c.hasMore() {
t.Error("chunk should not have more")
}
}
15 changes: 5 additions & 10 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,15 @@ package main
import "fmt"

func main() {
C := func(i value) Entry { return constantEntry(i) }
Op := func(o opcode) Entry { return opEntry(o) }
// Make our stack
s := newStack()
// Create a chunk of code
c := newChunk()
// Create code to push 1 and 2 on the stack, add them, print the
// result, and return:
c.add(constantEntry(1))
c.add(constantEntry(2))
c.add(opEntry(op_add))
c.add(opEntry(op_print))
c.add(opEntry(op_ret))
// Create a VM
c := newChunk(C(1), C(2), Op(op_add), Op(op_ret))
// Run the code in a new VM:
vm := newVM(c)
// Run the VM
vm.run(s)
fmt.Println("OK")
fmt.Println(vm.run(s))
}
19 changes: 15 additions & 4 deletions vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ func newVM(c *chunk) *vm {
return &vm{code: c, ip: 0}
}

func (v *vm) execOpcode(o opcode, s *stack) {
func (v *vm) execOpcode(o opcode, s *stack) *value {
switch o {
case op_add:
b, err := s.pop()
Expand All @@ -28,17 +28,28 @@ func (v *vm) execOpcode(o opcode, s *stack) {
}
println(v)
case op_ret:
return
v, err := s.pop()
if err != nil {
panic(err) // fixme
}
// End of processing may be signalled by returning a value:
return &v
}
return nil
}
func (v *vm) run(s *stack) {

func (v *vm) run(s *stack) value {
for v.code.hasMore() {
e := v.code.next()
switch e.typ {
case typ_opcode:
v.execOpcode(e.opcode, s)
ret := v.execOpcode(e.opcode, s)
if ret != nil {
return *ret
}
case typ_constant:
s.push(e.value)
}
}
return 0
}

0 comments on commit 1cad80c

Please sign in to comment.