/* Brainfuck interpreter in roco by Lode Vandevenne */ /* Run this BF interpreter using a roco interpreter. When the program runs, enter a Brainfuck string. The program considers the *newline* to be the end of the program, so you have to enter the complete BF program on one line and then press enter. */ /* Usage of the variables in this program: variable 0 = current bf character variable 7 = index of last currently allocated bf memory cell variable 8 = bf memory pointer variable 9 = bf instruction pointer variable 10 to x = bf source code variable x+1 to infinity: bf working memory */ /* BF example (prints Hello World!) ++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. */ /*read the BF input from the user*/ co inputBF { cin [2] set [[1]] [2] inc [1] eq [3] [2] 10 if [3] ac /*stop when newline is reached*/ } set [1] 10 /*the first source code cell to fill is at 10*/ ca inputBF set [8] [1] /*make it point to first memory cell*/ set [7] [8] /*remember that for now only 1 cell is allocated*/ set [[8]] 0 /*make first memory cell zero; rest will be allocated when needed*/ /*the BF operations*/ co incr /* + */ { inc [[8]] eq [1] [[8]] 256 if [1] set [[8]] 0 /*make the value wrap in the range 0-255*/ ac } co decr /* - */ { dec [[8]] eq [1] [[8]] -1 if [1] set [[8]] 255 /*make the value wrap in the range 0-255*/ ac } co incrp /* > */ { inc [8] co newmem /* allocate new memory (i.e. set it to 0) if needed */ { set [[8]] 0 set [7] [8] ac } gt [1] [8] [7] if [1] ca newmem ac } co decrp /* < */ { dec [8] ac } co jump /* [ */ { co go /*go to matching ]*/ { inc [9] eq [1] [[9]] 91 if [1] inc [9] /*if another [ is encountered, increment the accumulator*/ eq [3] [[9]] 93 eq [4] [2] 0 and [4] [3] [4] if [3] dec [2] /*decrement accumulator if ] is encountered*/ if [4] ac /*done if accumulator is 0 and ] is encountered*/ } set [2] 0 /*accumulator*/ eq [1] [[8]] 0 /*if memory cell is 0...*/ if [1] ca go /*then go to the matching bracket*/ ac } co jumpb /* ] */ { co go /*jump back to [*/ { dec [9] eq [1] [[9]] 93 if [1] inc [9] /*if another ] is encountered, increment the accumulator*/ eq [3] [[9]] 91 eq [4] [2] 0 and [4] [3] [4] if [3] dec [2] /*decrement accumulator if [ is encountered*/ if [4] ac /*done if accumulator is 0 and [ is encountered*/ } set [2] 0 /*accumulator*/ ca go dec [9] /*decrement once more so that it's on this symbol next time*/ ac } co out /* . */ { cout [[8]] ac } co in /* , */ { cin [[8]] ac } /*run it all*/ co run { set [0] [[9]] eq [1] [0] 62 if [1] ca incrp eq [1] [0] 60 if [1] ca decrp eq [1] [0] 43 if [1] ca incr eq [1] [0] 45 if [1] ca decr eq [1] [0] 91 if [1] ca jump eq [1] [0] 93 if [1] ca jumpb eq [1] [0] 46 if [1] ca out eq [1] [0] 44 if [1] ca in eq [1] [0] 10 if [1] ac inc [9] } set [9] 10 /*the BF instruction pointer starts here*/ ca run /*run the BF program*/ ac