From 460425c490bf1ac5f4a4838f2b40723bf0d5239b Mon Sep 17 00:00:00 2001 From: Tristan Morgan Date: Fri, 10 May 2024 12:35:46 +1000 Subject: [PATCH] cleanup common code. --- parser/instruction.go | 8 ++++++++ parser/instruction_test.go | 30 ++++++++++++++++++++++++++++++ parser/tokenise.go | 8 ++------ 3 files changed, 40 insertions(+), 6 deletions(-) diff --git a/parser/instruction.go b/parser/instruction.go index 30d71a4..39c315c 100644 --- a/parser/instruction.go +++ b/parser/instruction.go @@ -78,3 +78,11 @@ func (inst Instruction) SameOp(instTwo Instruction) bool { func (inst Instruction) Complement(instTwo Instruction) bool { return inst.SameOp(instTwo) && inst.operand+instTwo.operand == 0 } + +// IsZeroOp returns true for ops that have left the pointer on a zero +func (inst Instruction) IsZeroOp() bool { + return inst.operator == opJmpNz || + inst.operator == opNoop || + inst.operator == opMove || + (inst.operator == opSetVal && inst.operand == 0) +} diff --git a/parser/instruction_test.go b/parser/instruction_test.go index 5c6cee3..64652dd 100644 --- a/parser/instruction_test.go +++ b/parser/instruction_test.go @@ -32,6 +32,36 @@ func TestNewInstruction(t *testing.T) { } } +func TestIsZeroOp(t *testing.T) { + program := []Instruction{ + {opNoop, 0}, + {opAddDp, 1}, + {opAddVal, 1}, + {opSetVal, -1}, + {opSetVal, 0}, + {opOut, 1}, + {opIn, 1}, + {opJmpZ, 0}, + {opJmpNz, 0}, + } + want := []bool{ + true, + false, + false, + false, + true, + false, + false, + false, + true, + } + + for idx, val := range program { + if want[idx] != val.IsZeroOp() { + t.Errorf("testing %v got %v want %v", val, val.IsZeroOp(), want[idx]) + } + } +} func TestSameOp(t *testing.T) { opsList := []Opcode{ opNoop, diff --git a/parser/tokenise.go b/parser/tokenise.go index c434445..e71f988 100644 --- a/parser/tokenise.go +++ b/parser/tokenise.go @@ -36,9 +36,7 @@ func Tokenise(input io.ByteReader) (program []Instruction, err error) { program[pc-1].operand += instruction.operand program = program[:pc] pc-- - } else if program[pc-1].SameOp(NewInstruction(']')) || - program[pc-1].operator == opMove || - program[pc-1].operator == opNoop { + } else if program[pc-1].IsZeroOp() { operand := instruction.operand program = program[:pc] program = append(program, Instruction{opSetVal, operand}) @@ -53,9 +51,7 @@ func Tokenise(input io.ByteReader) (program []Instruction, err error) { jmpStack = jmpStack[:len(jmpStack)-1] program[pc].operand = jmpPc program[jmpPc].operand = pc - if jmpPc == 1 || - program[jmpPc-1].Complement(Instruction{opSetVal, 0}) || - program[jmpPc-1].SameOp(NewInstruction(']')) { + if program[jmpPc-1].IsZeroOp() { pc = jmpPc program = program[:pc] pc--