brainfuck interpreter

This commit is contained in:
2025-06-30 13:59:17 +02:00
parent 152e0189fe
commit a0bee3f5ca
7 changed files with 68 additions and 22 deletions

View File

@@ -1,5 +0,0 @@
func main[] : I64
let xs: Array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for x in 0..3
for y in 0..3
print_i64(xs[y][x])

45
examples/brainfuck.zr Normal file
View File

@@ -0,0 +1,45 @@
func main[] : I64
let src: String = "++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[-<<<[->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<]>.>+[>>]>+]"
let src_len: I64 = strlen(src)
let i: I64 = 0
let memory: Ptr = calloc(1, 30000)
let p: I64 = 0
while i < src_len
let op: U8 = String.nth(src, i)
if op == '>'
p = p + 1
else if op == '<'
p = p - 1
else if op == '+'
String.set(memory, p, String.nth(memory, p)+1)
else if op == '-'
String.set(memory, p, String.nth(memory, p)-1)
else if op == '.'
printf("%c", String.nth(memory, p))
else if op == ','
String.set(memory, p, getchar())
else if op == '['
if !String.nth(memory, p)
i = i + 1
let opened: I64 = 0
while i < src_len && !(String.nth(src, i) == ']' && !opened)
if String.nth(src, i) == '['
opened = opened + 1
else if String.nth(src, i) == ']'
opened = opened - 1
i = i + 1
else if op == ']'
if String.nth(memory, p)
i = i - 1
let closed: I64 = 0
while i >= 0 && !(String.nth(src, i) == '[' && !closed)
if String.nth(src, i) == ']'
closed = closed + 1
else if String.nth(src, i) == '['
closed = closed - 1
i = i - 1
i = i + 1

View File

@@ -4,7 +4,7 @@ func main[] : I64
panic("socket() failed")
let port: I64 = 80
let sa: Ptr = calloc(16)
let sa: Ptr = calloc(1, 16)
String.set(sa, 0, 2)
String.set(sa, 1, 0)
String.set(sa, 2, Bit.rshift(port, 8) && 255)

View File

@@ -4,7 +4,7 @@ func main[] : I64
panic("socket() failed")
let port: I64 = 8080
let sa: Ptr = calloc(16)
let sa: Ptr = calloc(1, 16)
String.set(sa, 0, 2)
String.set(sa, 1, 0)
String.set(sa, 2, Bit.rshift(port, 8) && 255)