-
Notifications
You must be signed in to change notification settings - Fork 0
/
bf.py
70 lines (63 loc) · 1.94 KB
/
bf.py
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
from scale import *
from scale.quote import macros, q
@scale.native
def putchar(n: int) -> int: pass
@scale.native
def getchar() -> int: pass
def compile(code, N):
def body(data, ptr):
stmts = []
jump_i = 0
jumpstack = []
for i in range(len(code)):
c = code[i]
if c == '>':
with q as stmt: ptr = (ptr + 1) % N
elif c == '<':
with q as stmt: ptr = (ptr + N - 1) % N
elif c == '+':
with q as stmt: data[ptr] = data[ptr] + 1
elif c == '-':
with q as stmt: data[ptr] = data[ptr] - 1
elif c == '.':
with q as stmt: _ = putchar(data[ptr])
elif c == ',':
with q as stmt: data[ptr] = getchar()
elif c == '[':
target = ('before_' + str(jump_i), 'after_' + str(jump_i))
jumpstack.append(target)
jump_i += 1
with q as stmt:
label ^(u[target[0]])
if data[ptr] == 0:
goto ^(u[target[1]])
elif c == ']':
target = jumpstack.pop()
with q as stmt:
goto ^(u[target[0]])
label ^(u[target[1]])
else:
continue
stmts.append(stmt)
return stmts
@scale.anonymous
def inner() -> int:
data = create_int_array(N)
for i in range(N):
data[i] = 0
ptr = 0
{ body(data, ptr) }
return data[ptr]
return inner
# hello_world = compile('++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.', 256)
# hello_world()
print_0 = compile('+++++++[>+++++++<-]>-.', 2)
print_0()
print_0()
print_0()
cat = compile(',+[-.,+]', 1)
cat.compile()
print(print_0.llvm())
print(print_0.opcode())
print(cat.opcode())
# cat()