forked from terralang/terra
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bf.t
60 lines (55 loc) · 1.37 KB
/
bf.t
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
local C = terralib.includec("stdio.h")
local function compile(code,N)
local function body(data,ptr)
local stmts = terralib.newlist()
local jumpstack = {}
for i = 1,#code do
local c = code:sub(i,i)
local stmt
if c == ">" then
stmt = quote ptr = ptr + 1 end
elseif c == "<" then
stmt = quote ptr = ptr - 1 end
elseif c == "+" then
stmt = quote data[ptr] = data[ptr] + 1 end
elseif c == "-" then
stmt = quote data[ptr] = data[ptr] - 1 end
elseif c == "." then
stmt = quote C.putchar(data[ptr]) end
elseif c == "," then
stmt = quote data[ptr] = C.getchar() end
elseif c == "[" then
local target = { before = label(), after = label() }
table.insert(jumpstack,target)
stmt = quote
::[target.before]::
if data[ptr] == 0 then
goto [target.after]
end
end
elseif c == "]" then
local target = table.remove(jumpstack)
assert(target)
stmt = quote
goto [target.before]
:: [target.after] ::
end
else
error("unknown character "..c)
end
stmts:insert(stmt)
end
return stmts
end
return terra()
var data : int[N]
for i = 0, N do
data[i] = 0
end
var ptr = 0;
[ body(data,ptr) ]
end
end
local helloworld = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
local fn = compile(helloworld,256)
fn()