-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathbf.go
More file actions
156 lines (133 loc) · 2.2 KB
/
bf.go
File metadata and controls
156 lines (133 loc) · 2.2 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package main
import (
"fmt"
"io/ioutil"
"net"
"os"
"runtime"
)
const (
INC = iota
MOVE
PRINT
LOOP
)
type Op struct {
O int
V int
Loop []Op
}
func NewOp(op int, v int) Op {
return Op{O: op, V: v}
}
func NewOpLoop(op int, l []Op) Op {
return Op{O: op, Loop: l}
}
type StringIterator struct {
Text []byte
Pos int
}
func NewStringIterator(s string) *StringIterator {
si := &StringIterator{Text: []byte(s), Pos: 0}
return si
}
func (si *StringIterator) Next() byte {
if si.Pos < len(si.Text) {
res := si.Text[si.Pos]
si.Pos += 1
return res
} else {
return byte(0)
}
}
type Tape struct {
tape []int
pos int
}
func NewTape() *Tape {
t := &Tape{pos: 0}
t.tape = make([]int, 1)
return t
}
func (t *Tape) Inc(x int) {
t.tape[t.pos] += x
}
func (t *Tape) Move(x int) {
t.pos += x
for t.pos >= len(t.tape) {
t.tape = append(t.tape, 0)
}
}
func (t *Tape) Get() int {
return t.tape[t.pos]
}
type Program struct {
Ops []Op
}
func NewProgram(code string) *Program {
return &Program{Ops: parse(NewStringIterator(code))}
}
func (p *Program) Run() {
_run(p.Ops, NewTape())
}
func parse(si *StringIterator) []Op {
res := make([]Op, 0)
for true {
c := si.Next()
var op Op
switch c {
case '+':
op = NewOp(INC, 1)
case '-':
op = NewOp(INC, -1)
case '>':
op = NewOp(MOVE, 1)
case '<':
op = NewOp(MOVE, -1)
case '.':
op = NewOp(PRINT, 0)
case '[':
op = NewOpLoop(LOOP, parse(si))
case ']':
return res
case byte(0):
return res
default:
continue
}
res = append(res, op)
}
return res
}
func _run(program []Op, tape *Tape) {
for i := 0; i < len(program); i++ {
switch program[i].O {
case INC:
tape.Inc(program[i].V)
case MOVE:
tape.Move(program[i].V)
case LOOP:
for tape.Get() > 0 {
_run(program[i].Loop, tape)
}
case PRINT:
fmt.Printf("%c", tape.Get())
}
}
}
func notify(msg string) {
conn, err := net.Dial("tcp", "localhost:9001")
if err == nil {
fmt.Fprintf(conn, msg)
conn.Close()
}
}
func main() {
Code, err := ioutil.ReadFile(os.Args[1])
if err != nil {
panic(fmt.Sprintf("%v", err))
}
notify(fmt.Sprintf("%s\t%d", runtime.Compiler, os.Getpid()))
NewProgram(string(Code)).Run()
notify("stop")
}