From 7fab11f595d7c75ad4f859fb9af9d06b931a1b14 Mon Sep 17 00:00:00 2001 From: tomsmeding Date: Sat, 22 Aug 2015 09:59:55 +0200 Subject: Fully working BF interpreter :tada: --- bf.prn | 85 +++++++++++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 66 insertions(+), 19 deletions(-) diff --git a/bf.prn b/bf.prn index 8d17979..1b305e1 100644 --- a/bf.prn +++ b/bf.prn @@ -1,21 +1,36 @@ -10000 "TAPELEN" store +200 "TAPELEN" store ##First, read in the source -"" -1 while - getline - dup -1 = if - pop - 0 - else - "\n" swap + + - 1 - end +# "" +# 1 while +# getline +# dup -1 = if +# pop +# 0 +# else +# "\n" swap + + +# 1 +# end +# end +# strlen 1 swap substr swap pop +# #bottom of stack now contains 1 string, the source code +# strlen "len" store +# "code" store + +argc 1 = ! if + "Please give the brainfuck file as a command-line argument." print lf + exit end -strlen 1 swap substr swap pop -#bottom of stack now contains 1 string, the source code +0 argvget "r" fopen "filehandle" store +"" +filehandle fgetc +dup -1 = ! while + + + filehandle fgetc +dup -1 = ! end +pop strlen "len" store "code" store @@ -46,27 +61,59 @@ dup 0 > while "code" depth + dup swapoutvar i stridx "c" store swap store #uses the dupped name before the matching swapoutvar - #"c = " c + print lf + #"c = " c + print stackdump + c "#" = if stackdump end c "+" = if 1 + 256 % end c "-" = if 255 + 256 % end c "." = if dup chr print end - c "," = if pop getc ord 256 % end - c ">" = if 1 roll end - c "<" = if -1 roll end + c "," = if + pop + getc + dup -1 = if + pop 255 + else + ord 256 % + end + #{}"Input put on stack " print dup print lf + end + c ">" = if -1 roll end + c "<" = if 1 roll end c "]" = if i "loopend" depth 1 - + store - len "i" store #essentially, break + len "i" store # == break end c "[" = if i "loopstart" depth + store #"loopstart" print depth print " = " print "loopstart" depth + get print lf + 0 "didloop" depth + store dup while + 1 "didloop" depth + store "code" depth + swapoutvar i 1 + len substr swap "code" depth + store execute #stackdump "i = " print i print lf "loopstart" depth + get "i" store dup end - "loopend" depth + get 1 + "loopstart" depth + get + "i" store + "didloop" depth + get ! if + 1 "searchdepth" store + i 1 + "i" store + "code" depth + dup swapoutvar + i len < searchdepth 0 > * while + i stridx "c" store + #"Searching index " print i print " (char " print c print ")" print lf + c "[" = if searchdepth 1 + "searchdepth" store end + c "]" = if searchdepth 1 - "searchdepth" store end + i 1 + "i" store + i len < searchdepth 0 > * end + #stackdump + swap store + searchdepth 0 = ! if + "No matching ']' found for '[' at index " print loopstart print lf + exit + end + i 1 - "i" store + else + "loopend" depth + get 1 + "loopstart" depth + get + "i" store + end #"after loop, i = " print i print lf end -- cgit v1.2.3-54-g00ecf