]> gitweb.factorcode.org Git - factor.git/blob - extra/brainfuck/brainfuck.factor
Merge branch 'irc' of git://tiodante.com/git/factor
[factor.git] / extra / brainfuck / brainfuck.factor
1 ! Copyright (C) 2009 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3
4 USING: accessors assocs fry io io.streams.string kernel macros math 
5 peg.ebnf prettyprint quotations sequences strings ;
6
7 IN: brainfuck
8
9 <PRIVATE
10
11 TUPLE: brainfuck pointer memory ;
12
13 : <brainfuck> ( -- brainfuck ) 
14     0 H{ } clone brainfuck boa ;
15
16 : get-memory ( brainfuck -- brainfuck value )
17     dup [ pointer>> ] [ memory>> ] bi at 0 or ;
18
19 : set-memory ( brainfuck value -- brainfuck )
20     over [ pointer>> ] [ memory>> ] bi set-at ;
21
22 : (+) ( brainfuck n -- brainfuck )
23     [ get-memory ] dip + 255 bitand set-memory ;
24
25 : (-) ( brainfuck n -- brainfuck )
26     [ get-memory ] dip - 255 bitand set-memory ;
27
28 : (?) ( brainfuck -- brainfuck t/f )
29     get-memory 0 = not ;
30
31 : (.) ( brainfuck -- brainfuck )
32     get-memory 1string write ;
33
34 : (,) ( brainfuck -- brainfuck )
35     read1 set-memory ;
36
37 : (>) ( brainfuck n -- brainfuck )
38     [ dup pointer>> ] dip + >>pointer ;
39
40 : (<) ( brainfuck n -- brainfuck ) 
41     [ dup pointer>> ] dip - >>pointer ;
42
43 : (#) ( brainfuck -- brainfuck ) 
44     dup 
45     [ "ptr=" write pointer>> pprint ] 
46     [ ",mem=" write memory>> pprint nl ] bi ;
47
48 : compose-all ( seq -- quot ) 
49     [ ] [ compose ] reduce ;
50
51 EBNF: parse-brainfuck
52
53 inc-ptr  = (">")+  => [[ length 1quotation [ (>) ] append ]]
54 dec-ptr  = ("<")+  => [[ length 1quotation [ (<) ] append ]]
55 inc-mem  = ("+")+  => [[ length 1quotation [ (+) ] append ]]
56 dec-mem  = ("-")+  => [[ length 1quotation [ (-) ] append ]]
57 output   = "."  => [[ [ (.) ] ]]
58 input    = ","  => [[ [ (,) ] ]]
59 debug    = "#"  => [[ [ (#) ] ]]
60 space    = (" "|"\t"|"\r\n"|"\n")+ => [[ [ ] ]] 
61 unknown  = (.)  => [[ "Invalid input" throw ]]
62
63 ops   = inc-ptr|dec-ptr|inc-mem|dec-mem|output|input|debug|space
64 loop  = "[" {loop|ops}+ "]" => [[ second compose-all 1quotation [ [ (?) ] ] prepend [ while ] append ]]
65
66 code  = (loop|ops|unknown)*  => [[ compose-all ]]
67
68 ;EBNF
69
70 PRIVATE>
71
72 MACRO: run-brainfuck ( code -- )
73     [ <brainfuck> ] swap parse-brainfuck [ drop flush ] 3append ;
74
75 : get-brainfuck ( code -- result ) 
76     [ run-brainfuck ] with-string-writer ; inline 
77