Machine is now a generic type

This commit is contained in:
Sasha Koshka 2022-08-29 10:48:45 -04:00
parent 810ecdb3ac
commit 635aced0d4
4 changed files with 56 additions and 44 deletions

View File

@ -1,24 +1,31 @@
package creature package creature
// Word is a type constraint defining possible word types for the Machine.
type Word interface {
int8 | int16 | int32 | int64 |
uint8 | uint16 | uint32 | uint64 |
int | uint
}
// Machine is a stack machine. It contains an array of integers as its program // Machine is a stack machine. It contains an array of integers as its program
// data, and provides methods to run this program data, as well as interact with // data, and provides methods to run this program data, as well as interact with
// it. // it.
type Machine struct { type Machine [WORD Word] struct {
// Program is not modified by the machine, and can be freely set before // Program is not modified by the machine, and can be freely set before
// the machine is started. // the machine is started.
Program []int Program []WORD
stack []int stack []WORD
block []int block []WORD
counter int counter WORD
pointer int pointer WORD
functions map[int]MachineFunction functions map[WORD]MachineFunction[WORD]
} }
// MachineFunction is a function that can extend the functionality of the stack // MachineFunction is a function that can extend the functionality of the stack
// machine. It is passed a pointer to the machine that is calling it, and the // machine. It is passed a pointer to the machine that is calling it, and the
// machine will halt execution if true is returned. // machine will halt execution if true is returned.
type MachineFunction func(machine *Machine) (stop bool) type MachineFunction [WORD Word] func(machine *Machine[WORD]) (stop bool)
// All supported opcodes // All supported opcodes
const ( const (
@ -68,7 +75,7 @@ func (err Error) Error() (description string) {
// Reset resets the stack of the machine. This should be called before Execute, // Reset resets the stack of the machine. This should be called before Execute,
// since Execute does not reset the stack. // since Execute does not reset the stack.
func (machine *Machine) Reset() { func (machine *Machine[WORD]) Reset() {
machine.stack = nil machine.stack = nil
machine.pointer = 0 machine.pointer = 0
} }