-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuckbrain.go
86 lines (79 loc) · 1.4 KB
/
fuckbrain.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"log"
"os"
"strings"
)
type Stack []int
func (s *Stack) Push(v int) {
*s = append(*s, v)
}
func (s *Stack) Pop() (int, bool) {
if len(*s) == 0 {
return 0, false
}
v := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return v, true
}
func (s *Stack) Peek() (int, bool) {
if len(*s) == 0 {
return 0, false
}
return (*s)[len(*s)-1], true
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: fuckbrain <filename>")
return
}
file_name := os.Args[1]
if strings.Split(file_name, ".")[1] != "bf" {
fmt.Println("Invalid file type. Please provide a .bf file")
return
}
file, err := os.ReadFile(file_name)
if err != nil {
fmt.Println("Error opening file:", err)
return
}
arrTape := make([]byte, 30000)
ptr := 0
stack := Stack{}
for i := 0; i < len(file); i++ {
char := rune(file[i])
switch char {
case '>':
if ptr == len(arrTape)-1 {
log.Fatal("Index out of bounds of memory tape")
return
}
ptr++
case '<':
if ptr == 0 {
log.Fatal("Index out of bounds of memory tape")
return
}
ptr--
case '+':
arrTape[ptr]++
case '-':
arrTape[ptr]--
case '.':
fmt.Printf("%c", arrTape[ptr])
case ',':
fmt.Scanf("%c", &arrTape[ptr])
case '[':
stack.Push(i)
case ']':
if len(stack) == 0 {
log.Fatal("Unmatched ']' at index ", i)
}
start, _ := stack.Pop()
if arrTape[ptr] != 0 {
i = start - 1
}
}
}
}