Skip to content

Commit

Permalink
Implement an iterator for byte to Instruction convertion.
Browse files Browse the repository at this point in the history
  • Loading branch information
tristanmorgan committed Oct 13, 2024
1 parent 351444c commit 7345dcb
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 11 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/tristanmorgan/bfg

go 1.22.0
go 1.23.0
21 changes: 21 additions & 0 deletions parser/instruction.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
package parser

import (
"io"
"iter"
)

// Instruction structure for intermediate program
type Instruction struct {
operator Opcode
Expand Down Expand Up @@ -37,6 +42,22 @@ var instMap = map[byte]Instruction{
']': {opJmpNz, 0},
}

// Instructions returns an iterator of the instructions.
func Instructions(input io.ByteReader) iter.Seq[Instruction] {
return func(yield func(Instruction) bool) {

for {
chr, err := input.ReadByte()
if err == io.EOF {
break
}
if !yield(NewInstruction(chr)) {
return
}
}
}
}

// NewInstruction created from a sourcecode byte
func NewInstruction(chr byte) Instruction {
return instMap[chr]
Expand Down
7 changes: 5 additions & 2 deletions parser/instruction_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package parser

import (
"bufio"
"fmt"
"reflect"
"strings"
"testing"
"unsafe"
)
Expand Down Expand Up @@ -57,15 +59,16 @@ func TestNewInstruction(t *testing.T) {
{opJmpNz, 0},
}

for idx, val := range []byte(sourceCode) {
idx := 0
for got := range Instructions(bufio.NewReader(strings.NewReader(sourceCode))) {
t.Run(program[idx].String(), func(t *testing.T) {
got := NewInstruction(val)
want := program[idx]

if !reflect.DeepEqual(got, want) {
t.Errorf("got %v want %v", got, want)
}
})
idx++
}
}

Expand Down
9 changes: 1 addition & 8 deletions parser/tokenise.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,7 @@ func Tokenise(input io.ByteReader) (program []Instruction, err error) {
jmpStack := make([]int, 0)
program = append(program, Instruction{opNoop, 0})
pc++
for {
chr, err := input.ReadByte()
if err == io.EOF {
break
} else if err != nil {
return nil, errors.New("tokenisation read error")
}
instruction := NewInstruction(chr)
for instruction := range Instructions(input) {
program = append(program, instruction)
switch instruction.operator {
case opNoop:
Expand Down

0 comments on commit 7345dcb

Please sign in to comment.