Program wrapper struct

This commit is contained in:
Ian Gulliver
2021-11-19 20:16:01 -10:00
parent c536961df3
commit 5ccf6832c8
3 changed files with 18 additions and 13 deletions

View File

@@ -7,27 +7,27 @@ import "strings"
import "github.com/firestuff/subcoding/vm" import "github.com/firestuff/subcoding/vm"
import "github.com/pkg/errors" import "github.com/pkg/errors"
func Assemble(src []byte) ([][]*vm.Instruction, error) { func Assemble(src []byte) (*vm.Program, error) {
prog, err := parse(src) parsed, err := parse(src)
if err != nil { if err != nil {
return nil, err return nil, err
} }
fncs := [][]*vm.Instruction{} ret := &vm.Program{}
for f, fnc := range prog.Functions { for f, fnc := range parsed.Functions {
instrs, err := assembleFunction(fnc) instrs, err := assembleFunction(fnc)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "At function index %d\n", f) return nil, errors.Wrapf(err, "At function index %d\n", f)
} }
fncs = append(fncs, instrs) ret.Functions = append(ret.Functions, instrs)
} }
return fncs, nil return ret, nil
} }
func AssembleString(src string) ([][]*vm.Instruction, error) { func AssembleString(src string) (*vm.Program, error) {
return Assemble([]byte(src)) return Assemble([]byte(src))
} }

5
vm/program.go Normal file
View File

@@ -0,0 +1,5 @@
package vm
type Program struct {
Functions [][]*Instruction
}

View File

@@ -6,7 +6,7 @@ type State struct {
running bool running bool
err error err error
functions [][]*Instruction program *Program
functionIndex int64 functionIndex int64
instructionIndex int64 instructionIndex int64
@@ -15,9 +15,9 @@ type State struct {
stack []*stackFrame stack []*stackFrame
} }
func NewState(functions [][]*Instruction) (*State, error) { func NewState(prog *Program) (*State, error) {
return &State{ return &State{
functions: functions, program: prog,
globalMemory: NewMemory(16), globalMemory: NewMemory(16),
}, nil }, nil
} }
@@ -43,7 +43,7 @@ func (state *State) stackFrame() *stackFrame {
} }
func (state *State) function() []*Instruction { func (state *State) function() []*Instruction {
return state.functions[state.functionIndex] return state.program.Functions[state.functionIndex]
} }
func (state *State) setError(err error) { func (state *State) setError(err error) {
@@ -52,7 +52,7 @@ func (state *State) setError(err error) {
} }
func (state *State) setHandlers() { func (state *State) setHandlers() {
for _, fnc := range state.functions { for _, fnc := range state.program.Functions {
for _, instr := range fnc { for _, instr := range fnc {
handler, found := opHandlers[instr.OpCode] handler, found := opHandlers[instr.OpCode]
if !found { if !found {
@@ -71,7 +71,7 @@ func (state *State) processInstruction() {
state.instructionIndex += 1 state.instructionIndex += 1
instr.opHandler(state, instr) instr.opHandler(state, instr)
if state.functionIndex >= int64(len(state.functions)) { if state.functionIndex >= int64(len(state.program.Functions)) {
state.ret() state.ret()
} }