-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathbf.v
More file actions
161 lines (137 loc) · 2.39 KB
/
bf.v
File metadata and controls
161 lines (137 loc) · 2.39 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
157
158
159
160
161
import os
import net
const (
INC = 0
MOVE = 1
PRINT = 2
LOOP = 3
)
struct Op {
o int
v int
loop []Op
}
fn new_op(op int, v int) Op {
return Op{o: op, v: v}
}
fn new_op_loop(op int, l []Op) Op {
return Op{o: op, loop: l}
}
struct Tape {
mut:
tape []int
pos int
}
fn new_tape() Tape {
t := Tape {
pos: 0
tape: [0]
}
return t
}
fn (t Tape) get() int {
return t.tape[t.pos]
}
fn (t mut Tape) inc(x int) {
t.tape[t.pos] += x
}
fn (t mut Tape) move(x int) {
t.pos += x
for t.pos >= t.tape.len {
t.tape << 0
}
}
struct Program {
ops []Op
}
fn new_program(code string) Program {
si := new_si(code)
return Program{ops: parse(mut si)}
}
fn parse(si mut StringIterator) []Op {
mut res := []Op
for true {
c := si.next()
match c {
`+` { res << new_op(INC, 1) }
`-` { res << new_op(INC, -1) }
`>` { res << new_op(MOVE, 1) }
`<` { res << new_op(MOVE, -1) }
`.` { res << new_op(PRINT, 0) }
`[` { res << new_op_loop(LOOP, parse(mut si)) }
`]` { return res }
`\0`{ return res }
else { continue }
}
}
return res
}
fn (p Program) run() {
mut t := new_tape()
run_ops(p.ops, mut t)
}
fn run_ops(ops []Op, tape mut Tape) {
for op in ops {
match op.o {
INC { tape.inc(op.v) }
MOVE { tape.move(op.v) }
PRINT {
print(byte(tape.get()).str())
os.flush_stdout()
}
LOOP {
for tape.get() > 0 {
run_ops(op.loop, mut tape)
}
}
else {}
}
}
}
struct StringIterator {
code string
mut:
pos int
}
fn new_si(s string) StringIterator {
return StringIterator{code: s, pos: 0}
}
fn (si mut StringIterator) next() byte {
if si.pos < si.code.len {
res := si.code[si.pos]
si.pos++
return res
}
else {
return 0
}
}
fn notify(msg string) {
sock := net.dial('127.0.0.1', 9001) or {
return
}
sock.write(msg) or {}
sock.close() or {}
}
fn main() {
args := os.args
mut filename := ''
if args.len == 2 {
filename = args[1]
}
else {
eprintln('Usage: bf2 filename.b')
return
}
code := os.read_file(filename) or {
eprintln('Failed to open file $filename')
return
}
mut lang := "V GCC"
$if clang {
lang = "V Clang"
}
notify('${lang}\t${C.getpid()}')
new_program(code).run()
notify("stop")
}