Machine.Execute returns an error on unknown instruction

This commit is contained in:
Sasha Koshka 2022-08-28 17:56:41 -04:00
parent 7b93b550e5
commit a2b64fcc19
1 changed files with 12 additions and 2 deletions

View File

@ -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.