~jacksonchen666/brainfuck_interpreter

2dd3f7780c38b37fb490c10fc5546fb4aa7ae47c — Jackson Chen 1 year, 1 month ago 02b0942
refactor Step function

- step function part of ProgramState
- current memory now has a dedicated variable
- now relies on ProgramState for stuff like code
2 files changed, 10 insertions(+), 8 deletions(-)

M brainfuck.go
M cmd/test/main.go
M brainfuck.go => brainfuck.go +9 -7
@@ 50,31 50,31 @@ func getChar() (byte, error) {
}

// Does a single brainfuck instruction.
// ps: ProgramState
// instruction: The single instruction
func Step(ps *ProgramState, instruction rune) {
func (ps *ProgramState) Step() {
	if ps.memoryPointer >= len(*ps.tape) {
		*ps.tape = append(*ps.tape, 0)
	}
	instruction := (*ps.code)[ps.codePointer]
	currentMemory := (*ps.tape)[ps.memoryPointer]
	switch instruction {
	case '+':
		(*ps.tape)[ps.memoryPointer]++
		currentMemory++
	case '-':
		(*ps.tape)[ps.memoryPointer]--
		currentMemory--
	case '<':
		// oh no, a float on an int
		ps.memoryPointer = int(math.Max(float64(ps.memoryPointer-1), 0))
	case '>':
		ps.memoryPointer++
	case '.':
		char := string((*ps.tape)[ps.memoryPointer])
		char := string(currentMemory)
		fmt.Print(char)
	case ',':
		char, err := getChar()
		if err != nil {
			panic(err) // TODO: something more graceful
		}
		(*ps.tape)[ps.memoryPointer] = char
		currentMemory = char
		// TODO: finish instruction set
		/*
			idea for [ and ]:


@@ 85,6 85,8 @@ func Step(ps *ProgramState, instruction rune) {
			on zero and ]: continue
		*/
	}
	(*ps.tape)[ps.memoryPointer] = currentMemory
	ps.codePointer++
}

func InitProgramState(code *string) *ProgramState {

M cmd/test/main.go => cmd/test/main.go +1 -1
@@ 16,6 16,6 @@ func main() {
	programState := brainfuck_interpreter.InitProgramState(&instructions)

	for _, instruction := range instructions {
		brainfuck_interpreter.Step(programState, instruction)
		programState.Step()
	}
}