~jacksonchen666/brainfuck_interpreter

b17369369b82dc213a771a8c1bd343c74c02730b — Jackson Chen 1 year, 1 month ago e691bbe
implement [ and ]

untested
1 files changed, 22 insertions(+), 1 deletions(-)

M brainfuck.go
M brainfuck.go => brainfuck.go +22 -1
@@ 7,6 7,7 @@ import (
	"log"
	"os"
	"regexp"
	"strings"

	"golang.org/x/term"
)


@@ 92,7 93,27 @@ func (ps *ProgramState) Step() error {
			return err
		}
		currentMemory = char
		// TODO: finish instruction set
	case '[':
		if currentMemory == 0 {
			// TODO: debug check for sanity
			code_after := (*ps.code)[ps.codePointer:]
			location := strings.Index(code_after, "]") + ps.codePointer
			if location == -1 {
				panic("next ] not found") // TODO: something more graceful
			}
			ps.codePointer = location
			break
		}
		*ps.loopStack = append(*ps.loopStack, ps.codePointer)
		// and continue the things inside the loop.
	case ']':
		if currentMemory != 0 {
			last := (*ps.loopStack)[len(*ps.loopStack)-1]
			*ps.loopStack = (*ps.loopStack)[:len(*ps.loopStack)-1]
			ps.codePointer = last
		} else {
			// just ignore ] because [ won't continue on currentMemory == 0
		}
		/*
			idea for [ and ]:
			a stack of loops, which has a pointer pos relative to brainfuck code after removing non-brainfuck code.