-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
64 lines (54 loc) · 1.04 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: brainfuck program.b\n")
os.Exit(1)
}
file := os.Args[1]
contents, err := os.ReadFile(file)
if err != nil {
fmt.Printf("Failed to load file %v\n", file)
os.Exit(1)
}
p := NewParser(string(contents))
nodes := p.Parse(0, 0)
if p.Error != nil {
fmt.Println(p.Error)
}
memory := [30000]byte{}
ptr := 0
Execute(nodes, &memory, &ptr)
}
func Execute(nodes []Node, memory *[30000]uint8, ptr *int) {
reader := bufio.NewReader(os.Stdin)
for _, node := range nodes {
switch node.Type {
case AddNode:
memory[*ptr]++
case SubNode:
memory[*ptr]--
case MoveRightNode:
*ptr++
case MoveLeftNode:
*ptr--
case OutputNode:
fmt.Printf("%c", memory[*ptr])
case InputNode:
result, err := reader.ReadByte()
if err != nil {
fmt.Println("Failed to read input from stdin")
os.Exit(1)
}
memory[*ptr] = result
case LoopNode:
for memory[*ptr] != 0 {
Execute(node.Children, memory, ptr)
}
}
}
}