From a2b64fcc199ae0e6dbda839bfec95c0d5ac91e75 Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Sun, 28 Aug 2022 17:56:41 -0400 Subject: [PATCH] Machine.Execute returns an error on unknown instruction --- creature.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/creature.go b/creature.go index ce58b6b..ae992b8 100644 --- a/creature.go +++ b/creature.go @@ -28,6 +28,7 @@ const ( // ErrorIDTaken is returned by Register when a new function is // registered with the same ID as another one. ErrorIDTaken Error = iota + ErrorUnknownInstruction ) // Error returns a textual description of the error. @@ -35,6 +36,8 @@ func (err Error) Error() (description string) { switch err { case ErrorIDTaken: description = "this ID is taken by another function" + case ErrorUnknownInstruction: + description = "machine encountered unknown instruction" } return @@ -49,8 +52,9 @@ func (machine *Machine) Reset() { // 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 -// reached. -func (machine *Machine) Execute(offset int) { +// reached. If an unknown instruction is encountered, the machine halts and +// returns an error. +func (machine *Machine) Execute(offset int) (err error) { machine.counter = offset for machine.counter < len(machine.Program) { @@ -173,9 +177,15 @@ func (machine *Machine) Execute(offset int) { return } } + + default: + err = ErrorUnknownInstruction + return } machine.counter++ } + + return } // Instruction returns the current instruction in program memory.