Created
August 22, 2013 07:46
-
-
Save aisk/6304249 to your computer and use it in GitHub Desktop.
Go brainfuck hello world
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
const ( | |
MEMORY_SIZE = 100 | |
) | |
type State struct { | |
Instructions string | |
Memory []byte | |
Ip int | |
Mp int | |
} | |
func NewState(instruactions string) *State { | |
return &State{ | |
Instructions: instruactions, | |
Memory: make([]byte, MEMORY_SIZE), | |
} | |
} | |
func (self *State) Step() { | |
// self.PrintInstruction() | |
instruction := self.getInstruction() | |
self.Ip ++ | |
switch instruction { | |
case '+': | |
self.handlePlus() | |
case '-': | |
self.handleMinus() | |
case '>': | |
self.handleLeft() | |
case '<': | |
self.handleRight() | |
case '[': | |
self.handleStart() | |
case ']': | |
self.handleEnd() | |
case '.': | |
self.handleOutput() | |
} | |
} | |
func (self *State) PrintInstruction() { | |
// fmt.Println(self.Memory) | |
// for i:=0; i<self.Mp; i++ { | |
// fmt.Print(" ") | |
// } | |
// fmt.Println("^") | |
println(self.Instructions) | |
for i:=0; i<self.Ip; i++ { | |
print(" ") | |
} | |
println("^") | |
} | |
func (self *State) Run() { | |
defer func() { | |
recover() | |
}() | |
for { | |
self.Step() | |
} | |
} | |
func (self *State) getInstruction() byte { | |
return self.Instructions[self.Ip] | |
} | |
func (self *State) handlePlus() { | |
self.Memory[self.Mp] ++ | |
} | |
func (self *State) handleMinus() { | |
self.Memory[self.Mp] -- | |
} | |
func (self *State) handleLeft() { | |
self.Mp ++ | |
} | |
func (self *State) handleRight() { | |
self.Mp -- | |
} | |
func (self *State) gotoStart() { | |
depth := 0 | |
self.Ip -- | |
for { | |
self.Ip -- | |
instruction := self.getInstruction() | |
if instruction == ']' { | |
depth ++ | |
} else if instruction == '[' && depth != 0 { | |
depth -- | |
} else if instruction == '[' { | |
break | |
} | |
} | |
} | |
func (self *State) gotoEnd() { | |
depth := 0 | |
for { | |
self.Ip ++ | |
instruction := self.getInstruction() | |
if instruction == '[' { | |
depth ++ | |
} else if instruction == ']' && depth != 0 { | |
depth -- | |
} else if instruction == ']' { | |
break | |
} | |
} | |
} | |
func (self *State) handleStart() { | |
if self.Memory[self.Mp] == 0 { | |
self.gotoEnd() | |
} | |
} | |
func (self *State) handleEnd() { | |
if self.Memory[self.Mp] != 0 { | |
self.gotoStart() | |
} | |
} | |
func (self *State) handleOutput() { | |
print(string(self.Memory[self.Mp])) | |
} | |
func main() { | |
state := NewState("++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.") | |
state.Run() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment