1 ! Copyright (C) 2009 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: accessors assocs fry io io.streams.string kernel macros math
5 peg.ebnf quotations sequences strings ;
11 TUPLE: brainfuck pointer memory ;
13 : <brainfuck> ( -- brainfuck )
14 0 H{ } clone brainfuck boa ;
16 : get-memory ( brainfuck -- brainfuck value )
17 dup [ pointer>> ] [ memory>> ] bi at 0 or ;
19 : set-memory ( brainfuck value -- brainfuck )
20 over [ pointer>> ] [ memory>> ] bi set-at ;
22 : (+) ( brainfuck n -- brainfuck )
23 [ get-memory ] dip + 255 bitand set-memory ;
25 : (-) ( brainfuck n -- brainfuck )
26 [ get-memory ] dip - 255 bitand set-memory ;
28 : (?) ( brainfuck -- brainfuck t/f )
31 : (.) ( brainfuck -- brainfuck )
32 get-memory 1string write ;
34 : (,) ( brainfuck -- brainfuck )
37 : (>) ( brainfuck n -- brainfuck )
38 [ dup pointer>> ] dip + >>pointer ;
40 : (<) ( brainfuck n -- brainfuck )
41 [ dup pointer>> ] dip - >>pointer ;
43 : compose-all ( seq -- quot )
44 [ ] [ compose ] reduce ;
48 inc-ptr = (">")+ => [[ length 1quotation [ (>) ] append ]]
49 dec-ptr = ("<")+ => [[ length 1quotation [ (<) ] append ]]
50 inc-mem = ("+")+ => [[ length 1quotation [ (+) ] append ]]
51 dec-mem = ("-")+ => [[ length 1quotation [ (-) ] append ]]
52 output = "." => [[ [ (.) ] ]]
53 input = "," => [[ [ (,) ] ]]
54 space = (" "|"\t"|"\r\n"|"\n")+ => [[ [ ] ]]
55 unknown = (.) => [[ "Invalid input" throw ]]
57 ops = inc-ptr | dec-ptr | inc-mem | dec-mem | output | input | space
58 loop = "[" {loop|ops}* "]" => [[ second compose-all 1quotation [ [ (?) ] ] prepend [ while ] append ]]
60 code = (loop|ops|unknown)* => [[ compose-all ]]
66 MACRO: run-brainfuck ( code -- )
67 [ <brainfuck> ] swap parse-brainfuck [ drop flush ] 3append ;
69 : get-brainfuck ( code -- result )
70 [ run-brainfuck ] with-string-writer ; inline