RosettaCodeData/Task/Execute-Brain-/Arturo/execute-brain--1.arturo
2026-02-01 16:33:20 -08:00

85 lines
2.1 KiB
Text

;
; Brainf*ck compiler
; In Arturo
;
Tape: [0]
DataPointer: 0
InstructionPointer: 0
; Look for jumps in Code an register them
; in the Jumps table
precomputeJumps: function [][
vstack: []
jumphash: #[]
instrPointer: 0
while [instrPointer<CodeLength] [
command: get split Code instrPointer
switch command="[" -> 'vstack ++ instrPointer
[
if command="]" [
target: last vstack
chop 'vstack
jumphash\[target]: instrPointer
jumphash\[instrPointer]: target
]
]
instrPointer: instrPointer+1
]
jumphash
]
; Check if current state is valid
StateIsValid: function [][
all? @[
0 =< DataPointer
DataPointer < size Tape
0 =< InstructionPointer
InstructionPointer < CodeLength
]
]
; Compile the program
interpret: function [].export:[DataPointer,InstructionPointer,Tape][
while [StateIsValid][
command: get split Code InstructionPointer
case command [
"+" -> Tape\[DataPointer]: Tape\[DataPointer]+1
"-" -> Tape\[DataPointer]: Tape\[DataPointer]-1
">" [
inc 'DataPointer
if DataPointer = size Tape -> Tape: Tape ++ 0
]
"<" -> dec 'DataPointer
"." -> prints to :string to :char Tape\[DataPointer]
"," [
inp: to :integer input ""
if inp=13 -> inp: 10
if inp=3 -> panic "something went wrong!"
set Tape DataPointer inp
]
"[" ->
if 0 = get Tape DataPointer [ InstructionPointer: new Jumps\[InstructionPointer] ]
"]" ->
if 0 <> get Tape DataPointer [
InstructionPointer: new Jumps\[InstructionPointer]
]
]
inc 'InstructionPointer
]
]
Code: ""
switch 1>size arg -> Code: "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
-> Code: read arg\0
CodeLength: size Code
Jumps: precomputeJumps
interpret