Skip to content

Commit

Permalink
cleanup common code.
Browse files Browse the repository at this point in the history
  • Loading branch information
tristanmorgan committed May 10, 2024
1 parent be1a32f commit 460425c
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 6 deletions.
8 changes: 8 additions & 0 deletions parser/instruction.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
30 changes: 30 additions & 0 deletions parser/instruction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
8 changes: 2 additions & 6 deletions parser/tokenise.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand All @@ -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--
Expand Down

0 comments on commit 460425c

Please sign in to comment.