Machine.Execute returns an error on unknown instruction
This commit is contained in:
parent
7b93b550e5
commit
a2b64fcc19
14
creature.go
14
creature.go
|
@ -28,6 +28,7 @@ const (
|
||||||
// ErrorIDTaken is returned by Register when a new function is
|
// ErrorIDTaken is returned by Register when a new function is
|
||||||
// registered with the same ID as another one.
|
// registered with the same ID as another one.
|
||||||
ErrorIDTaken Error = iota
|
ErrorIDTaken Error = iota
|
||||||
|
ErrorUnknownInstruction
|
||||||
)
|
)
|
||||||
|
|
||||||
// Error returns a textual description of the error.
|
// Error returns a textual description of the error.
|
||||||
|
@ -35,6 +36,8 @@ func (err Error) Error() (description string) {
|
||||||
switch err {
|
switch err {
|
||||||
case ErrorIDTaken:
|
case ErrorIDTaken:
|
||||||
description = "this ID is taken by another function"
|
description = "this ID is taken by another function"
|
||||||
|
case ErrorUnknownInstruction:
|
||||||
|
description = "machine encountered unknown instruction"
|
||||||
}
|
}
|
||||||
|
|
||||||
return
|
return
|
||||||
|
@ -49,8 +52,9 @@ func (machine *Machine) Reset() {
|
||||||
|
|
||||||
// Execute starts execution at the address specified by offset. The machine will
|
// Execute starts execution at the address specified by offset. The machine will
|
||||||
// run until a HALT instruction is encountered, or the end of program memory is
|
// run until a HALT instruction is encountered, or the end of program memory is
|
||||||
// reached.
|
// reached. If an unknown instruction is encountered, the machine halts and
|
||||||
func (machine *Machine) Execute(offset int) {
|
// returns an error.
|
||||||
|
func (machine *Machine) Execute(offset int) (err error) {
|
||||||
machine.counter = offset
|
machine.counter = offset
|
||||||
|
|
||||||
for machine.counter < len(machine.Program) {
|
for machine.counter < len(machine.Program) {
|
||||||
|
@ -173,9 +177,15 @@ func (machine *Machine) Execute(offset int) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
default:
|
||||||
|
err = ErrorUnknownInstruction
|
||||||
|
return
|
||||||
}
|
}
|
||||||
machine.counter++
|
machine.counter++
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Instruction returns the current instruction in program memory.
|
// Instruction returns the current instruction in program memory.
|
||||||
|
|
Loading…
Reference in New Issue